title: ActiveRecord leaks connections when using in Rack middleware
body: <p>For a very database intensive view, I've turned to database denormalization/caching to reduce server resource demand and increase performance for users. The view is a summary view composed of data from many different tables, so a lot of different data changes also update the cache.</p>
  
  <p>To reduce the churn in the cache, I turned to Rack middleware. My middleware looks like this:</p>
  
  <pre><code>class MyMiddleware
    def initialize(app)
      @app = app
    end
    def call(env)
      # ... prepare in memory storage for what needs to change
      return_value = @app.call(env)
      # ... commit changes to the database
      return_value
    end
  end
  </code></pre>
  
  <p>Everything looked great until the app was put under load for a while. Then I started seeing the following error occassionally in the logs:</p>
  
  <pre><code>Status: 500 Internal Server Error
  could not obtain a database connection within 5 seconds.  The max pool size is currently 5; consider increasing it.
  </code></pre>
  
  <p>When I remove the middleware, the application works normally again.</p>
  
  <p>How do I fix the connection leak when using ActiveRecord from Rack middleware?</p>