Verify Database Connections in Long-Running Idle Rails Processes

July 03, 2008

I recently interfaced one of my [xmpp4r bots](http://barkingiguana.com/2008/05/28/xmpp4r-simple-makes-xmpp-in-ruby-uhh-simple) with the Xeriom Networks control panel. I'd planned to write a post about how easy it is, but [RubyPond beat me to it](http://rubypond.com/articles/2008/06/26/make-your-own-im-bot-in-ruby-and-interface-it-with-your-rails-app). 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: ```ruby 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.*
Questions or thoughts? Get in touch.