Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 12

Zero-Downtime Deploys Promised, 150 Errors per Deploy Delivered: The Missing Half of Graceful Shutdown

The API runs as two replicas, deploys replace them one at a time, and the proxy probes each replica's /ready every 2 seconds. Even so, ~150 requests fail with 502 on every deploy. We look step by step at what the code's 'graceful' shutdown skips, how a load balancer finds out that a replica is gone, and the recipe for zero errors in a rolling deploy (announce, drain, close).

29 min read75 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 12 · Difficulty ★★☆ · Reading ~20 min · Lab ~45–75 min

In April 2022, the on-call engineer on GitLab’s SRE team was woken by the same alert every day: GitLab Pages was burning through its error budget (GitLab’s write-up). The errors were brief and went away on their own, but they reached users as 502s. The pattern was clear: on every deploy, every scale-down, every pod termination. The investigation followed a few false trails. The readiness probe took ~30 seconds to take a pod out of service (a 10-second interval × 3 failures); shortening the interval stopped the daily alert but didn’t end the errors. The real cause: the process inside the container never heard SIGTERM, because PID 1 was a shell that didn’t forward the signal. The process kept accepting requests on a terminating pod and was killed when the grace period ran out.

A few seconds of errors on every deploy is the kind of thing people shrug off. An alert that looks at averages doesn’t see it; even if it did, it clears by itself. But for a team that deploys ten times a day, it means hundreds of customers seeing a “Something went wrong” screen every day.

In this part we live through the Node.js member of the same family. Our process does hear SIGTERM; the code has had a “graceful shutdown” since the first version. The problem is that it does it too fast and without telling anyone.

In Part 11 we closed out Monday’s checkout outage. The next day the platform team made deploys safe: two replicas, rolling deploys, a readiness check. The promise was zero downtime. This part is about why that promise wasn’t kept.

What you’ll learn

  • How a load balancer finds out that a replica is gone (and how late it finds out)
  • Readiness vs. liveness; /ready meaning “you may send me requests”
  • The two halves of “graceful shutdown”: finishing in-flight requests, and giving the load balancer time to stop sending new ones
  • Finding short error bursts: deploy annotations, short-window counters, a log + trace timeline
  • How server.close() behaves with keep-alive connections, and closeIdleConnections()
  • The fix: announce → drain → close; the timings (check interval < drain < grace period)
  • The exact Kubernetes equivalent: preStop, readiness and terminationGracePeriodSeconds

Prerequisites

You can read this article without running the lab. These help:

TopicWhySource
Pod termination sequenceSIGTERM, grace period, SIGKILL; removal from endpoints when readiness failsKubernetes, Pod Lifecycle
docker stopSIGTERM, then SIGKILL at the end of the grace period (10 s by default on Linux)docker container stop
server.close() and keep-aliveWhat happens to connections when Node’s HTTP server closesNode.js, HTTP
Health checks in a load balancerThe proxy in the lab is Traefik; unhealthy servers are taken out of rotationTraefik, load balancing service
The app’s retries, idempotent checkoutBackground to the incident: why checkouts mostly survivePart 10 · Part 11

1. Concept: the load balancer only finds out when it asks

In a rolling deploy, each replica goes through this in turn:

  1. The orchestrator (Docker, Kubernetes, ECS…) sends the process SIGTERM: “I’d like you to shut down”.
  2. If the process hasn’t exited within a set time (the grace period; 10 s in Docker), SIGKILL follows.
  3. The new version starts and begins taking traffic once it passes the health check.

What does the load balancer know during all this? Usually nothing. The process receives SIGTERM; the load balancer doesn’t. The load balancer learns a replica’s state either from a periodic health check (in the lab, Traefik does GET /ready every 2 seconds) or from someone explicitly telling it “remove this replica” (an endpoint update in Kubernetes, target deregistration in AWS). Both happen after SIGTERM, and asynchronously.

time ──────────────────────────────────────────────────────────────►
api-1:  [serving        ][SIGTERM → server.close(): no new connections ··········]
proxy:  ✓ /ready      ✓ /ready  ... sends half to api-1 ...   ✗ /ready → out of rotation
request:                       ✗502 ✗502 ✗502 ✗502 ✗502 ✗502
                               └────────── up to one check interval ──────────┘

If the process shuts the door as soon as it gets SIGTERM, every request the proxy sends until its next check hits a closed door. The code is “graceful” because it finishes the requests already inside. But it doesn’t think about the ones waiting at the door.

The right order has three steps:

  1. Announce: when SIGTERM arrives, /ready starts returning 503. The proxy takes the replica out of rotation at its next check.
  2. Drain: keep serving normally for longer than the check interval. Every request that arrives in this time still gets an answer.
  3. Close: nobody is sending new requests any more. Stop listening, finish in-flight requests, close the database pool, exit. All within the grace period.

See for yourself: a 50-line experiment

Two “replicas”, a small proxy that probes /ready every 2 seconds, and ~100 requests per second. At 2.1 s we send replica 1 a “SIGTERM”; in naive mode it shuts down immediately, in drain mode it announces first and drains for 3 seconds.

// deploy-race.mjs: two replicas, a proxy probing /ready every 2 s, 100 requests per second.
// node deploy-race.mjs naive   |   node deploy-race.mjs drain
import http from 'node:http';

const MODE = process.argv[2] ?? 'naive';
const agent = new http.Agent({ keepAlive: false }); // a new connection for every request

function backend(port) {
  let draining = false;
  const server = http.createServer((req, res) => {
    if (req.url === '/ready') return res.writeHead(draining ? 503 : 200).end();
    if (draining) res.setHeader('Connection', 'close');
    setTimeout(() => res.end('ok'), 5); // 5 ms of "work"
  }).listen(port);
  return {
    port, healthy: true,
    sigterm() {
      if (MODE === 'naive') return server.close();            // close immediately
      draining = true;                                          // 1. announce
      setTimeout(() => { server.close(); server.closeIdleConnections(); }, 3000); // 2. drain, 3. close
    },
  };
}

const backends = [backend(4001), backend(4002)];
const get = (port, path) => new Promise((resolve) => {
  http.get({ port, path, agent }, (res) => { res.resume(); res.on('end', () => resolve(res.statusCode)); })
    .on('error', (err) => resolve(err.code));
});

// Proxy: health check every 2 s; spreads requests round-robin over healthy replicas.
setInterval(async () => {
  for (const b of backends) b.healthy = (await get(b.port, '/ready')) === 200;
}, 2000);

let next = 0;
const counts = {};
const t0 = Date.now();
const load = setInterval(async () => {
  const pool = backends.filter((b) => b.healthy);
  const b = pool[next++ % pool.length];
  const status = await get(b.port, '/');
  const key = status === 200 ? '200' : `502 (${status})`;
  counts[key] = (counts[key] ?? 0) + 1;
}, 10); // ~100 requests/s

setTimeout(() => { console.log(`t=${Date.now() - t0} ms: SIGTERM to replica 1`); backends[0].sigterm(); }, 2100);
setTimeout(() => { clearInterval(load); console.log(MODE, counts); process.exit(0); }, 8000);
node deploy-race.mjs naive
node deploy-race.mjs drain

On my machine (Node.js 22.18), all four repetitions gave the same result:

t=2101 ms: SIGTERM to replica 1
naive { '200': 661, '502 (ECONNREFUSED)': 86 }
t=2101 ms: SIGTERM to replica 1
drain { '200': 753 }
  • naive: 86 requests refused. SIGTERM at 2.1 s, the next check at 4.0 s: for ~1.9 seconds, half the requests (~47/s) went to a closed door. 1.9 × 47 ≈ 89.
  • drain: zero. Replica 1 effectively shut down at the same moment, but first it said “I’m leaving” via /ready and kept answering until the proxy took it out of rotation.

Both runs have the same code, the same shutdown time and the same proxy. The only thing that changes is the order.

Note: in the demo the proxy opens a new connection for every request (keepAlive: false), because I wanted to show the “new connection refused” case cleanly. Real proxies reuse connections; we’ll see in the lab how that muddies things even further.


2. The incident: Wednesday, the tenth deploy of the day

🔁 [RECURRING] Every deploy: about a hundred requests fail with 502 at the edge

After Monday’s outage, the platform team made deploys safe:

  • The API now runs as two replicas: api-1 and api-2, behind the edge proxy (Traefik).
  • Deploys replace the replicas one at a time: api-2 serves while api-1 restarts, then the other way round.
  • The proxy probes each replica’s GET /ready every 2 seconds and only sends requests to those that pass.

The promise was zero downtime. But each of the ~10 deploys a day brings a burst of 502s across all endpoints. The mobile app shows “Something went wrong”; checkouts mostly survive because the app retries (and since Part 10, retries are safe).

The API’s shutdown code has been “graceful” since the first version. Recent changes have nothing to do with this area:

VersionWhenChange
2.25.1yesterdayAt most one retry for TaxRate quotes, within a retry budget (the fix from Part 11)
2.25.05 days agoRetry TaxRate quotes

Rules: you can’t change the proxy, the 2-second check interval or Docker’s 10-second grace period. The fix goes in app/src.

If you have set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 012

💡 Want to try it yourself first? Stop here. With traffic running, run ./lab deploy, watch ./lab logs in a second terminal, open Grafana (http://localhost:3000) and investigate on your own for 30 minutes. The results of the steps below are in collapsed boxes; open them when you get stuck. For the lab’s own hints: ./lab hint 012.


3. Investigation, step by step

This incident has one nice property: you can reproduce it whenever you like. ./lab deploy performs a rolling deploy even with unchanged code. I ran it twice, 3 minutes apart.

Step 1: When do the errors happen?

Look at the Requests per second by status graph on the dashboard. The orange dashed lines are deploy annotations.

What do we see?

Traffic is ~66 requests/s. There are no 502s outside the deploys; every deploy brings a red slice. I counted with the counter in Prometheus: 158 requests came back as 502 in the first deploy and 140 in the second. Plus another 53 at 04:11, when I restarted only api-1 by hand.

Grafana: edge requests per second by status; red 502 slices just to the left of the two deploy lines at 04:06 and 04:09 and at 04:11, none in between

The red slices appear only at deploys (the orange lines are drawn when the deploy finishes, so the errors sit just to the left of the line). The dip at 04:11 without a line is when I restarted a single replica by hand.

The rate in this Grafana panel is smoothed over a one-minute window: a burst lasting a few seconds looks like 5 errors per second. With a short window the picture sharpens:

Grafana Explore: 502 per second (green) and 2xx (yellow) with a 10-second window; between 04:05:45–04:06:00 and 04:08:35–04:08:55 502 rises to 5–10 per second, zero in between

Green line is 502, yellow line is 2xx (10-second window). Deploy 1 sent api-1 SIGTERM at 04:05:40, deploy 2 at 04:08:31. Every deploy has two clusters: one per replica.

These two observations tell us:

  • The errors don’t come from a code path: they hit every endpoint (products, categories, orders, account).
  • Load, the database and dependencies are normal. The errors are produced by the deploy itself.

Lesson: Short bursts disappear in averages. Without deploy annotations and short-window counters, this incident gets brushed off as “the odd error”.

Step 2: Who produces the 502, and on the way to whom?

A 502 is the proxy saying “I couldn’t get a response from the server behind me”. Is there any trace of these requests in the API’s logs? In Jaeger, select the traefik service and open traces that returned 502.

What do we see?

There is no trace of these requests on the API side: not a span, not a log line. The API never processed them. The Jaeger traces contain only the proxy’s two spans. The target is visible in the attributes of the ReverseProxy span:

Jaeger: traefik GET trace, 502; the ReverseProxy span lasts 196 microseconds and network.peer.address = api-1

The proxy sent the request to api-1 and got a 502 in 196 microseconds. An error that fast means the connection was never established: the door is closed.

Look at the time: 04:05:43, i.e. 3 seconds after api-1 was sent SIGTERM. Every 502 trace in this deploy targets the replica that is being stopped at that moment: first api-1, then api-2.

Red herring: “The new replica takes traffic before it’s ready.” The proxy doesn’t send requests to the new replica until its /ready passes, and the errors are on requests going to the old replica. The bursts start before the new replica even exists.

Step 3: Build the timeline

You have three clocks: the API’s logs (./lab logs), the proxy’s logs (Traefik’s health check warnings via docker logs) and the traces. Put them all on the same time axis.

The second deploy, second by second

Timeline: 04:08:31.739 api-1 SIGTERM; 502s to api-1 between 31.880 and 34.280; 34.763 Traefik's check of api-1 fails with connection refused; a few more 502s between 36.786 and 37.779; 37.837 new api-1 listening; 43.280 api-2 SIGTERM; 502s to api-2 between 50.949 and 51.990; ~51.3 old api-2 exit code 1; 52.340 new api-2 listening

Yellow rows are the replicas’ lifecycle, the blue row is the proxy’s health check, red rows are the proxy’s 502 spans (traces are sampled at 20%, so roughly one fifth of the real errors). Two replicas, two different failures.

api-1: the door closes immediately, the proxy notices 3 seconds later.

  • 04:08:31.739: shutting down. The code calls server.close(): the listening socket closes, new connections are refused.
  • First 502 141 ms later. For the next 3 seconds the proxy keeps sending half the requests to api-1; each one gets connection refused.
  • 04:08:34.763: the proxy’s /ready check fails. Only now does api-1 leave the rotation.
  • While the container is being replaced (until the old process exits and the new one starts listening) there’s another small cluster lasting about a second.

api-2: the door closes but the proxy never notices, then the process is killed.

  • 04:08:43.280: shutting down. One 502 in the sampled traces and then 7 seconds of silence. Traefik’s log has no failed check at all for api-2 (Traefik logs every failed check; we’ll see each one in the deploy after the fix).
  • Why? The proxy reuses its open keep-alive connections to api-2. server.close() refuses new connections and closes those that are idle at that moment, but connections that are busy at that moment stay open, and later requests arriving over them keep getting answers. That’s the explanation consistent with what we see: as long as requests and health checks go over those connections, api-2 is healthy as far as the proxy is concerned.
  • That’s why the server.close() callback is never called: the server doesn’t count as “closed” until the connections close. The code knows this and has a safety timer: process.exit(1) at 8 seconds.
  • ~04:08:51.3: the old api-2 “exited with code 1”. The connections the proxy is holding snap all at once: a cluster of 502s until the new replica starts listening at 52.340.

Two faces of the same bug: the process doesn’t tell the proxy it’s about to shut down. Either the proxy finds out one check interval late (api-1), or, because of keep-alive, it never finds out and runs into the process’s death instead (api-2).

Which of the two happens depends on how many connections to the replica are busy at the moment of SIGTERM. That’s why the error count varies from deploy to deploy and why the process sometimes exits with 0 and sometimes with 1: of four shutdowns without the fix, three finished on their own and one was left to the safety timer.

You can also watch directly what a replica does after SIGTERM. From inside api-2 I probed api-1:3000/ready every 50 ms and restarted api-1: 24 ms after SIGTERM new connections got ECONNREFUSED, the process was gone after 8.1 s (safety timer), and the new process answered ~0.8 s later.

Lesson: You won’t solve this incident without putting a replica’s lifecycle (SIGTERM, last request, exit) on the same axis as what the proxy sees. The errors are neither in the API’s logs nor in its metrics; they’re only in between.

Step 4: Finally, the code

// server.ts, since the first version
let shuttingDown = false;

function shutdown(signal: NodeJS.Signals): void {
  if (shuttingDown) return;
  shuttingDown = true;
  logger.info({ signal }, 'shutting down');

  // Docker sends SIGKILL after 10s; leave in a controlled way before that.
  setTimeout(() => process.exit(1), 8_000).unref();

  server.close(() => {
    metricsServer.close();
    pool.end().finally(() => process.exit(0));
  });
}

process.on('SIGTERM', shutdown);
// platform/health.routes.ts
/** Readiness: dependencies are reachable. */
healthRouter.get('/ready', async (_req, res) => {
  await pool.query('SELECT 1');
  res.json({ status: 'ready' });
});

Nothing in the code looks wrong; most “graceful shutdown” examples look exactly like this. It doesn’t cut requests off midway, it closes the pool after the server, and it exits in a controlled way before SIGKILL. What’s missing:

  1. /ready returns 200 until the server has closed. The proxy is told nothing in advance.
  2. server.close() is called in the first millisecond after SIGTERM: zero time for the proxy to react.
  3. Keep-alive connections aren’t closed (keepAliveTimeout is 95 s), so close() often never completes and the process is killed at 8 seconds.
The lab’s diagnosis questions and answers (./lab submit 012)
QuestionAnswer
When exactly do the 502s happen?Between the moment an instance is told to stop and the moment the proxy stops sending it requests
What does a replica get wrong when it receives SIGTERM?It stops accepting connections at once, while its /ready still passes and the proxy still sends it requests
How long should a replica keep serving after SIGTERM?Longer than the proxy’s readiness check interval, with /ready failing meanwhile

4. Mitigation

The fix needs a code change and a deploy; and the deploy itself is part of the problem. In the meantime:

  • Pause deploys, or batch them into quiet hours. It doesn’t remove the errors; it moves them to a time when fewer people will see them. As in the postmortem: no deploys except the fix.
  • Retries at the proxy for idempotent requests (GET). Hides most of the burst from browsing customers. Useless for POST: the proxy can’t know whether it’s safe to resend an order whose outcome is unknown.
  • Don’t: add more replicas. With ten replicas, each deploy means ten small bursts; the total stays the same.

Be aware that the deploy carrying the fix will have errors too: the processes shutting down in that deploy are still running the old code. In my measurement, the deploy carrying the fix (04:17) still produced 140 errors; the first deploy made with the fix (04:20) produced zero.

5. The fix: announce, drain, close

We split the shutdown into two phases. First, a small module that holds the state:

// platform/lifecycle.ts (new)
import type { RequestHandler } from 'express';

let draining = false;

/** Shutting down: the instance still answers, but asks not to get new requests. */
export const isDraining = () => draining;

export function startDraining(): void {
  draining = true;
}

/**
 * While draining, every response closes its connection: the proxy then opens a
 * new one for its next request, to an instance that isn't going away, instead of
 * reusing a connection this instance is about to close.
 */
export const closeConnectionsWhileDraining: RequestHandler = (_req, res, next) => {
  if (draining) res.set('Connection', 'close');
  next();
};

1. Announce: /ready returns 503 as soon as draining starts.

// platform/health.routes.ts
/** Readiness: the proxy may send requests here. Not while shutting down. */
healthRouter.get('/ready', async (_req, res) => {
  if (isDraining()) {
    res.status(503).json({ status: 'draining' });
    return;
  }
  await pool.query('SELECT 1');
  res.json({ status: 'ready' });
});

In app.ts, app.use(closeConnectionsWhileDraining) is added at the very top. Connection: close solves the problem we saw with api-2: the proxy won’t reuse its open keep-alive connections to a replica that’s about to shut down; it opens a new connection for its next request, and that connection goes to the replica whose /ready passes.

2. Drain, 3. close:

// server.ts
// The proxy checks each instance's /ready every 2 s. Keep serving for longer than
// that after SIGTERM, so it has stopped sending requests here before we stop
// accepting them.
const DRAIN_MS = 5_000;

let shuttingDown = false;

function shutdown(signal: NodeJS.Signals): void {
  if (shuttingDown) return;
  shuttingDown = true;
  // 1. /ready answers 503, and responses close their connections.
  startDraining();
  logger.info({ signal, drainMs: DRAIN_MS }, 'shutting down: draining');

  // Docker sends SIGKILL after 10s; leave in a controlled way before that.
  setTimeout(() => process.exit(1), 9_000).unref();

  // 2. Once the proxy has moved on: stop accepting connections, let the requests
  // in flight finish, then close the database pool and exit.
  setTimeout(() => {
    logger.info('shutting down: closing');
    server.close(() => {
      metricsServer.close();
      pool.end().finally(() => process.exit(0));
    });
    server.closeIdleConnections();
  }, DRAIN_MS).unref();
}

The timings depend on each other; write them down side by side:

DurationValueRule
Proxy check interval2 sThe longest it takes the proxy to learn the replica is leaving
Drain5 s> check interval (plus the duration of a check itself, and some margin)
Safety timer9 s> drain + slowest request; < grace period
Docker grace period10 sExceed it and you get SIGKILL

Why closeIdleConnections() after close()? The Node documentation recommends exactly that: stop new connections first, then close the idle ones; in the opposite order a new connection can slip in between (Node.js HTTP, server.closeIdleConnections()).

And why wait 5 seconds instead of killing the process right away? Because during those 5 seconds the replica is serving at full capacity; it’s only telling the proxy “don’t give me new work”. Nobody waits, no request is lost.

6. Verification

./lab deploy
./lab verify 012

verify runs the standard traffic (~66 requests/s) for 60 seconds; at second 15 it restarts api-1 and, once that’s healthy, api-2 (like a deploy), and counts the results from the client side:

MeasurementTargetBeforeAfter
Server errors (5xx) during the rolling restart= 01280
CPU0.29 cores0.32 cores
Event loop delay (max)147 ms159 ms
Waiting in pool (max)00

3,980 requests in 60 seconds; all 28 functional checks passed (the API’s responses didn’t change). The runtime numbers are almost identical: this fix isn’t about performance, it’s about the order of the shutdown. Unlike in earlier parts, CPU, event loop and pool tell you nothing here; the only signal is the 5xx count at the edge.

The graphs say the same. The orange dashed lines are deploys; the last two are the deploy carrying the fix (04:17) and the first deploy made with the fix (04:20):

Before and after the fix: edge requests per second by status; red 502 slices at 04:06, 04:09, 04:11 and 04:17, no red at all at the 04:20 deploy line

The 04:17 deploy carried the fix, but the processes shutting down were old code: the same red slice. In the 04:20 deploy the processes shutting down are now the fixed code: no red.

Grafana Explore, 04:16:30–04:21:30: 502/s (green) rises to 10 at 04:17 and stays flat at zero throughout the 04:20 deploy

Green line is 502, yellow line is 2xx. The deploy starting at 04:17:02 shows 502s for the last time; in the deploy starting at 04:19:59 the green line never leaves zero, and the yellow line doesn’t even dip.

And the same timeline, with the fix:

Timeline, with the fix: api-1 SIGTERM at 04:20:00.218, 500 ms later Traefik's check fails with 503, closing and exit code 0 at 05.217, new process at 06.170; the same for api-2; no 502 spans in this interval

500 ms after SIGTERM, the proxy takes the replica out of rotation (/ready → 503). The replica keeps answering for 5 more seconds, then exits cleanly (exit code 0, no need for the safety timer). Not a single 502 trace in this interval.

A side benefit: in the old code, shutdown either never completed (forced exit at 8 s) or was down to luck. In the new one, every replica exits with exit code 0 ~5 s after SIGTERM and the new replica is listening within ~1 s. Deploys are both error-free and predictable.


7. Fixes that look right but aren’t

AttemptWhy it falls short
Failing /ready and closing immediatelyThe proxy reads /ready every 2 s; until then, the same refused connections. Announcing is useless without waiting.
A drain shorter than the check interval (e.g. 1 s)Errors on some deploys, none on others: it depends on where SIGTERM lands relative to the check. Its sneakiest form: it passes in testing.
Ignoring SIGTERM/ready keeps passing; Docker sends SIGKILL after 10 s: in-flight requests are cut off, then requests are refused until the next check.
process.exit() on SIGTERMIn-flight requests are cut off too.
More replicasEvery replica opens the same window as it shuts down; total errors stay the same, just split into smaller pieces.
“Let the proxy retry”A good safety net for a refused GET; not for a POST whose outcome is unknown. No substitute for a clean shutdown.
Shortening keepAliveTimeoutBrings back the risk of Node closing a connection the proxy is about to reuse (the reason it’s 95 s in the code is the proxy’s 90 s idle timeout). The problem isn’t the connection’s lifetime, it’s the replica not telling anyone it’s leaving.

8. In production: alternatives and prevention

The same race in Kubernetes. When a pod is deleted, Kubernetes starts two things at the same time: the kubelet sends the container SIGTERM (running the preStop hook first, if there is one), and the control plane removes the pod from the Service’s endpoints. The second takes time to propagate to kube-proxy, the ingress controller and the cloud load balancer, and there’s no guarantee about how long (LearnKube, Graceful shutdown in Kubernetes). The practical recipe is the same three steps:

spec:
  terminationGracePeriodSeconds: 30     # > preStop + drain + slowest request
  containers:
    - name: api
      readinessProbe:
        httpGet: { path: /ready, port: 3000 }
        periodSeconds: 2
      lifecycle:
        preStop:
          exec:
            command: ["sleep", "10"]   # time for propagation; SIGTERM comes AFTER this

A preStop sleep and the application’s own drain do the same job; pick one, or fit their sum into the grace period. (The lesson from the GitLab case belongs here too: make sure SIGTERM actually reaches your process. If CMD is in shell form, PID 1 is a shell and may not forward the signal.)

In cloud load balancers the same idea is called deregistration delay or connection draining. An AWS ALB stops sending new requests to a deregistering target and waits, 300 seconds by default, for in-flight ones; if the target closes the connection before that, the client gets a 5xx (AWS, Deregistration delay). If your deploy tool deregisters the target first and only then stops the process, the drain on the application side can be kept short.

Measure errors per deploy, not the average. An error-rate alert looking at a 2-minute average won’t see a 3-second burst. Put the 5xx count in the deploy window next to your deploy annotations:

- alert: ErrorsDuringDeploy
  # Any 5xx at the edge in the last minute; read alongside deploys
  expr: sum(increase(traefik_entrypoint_requests_total{entrypoint="web",code=~"5.."}[1m])) > 0
  labels:
    severity: ticket
  annotations:
    summary: "{{ $value }} 5xx at the edge (last 1 min). Was there a deploy?"

Better still: have the deploy pipeline post the 5xx count for the deploy window to the deploy channel when it finishes. A team that reads “this deploy dropped 140 requests” every day spots the problem in two hours, not two days.

Checklist:

  • Is failing readiness the first thing you do on SIGTERM?
  • Is the drain longer than the time it takes the load balancer to take you out of rotation (check interval × required failures + propagation)?
  • Is grace period > drain + slowest request? Is there a separate plan for long-lived connections (WebSocket, streaming)?
  • Are keep-alive connections closed during the drain (Connection: close, closeIdleConnections())?
  • Is the process really PID 1, or is there an init that forwards signals (e.g. tini)?
  • Deploy test under load: a deploy made while a load test is running should produce zero errors. The lab’s verify is exactly that test.

Key takeaways

  • “Graceful shutdown” has two halves: finishing the requests already inside and waiting for the load balancer to stop sending new ones. Most code only does the first.
  • A load balancer learns that a replica is leaving not from SIGTERM but from a health check (or an explicit deregistration), and it learns late.
  • The recipe: announce (/ready → 503) → drain for longer than the check interval → close (stop listening, finish in-flight requests, close the pool, exit).
  • Write the timings down side by side: check interval < drain < drain + slowest request < grace period.
  • Keep-alive connections can mean the proxy never notices a replica leaving. Connection: close while draining.
  • Short bursts disappear in averages; measure errors per deploy.
  • The deploy carrying the fix still shuts down with the old shutdown code: expect one last burst.

Test yourself

1. If we went from 2 replicas to 10, what would happen to the errors per deploy?

They’d stay roughly the same. As it shuts down, each replica refuses its share of the traffic (1/10) for one check interval; ten replicas do it ten times. The bursts get smaller but there are more of them; the total is similar. The problem isn’t capacity, it’s the order of the shutdown.

2. What happens if we cut the drain to 1 second? Why might it go unnoticed in a test environment?

Because the check interval is 2 s, if SIGTERM arrives more than 1 s after the last check, the next check comes within the drain, the proxy takes the replica out before it closes and there are no errors; if it arrives less than 1 s after the last check, the proxy is still sending requests when the replica closes. Errors become a matter of probability: some deploys are clean, some aren’t. A test of a handful of deploys can easily miss it.

3. In the old code, some replicas exited with code 0 and some with 1. Why?

The server.close() callback is only called once every connection has closed. Connections that are idle at the moment of SIGTERM are closed immediately; busy ones stay open and the proxy keeps reusing them (keep-alive). If they all close in time, the process exits with 0; if not, the safety timer at 8 seconds calls process.exit(1) and the open connections snap.

4. In Kubernetes, is failing the readiness probe on SIGTERM enough on its own?

No; the process also has to keep serving for a while. Removal from endpoints starts anyway when the pod is deleted, but its propagation to kube-proxy and the ingress is asynchronous. The application has to cover that time, either by waiting in preStop or with its own drain; and terminationGracePeriodSeconds has to cover the wait + the slowest request.

Further reading

Basics

Deep dives

Real-world incidents


Next up: Intermittent 503s. This part’s fix is live: /ready now returns 503 during shutdown. The next day another release goes out and teaches /ready to check every dependency. A few times an hour, every page of the site returns 503 for about ten seconds, then recovers on its own; the API logs no errors and no replica restarts. We’ll look at what should and shouldn’t go into a readiness check.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 012 to generate the postmortem template and compare it with your own write-up.