→ SQL server has gone away

19 November 2009

Garry Tan posted today about a Resque gotcha: Mysql::Error: MySQL server has gone away.

You'll get this error if your workers are idle for an extended period of time. They'll lose their MySQL connection and any subsequent statements will fail.

This post explains a few possible solutions. For us, automatically re-connecting fits best. We don't care if the connection has gone away.

Just stick this code in config/initializers/connection_fix.rb and never worry again!

module ActiveRecord::ConnectionAdapters
  class MysqlAdapter
    alias_method :execute_without_retry, :execute

    def execute(*args)
      execute_without_retry(*args)
    rescue ActiveRecord::StatementInvalid => e
      if e.message =~ /server has gone away/i
        warn "Server timed out, retrying"
        reconnect!
        retry
      else
        raise e
      end
    end
  end
end

Gist

I completely forgot we ran into this problem so neglected to mention it in the Resque documentation. Sorry Garry!