In this post we will be discussing about gracefully shutting down Nodejs server. When you shutdown a server there are exchange of protocol messages between two endpoints known as shutdown sequence. Shutdown sequence are of two types graceful and abortive.
Graceful shutdown are the one where any data that has been queued, prior to sending signal of shutdown, will be processed. Whereas in abortive shutdown any unsent data will be lost.
When abortive shutdown happens your application terminates imeediately before completion of any queued requets thus giving an horrible user experience. In the graceful shutdown server stops accepting new connections, it stops fulfilling new requests and complets the queued requests before shutting down.
In Node.js we can use generic signal called SIGTERM or SIGINT which is actually used for program termination. Using this generic signal we are actually asking the program to terminate and clean up the resources utilized by the program.
var http = require('http');
var app = http.createServer(function (req,res) {
console.log('Starting Server...');
res.writeHead(200, {'Content-Type': 'text/plain'});
setTimeout(function () {res.end('OK\n');}, 5000);
console.log('Written To Server');
});
// e.g. kill
process.on('SIGTERM', function() {
console.log('Closing Gracefully');
app.close();
process.exit();
});
//e.g. Ctrl + C
process.on('SIGINT', function() {
console.log('Closing Gracefully');
app.close();
process.exit();
});
app.listen(5000);
Please Like and Share the Blog, if you find it interesting and helpful.
Graceful shutdown are the one where any data that has been queued, prior to sending signal of shutdown, will be processed. Whereas in abortive shutdown any unsent data will be lost.
When abortive shutdown happens your application terminates imeediately before completion of any queued requets thus giving an horrible user experience. In the graceful shutdown server stops accepting new connections, it stops fulfilling new requests and complets the queued requests before shutting down.
In Node.js we can use generic signal called SIGTERM or SIGINT which is actually used for program termination. Using this generic signal we are actually asking the program to terminate and clean up the resources utilized by the program.
Code :
var http = require('http');
var app = http.createServer(function (req,res) {
console.log('Starting Server...');
res.writeHead(200, {'Content-Type': 'text/plain'});
setTimeout(function () {res.end('OK\n');}, 5000);
console.log('Written To Server');
});
// e.g. kill
process.on('SIGTERM', function() {
console.log('Closing Gracefully');
app.close();
process.exit();
});
//e.g. Ctrl + C
process.on('SIGINT', function() {
console.log('Closing Gracefully');
app.close();
process.exit();
});
app.listen(5000);
Please Like and Share the Blog, if you find it interesting and helpful.
No comments:
Post a Comment