Posted over 7 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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Andreas Robecke
Last edit:
over 7 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