title: Leaking database connections: PostgreSQL, SQLAlchemy, Flask
body: <p>I'm running PostgreSQL 9.3 and SQLAlchemy 0.8.2 and experience database connections leaking. After deploying the app consumes around 240 connections. Over next 30 hours this number gradually grows to 500, when PostgreSQL will start dropping connections.</p>
  
  <p>I use SQLAlchemy <a href="http://docs.sqlalchemy.org/en/rel_0_8/orm/session.html#contextual-thread-local-sessions" rel="nofollow">thread-local sessions</a>:</p>
  
  <pre><code>from sqlalchemy import orm, create_engine
  
  engine = create_engine(os.environ['DATABASE_URL'], echo=False)
  Session = orm.scoped_session(orm.sessionmaker(engine))
  </code></pre>
  
  <p>For the Flask web app, the <code>.remove()</code> call to the <code>Session</code> proxy-object is send during request teardown:</p>
  
  <pre><code>@app.teardown_request
  def teardown_request(exception=None):
      if not app.testing:
          Session.remove()
  </code></pre>
  
  <p>This should be the same as what <code>Flask-SQLAlchemy</code> is doing.</p>
  
  <p>I also have some periodic tasks that run in a loop, and I call <code>.remove()</code> for every iteration of the loop:</p>
  
  <pre><code>def run_forever():
      while True:
          do_stuff(Session)
          Session.remove()
  </code></pre>
  
  <p>What am I doing wrong which could lead to a connection leak?</p>