You're viewing a post from the archive. Don't forget to checkout our latest post Adding awesome mini views to your web apps

MySQL per default kills inactive connections after 8 hours. This timeout can be changed in my.cnf by setting wait_timeout value. If you use Active Record and your program tries to use persistent connection after 8 hours of inactivity, you are likely to see the following error:


Mysql::Error: MySQL server has gone away ...

This is not a problem if Active Record is used within Rails controller actions. Rails verifies and reconnects inactive connections before invoking an action.
If you use Active Record outside Rails or at least outside controller actions you have to verify connections on your own before executing a database statement. This can be done with the following code:


ActiveRecord::Base.verify_active_connections!

Since Active Record uses one connection per thread, in multi-threaded applications this verification has to be executed for each thread separately.

I started looking if there is any better, automated way to ensure connection is active before executing a statement. MySQL client, since version 5.0.13, provides MYSQL_OPT_RECONNECT option, which tells it to automatically reconnect if it finds that a connection is down.

Fortunately Active Record since version 2.3 supports this reconnect option. Per default it's set to false, but it can be enabled by adding reconnect = true to database options in database.yml.