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

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.

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.

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
Andreas Robecke almost 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more