ActiveRecord Binds Connections When Used in Rack Middleware

For a very intensive database scan, I turned to denormalizing / caching the database to reduce the need for server resources and increase productivity for users. A view is a summary view consisting of data from many different tables, so many different data changes also update the cache.

To reduce cache outflow, I turned to the Rack middleware. My middleware is as follows:

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 

Everything looked great until the application was downloaded for a while. Then in the logs, I accidentally noticed the following error:

 Status: 500 Internal Server Error could not obtain a database connection within 5 seconds. The max pool size is currently 5; consider increasing it. 

When I uninstall the middleware, the application works fine again.

How to fix connection leaks when using ActiveRecord from Rack middleware?

+4
source share
1 answer

ActiveRecord provides a way to manually clear connections - ActiveRecord::Base.clear_active_connections! . Update the call method in the middleware to clear active connections after making changes to the database.

 def call(env) # ... prepare in memory storage for what needs to change return_value = @app.call(env) # ... commit changes to the database ActiveRecord::Base.clear_active_connections! # fixes the connection leak return_value end 

http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html

+6
source

Source: https://habr.com/ru/post/1488132/


All Articles