Search code examples
mysqlrubyactiverecordsinatraconnection-timeout

MySQL connection timeout - MySQL server has gone away (Sinatra, ActiveRecord)


Here is an outline of my app:

require 'sinatra'
require 'active_record'

ActiveRecord::Base.establish_connection(
     :adapter => "mysql", host => $DB_HOSTNAME,
     :database => $DB_NAME,:username => $DB_USERNAME,:password => $DB_PASSWORD)

class Sometable < ActiveRecord::Base
end

get '/' do
  #stuff with Sometable
end

# a lot of route handlers..

etc.

I call establish_connection just once - during the app initialization. I encountered the 8 hour idle connection limit of MySQL (MySQL server has gone away) and am wondering the best approach to it.

I went through ActiveRecord source and found that it pools db server connections. So, should I ideally create a new connection inside every web request or increase the timeout setting?

Thanks for your time!


Solution

  • Thanks for all the answers. MYSQL_OPT_RECONNECT seems to be a good solution. But I'm not sure how to do it using ActiveRecord.

    For now, I've solved it using:

    #prevent MySQL server has gone away by verifying connections every 30 minutes.
    Thread.new { 
      loop {
        sleep(60*30);
        ActiveRecord::Base.verify_active_connections!
      }
    }.priority = -10