A rolling deployment can look healthy in Kubernetes while clients receive connection resets and consumers repeat work. The problem is often not the rollout strategy but the application shutdown contract. A process must stop accepting new work, finish or safely abandon existing work, and exit before the orchestrator runs out of patience.

1. Understand the termination budget

Kubernetes starts the termination grace period before running a preStop hook. The container normally receives SIGTERM after that hook, and remaining processes can be forcibly killed when the grace period expires. Endpoint updates and container termination happen concurrently, so readiness alone is not an instantaneous traffic barrier.

For example, with a 45-second grace period, reserve five seconds for a measured routing propagation delay and five seconds for uncertainty. Give the application at most 35 seconds, including database cleanup. These are illustrative budgets, not universal defaults. Measure them with your actual ingress and clients.

2. Make shutdown a one-way state transition

Keep liveness independent from readiness. During shutdown, readiness should fail while liveness remains healthy. Reject new business requests with a retryable 503 where appropriate, but allow admitted requests to finish. Avoid starting a second shutdown sequence if another signal arrives.

import { createServer } from 'node:http';
let draining = false;
const server = createServer(async (req, res) => {
  if (req.url === '/live') {
    res.end('ok'); return;
  }
  if (req.url === '/ready') {
    res.statusCode = draining ? 503 : 200;
    res.end(); return;
  }
  if (draining) {
    res.writeHead(503, { Connection: 'close' });
    res.end('draining'); return;
  }
  // Await application work and handle errors here.
  res.end('ok');
});
server.listen(8080);

Use a real admission gate in the application middleware, not just the health endpoint. If the ingress retries a POST after a reset, the operation may already have committed. Protect mutation endpoints with idempotency keys.

3. Drain HTTP before closing shared dependencies

On modern Node.js releases, server.close stops accepting connections and closes idle HTTP connections. Active requests may still use the database or Redis. Closing those clients first turns an otherwise clean deployment into a cascade of application errors. Upgraded connections such as WebSockets require separate tracking and shutdown.

async function shutdown() {
  if (draining) return;
  draining = true;
  const deadline = setTimeout(() => {
    console.error('shutdown deadline exceeded');
    server.closeAllConnections();
    process.exit(1);
  }, 35_000);
  try {
    await new Promise<void>((resolve, reject) => {
      server.close(err => err ? reject(err) : resolve());
    });
    // Await consumer shutdown and pool.end() here.
    clearTimeout(deadline);
    process.exitCode = 0;
  } catch (err) {
    console.error('shutdown failed', err);
    process.exit(1);
  }
}
process.once('SIGTERM', () => void shutdown());
process.once('SIGINT', () => void shutdown());

This is a minimal HTTP example, not a complete service framework. Keep the deadline referenced until all owned resources have closed; track background jobs and upgraded sockets separately. In a combined HTTP and worker service, initiate both admission stops immediately, then await both drains before closing shared dependencies.

4. Stop Kafka work without losing offsets

Stop fetching or admitting new records using the consumer library's supported lifecycle. Wait for already admitted handlers within the same shutdown budget. Commit offsets only after durable side effects complete, and never advance a partition past an unfinished earlier record. If time expires, leave unfinished records eligible for replay. Consumer group rebalances can happen during shutdown, so handle commit failures and make effects idempotent rather than assuming the final commit always succeeds.

Shutdown is a correctness boundaryA forced exit may interrupt a request after its database commit but before its response. A replay-safe operation is more valuable than a promise that every connection will survive a deployment.

5. Configure Kubernetes around measured behavior

spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: api
      readinessProbe:
        httpGet:
          path: /ready
          port: 8080
      livenessProbe:
        httpGet:
          path: /live
          port: 8080

This is a pod-spec fragment. A preStop delay may help when load balancer propagation is slow, but consumes the same grace period. Do not add arbitrary sleeps without measuring endpoint removal and request arrival. Ensure the container entrypoint forwards signals, preferably by running Node directly using an exec-form command. Use rolling update settings and sufficient spare capacity so draining one replica does not overload the others.

6. Prove the rollout under load

  1. Generate sustained traffic including slow requests and keep-alive connections.
  2. Roll out a new image while recording request IDs, response codes and latency.
  3. Compare admitted and completed requests for each terminating pod.
  4. Interrupt a Kafka handler before and after its durable side effect; verify replay safety.
  5. Simulate a stalled database query and confirm the process exits within the deadline.
  6. Repeat with WebSockets or streaming responses if the service supports them.

Track shutdown duration, active requests at signal receipt, forced exits, consumer replay rates, and deployment-window error rates. Compare against the normal traffic baseline rather than celebrating a green deployment status. A service that exits cleanly under idle conditions has not yet demonstrated graceful shutdown under production load.

Further reading

Related articles