HTTP versions, L4 vs L7 balancing, health checks, retries, and the 5xx taxonomy

502 means the proxy reached the backend and got nothing usable; 503 means it had no backend to try; 504 means the backend never answered in time. Timeouts must shrink inward and retries need a budget.

Read the briefing
About 4 min to read 9 drills

What to remember

  1. The 5xx triangle: 502 backend, 503 no backend, 504 too slow. Three different investigations. Read the code before opening a dashboard.
  2. Deadlines shrink along the chain, and propagate. Equal timeouts mean the outer hop gives up while inner hops keep working for nobody.
  3. Retries need a budget (~10%) and jitter. Three layers of three attempts is 27× load on a dependency that is already struggling.
  4. Only idempotent methods can be retried blind. POST needs an idempotency key, or you double-charge someone.
  5. Deploy-time 502s are draining, not luck. Readiness false first, a preStop delay for endpoint propagation, then drain with a deadline.

The big picture

Load balancing is where protocol knowledge becomes operational judgment: L4 versus L7 and what each can do, health checks that actually detect failure, connection draining and sticky sessions, timeouts and retries that do not amplify an outage, and the 5xx taxonomy that tells you whether the proxy or the backend is at fault. Add the HTTP version differences and you can explain most of a modern request path.

The mental model

A request passes through layers that each have their own timeout, retry policy, and view of health. Ask three questions of any incident: which layer produced this status code, whose timeout fired first, and did retries make it worse? The answers come from the proxy's access logs plus the backend's own metrics.

In depth

HTTP versions and what they change

HTTP/1.1 does one request at a time per connection, so browsers open several connections per origin and head-of-line blocking is per connection. HTTP/2 multiplexes many streams over one TCP connection with header compression, which removes HTTP-level head-of-line blocking but not TCP's: one lost segment stalls every stream on that connection. HTTP/3 runs over QUIC (UDP) with per-stream loss recovery, 0-RTT resumption, and connection migration, which is why it helps most on lossy mobile networks. Operationally: h2 between a proxy and backends means far fewer connections but concentrates load per connection (watch max_concurrent_streams and load balancing granularity: an L4 balancer sees one long-lived connection and cannot spread the streams), and gRPC's use of h2 is why gRPC needs L7-aware balancing.

L4 vs L7, health checks, draining

An L4 balancer forwards flows by 5-tuple hash: cheap, transparent, preserves end-to-end TLS, but it cannot read a request, cannot retry, and cannot route by path or header. An L7 balancer terminates the connection, sees requests, and can route, retry, rewrite, rate-limit, and observe per-request; it costs CPU and terminates TLS (or re-originates it).

Health checks: active probes hit a dedicated endpoint on an interval with unhealthy/healthy thresholds; passive outlier detection ejects a backend that is producing errors on real traffic. A health endpoint that only returns 200 from the web framework proves the process is up, not that it can serve, so include the critical dependency check but avoid cascading failure: if every backend marks itself unhealthy because a shared dependency is degraded, the balancer has nowhere to send traffic and a partial outage becomes total. The usual compromise is a shallow liveness check and a deeper readiness check with hysteresis, plus a "fail-open when all backends are unhealthy" policy.

Draining stops sending new requests to a backend while in-flight requests finish within a deadline, which is what makes rolling updates invisible; without it, deploys reset connections. Sticky sessions pin a client to a backend (cookie or hash); they undermine even load distribution and make draining harder, so prefer stateless backends with shared session storage.

Timeouts, retries, and the 5xx taxonomy

Timeouts must shrink along the call chain: each callee's deadline shorter than its caller's, with the deadline propagated, or callers give up while work continues downstream, burning capacity for nobody. Retries must be bounded by a budget and use jittered backoff; retrying at every layer multiplies load (three layers of three attempts is 27×) exactly when a dependency is struggling. Only safe (GET, HEAD) and idempotent (PUT, DELETE) methods can be retried automatically; POST cannot, unless the server deduplicates on an idempotency key.

The 5xx taxonomy from a proxy's point of view is a diagnostic shortcut: 502 Bad Gateway means it reached the backend and got an invalid or no response (connection refused, reset, malformed reply); 503 Service Unavailable means the proxy itself had no healthy backend (or shed load deliberately); 504 Gateway Timeout means the backend accepted the request and did not answer in time. So 502 points at backend crashes or protocol mismatch, 503 at health checking, capacity, or deployment, and 504 at backend latency or a timeout that is shorter than the work. Access logs with upstream status, upstream response time, and retry counts turn this from folklore into evidence.

Myths and facts

Myth: 503 means the backend returned an error.

Fact: 503 usually means the proxy had no healthy backend to send to; the backend may never have seen the request.

Myth: Retries always improve reliability.

Fact: Unbudgeted retries at multiple layers multiply load during failures and turn degradation into outage.

Myth: A health check should verify every dependency.

Fact: Deep checks can mark the whole fleet unhealthy over one shared dependency; keep liveness shallow, readiness deeper, and fail open when everything is unhealthy.

Myth: HTTP/2 everywhere makes load balancing better.

Fact: L4 balancing of h2 concentrates many streams on one connection; you need L7-aware balancing to spread requests.

Myth: Sticky sessions are a reasonable default.

Fact: They skew load, complicate draining, and hide state that should be shared; use them only when the backend genuinely cannot be stateless.

How pros do it

  • Shrink timeouts down the call chain and propagate deadlines; never let a callee's timeout exceed its caller's.
  • Budget retries (for example 10% of requests), use jittered backoff, and retry only idempotent operations.
  • Separate liveness from readiness, add hysteresis, and define behaviour when all backends are unhealthy.
  • Enable connection draining with a deadline matched to your slowest normal request.
  • Log upstream status, upstream latency, and retry counts at the proxy; alert on 502/503/504 separately.

Questions people ask

What is the difference between 502, 503 and 504?

Answer from the proxy's point of view, in one breath: 502 — it picked a backend and got a bad or missing reply (refused, reset, closed early, garbage); 503 — it had no usable backend at all, or shed load on purpose; 504 — a backend accepted the request and did not answer within the upstream timeout. Then say where each sends you: 502 to backend crashes and protocol mismatch, 503 to health checks and capacity, 504 to backend latency or a timeout shorter than the work. Add the caveat that Envoy and HAProxy report a failed connect as 503, so you read the proxy's own error reason, not the code alone.

L4 versus L7 — what is the difference, and when do you pick each?

Lead with what each layer sees. L4 sees addresses and ports and forwards whole flows without reading a request: cheap, any protocol, TLS end to end, but no path routing, no retries, no status codes, and a long-lived connection stays pinned to one backend. L7 terminates TLS and HTTP and sees every request, so it can route, retry, rate-limit and observe, at the cost of latency, CPU, and owning the certificate and the timeouts. Pick L4 for non-HTTP protocols or end-to-end TLS, L7 for HTTP APIs — and pre-empt the follow-up: gRPC multiplexes over one h2 connection, so it needs L7 or client-side balancing.

How do I stop retry storms?

Say the multiplication first — three layers of three attempts is 27× — then the controls: retry in one layer only, a budget of about 10% of requests, jittered exponential backoff, only idempotent operations or ones carrying an idempotency key, a distinct 'overloaded, do not retry' signal from the backend, and deadlines that make late retries pointless.

A deploy causes brief 502 spikes. Why?

Connections to terminating pods are cut before the balancer notices the endpoint is gone. Give the fix as an ordered contract: readiness flips false first, a preStop delay long enough for endpoint removal to propagate, then a graceful shutdown that finishes in-flight requests, with the grace period above the sum — and say you would verify by deploying and watching the 502 burst disappear.

Should gRPC go through an L4 or L7 balancer?

L7, or a client-side or mesh balancer. Give the reason in one sentence: gRPC multiplexes every call over one long-lived HTTP/2 connection, so an L4 balancer hashes that connection to one backend and every call follows it; balancing has to happen per stream.

Is it safe for the health endpoint to check the database?

Split the answer. For readiness, often yes — with hysteresis and a fail-open rule when everyone is unhealthy, or one database blip removes the whole fleet; for liveness, no, or the same blip restarts every pod. The principle to say out loud: the check must exercise what traffic needs without being able to take down more than traffic would.

We see 504s only for one endpoint. Where do I look?

That endpoint's backend latency against the proxy's route timeout: either the work got slower or the timeout was always shorter than the work. Say you would read the proxy's upstream response time for that route first, then the backend's own latency histogram, and only then touch a timeout.

Further reading

Drills · 9

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

Quick one — 502, 503 or 504? An nginx reverse proxy with a single upstream server forwards GET /api/orders/42. The backend refuses the TCP connection (nginx logs connect() failed (111: Connection refused) while connecting to upstream). Which status does the client get, and what is that code actually telling you?

  1. 502 Bad Gateway — the proxy selected an upstream and got an invalid or no response from it; the failure is in that upstream's reply, not in pool capacity and not a timeout. 502 is 'the gateway received a bad answer': refused, reset, closed early, or garbage from the backend it picked.
  2. 500 Internal Server Error — the proxy reports the backend's crash as a generic server error. 500 is a server's own unhandled error; proxies use the 502/503/504 family precisely so you can tell 'bad reply' from 'nobody available' from 'too slow'.
  3. 503 Service Unavailable — any backend failure means the service is unavailable. 503 means the proxy could not find a usable upstream at all (every backend unhealthy, queue or connection limit reached, maintenance) or the backend itself answered 503; a bad reply from a selected backend is 502.
  4. 504 Gateway Timeout — the request could not complete, so it timed out. 504 is reserved for the proxy's upstream timeout expiring with no response; a RST or an immediate close is an instant failure, not a timeout.
In short

nginx returns 502 Bad Gateway: it reached a backend and got a bad or missing reply.

Why

The 5xx family from a proxy encodes where the request died. 502 means the proxy talked (or tried to talk) to a specific backend and the reply was invalid or absent: connection refused, reset, closed before headers, or unparsable. 503 means the proxy could not serve at all — no healthy backend, its own overload or connection limits, or a backend explicitly saying 503. 504 means the proxy's read timeout expired while waiting. Implementations differ at the edges: Envoy returns 503 (response flag UF) for a failed connection and reserves 502 for protocol errors, HAProxy likewise uses 503 for connect failures and 502 for aborted or malformed replies — so read the proxy's error log or response flags rather than trusting the code alone. One nginx detail worth saying out loud: with more than one server in the upstream block, the default proxy_next_upstream error timeout makes nginx try the next server after a refused or prematurely closed connection (not after an invalid header) before giving up, so the client sees 502 only once every server it tried has failed.

The common mistake

Treating 503 as 'the backend is overloaded' and scaling it. From a proxy, 503 most often means the proxy never reached a backend at all — health checks, endpoint discovery or a connection limit — and the backend may never have seen the request.

Read the docs

2 Answer out loud

L4 versus L7 load balancing — what is the difference, what can each one do that the other cannot, and when would you put each in front of a service? Four to six sentences; assume I will ask about gRPC and about TLS.

In short

L4 forwards whole connections by address and port without reading requests; L7 terminates HTTP and can route, retry and observe each request, at the cost of latency and owning TLS.

What a strong answer does
  • mechanism: L4 hashes the 5-tuple and forwards or splices the connection — no request visibility, end-to-end TLS preserved, cannot retry or route by path, one long-lived connection stays pinned to one backend; L7 terminates TLS and HTTP, sees every request, can route, rewrite, retry, rate-limit and observe status codes, and adds latency plus its own connection, buffer and header limits.
  • judgment: Picks per case with the consequence stated: L4 when TLS must stay end to end, for non-HTTP protocols, or for raw throughput; L7 for path routing, retries and per-request observability; says that gRPC and any HTTP/2 client need L7 or client-side balancing because L4 pins all streams of one connection to one backend; notes that with L7 the certificate, retries and timeouts now live in the balancer.
  • communication: One-sentence distinction (what each layer sees), capabilities stated as consequences of that, then the placement rule with the gRPC and TLS follow-ups pre-empted.
Why

The whole distinction follows from visibility. An L4 balancer sees IP addresses and ports, hashes the 5-tuple, and forwards or splices the connection; it never reads the request, so it is cheap and protocol-agnostic and preserves end-to-end TLS, but it cannot route by path, retry, or observe status codes, and one long-lived connection stays on one backend. An L7 balancer terminates TLS and HTTP and sees every request, so it can route, rewrite, retry, rate-limit and report per-request latency and status — at the cost of latency, CPU, and its own connection, buffer and header limits. The two follow-ups that separate levels: gRPC and any HTTP/2 client multiplex streams over a single connection, so L4 hashing pins all their calls to one backend and they need L7 (or client-side or mesh) balancing; and with L7, certificates, timeouts and the retry budget move into the balancer, which is where the 502/503/504 taxonomy comes from.

The common mistake

Answering "L7 is smarter, so use L7 everywhere". The interviewer is listening for the costs — terminated TLS, an extra hop of latency, a balancer that now owns certificates, retries and connection limits — and for the cases where L4 is the right answer.

Read the docs

3 Answer out loud

A request flows client → edge proxy → API service → database. How would you set the timeouts and retries at each hop so that a slow database does not become a full outage — and where does idempotency come in? Three to six sentences; I will ask for numbers.

In short

A strong answer makes each timeout shorter than its caller's, retries in one layer only with a budget, and retries writes only with an idempotency key.

What a strong answer does
  • deadline structure: Deadlines shrink toward the leaf and each caller's timeout ≥ its callee's attempts × per-try timeout (or the deadline is propagated in a header); a slow database therefore fails fast at the API instead of hanging the edge and exhausting its connections.
  • retry discipline: Retries at a single layer, jittered exponential backoff, a budget (~10% of requests) or circuit breaker, only for idempotent operations or with an idempotency key the server dedups on; the leaf sheds load rather than queueing.
  • communication: States the principle (deadlines shrink inward, retries in one place), then applies it hop by hop with numbers, then names idempotency as the precondition for retrying writes.
Why

The two mechanisms interviewers listen for are deadline hierarchy (a caller must outlive its callee's total attempts, or it retries into work still running and exhausts its own resources) and single-layer, budgeted, idempotent retries. Concrete numbers — a budget percentage, the multiplication factor, the deadline arithmetic — separate a senior answer from a list of knobs.

The common mistake

Setting one generous timeout everywhere, or giving the database the longest timeout 'because it does the most work'. Equal or inverted timeouts mean the edge gives up and retries while inner hops keep working for nobody, which is exactly how a slow dependency becomes a full outage.

Read the docs

4 Pick the strongest answer

Here is a request path: client SDK → edge proxy → API gateway → backend. Each of the three hops is configured to make up to 3 attempts (one try plus retries) on any 5xx or timeout. The backend slows down and starts returning 503 to some requests. Worst case, how many backend attempts can one user request generate — and what would you change?

  1. Increase retries at every layer so at least one attempt lands on a healthy instance. More retries deepen the amplification and keep the backend saturated; availability comes from budgets, load shedding and fast failure, not from hammering.
  2. Up to 27 attempts (3³) — every attempt at one layer fans out into the full attempt count of the layer below. Retry at one layer only, cap it with a budget (retries ≤ ~10% of requests) and jittered backoff, and make the layers below fail fast. Retries multiply across layers, and they multiply hardest exactly when the backend is weakest; budgets and single-layer retrying keep the amplification bounded.
  3. About 3 × 3 attempts — the retries add up across the three hops. Each parent attempt triggers the child's full attempt count, so the counts multiply; 3³, not 3 × 3.
  4. Retries don't matter for load — a healthy backend absorbs them; only latency increases. The backend is returning 503 because it is overloaded; retries raise its load by up to 27× at the moment its capacity is lowest — that is the retry storm.
In short

Retries multiply across layers, so the attempt counts are multiplied, not added; retry in one layer only, with a budget and jittered backoff.

Why

Retries are a multiplier, not an adder: with 3 attempts at each of three layers, one request can become 3³ = 27 backend calls, and this happens precisely during a partial failure — the situation the retries were meant to survive. The SRE Book's answer is a per-client retry budget (retry only while retries are under about 10% of requests), retrying at a single layer with exponential backoff and jitter, and returning a distinct 'overloaded, do not retry' signal from the backend so callers stop rather than pile on. Layers below the retrying one should fail fast and propagate the error.

Read the docs

5 Read the output

Read me this curl -v. What has it established about where the fault is — and where it is not?

$ curl -sv https://api.example.com/v1/orders/8812
*   Trying 203.0.113.10:443...
* Connected to api.example.com (203.0.113.10) port 443
* ALPN: curl offers h2,http/1.1
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN: server accepted h2
* Server certificate:
*  subject: CN=api.example.com
*  SSL certificate verify ok.
* using HTTP/2
* [HTTP/2] [1] OPENED stream for https://api.example.com/v1/orders/8812
> GET /v1/orders/8812 HTTP/2
> Host: api.example.com
> User-Agent: curl/8.6.0
> Accept: */*
>
< HTTP/2 503
< content-length: 19
< content-type: text/plain
< server: envoy
< date: Tue, 02 Sep 2025 09:14:31 GMT
<
no healthy upstream
* Connection #0 to host api.example.com left intact
  1. The TLS handshake is the problem — the response arrived before the request finished. 'SSL certificate verify ok' and 'ALPN: server accepted h2' show TLS completed; the request was sent (the > lines) and answered.
  2. HTTP/2 was misnegotiated; retry with --http1.1. ALPN completed and the server answered on stream 1 with a well-formed HTTP/2 response; the protocol is working.
  3. The backend application returned 503 because it is overloaded; scale the backend out. A backend response would carry x-envoy-upstream-service-time and the application's own headers; 'no healthy upstream' is Envoy's locally generated body, meaning no backend was contacted.
  4. DNS, TCP, TLS 1.3 (certificate verified) and HTTP/2 negotiation to the edge all succeeded, and the 503 was generated by the Envoy proxy itself (body 'no healthy upstream', server: envoy, and no x-envoy-upstream-service-time header, which Envoy adds only when a backend answered). The client-to-edge path is fine; the fault is between the proxy and its backend pool — health checks marking every backend down, or a cluster with zero endpoints. Read the layers in order: each one completed until the proxy's own locally generated 503, which names its cause and carries none of the headers a backend response would.
In short

Everything up to the edge worked, and Envoy itself sent the 503 with no healthy backend; look at the health checks and the backend pool.

Why

curl -v is a layer-by-layer bisection you get for free: 'Trying ' proves DNS, 'Connected' proves TCP, the TLSv1.3 lines and 'verify ok' prove TLS and trust, ALPN proves protocol negotiation, and the > lines prove the request left. The response then tells you who answered: server: envoy, a plain-text 'no healthy upstream' body, and the absence of x-envoy-upstream-service-time mean the proxy answered on its own because its cluster had no healthy endpoints (Envoy response flag UH). The next questions are about the proxy's health checks and endpoint discovery, not about TLS, DNS or the client.

Read the docs

6 Pick the strongest answer

One from a postmortem. An RPC endpoint pool of 12 nodes sits behind an L7 balancer whose health check is GET /health every 5 s; the handler returns 200 whenever the node process is up. After a disk stall, one node falls 300 slots (~2 minutes) behind the rest of the pool and stays there, and 1/12 of read traffic is served stale data for an hour before a customer complains. What is the general fix?

  1. Add client-side retries so users land on a different node on the next attempt. The stale node returns 200 with stale data — nothing fails, so nothing is retried; correctness problems are invisible to retry logic.
  2. Check every 1 s instead of every 5 s so the balancer notices sooner. A faster check of the wrong thing is still the wrong thing; the node answers 200 at any frequency.
  3. The check is fine — 200 means healthy; the real problem was the disk, so add disk alerts. Disk alerts help operators, but the balancer keeps routing to the node until its check fails; liveness is not readiness.
  4. Make the health check a readiness signal about the data traffic depends on: the node reports its head slot and the check fails when it lags the pool's maximum by more than N slots (say 20), with hysteresis to avoid flapping and a floor so the balancer never ejects the whole pool; add passive outlier detection on error rate and latency. A check that proves only that the process is alive tells the balancer nothing about whether the node can answer correctly. Health checks must exercise what traffic needs — here, freshness relative to peers — because the balancer routes on the check, not on your dashboards.
In short

Make the health check fail when a node's data falls too far behind its peers, with slack so nodes do not flap and a floor so the whole pool is never ejected.

Why

A health check is the balancer's only model of a backend, so it must test the same dependency path and the same notion of 'can serve' that real traffic needs — for a replicated data service that means freshness, expressed relative to peers (lag against the pool's max) rather than an absolute number that drifts with load. Two guards make this safe: hysteresis so a node does not flap in and out at the threshold, and a panic floor (Envoy's default routes to all hosts when fewer than 50% are healthy) so a pool-wide lag does not eject everyone and turn a degradation into an outage. Passive outlier detection — ejecting on consecutive 5xx or latency — catches the failures the active check does not model. The web3 setting is incidental; the same rule applies to a read replica behind a database proxy.

Read the docs

7 Find what's broken

Here is the Envoy route config for a payments API. Customers report duplicate card charges after every payments backend deploy, and whenever the payments backend slows down its request rate rises ~10× while client traffic stays flat. Slow payments requests return 504 after exactly 5 s and are never retried. Which lines are responsible, and what do you change?

route_config:
  name: api_routes
  virtual_hosts:
    - name: api
      domains: ["api.example.com"]
      routes:
        - match: { prefix: "/v1/payments" }
          route:
            cluster: payments
            timeout: 5s
            retry_policy:
              retry_on: "5xx,connect-failure,reset"
              num_retries: 10
              per_try_timeout: 8s
              retry_back_off:
                base_interval: 0.025s
                max_interval: 0.25s
        - match: { prefix: "/v1/catalog" }
          route:
            cluster: catalog
            timeout: 2s
            retry_policy:
              retry_on: "connect-failure,refused-stream,retriable-status-codes"
              retriable_status_codes: [503]
              num_retries: 2
              per_try_timeout: 0.5s
In short

Lines 12, 13 and 14: do not retry POSTs on 5xx or reset, cap retries with a budget, and make the per-try timeout shorter than the route timeout.

What's broken
  • Line 12: retry_on: 5xx,...,reset on the payments route retries POSTs that may already have been processed: a backend that charges the card and then resets or 5xxs before replying gets the same charge again.
  • Line 13: num_retries: 10 with no retry budget means up to 11 attempts per request; during a slowdown the whole pool is hit with ~10× the client rate.
  • Line 14: per_try_timeout: 8s exceeds the route timeout: 5s, so the per-try timer can never fire; the overall timeout cuts the first slow attempt and Envoy does not retry a request whose total budget is exhausted.
Why

Three separate retry mistakes, each common. Retrying on 5xx or reset for a non-idempotent POST re-executes work that may have completed — payments need idempotency keys before they may be retried on anything but a failed connect. Ten retries with no budget turn a partial slowdown into a self-inflicted overload; Envoy's retry_budget bounds retries to a percentage of in-flight requests, which is the mechanism the SRE Book describes. And a per-try timeout must be shorter than the route timeout or it is dead code: the global timer fires first and a timed-out request is never retried. Line 16 is Envoy's default backoff (25 ms) and fine; the catalog route (lines 23–26) retries only conditions safe for GETs, with a per-try timeout that leaves room for retries within its 2 s deadline.

Read the docs

8 Scenario: what do you do next?

Every rolling deploy of catalog (Kubernetes Deployment, 12 pods, behind an L7 balancer with active health checks every 10 s and an unhealthy threshold of 3) produces a 20–40 s burst of 502s. Each burst spends about 0.5% of the monthly error budget, and the team deploys eight times a day. Pods pass readiness before receiving traffic. The prevailing explanation is "deploys are noisy".

Step 1. You own this now. What do you look at first?

  1. Slow the rollout (maxSurge 1, maxUnavailable 0) and see whether the burst shrinks. Changes a variable without evidence; you still would not know whether leaving or arriving pods cause the errors.
  2. Shorten the health-check interval to 1 s. You do not yet know health checks are involved, and no check frequency beats a pod that disappears instantly.
  3. Correlate the 502 timestamps with pod termination events from the rollout, and read the balancer's error reason for those 502s (nginx connect() failed (111) / upstream prematurely closed, or Envoy response flags UF/UR). Whether the burst lines up with pods leaving or pods arriving decides the diagnosis. Two cheap pieces of evidence — timing and the proxy's own error reason — split the hypothesis space in half before anything is changed.
  4. Add retries: 3 on 5xx at the balancer so the bursts are masked. Masks instead of diagnosing, risks duplicate writes on non-idempotent requests, and multiplies load if the backend really is failing.

Step 2. The 502s (reason: connection refused / connection reset) begin within a second of each pod's SIGTERM and stop ~25 s later — the balancer keeps sending to a pod for up to 30 s (3 failed checks × 10 s) after it stopped listening. The app exits 200 ms after SIGTERM. What is the fix?

  1. Make the pod drain before it stops listening: a preStop hook that waits longer than the balancer needs to observe unreadiness and remove the endpoint (10–15 s), then a graceful shutdown that stops accepting, finishes in-flight requests and exits, with terminationGracePeriodSeconds above the sum. Verify by deploying and confirming the 502 burst is gone. Connection draining is the mechanism: stop taking new work, finish existing work, then leave — and the balancer must learn you are leaving before you go.
  2. Send Connection: close on every response so the proxy never reuses a connection to a dying pod. Kills keepalive for all traffic (TIME_WAIT churn) and does nothing about new connections routed to a pod that already exited.
  3. Raise terminationGracePeriodSeconds to 60 without changing the app. The grace period only delays SIGKILL; the app still exits 200 ms after SIGTERM, long before the balancer notices.
  4. Health-check every 1 s with an unhealthy threshold of 1. Shrinks the window to ~1 s but keeps the race, and a threshold of 1 makes healthy pods flap out on a single slow response.

Step 3. Deploys are clean. The postmortem asks for a systemic action item. Which one?

  1. Switch every service to blue/green deployments. Blue/green still needs draining at the switch and doubles capacity for every service; the cause was the missing drain, not the strategy.
  2. Write a wiki page reminding teams to add preStop hooks. A reminder is not a mechanism; the next new service will miss it.
  3. Encode the graceful-shutdown contract (preStop ≥ endpoint-removal latency, SIGTERM handler, grace period) in the base Helm chart or an admission policy so every service inherits it, and alert on the 5xx ratio during rollouts as a deploy-quality SLI. A mechanism that applies to the next service automatically, plus a signal that catches regressions — not a reminder.
  4. Deploy only at night when traffic is lower. Shrinks the impact per deploy but keeps the defect, slows delivery, and moves errors to the on-call's sleep.
In short

Match the 502s to pod terminations first; the fix is a preStop wait plus graceful shutdown so the balancer stops sending before the pod exits.

Why

Active health checks are eventually consistent: a backend that stops listening at SIGTERM stays in rotation for endpoint-propagation time plus interval × threshold, and every request routed there in that window is a 502 (connection refused or reset). Draining inverts the order — announce departure (fail readiness), wait for the balancer to stop sending, finish in-flight work, then exit — and in Kubernetes the preStop sleep exists because endpoint removal runs asynchronously alongside termination. The interview shape: correlate first, fix the mechanism at the right layer, then make the fix the default for everyone.

Read the docs

9 Design round

Design the rate limiter for a public API served by 20 edge proxies across 3 regions. Peak load is 50,000 requests/s. There are 200,000 API keys; a typical key is limited to 1,000 requests/minute and a few hundred enterprise keys to 50,000/minute. Every request needs a decision, and the limiter may add at most 2 ms at p99 to a request whose own p99 is 40 ms. Say how you count, where the state lives, what happens when the store is unreachable, and how you will prove it works before launch.

  • Limits are per key across all 20 proxies — a key limited to 1,000/min must not get 20,000/min by spreading requests.
  • Added latency ≤ 2 ms p99; the regions are 60–90 ms apart, so a cross-region round trip per request is out.
  • Losing the limiter's store in one region must not take the API down.
In short

A strong answer keeps token buckets in a store per region, says how the global limit is split, picks fail-open or fail-closed with a short timeout, and tests in shadow mode first.

A strong answer covers
  • Chooses an algorithm with a reason: token bucket or sliding-window counters (bounded memory per key, controlled bursts) over a fixed window, which allows 2× the limit across a window boundary.
  • Places state per region (a Redis/Memcached shard set in each region, keyed by API key) because the 2 ms budget forbids a cross-region hop; states how the global limit is approximated — split per region by traffic share, or local counters synced every ~100 ms — and names the precision-vs-latency trade.
  • Sizes it: 200k keys × ~100 B ≈ 20 MB of state, trivially in memory; 50k ops/s across 3 regions ≈ 17k/s per region against ~100k+/s per shard; enterprise keys at 50k/min ≈ 830/s are not hot, but a true hot key would need per-proxy sub-buckets.
  • Decides fail-open vs fail-closed when the store is unreachable and justifies it (fail-open with alerting for most endpoints; fail-closed or a local fallback limit for abuse-sensitive ones), with a tight per-request timeout (~1 ms) so a slow store cannot breach the latency budget.
  • Keeps the decision to at most one local round trip (or a local cache with async reconciliation) and returns 429 with Retry-After, plus a shadow mode that logs decisions without enforcing.
  • Verification: load test at 2× peak with synthetic keys measuring added p99, kill the store in one region and observe the chosen failure mode, and compare shadow-mode decisions against ground truth for false positives before enforcing.
What a strong answer does
  • design quality: Algorithm chosen with reasons, regional state with an explicit approximation of the global limit, sized with numbers, an argued fail-open/closed decision, bounded per-request cost, and a verification plan including shadow mode.
  • tradeoffs: Two or more tradeoffs with a decision each: precision vs latency (regional approximation), availability vs abuse (fail-open), memory vs burst fairness (algorithm).
  • communication: Restates the numbers, derives sizes from them, presents the design as decisions with reasons, covers failure modes, ends with how success is measured.
Why

The design decisions interviewers expect: an algorithm chosen for burst behaviour and memory (token bucket or sliding window, not fixed window), state placed where the latency budget allows (regional, with an explicit story for how the global limit is approximated), sizes derived from the stated numbers, an argued fail-open/fail-closed decision with a tight timeout so the limiter cannot become the outage, and a verification plan that includes shadow mode. Candidates who reach for a single global Redis without noticing the cross-region RTT, or who never say what happens when the store is down, miss the two constraints that make this a design question.

Read the docs

Next lesson Network troubleshooting: layer-by-layer bisection with curl, dig, mtr, tcpdump and ss
Drill · HTTP versions, L4 vs L7 balancing, health checks, retries, and the 5xx taxonomy
0:00

Loading…