Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing database connection in Express 3

In Express 3, how do you handle closing database connections when the process exists?

The .on('close', ... event is not emitted unless you explicitly use a HTTP server's .close() call.

So far, this is the closest I've come, but it uses process.on instead of server.on:

process.on('SIGTERM', function () {
   // Close connections.
   process.exit(0);
});
like image 302
dgo.a Avatar asked Nov 16 '12 19:11

dgo.a


People also ask

Should I close DB connection?

Ensuring your database connections are closed in a timely fashion can go a long way in keeping your database performant and available.

Should I close DB connection after query?

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.


1 Answers

Based on the info from:

  • https://github.com/visionmedia/express/issues/1366
  • http://blog.argteam.com/coding/hardening-node-js-for-production-part-3-zero-downtime-deployments-with-nginx/

--

var express = require('express');

var app = express();
var server = app.listen(1337);
var shutting_down = false;

app.use(function (req, resp, next) {
 if(!shutting_down)
   return next();

 resp.setHeader('Connection', "close");
 resp.send(503, "Server is in the process of restarting");
 // Change the response to something your client is expecting:
 //   html, text, json, etc.
});

function cleanup () {
  shutting_down = true;
  server.close( function () {
    console.log( "Closed out remaining connections.");
    // Close db connections, other chores, etc.
    process.exit();
  });

  setTimeout( function () {
   console.error("Could not close connections in time, forcing shut down");
   process.exit(1);
  }, 30*1000);

}

process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);

The Connection: close header is used to tell any keep-alive connection to close the next time they send a HTTP request. More info here: http://www.jmarshall.com/easy/http/#http1.1s4

I have no idea if there are other ways of closing the keep-alive connection. The node process will hang unless the keep-alive connections are closed. The default idle timeout is 2 mins. More info. on node.js keep-alive timeouts (including on changing the timeout): How to set the HTTP Keep-Alive timeout in a nodejs server

like image 165
12 revs Avatar answered Sep 30 '22 21:09

12 revs