Running services on Amazon EKS behind an AWS Application Load Balancer can cause a short burst of 502 errors on every rollout, even when every pod is healthy and every deploy goes green. This post explains why it happens, how to tell whether your services are affected, and the small set of changes that fixed it.
Context
A few years ago I wrote about the Node.js application lifecycle, and how shutting an application down is just as important as starting it up. I still believe that. What I didn’t appreciate at the time is that a graceful shutdown inside the process is only half the story when there is a load balancer sitting in front of it.
At my place of work we run a number of Go services on Amazon EKS, fronted by Application Load Balancers managed by the AWS Load Balancer Controller. A while ago I started looking into a steady trickle of 502s on one of our public APIs. They were small in number, they came in short bursts, and nothing in our deploy pipeline ever went red.
It turned out every single burst lined up with a rollout.
ℹ️ This post assumes you are familiar with Kubernetes Deployments and readiness probes. If you have read my post on IAM Roles for Service Accounts, you’ll already have the building blocks.
Two Clocks
The part that took me longest to see is this. During a rollout there are two separate systems deciding whether a pod is healthy, and they don’t talk to each other.
- Kubernetes runs the readiness probe. When it passes, the pod is marked Ready.
- The ALB target group runs its own health checks against the same pod. Until enough of those pass, the target is in the
initialstate and receives no traffic.
Kubernetes decides when to kill the old pods using the first clock. The ALB decides where to send traffic using the second. The gap between them is your outage.
Let’s put some real numbers on it. On the service I was looking at:
- New pods were Ready about 11 seconds after starting.
- The target group needed 2 health checks, 15 seconds apart before a target was healthy.
- The last old pod was killed 17 seconds before the new targets left
initial.
So for 17 seconds, the ALB had old targets that were shutting down and new targets it wasn’t willing to use yet.
Here’s that as a timeline, for the last old pod in a rollout. The numbers are rounded, but the shape is what matters.
---
config:
gantt:
useWidth: 1000
---
gantt
dateFormat mm:ss
axisFormat %M:%S
tickInterval 5second
section New pod
Starting : t1, 00:00, 00:11
Ready for Kubernetes : milestone, t2, 00:11, 00:11
section New target
initial, no traffic : t3, 00:00, 00:30
Healthy : milestone, t4, 00:30, 00:30
section Old pod
Serving : done, t5, 00:00, 00:13
Listener closed : crit, t6, 00:13, 00:30
section Old target
Gets traffic : active, t7, 00:00, 00:18
Deregistered : t8, 00:18, 00:30
section Clients
Errors : crit, t9, 00:13, 00:30
Kubernetes is happy at 11 seconds. The ALB isn’t happy until 30. Everything in red happens in between.
A Graceful Shutdown Isn’t Enough
This is where things get interesting. A typical Go HTTP server shuts down something like this.
func main() { srv := &http.Server{Addr: ":8080", Handler: routes()}
go func() { if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } }()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM) defer stop() <-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { log.Printf("shutdown: %v", err) }}That looks like a textbook graceful shutdown, and inside the process it is one. In-flight requests get up to 60 seconds to finish.
But read the documentation for http.Server.Shutdown closely:
Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down.
The listener is closed the moment SIGTERM arrives. Any new connection after that point is refused. Idle keep-alive connections are closed straight away too, and the ALB keeps a pool of those to every target and reuses them.
Meanwhile, Kubernetes sends SIGTERM and removes the pod from the Service endpoints at roughly the same time. The AWS Load Balancer Controller notices the endpoint change and deregisters the target, but that takes a few seconds to reach the ALB. During those seconds the ALB still thinks the old pod is a perfectly good target, opens a connection, gets refused, and returns a 502 to the client.
Two clocks that disagree, plus a server that slams the door immediately. Put them together and you get about 15 seconds of continuous 502s on every deploy.
None of this is specific to Go. Shutdown does exactly what its documentation says. Any server that stops accepting connections as soon as it gets SIGTERM has the same problem, and most of them do.
The Variable That Decides Everything: Target Type
Before fixing anything, it’s worth knowing whether a service is even exposed to this. The answer lives in the TargetGroupBinding (or the alb.ingress.kubernetes.io/target-type annotation on your Ingress).
$ kubectl get targetgroupbindings -A \ -o custom-columns=NAME:.metadata.name,TYPE:.spec.targetTypeip Targets
Pods are registered with the target group directly. The ALB sends traffic straight to the pod IP.
This means target health check lag is the outage window. Full exposure.
instance Targets
Nodes are registered with the target group, and traffic flows ALB → NodePort → kube-proxy → pod. A pod rollout never deregisters a target, because the target is the node.
I’d expect a handful of 502s from keep-alive connections that land on a pod which is on its way out, but not 15 seconds of them. I haven’t measured that, so treat it as a reasoned guess.
This isn’t a reason to switch to instance targets. AWS recommends ip targets for EKS, and with the fixes below they behave well.
In our case only one service in each cluster used ip targets, and of course it was the public one.
The Fix
The fix ended up being four small changes in the Deployment, plus one label on the namespace.
1. Keep Serving While the ALB Catches Up
A preStop hook runs before the container receives SIGTERM. If it sleeps, the pod keeps serving traffic while the ALB finishes deregistering it.
spec: template: spec: containers: - name: api lifecycle: preStop: sleep: seconds: 25ℹ️ The built-in
sleepaction is available from Kubernetes 1.30. On older clusters you needexec: { command: ["sleep", "25"] }, which means you need asleepbinary in your image. Distroless images don’t have one.
For ip targets I found 15 seconds was not quite enough. 25 seconds was.
A fixed sleep can look like a hack. It’s the standard answer, and it’s the reason the sleep action was added to Kubernetes. Nothing tells a pod “every load balancer has stopped sending you traffic”, so the pod waits long enough for that to be true. Measure how long deregistration takes in your own cluster and pick a number a bit above it.
2. Give the Pod Enough Time to Finish
The grace period has to cover the preStop sleep and the time your server is allowed to drain. If it doesn’t, the kubelet sends SIGKILL part way through your graceful shutdown.
spec: template: spec: terminationGracePeriodSeconds: 9025 seconds of sleep plus a 60 second Shutdown timeout is 85 seconds. 90 gives a little room.
3. Make Kubernetes Wait for the ALB
This is the part that actually closes the gap between the two clocks. The AWS Load Balancer Controller can inject a pod readiness gate. With it, a new pod isn’t considered Ready until its ALB target is healthy.
Turn it on by labelling the namespace.
$ kubectl label namespace my-app elbv2.k8s.aws/pod-readiness-gate-inject=enabledNew pods in that namespace get an extra readiness gate, and the rollout waits on it before killing anything old. You can watch it flip with -o wide.
$ kubectl get pods -o wide
NAME READY STATUS ... READINESS GATESmy-app-7d9f8c-abcde 1/1 Running ... 0/1my-app-7d9f8c-fghij 1/1 Running ... 1/1The first pod’s container is up, but the ALB hasn’t marked its target healthy yet, so Kubernetes leaves the old pods alone.
❗ Warning: Readiness gates only make sense for
iptargets. Withinstancetargets there is no per-pod target to wait for.
A few more things to know before you rely on it. All of them are in the controller’s documentation.
- The gate is added when a pod is created, and only if a Service that matches the pod and a
TargetGroupBindingfor that Service already exist. Create the Service and Ingress, and label the namespace, before the pods. - The webhook that adds the gate fails open by default in controller versions after v2.11.0. If the webhook is unavailable, pods are created without the gate and nothing warns you. The docs recommend
failurePolicy: Failwith anobjectSelector, so only the pods you’ve opted in are affected. - On EKS Auto Mode the built-in load balancer controller uses a different label:
eks.amazonaws.com/pod-readiness-gate-inject=enabled.
4. Never Go Below Full Capacity
spec: strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0Bring one new pod up, wait for it to be properly healthy, then take one old pod down.
The Result
I ran a probe against the service in a tight loop through a production rollout before and after.
- Before: about 15 seconds of continuous 502s.
- After: 1 non-200 response in 1,248 calls.
A later re-test in another environment gave 747 calls with zero failures, so that one leftover failure was intermittent rather than part of every rollout.
Here’s the same pod replacement with all four changes in place.
---
config:
gantt:
useWidth: 1000
---
gantt
dateFormat mm:ss
axisFormat %M:%S
tickInterval 5second
section New pod
Starting : t10, 00:00, 00:11
Waiting for ALB target : t11, 00:11, 00:30
Ready for Kubernetes : milestone, t12, 00:30, 00:30
section New target
initial, no traffic : t13, 00:00, 00:30
Gets traffic : active, t14, 00:30, 01:00
section Old pod
Serving : done, t15, 00:00, 00:30
preStop sleep, serving : done, t16, 00:30, 00:55
Shutdown : t17, 00:55, 01:00
section Old target
Gets traffic : active, t18, 00:00, 00:35
Draining : t19, 00:35, 01:00
section Clients
All requests served : done, t20, 00:00, 01:00
The readiness gate moves “Ready” to the moment the ALB is ready, so the old pod isn’t touched until there is somewhere else for traffic to go. The preStop sleep keeps the old pod serving until the ALB has stopped sending it anything. Nothing is red.
Things That Look Like the Fix (But Aren’t)
While working through this I tried, or was tempted by, a few things that didn’t help. Some of them are worth knowing about even if you never hit this exact problem.
Lowering the Deregistration Delay
The target group’s deregistration delay sounds like exactly the right knob. It’s how long the ALB holds on to a target that’s being removed, so in-flight requests can finish. The default is 300 seconds.
It doesn’t touch the gap that causes the 502s. Look at the first timeline again: the 502s start before the old target is deregistered, while the ALB still thinks the old pod is a normal target. The delay only applies after that. Lowering it makes rollouts finish sooner, and if you set it lower than your slowest request, it cuts those requests off part way through.
For instance targets it does nothing at all during a rollout, because the target is a node and nodes aren’t being deregistered.
Changing maxUnavailable From 25%
The default maxUnavailable is 25%, and Kubernetes rounds it down. (maxSurge also defaults to 25%, and rounds up.)
| Replicas | 25% of replicas | maxUnavailable |
|---|---|---|
| 2 | 0.5 | 0 |
| 3 | 0.75 | 0 |
| 4 | 1 | 1 |
| 5 | 1.25 | 1 |
| 9 | 2.25 | 2 |
With 2 or 3 replicas it’s already 0, so setting it to 0 changes nothing. Most of our services ran 2 or 3 replicas, so for them the strategy change was a no-op and the preStop hook was doing all the work. It only made a difference on the couple of services with 5 or more.
Trusting helm upgrade --wait
--wait waits for pods to be Ready. That’s the first clock. It knows nothing about the ALB, so it reports success while users are getting 502s.
---
config:
gantt:
useWidth: 1000
---
gantt
dateFormat mm:ss
axisFormat %M:%S
tickInterval 5second
section Kubernetes
New pod starting : t21, 00:00, 00:11
New pod Ready : milestone, t22, 00:11, 00:11
helm --wait returns : milestone, t23, 00:13, 00:13
section Clients
Errors : crit, t24, 00:13, 00:30
The deploy goes green at about 13 seconds, and the errors carry on for another 17. This is why the whole problem was invisible from our deploy pipeline.
The readiness gate fixes this too. Once Ready means “the ALB target is healthy”, --wait is waiting on the right thing.
Adding a preStop Sleep to a Recreate Deployment
A Deployment with strategy: Recreate stops every old pod before it starts any new one. Some generic Helm charts use it as their default, so it’s worth checking which strategy you actually have. One of our two replica services had a full outage on every deploy for exactly this reason, and nobody had chosen it.
Adding a preStop sleep to a Recreate Deployment makes the outage longer. The old pods are already on their way out of the load balancer, so the sleep serves almost nobody, and the new pods can’t start until it’s over. The timings below are illustrative.
---
config:
gantt:
useWidth: 1000
---
gantt
dateFormat mm:ss
axisFormat %M:%S
tickInterval 5second
section Without preStop
Old pod stops : t25, 00:00, 00:02
New pod starting : t26, 00:02, 00:13
New target initial : t27, 00:13, 00:32
Errors : crit, t28, 00:00, 00:32
section With preStop
Old pod sleeps : done, t29, 00:00, 00:25
Old pod stops : t30, 00:25, 00:27
New pod starting : t31, 00:27, 00:38
New target initial : t32, 00:38, 00:57
Errors : crit, t33, 00:05, 00:57
If a service really can’t run two copies at once, for example because it mounts a volume that only one pod can attach, leave it on Recreate and skip the preStop hook. Otherwise switch it to RollingUpdate.
A Bonus Footgun: A Shell as PID 1
One of our services had this in its Dockerfile.
ENTRYPOINT sh -c "gunicorn app:server --bind 0.0.0.0:8080"This is the shell form of ENTRYPOINT, and Docker runs it inside /bin/sh -c. So PID 1 is a shell, with gunicorn two levels below it. PID 1 ignores any signal it hasn’t set up a handler for, and the shell hasn’t set one up for SIGTERM. So SIGTERM never reached gunicorn, and every pod sat there until the SIGKILL 30 seconds later. No grace period in the world helps with that.
Adding exec looks like the fix.
ENTRYPOINT sh -c "exec gunicorn app:server --bind 0.0.0.0:8080"It isn’t. The shell form still wraps the whole line in another /bin/sh -c, so exec only replaces the inner shell, and PID 1 is still a shell. I tested both versions with docker stop, and both waited for the full timeout before being killed.
The fix is the exec form, which runs the program directly with no shell at all.
ENTRYPOINT ["gunicorn", "app:server", "--bind", "0.0.0.0:8080"]Now gunicorn is PID 1 and gets the signal directly. Docker’s own build checks warn about the shell form for exactly this reason (JSONArgsRecommended). If you really need a shell, for example to expand an environment variable, use ["sh", "-c", "exec gunicorn ..."]. Then exec replaces the only shell there is.
A Note on Measuring This
I nearly went down the wrong path because of how I first measured the problem.
My first attempt was to line up the ALB’s HTTPCode_ELB_502_Count metric in CloudWatch against ReplicaSet creation times from kubectl get rs. That suggested most 502s happened outside of rollouts, which would have meant a second unknown cause and a much bigger job.
The catch is revisionHistoryLimit. It defaults to 10, so Kubernetes deletes old ReplicaSets. A busy service that deploys several times a day only keeps the last 10, and every older rollout simply disappears from the data. One of our services had rolled out 92 times in 14 days. kubectl showed me a handful.
When I counted rollouts from the EKS audit log instead (verb=create on replicasets), more than 90% of the 502s fell inside a rollout window.
The query returned a number. The number was wrong because of retention, and it pointed at a cause that didn’t exist. Always ask what your data source has already thrown away.
There’s one more trap when you measure the fix. The first deploy of a preStop change still shows errors, because the pods being replaced were created from the old spec, which has no sleep. Measure on the second rollout.
Not Every 502 Is a Rollout
Once I counted rollouts properly, more than 90% of the 502s fell inside one. The rest were a different problem, server timeouts, and one of them is worth knowing about because it looks a lot like this one.
The ALB keeps idle connections to each target open for up to 60 seconds by default. If your server closes idle connections sooner, the ALB can send a request down a connection the server has just closed, and the client gets a 502. AWS recommends setting the server’s keep-alive timeout higher than the ALB’s idle timeout. In Go that’s IdleTimeout, which falls back to ReadTimeout when it isn’t set.
srv := &http.Server{ Addr: ":8080", Handler: routes(), IdleTimeout: 75 * time.Second,}Summary
If you run services on EKS behind an ALB with ip targets, there is a good chance you have this problem and your pipeline will never tell you. The checklist:
- Find out which services use
iptargets - Add a
preStopsleep so pods keep serving while the ALB deregisters them - Set
terminationGracePeriodSecondshigher than the sleep plus your shutdown timeout - Enable pod readiness gates on
iptarget namespaces - Use
maxSurge: 1andmaxUnavailable: 0 - Check the Deployment strategy is
RollingUpdate, and notRecreateby accident - Use the exec form of
ENTRYPOINT, so your process is PID 1 and actually receivesSIGTERM - Keep your server’s keep-alive timeout above the ALB’s idle timeout
The only recommendation I will make is the one I keep coming back to. Take the time to understand the tools you are working with, including the parts that sit between your tools. Kubernetes and the ALB were each doing exactly what they were designed to do. The outage lived in the gap between them.
References
Load Balancing | Amazon EKS Best Practices
Pod readiness gate | AWS Load Balancer Controller
Container Lifecycle Hooks | Kubernetes
Pod Lifecycle: Termination of Pods | Kubernetes
http.Server.Shutdown | Go Documentation
Target groups for your Application Load Balancers | AWS
How do I troubleshoot Application Load Balancer HTTP 502 errors? | AWS
JSONArgsRecommended | Docker Documentation
Understanding and Managing the Node.js Application Lifecycle