Rails with multiple Sequel Databases


The Scenario

Most of the web apps I help maintain keep a connection to two separate databases: one MSSQL and one MySQL. These are accessed in the legacy apps via a models directory and in new apps via a gem. Both connections are handled using the Sequel gem.

The Problem

The legacy applications run on Passenger with a single thread. The database connections also use a single thread. With over 20 databases per server, and 50 users this gets messy. Fast. When doing operations that take a few seconds the database could be switched, giving all but the most recent user incorrect data, or worse, an internal server error.

The Solution

As I mentioned, the new apps use a gem to talk to the databases. They also use Unicorn to serve pages. A simple fix (that actually took quite a while to find using Google) follows:

worker_processes 10 # set to value of Sequel :max_connections

before_fork do |server, worker|
  MysqlDatasource::DB.disconnect
  MssqlDatasource::DB.disconnect
end

Everything has been running smooth for over a month now with no internal server errors :)