DEV Community

Cover image for Graceful Shutdown in Node.js: How to Deploy Without Dropping Requests (SIGTERM, Docker and Kubernetes)
Prism Infoways Private Limited
Prism Infoways Private Limited

Posted on Edited on

Graceful Shutdown in Node.js: How to Deploy Without Dropping Requests (SIGTERM, Docker and Kubernetes)

Every deploy kills your old processes. The only question is whether they die politely or take a few dozen user requests down with them.

If you've ever seen a burst of 502 Bad Gateway or ECONNRESET errors right after a rollout, and then everything magically recovers, you've met the problem this post is about. The fix is called graceful shutdown, and in Node.js it takes about 40 lines of code plus two lines of infrastructure config.

Here's what happens, why the defaults bite you, and the exact code we use on production APIs.

What actually happens when a container is stopped

Whether it's docker stop, a Kubernetes rolling update, or an autoscaler removing an instance, the sequence is roughly:

  1. The orchestrator sends SIGTERM to your process.
  2. It waits for a grace period (10 seconds for docker stop, 30 seconds by default in Kubernetes).
  3. If the process is still alive, it sends SIGKILL. No cleanup, no last words.

Node's default behaviour on SIGTERM is to exit immediately. That means:

  • Requests that were halfway through processing get cut off.
  • Database transactions are left to time out on the server side.
  • Background jobs are abandoned mid-run.
  • Load balancers may still be sending new traffic to a process that no longer exists.

Graceful shutdown is simply: catch SIGTERM, stop taking new work, finish the work you have, close your connections, then exit.

The naive version (and why it's not enough)

Most people start here:

process.on('SIGTERM', () => {
  server.close(() => process.exit(0));
});
Enter fullscreen mode Exit fullscreen mode

server.close() stops the server from accepting new connections and calls back once existing ones are done. Better than nothing, but there are three gaps:

  1. Keep-alive connections. Browsers, proxies and HTTP clients reuse connections. An idle keep-alive socket can keep server.close() waiting until it times out. (Node 19+ closes idle connections during close(), but connections that are mid-request will still pick up new requests until you tell them not to.)
  2. The load balancer race. In Kubernetes, sending SIGTERM and removing the pod from the Service endpoints happen in parallel. For a few seconds after SIGTERM, traffic can still arrive. If you stop listening instantly, those requests fail.
  3. No deadline. If one request hangs, your process waits until SIGKILL, and you lose control over what gets cleaned up.

A production-ready shutdown handler

Here's a complete Express + PostgreSQL example that handles all three:

const http = require('node:http');
const express = require('express');
const { Pool } = require('pg');

const app = express();
const pool = new Pool(); // reads PG* env vars
let shuttingDown = false;

// Readiness: tells the load balancer whether to send us traffic
app.get('/healthz/ready', (req, res) => {
  res.status(shuttingDown ? 503 : 200).send(shuttingDown ? 'draining' : 'ok');
});

// Liveness: "is the process alive?" Keep this 200 while draining
app.get('/healthz/live', (req, res) => res.send('ok'));

// While draining, ask clients to close keep-alive connections
app.use((req, res, next) => {
  if (shuttingDown) res.set('Connection', 'close');
  next();
});

app.get('/orders/:id', async (req, res, next) => {
  try {
    const { rows } = await pool.query('SELECT * FROM orders WHERE id = $1', [req.params.id]);
    res.json(rows[0] ?? null);
  } catch (err) {
    next(err);
  }
});

const server = http.createServer(app);
server.listen(3000, () => console.log('Listening on :3000'));

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function shutdown(signal) {
  if (shuttingDown) return; // ignore a second Ctrl+C / SIGTERM
  shuttingDown = true;
  console.log(`${signal} received, starting graceful shutdown`);

  // Hard deadline: never wait for SIGKILL
  const forceExit = setTimeout(() => {
    console.error('Graceful shutdown timed out, forcing exit');
    process.exit(1);
  }, 25_000);
  forceExit.unref();

  try {
    // 1. Give the load balancer time to see readiness = 503
    await sleep(5_000);

    // 2. Stop accepting connections and wait for in-flight requests
    await new Promise((resolve, reject) => {
      server.close((err) => (err ? reject(err) : resolve()));
      server.closeIdleConnections();
    });

    // 3. Close downstream resources
    await pool.end();

    console.log('Shutdown complete');
    process.exit(0);
  } catch (err) {
    console.error('Error during shutdown', err);
    process.exit(1);
  }
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
Enter fullscreen mode Exit fullscreen mode

What each step is doing

The shuttingDown flag flips the readiness probe to 503. Kubernetes (or your AWS/GCP load balancer health check) stops routing new requests to this instance, while requests already in flight carry on.

The 5-second sleep covers the race between SIGTERM and endpoint removal. During those seconds the server is still fully working, so any late requests succeed. Tune it to your load balancer: a couple of health-check intervals is a sensible starting point.

Connection: close makes every response during draining tell the client to drop the socket. Combined with server.closeIdleConnections() (Node 18.2+), keep-alive connections no longer hold the shutdown hostage.

pool.end() waits for checked-out database clients to be released and then closes the pool cleanly, so PostgreSQL doesn't log a pile of "unexpected EOF" errors.

The force-exit timer is your safety net. .unref() means the timer itself won't keep the process alive. Keep this deadline shorter than the orchestrator's grace period so you exit on your own terms.

Don't forget background workers

APIs aren't the only thing that gets interrupted. If you run queue consumers, close them in the same shutdown function so the current job finishes and no new job is picked up. With BullMQ, for example:

const { Worker } = require('bullmq');

const worker = new Worker('emails', async (job) => sendEmail(job.data), { connection });

// inside shutdown(), before closing Redis/DB:
await worker.close(); // waits for active jobs to finish, takes no new ones
Enter fullscreen mode Exit fullscreen mode

The same idea applies to cron-style timers (clearInterval), WebSocket servers (send a close frame, then close), and Kafka/RabbitMQ consumers (stop consuming, commit offsets or ack, then disconnect).

Order matters: stop intake first, finish work, then close shared resources (database, Redis, message broker). Closing the database before the in-flight requests finish just turns graceful shutdown into a different kind of crash.

The Docker gotcha: your process may never receive SIGTERM

This one trips up a lot of teams. If your Dockerfile looks like this:

CMD npm start
Enter fullscreen mode Exit fullscreen mode

that's the shell form, which runs your app under /bin/sh -c. The shell becomes PID 1, and it doesn't forward SIGTERM to Node. Your handler never runs, Docker waits out the grace period, then SIGKILLs everything.

Use the exec form and run Node directly:

CMD ["node", "server.js"]
Enter fullscreen mode Exit fullscreen mode

There's a second subtlety: a process running as PID 1 doesn't get the kernel's default signal behaviour. Without a handler, Node as PID 1 will simply ignore SIGTERM. Our handler above covers that, but adding a tiny init process is still a good idea because it also reaps zombie child processes:

docker run --init my-api
Enter fullscreen mode Exit fullscreen mode

Or in Kubernetes/Dockerfile, use tini as the entrypoint.

The Kubernetes side

Two settings to check in your Deployment:

spec:
  template:
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: api
          image: my-api:1.4.2
          readinessProbe:
            httpGet:
              path: /healthz/ready
              port: 3000
            periodSeconds: 2
            failureThreshold: 1
          livenessProbe:
            httpGet:
              path: /healthz/live
              port: 3000
            periodSeconds: 10
Enter fullscreen mode Exit fullscreen mode
  • terminationGracePeriodSeconds must be longer than your app's force-exit deadline (25s < 30s in our example).
  • Keep the liveness probe returning 200 while draining. If liveness fails during shutdown, Kubernetes may restart the container in the middle of a graceful exit.

If you'd rather keep the delay out of your application code, you can use a preStop hook instead of the in-app sleep(5_000). Kubernetes runs the hook before sending SIGTERM, and its duration counts toward the grace period:

lifecycle:
  preStop:
    sleep:
      seconds: 5
Enter fullscreen mode Exit fullscreen mode

The native sleep action is available on recent Kubernetes versions (1.30+ by default). On older clusters, exec: { command: ["sleep", "5"] } does the same job, provided your image actually contains a sleep binary (distroless images don't).

How to test it locally

Don't trust it until you've watched it work under load:

# Terminal 1
node server.js

# Terminal 2: 50 concurrent connections for 20 seconds
npx autocannon -c 50 -d 20 http://localhost:3000/orders/1

# Terminal 3: while autocannon is running
kill -TERM $(pgrep -f "node server.js")
Enter fullscreen mode Exit fullscreen mode

Without graceful shutdown you'll see errors and resets in the autocannon summary. With it, the in-flight requests complete, new connections start failing only after the server has actually stopped listening, and the logs show a clean Shutdown complete.

In a real cluster, run a load test while doing kubectl rollout restart deployment/my-api and watch your 5xx rate. It should stay flat.

Graceful shutdown checklist

  • [ ] SIGTERM and SIGINT handlers are registered
  • [ ] Readiness probe returns 503 as soon as shutdown starts; liveness stays 200
  • [ ] Short delay (in-app or preStop) before closing the server
  • [ ] server.close() plus closeIdleConnections() and Connection: close while draining
  • [ ] Queue workers, WebSockets and timers are stopped before shared resources close
  • [ ] Database pools and Redis/broker clients are closed last
  • [ ] A force-exit deadline shorter than the orchestrator's grace period
  • [ ] Dockerfile uses exec form (CMD ["node", "server.js"]), ideally with --init or tini
  • [ ] Tested under load with a real kill -TERM

Wrapping up

Graceful shutdown is one of those things nobody notices when it works, and everybody notices when it doesn't: a spike of failed checkouts every time you deploy, half-processed jobs, mysterious connection errors in the database logs. Forty lines of code and a couple of probe settings make deployments boring again, which is exactly what you want.

At Prism Infoways, we build and run web apps, APIs and cloud infrastructure for growing businesses, and zero-downtime deploys are part of every production setup we ship as part of our API development services. If your releases still come with a side of 502s, we're happy to help.

How do you handle shutdown in your Node.js services? Share your setup or war stories in the comments.

Top comments (0)