Posted almost 8 years ago. Visible to the public.

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

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Andreas Robecke
Last edit:
almost 8 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Andreas Robecke to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more