How to Fix MySQL 'Server Has Gone Away' Issue When Using MySQL2 Gem

After spending WAY too much time trying to find an answer for the correct fix for the error ActiveRecord::StatementInvalid Mysql2::Error: MySQL server has gone away: I eventually came across this answer.

Put the following code into a file config/initializers/mysql_fix.rb:

config/initializers/mysql_fix.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module ActiveRecord::ConnectionAdapters
  class Mysql2Adapter
    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

This is only a slight tweak from the MySQL gem version, but properly works for the MySQL2 gem.

Comments