Reliability · Backend

502 Bad Gateway After Every Deploy: Causes and Fixes

The deploy works, and for a few seconds users still see an error. Two different bugs cause it, and each has a small fix.

You ship at 2 pm. The rollout goes green and the new version works. But the error graph has a small spike at the minute of the deploy: a few dozen 502 Bad Gateway responses, then nothing. The next deploy does the same.

Most of those requests are GETs that a browser retries without anyone noticing. Some are not. A POST /payments that got a 502 may have run on the old server, or may not. You cannot tell from the response.

Two different bugs make this spike. They look the same on a graph and need different fixes. This post tells them apart and fixes both. The examples use Node, Kubernetes, an AWS Application Load Balancer (ALB) and nginx. The rules are the same for any proxy and any app.

Short version:

  • The proxy writes a 502, not your app. It means the proxy sent a request and got no usable reply. Read the proxy’s log, not the app’s.
  • If the 502s appear only while a deploy runs, the old process died while the proxy was still sending it traffic. Wait for the proxy to stop sending, then finish the requests in flight on SIGTERM. On Kubernetes, add a preStop sleep.
  • If you also see them at quiet times, the proxy reused a keep-alive connection that the app had already closed. The app’s idle timeout must be longer than the proxy’s. Node’s default is 5 seconds. An ALB’s is 60.

What a 502 means

RFC 9110 defines 502 as the answer a gateway or proxy gives when it got an invalid response from the server behind it. In practice: nginx, an ingress or an ALB forwarded your request, and the app gave back nothing usable. It refused the connection, closed the socket, or reset it.

So your app did not write this error. The proxy did. That is why the app’s own logs look clean and the error is annoying to chase.

A 502 is written by the proxy. The client sends a request to the proxy or load balancer, which forwards it to the app. If the app gives no usable reply, the proxy writes the 502 itself. The proxy log says which: connection refused means nobody is listening, prematurely closed connection means the app closed the socket, connection reset by peer means the app sent a reset, and an ALB access log shows elb_status_code 502 with target_status_code of a dash.

On an ALB, the access log field target_status_code is - when no reply came from the target, as the access log docs say. In CloudWatch, errors the load balancer made itself count in HTTPCode_ELB_5XX_Count and HTTPCode_ELB_502_Count. Errors your app returned count in HTTPCode_Target_5XX_Count. A deploy 502 shows up in the first pair.

An ALB uses three nearby codes for three different problems:

CodeThe ALB sends it when
502the target closed or reset the connection, sent a malformed reply, or “the deregistration delay period elapsed for a request being handled by a target that was deregistered”
503the target group has no registered targets, or all of them are unused
504the target did not reply before the idle timeout, or the connection took longer than 10 seconds to open

These come from the ALB troubleshooting page. Other proxies use the same codes with the same meaning.

Two causes, one error

Two causes of a 502 around deploys. Cause 1, the old pod dies mid-request: the 502s appear only in the deploy window, the proxy log says refused, reset or closed, and the fix is to drain with a preStop sleep and finish requests on SIGTERM. Cause 2, the proxy reuses a dead socket: the 502s are scattered at any hour, even with no deploy, the log says reset or closed on a reused idle connection, and the fix is an app idle timeout longer than the proxy’s.

Look at a quiet hour with no deploy. If the graph has a few 502s there too, you have cause 2. A deploy is just the moment you were watching. You can have both.

Cause 1: the old process dies while the proxy still sends it traffic

When Kubernetes replaces a pod, two things start at the same moment. The kubelet (the agent on the node) runs the container’s preStop hook if there is one, then sends SIGTERM. At the same time, the control plane starts removing the pod from the EndpointSlice objects that proxies read to find pods. The pod termination docs put it this way: “At the same time as the kubelet is starting graceful shutdown of the Pod, the control plane evaluates whether to remove that shutting-down Pod from EndpointSlice objects.”

The removal takes time to reach every proxy. If your app exits the moment it gets SIGTERM, there is a gap in which proxies still send it requests:

A rolling update with no drain. At the start the pod is marked Terminating and gets SIGTERM, while the proxy still has the pod in its list. The app exits at once. The proxy forwards a request to the pod anyway and gets a refused or reset connection, so it writes a 502 to the client. Only later does the update reach the proxy and the pod leave its list.

The same shape exists outside Kubernetes. An ALB stops sending new requests to a target that is deregistering and waits for the requests in flight. The wait is 300 seconds by default. If the target closes the connection before that wait ends, AWS says the client gets a 500-level error (target group docs). A deploy script that stops the process before it deregisters it is the same bug.

See it fail

I ran this on Node 22 in a container. The server takes 2 seconds to answer. The client sends one request, and half a second later I send SIGTERM:

no SIGTERM handler    client: error ECONNRESET socket hang up    server exit code: 143
with a handler        client: got 200 done                       server exit code: 0

Exit code 143 is 128 + 15. The process was killed by signal 15, SIGTERM. Node’s default is to exit right away, with the request still open.

Fix 1: handle SIGTERM in the app

On SIGTERM the app should do three things in order. Start failing its health check. Wait while the proxy catches up. Then stop accepting connections and let the requests in flight finish.

const http = require('node:http');

let draining = false;

const server = http.createServer({ keepAliveTimeout: 65_000 }, (req, res) => {
  if (req.url === '/ready') {
    res.statusCode = draining ? 503 : 200; // the health check fails first
    return res.end(draining ? 'draining' : 'ok');
  }
  // ... your normal handler
});
server.listen(3000);

process.on('SIGTERM', () => {
  draining = true;
  const waitMs = Number(process.env.DRAIN_MS ?? 0); // time for the proxy to stop sending
  setTimeout(() => {
    server.close(() => process.exit(0)); // stop accepting, wait for requests in flight
  }, waitMs);
});

server.close() stops the server from accepting new connections and closes idle ones. Since Node 19 it does this on its own, as the Node docs note. The callback runs when the last request in flight is done. I tested it with keepAliveTimeout at 65 seconds: the server exited as soon as the last response was sent, not after 65 seconds.

If a request never finishes, the process never exits, and the platform sends SIGKILL at the end of the grace period. That is an acceptable end for a stuck request.

DRAIN_MS is the wait for the proxy. On Kubernetes, leave it at 0 and use Fix 2 instead. Do not wait in both places. On a plain VM or Docker host, set it longer than your load balancer needs to notice a failing health check. That depends on the check interval and the unhealthy threshold you chose.

On Kubernetes you do not need to flip readiness yourself. The EndpointSlice docs say the terminating condition is set when the pod is first deleted, and a terminating endpoint is never ready. The pod is already marked. What it lacks is time.

Fix 2: buy time with a preStop sleep

spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: web
      lifecycle:
        preStop:
          sleep:
            seconds: 10

The lifecycle hook docs say the hook “must complete its execution before the TERM signal can be sent”. So for 10 seconds the app is still running and still answering, while the removal spreads to the proxies. Then SIGTERM arrives and Fix 1 does its work.

The sleep action is on by default since Kubernetes 1.30 and stable in 1.34, according to the feature gate table. On an older cluster use exec with ["sleep", "10"], which needs a sleep program inside the image.

Ten seconds is my starting point, not a documented number. The right value is however long your ingress takes to drop the pod, and that depends on your setup. Measure it with the test at the end.

A drain inside the grace period. Example values: terminationGracePeriodSeconds 45. For the first 10 seconds a preStop sleep keeps the app answering while the proxy forgets the pod. Then SIGTERM arrives and the app stops accepting, finishes requests in flight and exits, with up to 20 seconds for the longest request. The last 15 seconds are spare. At 45 seconds the kubelet sends SIGKILL to anything still running.

The grace period is one clock for everything. The docs say it covers the preStop hook and the time the container takes to stop. Their example: a 60 second grace period, a hook that takes 55, and a container that needs 10 to stop. The container is killed, because 55 + 10 is more than 60. The default is 30 seconds, so a 10 second sleep plus a 20 second request already uses all of it. Set the grace period above sleep + your longest request.

Fix 3: do not remove old pods before new ones are ready

strategy:
  rollingUpdate:
    maxUnavailable: 0
    maxSurge: 1
readinessProbe:
  httpGet: { path: /ready, port: 3000 }

The Deployment docs say both settings default to 25%. With maxUnavailable: 0, an old pod goes away only after a new one is ready. The readiness probe matters for the new pod too. Without a probe that checks the app is listening, Kubernetes has no way to know when it is, so traffic can reach a pod that is not ready yet. That is cause 1 in reverse, and it gives the same 502.

Fix 4: check that SIGTERM reaches your app

Docker’s docker stop sends SIGTERM to the main process, then SIGKILL after 10 seconds by default on Linux (docs). The Dockerfile docs warn that the shell form of ENTRYPOINT starts your program under /bin/sh -c, which “does not pass signals”, so the program is not PID 1 and never sees SIGTERM. The shell form of CMD works the same way.

# Shell form: runs under /bin/sh -c, so your app may never see SIGTERM
CMD node server.js

# Exec form: node is PID 1 and gets the signal
CMD ["node", "server.js"]

If a container always takes exactly the stop timeout to stop and exits with code 137 (128 + 9, SIGKILL), your app is not getting the signal. Call node directly. Do not start it through npm start, which adds one more layer.

Outside Kubernetes

The order that works on any platform:

  1. Take the instance out of the load balancer.
  2. Wait until it has no requests in flight. On an ALB that is the deregistration delay. AWS finishes it early if the target has no requests and no active connections.
  3. Send SIGTERM and let the app finish and exit.
  4. Send SIGKILL only after a timeout.

Cause 2: the proxy reuses a connection the app already closed

Opening a TCP connection costs a round trip, so proxies keep idle connections to the app and reuse them. Both sides have an idle timer. When the app’s timer fires first, the app closes the socket. That news takes a moment to reach the proxy. If the proxy picks that socket for its next request in that moment, the request goes to a socket that is gone. The answer is a reset, and the proxy writes a 502.

AWS describes this directly. It recommends that “the idle timeout of your application” be larger than the load balancer’s. Otherwise, if the application closes the connection, “the load balancer might send a request to the application before it receives the packet indicating that the connection is closed”, and the client gets a 502 (docs).

The keep-alive race. A proxy with an idle timeout of 60 seconds keeps a connection open to an app with an idle timeout of 5 seconds. At 5 seconds the app closes the idle socket. The proxy has not seen the close yet and sends the next request on that socket. The app side answers with a reset, and the proxy writes a 502 to the client. The fix is an app idle timeout of 65 seconds, above the proxy’s 60, so the proxy always closes first.

The window is small, so the 502s come one at a time and at any hour. You only notice them in a deploy window because you are staring at the graph.

The numbers behind the default setups:

  • An ALB closes an idle connection after 60 seconds by default.

  • Node’s server.keepAliveTimeout defaults to 5000 ms through Node 26, says the Node docs. I printed it from a new server on Node 20, 22, 24 and 26 and got 5000 each time. The http.createServer() option list in the Node 24 and 26 docs says 65000. That is a docs error: the real default through Node 26 is 5000. Check your own server:

    node -e "console.log(require('http').createServer().keepAliveTimeout)"
    
  • nginx keeps upstream connections for 60 seconds by default (keepalive_timeout in the upstream block, per the nginx docs). Upstream keepalive is on by default only since nginx 1.29.7. Before that you had to add keepalive to the upstream block, set proxy_http_version 1.1 and clear the Connection header.

So Node behind an ALB or nginx closes at 5 seconds, and the proxy holds on for 60. The proxy is the one that is surprised.

Idle timeouts side by side, in seconds. Node’s default keepAliveTimeout through Node 26 is 5. The AWS ALB idle timeout default is 60. The nginx upstream keepalive_timeout default is 60. Node with keepAliveTimeout set to 65000 milliseconds is 65. The app must hold the connection longer than the proxy in front of it.

The fix: the app closes last

const server = http.createServer({ keepAliveTimeout: 65_000 }, handler);

With Express, set server.keepAliveTimeout = 65_000 on the object that app.listen() returns, before traffic arrives. The Node docs say a change affects only new connections.

The rule is the same for every pair of servers: the one closer to your code closes last. Choose a few seconds of margin. I use 5 as a rule of thumb, not a documented number. You can also go the other way and shorten the proxy’s timer. For nginx, set keepalive_timeout 4s; in the upstream block. Raising the app’s timeout is the simpler change.

Three notes:

  • Node 22.19 and 24.6 added keepAliveTimeoutBuffer, 1000 ms by default, which is added to the socket timeout. The docs say it helps reduce connection resets. It narrows the window and does not close it.
  • Many guides also raise headersTimeout above the keep-alive timeout. The Node docs do not ask for it. I tested Node 20, 22 and 24 with headersTimeout at 4 seconds and keepAliveTimeout at 8: the idle socket stayed open until the keep-alive timer fired. I would leave headersTimeout alone.
  • Chains need the rule at every hop. ALB to nginx to Node works with defaults at the first hop, because nginx closes a client connection after 75 seconds by default and the ALB gives up after 60. The second hop is the broken one: nginx holds for 60 and Node closes at 5.

When it breaks

  • Long requests. Uploads, streams and WebSockets that outlive the grace period are cut when SIGKILL lands. Clients must reconnect. No setting makes this go away.
  • Node still says keep-alive while it is closing. In my Node 22 run, the last response during shutdown carried Connection: keep-alive, and then the server closed the socket. A proxy that has not yet dropped the pod can reuse that socket. This is one more reason the wait for the proxy comes first.
  • A retry may run twice. When an upstream group has more than one server, nginx can pass a failed request to the next one (proxy_next_upstream, default error timeout). It does not pass on a POST, LOCK or PATCH once the request has been sent, unless you add non_idempotent (docs). Turn that on only when the endpoint takes an idempotency key, or you will charge customers twice.
  • Workers die too. A queue worker gets the same SIGTERM. Let it finish the current job or give the job back. If a job is cut off, it runs again, so it has to be safe to run twice. The job queue post shows how a lease handles a worker that dies.
  • A 503 right after a deploy is a different bug. On an ALB it means no healthy target was registered. Check the rollout, not the timeouts.

Prove it before you ship it

Send steady traffic while you roll out, and count the status codes in a row:

# terminal 1: about 20 requests a second, one status code per line
while true; do
  curl -s -o /dev/null -w '%{http_code}\n' https://shop.example.com/health
  sleep 0.05
done | uniq -c

# terminal 2
kubectl rollout restart deployment/web

The output is a run-length count, for example a long run of 200, then a few 502, then 200 again. 000 means curl got no reply at all. Run it before and after each fix. I would want the 502s gone across five rollouts in a row before calling cause 1 fixed. For cause 2, let the loop run for an hour at low traffic with no rollout. The Node docs also show a small reproduction that sends requests right at the server’s keep-alive timeout.

Update, November 2026

Node 27, in alpha since 25 November 2026, changes the real default of keepAliveTimeout to 65 seconds (nodejs/node pull 62782). On Node 27 the cause 2 default is already above an ALB’s 60 seconds. Node 26 and older still close at 5 seconds, so keep the explicit setting there.

Questions people ask

Why do I get 502 only for a few seconds during a deploy? The old process stops while the proxy still routes requests to it. Removal from the proxy’s list and SIGTERM start together, and the list update can arrive later. A preStop sleep and a SIGTERM handler close the gap.

Is a preStop sleep a hack? It is the documented way to put a pause before SIGTERM. The hook has to finish before the signal is sent. The only part to watch is the grace period, which has to cover the sleep and the longest request.

Should I raise the ALB idle timeout or the app’s? Raise the app’s, so it stays above the ALB’s. Raise the ALB’s only when you have requests that stay quiet for more than 60 seconds, as in long uploads. If you do, raise the app’s timeout again to stay above it.

What is the difference between 502, 503 and 504? On an ALB, 502 means the target closed the connection or sent a bad reply. 503 means there is no target to send to. 504 means the target did not answer in time. During a deploy, 502 is the usual one.

Can the proxy retry for me? With several servers in the upstream group, nginx can pass a failed GET to the next one by default. It does not do that for a POST, and you should not force it unless the endpoint is idempotent. Retry from the client with an idempotency key instead.

Cheat sheet

Cheat sheet. Where: the proxy writes the 502, so read the proxy’s log. Cause 1: the old pod dies while the proxy still sends to it. Drain: preStop sleep, then SIGTERM, finish requests, exit. Grace: terminationGracePeriodSeconds above sleep plus the longest request. Signals: exec-form CMD, so the app is PID 1 and gets SIGTERM. Cause 2: the proxy reuses a socket the app already closed. Rule: the app’s idle timeout must be longer than the proxy’s. Node: keepAliveTimeout 65000 behind a 60 second ALB. Prove: a curl loop during a rollout, counting status codes.

Further reading

Written by Rafi Loom

Backend engineer who builds high-volume systems that move money. More about Rafi