# How to avoid losing mysql connections with Rails

**URL:** <https://www.ruby-forum.com/t/how-to-avoid-losing-mysql-connections-with-rails/176948>\
**Category:** Rails\
**Created:** [October 8, 2009, 7:40pm UTC](https://www.ruby-forum.com/t/how-to-avoid-losing-mysql-connections-with-rails/176948 "2009-10-08T19:40:40Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![sumwutdum](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b77776/32.png) [@sumwutdum](https://www.ruby-forum.com/u/sumwutdum)\
**Post date:** [October 8, 2009, 7:40pm UTC](https://www.ruby-forum.com/t/how-to-avoid-losing-mysql-connections-with-rails/176948/1 "2009-10-08T19:40:40Z")

</div>

HI everyone,

What’s the current best practice for avoiding ActiveRecord mySQL errors  
like these two here?

ActiveRecord::StatementInvalid: Mysql::Error: MySQL server has gone  
away:

or

ActiveRecord::StatementInvalid: Mysql::Error: Lost connection to MySQL  
server during query

I have an app that’s just sent me a few such errors in quick succession,  
and I’m trying to find the best way to stop this happening again, and  
Im’ somewhat confused about what most of you guys tend to do when faced  
with an error like this.

The easiest option, to add a ‘reconnect: true’ flag to database.yaml  
seems to be something that’s advised against in the MySQL  
documentation[1].

The other first option that comes to me to put a reconnect function in  
the :before filter, doesn’t seem to work too well either according to  
this guy[3] either, and I’m not familiar enough with Rails’s source to  
try hacking around without some guidance.

I think these are happening when a MySQL connection times out without  
the rails process picking up on this, but I’m not sure.

Would some kind soul help shed some light on the best course of action  
here?

Many thanks,

Chris

[1]  
[http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html)  
[2] [http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html](http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html)  
[3] [Rails and mysql timeouts | Notes In The Margin](http://wooga.drbacchus.com/rails-and-mysql-timeouts)
