Verify Database Connections in Long-Running Idle Rails Processes

July 03, 2008 · 1 min read

I recently interfaced one of my xmpp4r bots with the Xeriom Networks control panel. I’d planned to write a post about how easy it is, but RubyPond beat me to it. I can, however, offer one piece of advice that will save you from a subtle bug: periodically verify your database connections.

If your Rails process sits idle for a while – which is normal for something like a chat bot waiting for messages – MySQL (and other databases) will silently drop the connection. When the bot finally tries to use it, everything falls over.

The fix is simple. Spin up a background thread that pings the connection every half hour:

RAILS_DEFAULT_LOGGER.debug "Launching database connection verifier"
Thread.new do
  loop do
    sleep 1800 # Half an hour
    RAILS_DEFAULT_LOGGER.debug "Verifying database connections"
    ActiveRecord::Base.verify_active_connections!
  end
end

Drop this into your script and stale connections will be reconnected before they cause trouble.

Update: the Xeriom support bot is no longer running. It was fun, but not hugely useful in that context.

These posts are LLM-aided. Backbone, original writing, and structure by Craig. Research and editing by Craig + LLM. Proof-reading by Craig.