Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Server with mysql hangs

I am writing an application using NodeJS, Express, mysql, so far everything works fine, but when I run my application after sometime when mysql connection is interrupted my application throughs this exception and my application goes down.

Error: read ECONNRESET
    at errnoException (net.js:901:11)
    at TCP.onread (net.js:556:19)

From another stackquestion i came to know that i have to handle such uncaught exceptions like this.

process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err);
    console.log(err.stack);
});

after this now my application does not exit, but instead it hangs up, so my question is how do I handle this exception so that mysql connection is ok even after this exception and my application does not hang up.

like image 867
KKK Avatar asked Mar 24 '14 06:03

KKK


2 Answers

I'm not sure if you're using the node-mysql module for your project, but I was, and I encountered the same ECONNRESET issue. Here's a repeat of my answer on my issue:

I reached out to the node-mysql folks on their Github page and got some firm answers.

  1. MySQL does indeed prune idle connections. There's a MySQL variable "wait_timeout" that sets the number of second before timeout and the default is 8 hours. We can set the default to be much larger than that. Use show variables like 'wait_timeout'; to view your timeout setting and set wait_timeout=28800; to change it.

  2. According to this issue, node-mysql doesn't prune pool connections after these sorts of disconnections. The module developers recommended using a heartbeat to keep the connection alive such as calling SELECT 1; on an interval. They also recommended using the node-pool module and its idleTimeoutMillis option to automatically prune idle connections.

like image 197
Brent Traut Avatar answered Oct 20 '22 11:10

Brent Traut


I found the solution and I am posting if someone else is facing the same problem this might help you guys as well.

First I caught all uncaught exceptions, which made my application not to exit abnormally.

Second the problem of hanging I had was because when server would close the connection, all my requested queries would fail and my server would simply hang up I guess its node-mysql bug, but I solved it using connecting pooling, in pooling if server close the connection its re-aquired after a second or so again so my problem was solved this way.

Here is how to make most out of node-mysql pooling

like image 36
KKK Avatar answered Oct 20 '22 10:10

KKK