DEV Community

Saurav Pandey
Saurav Pandey

Posted on

Mastering Graceful Shutdown in Node.js: Prevent Data Loss in Production

What Is a Graceful Shutdown?

Graceful shutdown in Node.js is the process of stopping an application server cleanly without interrupting ongoing user requests or damaging active database operations. Instead of instantly killing the application process when a stop command is issued, the server stops accepting new incoming traffic, finishes processing current HTTP requests, closes database connections properly, and then exits safely. This process guarantees that active users do not experience sudden network errors and that pending write operations complete successfully.

A Real-World Analogy: Closing a Restaurant

Imagine a busy restaurant reaching its closing hour at 10:00 PM. The management does not turn off the dining room lights and kick paying customers out in the middle of their meals. Instead, the host locks the front door to prevent new diners from walking in, while the kitchen continues cooking orders for guests who are already seated. Once every remaining customer finishes eating, pays their bill, and leaves, the staff cleans up, turns off the stoves, and locks the building. In Node.js, shutting down gracefully works the exact same way: locking the front door represents refusing new HTTP connections, and letting seated guests finish their meals represents completing active requests.

Why It Matters in Modern Tech Infrastructure

In cloud platforms like Kubernetes, Docker, or AWS, application servers are frequently restarted, autoscaled, or redeployed during software updates. When the host system needs to terminate your application instance, it sends an operating system signal such as SIGTERM to announce the upcoming shutdown. Without a graceful shutdown handler, your server immediately dies mid-operation. If a user is currently submitting a credit card payment or saving a profile update to a MySQL database when that process dies, their HTTP request drops instantly and database records can be left in an incomplete or corrupted state. Engineers implement graceful shutdowns so that deployments and server restarts happen with zero downtime and zero data loss.

Code Example: Graceful Shutdown in Express.js

Here is how you can set up a clean termination workflow in an Express application connected to a MySQL database pool using native Node.js process events:

const express = require('express');
const mysql = require('mysql2/promise');

const app = express();
const PORT = process.env.PORT || 3000;

// Create a MySQL database connection pool
const dbPool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'secretpassword',
  database: 'production_db',
  connectionLimit: 10
});

app.get('/checkout', async (req, res) => {
  try {
    // Simulate a database operation
    await dbPool.query('INSERT INTO orders (status) VALUES (?)', ['completed']);
    res.status(200).send('Order processed successfully!');
  } catch (error) {
    res.status(500).send('Database transaction failed');
  }
});

const server = app.listen(PORT, () => {
  console.log(`Express app listening on port ${PORT}`);
});

// Handle process termination signals
function shutdownGracefully(signal) {
  console.log(`Received ${signal}. Starting graceful shutdown...`);

  // Stop accepting new network connections
  server.close(async () => {
    console.log('HTTP server closed. No longer accepting new requests.');

    try {
      // Close database connection pool cleanly
      await dbPool.end();
      console.log('MySQL database connection pool drained and closed.');
      process.exit(0);
    } catch (error) {
      console.error('Error shutting down database pool:', error);
      process.exit(1);
    }
  });
}

// Register listeners for common termination signals
process.on('SIGTERM', () => shutdownGracefully('SIGTERM'));
process.on('SIGINT', () => shutdownGracefully('SIGINT'));
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

Graceful shutdown is a fundamental backend reliability pattern that converts abrupt, risky server kills into predictable, controlled exits. By taking a few extra seconds to close open connections and flush pending requests during process termination, developers ensure uninterrupted user experiences and long-term data integrity.


Buy Me A Coffee

Enjoyed this breakdown? Support my open-source work on Buy Me a Coffee or explore react-hook-lab!

Originally published on my blog. You can read the alternative breakdown here.

Top comments (1)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

One thing bites this exact code behind a load balancer: server.close() only stops new connections, and a client that keeps its keep-alive socket busy is never cut off. I ran it on Node 22 with a keep-alive client sending one 300ms request after another. After SIGTERM the server kept answering on that socket with Connection: keep-alive for 11 more seconds (37 more requests), and the close callback only fired when the client stopped on its own. Ingress proxies keep pooled connections like that, so with steady traffic the callback can wait until Kubernetes sends SIGKILL after the grace period, and dbPool.end() never runs.

Second small one: pressing Ctrl+C twice calls server.close() again, and that callback also fires (with ERR_SERVER_NOT_RUNNING, which the code ignores), so dbPool.end() runs twice. In my stub the second end threw, so the process exited 1 even though shutdown worked.

This version finished the in-flight request and exited in about 75ms in the same test (my test server was plain http, same hook):

let shuttingDown = false;

app.use((req, res, next) => {
  // decide when headers go out, so requests already running when SIGTERM lands also get it
  const writeHead = res.writeHead;
  res.writeHead = function (...args) {
    if (shuttingDown) this.setHeader('Connection', 'close');
    return writeHead.apply(this, args);
  };
  next();
});

function shutdownGracefully(signal) {
  if (shuttingDown) return;
  shuttingDown = true;

  // stay under terminationGracePeriodSeconds
  setTimeout(() => process.exit(1), 10_000).unref();

  server.close(async () => {
    await dbPool.end();
    process.exit(0);
  });
  server.closeIdleConnections();
}
Enter fullscreen mode Exit fullscreen mode

Requests already running finish and get Connection: close, idle sockets drop right away, and the timer covers the request that hangs forever.