Read more

ActiveRecord::StatementInvalid: Mysql2::Error: closed MySQL connection

Andreas Robecke
October 01, 2013Software engineer

I recently experienced the error ActiveRecord::StatementInvalid: Mysql2::Error: closed MySQL connection. Apparently this happens when there is a timeout during query execution. In order to fix this you can reconnect to your db.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Therefore either add reconnect: true to your database.yml for automatic reconnection when the error occurs or catch the error and manually and reconnect explicitly via ActiveRecord::Base.connection.reconnect!

Be aware that reconnecting will have the following impact on your current connection:

  • Any active transactions are rolled back and autocommit mode is reset.
  • All table locks are released.
  • All TEMPORARY tables are closed (and dropped).
  • ...

For further details see the mysql doc Show archive.org snapshot .

You can actually force this error by setting a short timeout and sleeping in the query:

Timeout.timeout(1) { User.find_by_sql('SELECT sleep(2) FROM users;') }
# All subsequent queries then will fail with the error mentioned above
User.count
Posted by Andreas Robecke to makandra dev (2013-10-01 13:23)