Your App Returned a 502: Debugging HTTP Status Codes by Who Generated Them
At 02:14 you get paged for a spike in 502 Bad Gateway on POST /checkout. You open the application logs for the checkout pods. Nothing. CPU is flat, memory is flat, zero panics, zero restarts, and every request that actually reached the container returned 200 OK in 18 ms.
The trap in most status-code cheat sheets is treating a status code as a pointer to a specific component (“500 means your app crashed”, “502 means your pod is in CrashLoopBackOff”, “503 means 0/3 pods ready”). An HTTP status code identifies a failure class, not who emitted the response. Along a typical path—Client → Load Balancer → Ingress / Auth Proxy → App → Upstream—almost every hop can either generate a status code itself or forward one it received from the next hop down.
Cutting an incident from an hour to two minutes starts with one question before you open a single application log: which hop synthesized those three digits?
Step Zero: Check elb_status_code vs target_status_code
On AWS Application Load Balancers, the load balancer forwards valid HTTP responses from targets untouched—including 4xx and 5xx responses—and increments HTTPCode_Target_4XX_Count or HTTPCode_Target_5XX_Count. When the load balancer itself cannot complete the request, it synthesizes the error and increments HTTPCode_ELB_4XX_Count or HTTPCode_ELB_5XX_Count.
In ALB access logs, every line records both sides of the hop:
# Case A: the load balancer generated the 502; the request never got a valid HTTP response from the target
http 2026-12-02T02:14:11.402190Z app/checkout-alb/9f8e7d6c5b4a3210
203.0.113.42:54321 10.0.14.88:3000 0.001 0.000 -1
502 - 614 148 "POST https://api.example.com:443/checkout HTTP/2.0"
# Case B: the target returned 502 (for example, the app failed talking to a payment gateway) and the ALB forwarded it
http 2026-12-02T02:14:12.118004Z app/checkout-alb/9f8e7d6c5b4a3210
203.0.113.42:54322 10.0.14.88:3000 0.001 0.412 0.000
502 502 614 295 "POST https://api.example.com:443/checkout HTTP/2.0"
Look at the three timing fields (request_processing_time, target_processing_time, response_processing_time) and the two status fields (elb_status_code, target_status_code):
- In Case A,
target_processing_timeis-1andtarget_status_codeis-. The load balancer generated the502. Grepping application logs for that request ID is a waste of time because the application never saw the request (or its socket closed before headers were written). - In Case B,
elb_status_codeis502andtarget_status_codeis502after412 ms. The container ran your handler, tried to call an upstream dependency, and returned a502payload of its own.
Envoy and ingress-nginx expose the same split via $upstream_status / $status and Envoy response flags (UF for upstream connection failure, UC for upstream connection termination, UT for upstream request timeout, NR for no route configured). Check that field first.
The Classic Ghost 502: ALB Idle Timeout vs Bun’s idleTimeout
Case A above—sporadic 502s with target_status_code = - and nothing in the app logs—is most famously caused by a keep-alive race between an AWS ALB and a backend with a shorter idle timeout.
Compare the two defaults from the official documentation:
- AWS ALB
idle_timeout.timeout_seconds: defaults to60seconds. The load balancer keeps an idle HTTP/1.1 connection to a target in its pool and reuses it for up to60 s. - Bun’s
idleTimeout(Bun.serveoption): defaults to10seconds. When a request has been quiet for longer than that, Bun closes the connection mid-response. (Node.js’sserver.keepAliveTimeouthas the same shape, with a5-second default sincev8.0.0— the race just fires earlier.)
When a pooled connection sits idle for 10–11 seconds and a new request arrives at the exact moment Bun sends a FIN:
ALB (idle_timeout = 60s) Bun (idleTimeout = 10s)
| |
|--- Request #1: POST /checkout ------------------>|
|<-- 200 OK (Connection: keep-alive) --------------|
| |
| ... 10.000 seconds of silence ... |
| | (idle timeout fires)
|--- Request #2: POST /checkout ----\ /--- FIN --|
| \ / |
| X |
|<-- TCP RST (socket already closed) / \ |
| |
[Synthesizes 502 Bad Gateway] | (nothing logged)
AWS lists this directly in the ALB 502 troubleshooting checklist: “The target closed the connection with a TCP RST or a TCP FIN while the load balancer had an outstanding request to the target. Check whether the keep-alive duration of the target is shorter than the idle timeout value of the load balancer.”
The fix in Bun is to keep the target’s socket open longer than the load balancer’s idle timeout:
// ALB default idle_timeout.timeout_seconds is 60s.
// Bun closes an idle connection after `idleTimeout` seconds (default: 10).
Bun.serve({
port: 3000,
idleTimeout: 65, // seconds, not milliseconds; 0 disables, max 255
fetch(req) {
return Response.json({ ok: true });
},
});
Two Bun-specific gotchas: idleTimeout is measured in seconds (the ALB value is in seconds too, so 65 beats 60; setting 65000 thinking it is milliseconds leaves the default 10 intact); and for long-lived streaming responses, raise the limit per request with server.timeout(req, seconds) instead of disabling it globally.
The same race bites Go (http.Server.IdleTimeout), Node.js (server.keepAliveTimeout, default 5 seconds), Gunicorn (--keep-alive, default 2 seconds!), and Uvicorn (--timeout-keep-alive, default 5 seconds) whenever they sit directly behind a reverse proxy or load balancer that pools HTTP/1.1 connections for 60 seconds.
502 vs 503 vs 504: What the Specs and Proxies Actually Do
In RFC 9110 (HTTP Semantics), the four main 5xx codes have tight definitions:
500 Internal Server Error(§15.6.1): “the server encountered an unexpected condition that prevented it from fulfilling the request.”502 Bad Gateway(§15.6.3): “the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.”503 Service Unavailable(§15.6.4): “the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. The server MAY send aRetry-Afterheader field (§10.2.3).”504 Gateway Timeout(§15.6.5): “the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.”
In production, reverse proxies map transport failures onto those three gateway codes in ways that surprise people on call:
1. “502 means the backend sent garbage back” is rarely literal bytes
Malformed HTTP response headers or a response header block over 32 KiB will trigger an ALB 502, as will a Lambda target returning a body over 1 MB. In practice, most 502s are connection-level:
- The target refused the TCP connection (
TCP RSTduring the handshake) because the process crashed or bound to127.0.0.1instead of0.0.0.0. - The target closed the connection mid-flight (
TCP RSTorFIN) because of the keep-alive race above, an OOM kill, or aSIGTERMhandler that exited immediately instead of draining in-flight requests after the load balancer’s deregistration delay. - TLS handshake failure between the load balancer and the target.
2. “0/3 pods ready” is a 503 on AWS ALB, and often a 502 or 503 in Kubernetes
On AWS ALB, 503 Service Unavailable means the target group has no registered targets or every registered target failed health checks (so no target is in service).
In Kubernetes with ingress-nginx, readiness probes gate membership in EndpointSlice. When a pod enters CrashLoopBackOff or its readiness probe fails, the kubelet removes it from ready endpoints. What status code the caller sees depends on the timing and proxy configuration:
- While the crashing pod is still in the active upstream list (before probe failure threshold × period has elapsed) and nginx connects to a dying container, nginx gets
connect() failed (111: Connection refused) while connecting to upstreamorupstream prematurely closed connectionand returns502 Bad Gateway(or retries the next upstream ifproxy_next_upstreampermits). - Once all pods fail readiness and the Service has zero ready endpoints,
ingress-nginxroutes the request to its internal placeholder upstream and returns503 Service Unavailable—unless a customdefault-backendor service-less path rule intercepts it first.
3. Even 500 can come from the load balancer
An on-call rule of thumb says “500 → go straight to application logs.” Usually true, except when your load balancer terminates authentication or runs WAF rules. AWS ALB generates its own 500 Internal Server Error when:
- An AWS WAF rule execution fails.
- An OIDC/Cognito identity provider’s token or user-info endpoint is unreachable or takes longer than
5seconds. - The user claims returned by the IdP exceed
11 KiB, or the JWKS endpoint response exceeds150 KiB.
Again, elb_status_code = 500 with target_status_code = - tells you immediately that the request died in the load balancer’s auth/WAF layer before touching your pod.
4. 504 is not only “slow SQL query”
A 504 Gateway Timeout happens whenever the proxy’s clock runs out before the upstream finishes. On ALB that means either the idle timeout (default 60 s) expired while waiting for response bytes, or the connection timeout (10 s) / TLS handshake timeout (10 s) expired before a connection could even be established. One subtle network cause documented by AWS: a stateless Network ACL on the target subnet that allows inbound traffic on the container port (say 8080) but blocks outbound traffic on ephemeral ports (1024–65535) back to the load balancer nodes.
What Failure Research Shows About 5xx in Microservices
Three findings from recent systems papers are worth keeping in mind when you wire up alerts and retries around 502, 503, and 504:
- A
5xxat the edge is a propagation symptom, not a root-cause address. In MicroHECL: High-Efficient Root Cause Localization in Large-Scale Microservice Systems (Liu et al., ICSE-SEIP 2021), which studied over30,000microservices at Alibaba, availability incidents split across performance (latency), reliability (error counts from code defects or infrastructure failures), and traffic anomalies (QPS spikes, Nginx limits, stress tests). Error counts propagate upstream along the call graph from the failing leaf service to the edge gateway. Looking only at the service directly behind the ingress finds the victim, not the culprit; tracing tools like MicroHECL and Sieve (Thalheim et al., Middleware 2017) correlate metrics along the dependency graph precisely because status codes alone lose causality across hops. - Naive client retries turn a 1-second
502blip into a sustained outage. In FailureAtlas (Pandey & Singh, 2026), a transient upstream502combined with100concurrent clients using fixed-interval retries produced a synchronized retry storm where25%of requests failed permanently even though the underlying hiccup had already cleared. The reverse proxy was behaving according to spec by relaying the upstream502; the outage was caused by retry amplification without exponential backoff and jitter. - Health checks themselves can manufacture
503s—or hide broken backends behind200 OK. In Signalling Health for Improved Kubernetes Microservice Availability (Roberts, Archibald & Trinder, 2025), poll-based Kubernetes readiness/liveness probes erroneously flagged healthy pods under load, reducing service availability by4%, whereas event/signal-driven health reporting detected real failures86%faster. Conversely, FailureAtlas documents silent failures where a race condition or synchronous health-check handler returned200 OKon/healthzwhile real traffic degraded or timed out. When you see503with0/3pods ready, inspect what the readiness probe checks—a readiness probe that pings a shared database or runs a heavy query can knock every pod out of rotation simultaneously during a brief latency spike.
4xx Semantics: Who Rejected the Request, and Why 429 Is Special
Client-error codes (4xx) look simpler, yet the same “which hop generated it?” question applies:
| Code | Normative definition | Common proxy/gateway source | Common application source |
|---|---|---|---|
400 Bad Request |
RFC 9110 §15.5.1: perceived client error (malformed syntax, invalid framing, deceptive routing) | ALB rejects request lines > 16 KiB, single headers > 16 KiB, total headers > 64 KiB, or client closing before full body |
Malformed JSON or schema failure (note: RFC 9110 §15.5.21 defines 422 Unprocessable Content when syntax is valid JSON but semantics fail) |
401 Unauthorized |
RFC 9110 §15.5.2: lacks valid authentication credentials; server MUST send WWW-Authenticate |
ALB OIDC listener rule with OnUnauthenticatedRequest = deny, expired JWT at API Gateway |
Missing/expired bearer token or session cookie |
403 Forbidden |
RFC 9110 §15.5.4: understood request, refuses to authorize it; re-authenticating will not help | AWS WAF block action, CloudFront geo/IP restriction, mTLS policy | Caller is authenticated, lacks RBAC role / IAM permission / tenant scope |
404 Not Found |
RFC 9110 §15.5.5: no current representation for target resource (use 410 Gone if known permanent) |
Kubernetes Ingress host or pathType: Exact / Prefix mismatch, missing rewrite annotation |
Route exists, domain entity ID does not exist (or caller is not allowed to know it exists) |
429 Too Many Requests |
RFC 6585 §4: user sent too many requests in a given amount of time; MAY include Retry-After; MUST NOT be cached |
API Gateway / WAF / Envoy rate-limit filter | Application / Redis token bucket or GCRA limiter |
Two details worth knowing cold:
1. Most 404s in the wild are dead resources, not broken Ingress rules
Checking Ingress path and host rules is smart right after a Kubernetes deployment, when 100% of requests to a new route return 404 from the ingress controller’s default backend. In steady state, empirical web measurements tell a different story: a 2024 crawl of the top 88,000 Majestic Million sites (Broken Links on the Web, Mouchoux et al.) found that 35.2% of homepages contain at least one broken link, and a large-scale study of 11.9 million links on Stack Overflow (Liu et al., IEEE TSE 2021) found 14.2% broken (404), predominantly pointing to moved or deleted resources. If only specific IDs or old URLs 404, check data lifecycle and redirects (301 Moved Permanently / 308 Permanent Redirect, or 410 Gone) before rewriting Ingress YAML.
2. 429 Too Many Requests is in RFC 6585, and can be a server-side bug
Unlike 400–422 and 426, 429 is not defined in RFC 9110; its normative home is RFC 6585 §4 (Additional HTTP Status Codes). Two requirements in RFC 6585 matter in production:
- Caches must never store a
429: “Responses with the 429 status code MUST NOT be stored by a cache.” A misconfigured CDN that caches429without respecting this rule will lock out every user behind that cache key even after the rate-limit window resets. - Not every
429is an abusive client: if your limiter tracks concurrency with a distributed semaphore (for example, in Redis) and an exception path forgets to release a slot on timeout, the counter leaks upward until the service returns permanent429s with zero requests in flight—one of the exact production failure modes cataloged in FailureAtlas.
A Two-Minute Triage Flow for On-Call
When an HTTP error alarm fires, run through these four checks in order instead of guessing from the status code name:
- Compare proxy status vs upstream status in the edge access log (
elb_status_codevstarget_status_codeon ALB,$statusvs$upstream_statuson NGINX, response flags on Envoy).- If the upstream status is
-, the request never got a valid HTTP response from your container. Stay in the proxy/network/kubelet layer. - If the upstream status matches the edge status, your container generated or forwarded it. Move to your service’s logs and distributed traces.
- If the upstream status is
- Look at
target_processing_time/$upstream_response_time.~0 ms+502→ connection refused (RST), keep-alive race (FINreuse), or TLS handshake failure.= timeout(e.g.60.000 s) +504→ upstream hung or return path blocked.-1+503→ zero healthy targets in the target group orEndpointSlice. Check why readiness probes failed—and verify the probe endpoint itself isn’t coupled to a slow downstream dependency.
- Check whether your service is itself a client. If your pod logged a
502or504after400 ms, inspect the outbound call span (payment provider, auth service, internal gRPC/HTTP dependency) rather than the inbound handler. - Watch client retry behavior during recovery. Ensure callers use capped exponential backoff with jitter and honor
Retry-Afteron429and503so a brief upstream restart doesn’t turn into a self-inflicted retry storm.