I was playing around with Sinatra and ActiveRecord when I found that a connections are not reused automatically by this simple API.
create_table :subscribers do |t|
class Subscriber < ActiveRecord::Base
validates :email, presence: true
class Newsletter < Sinatra::Base
set :server, :thin
get '/subscribers/:email' do
s = Subscriber.find_by_email(params[:email])
if s == nil
post '/subscribers/:email' do
One way of cleaning connections is to call
ActiveRecord::Base.clear_active_connections! after each use of
Subscriber.create, like so.
after do ActiveRecord::Base.clear_active_connections! end
Somewhere else, some people suggest using middleware
ActiveRecord::ConnectionAdapters::ConnectionManagement. That does not work in Thin because Thin starts processing each request in a thread and finishes processing the request in another thread.
ConnectionManagement only returns to the pool those connections that are active for the current thread and Thin applies
ConnectionManagement in the second thread instead of the first.
I made an explanation of why using middleware
ActiveRecord::Connectionadapters::ConnectionManagement won't work with Thin in threaded mode, which you can find here.