Josh1billion Josh1billion - 1 month ago 8
MySQL Question

Safely keeping MySQL connections alive

I'm working on a node.js application that connects to a MySQL server. The following likely isn't node.js-specific, though.

Currently, my code initializes a MySQL connection at the application start-up, and then it uses that connection every time it needs to make a query.

The issue I'm facing with my approach is that the connection tends to close after a period of time. I'm not sure how long that period of time is, but it seems to be at least several hours. I'm also not sure whether it's caused by inactivity.

In any case, I'm wondering what would be a better approach for managing MySQL connections long-term. Of possible approaches, I've considered:


  • Simply checking before each query to see whether the connection is still valid. If not, reconnect before executing the query.

  • Pooling MySQL connections. Would this be overkill for a fairly small application?

  • Periodically (every hour or so), execute a query, in case this is occurring due to inactivity. However, this doesn't remedy the situation in possible cases not caused by inactivity.

  • Connect and disconnect before/after queries. Bad idea because of the overhead involved.



I'm leaning toward using one of the first two options, as you might imagine. Which of the options would be most reliable and efficient?

Answer

The best practice for Node.js seems to be to use a connection pool. See Node.js MySQL Needing Persistent Connection.

The default timeout for idle connections is 28800 seconds, and is configurable with the wait_timeout variable. See http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_wait_timeout

Comments