Skip to content
Tech Interview Prep
Technical interview guide

Load Balancing

Distributing traffic across multiple backend instances: algorithms, health checks, and layer 4 vs layer 7 balancing.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current HTTP/1.1, HTTP/2, QUIC, TLS 1.3, Forwarded, HAProxy 3.2, NGINX, Envoy, Kubernetes, AWS ELB, and Google Cloud Load Balancing references reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-6

Define readiness and liveness for a backend.

Answer

The 90-second answer. Readiness answers "should this instance get traffic right now?" Liveness answers "is this process wedged in a state a restart can fix?" The consequence is what separates them. A failed readiness check removes the pod from the Service's endpoints: the process keeps running, in-flight requests finish, no restart. A failed liveness check makes kubelet kill the container and restart it under the pod's restartPolicy. So readiness is a traffic decision, liveness is a recovery decision, and the test for putting anything in a liveness check is: would restarting this process plausibly fix it? If the answer is no, it does not belong there.

Mechanism. kubelet runs each probe every periodSeconds (default 10) with timeoutSeconds (default 1) and acts after failureThreshold consecutive failures (default 3). Readiness failure flips the pod's Ready condition to false; the endpoint controller drops the pod IP from the Endpoints/EndpointSlice and kube-proxy stops routing new connections to it. Liveness failure makes kubelet kill the container; the restart backoff doubles from 10s to a 5-minute cap and resets after the container has run 10 minutes. A startup probe suppresses both others until it passes, which is how you protect a slow boot from being killed.

YAML
# Kubernetes 1.29, Go HTTP server on :8080
startupProbe:
  httpGet: { path: /livez, port: 8080 }
  periodSeconds: 5
  failureThreshold: 60        # up to 5 min to boot
readinessProbe:
  httpGet: { path: /readyz, port: 8080 }
  periodSeconds: 5
  timeoutSeconds: 2
  failureThreshold: 2         # unready after ~10s
livenessProbe:
  httpGet: { path: /livez, port: 8080 }
  periodSeconds: 10
  timeoutSeconds: 2
  failureThreshold: 3         # restart after ~30s wedged
probewho actsactionprocess survives?
readinessendpoint controller, via kubelet statuspod removed from Endpointsyes
livenesskubeletcontainer killed, restarted per policyno
startupkubeletgates the other two until it passesyes

Trade-offs. The design decision interviewers push on is whether either check touches a shared dependency. Coupling readiness to the database is defensible: if the instance genuinely cannot serve, shedding traffic is correct. But it converts a partial outage into a total one: every pod goes unready and the Service has zero endpoints. Coupling liveness to a shared dependency is almost never right, because the dependency being down is not something restarting your process fixes. The deciding criterion is whether the instance can still do useful work: a service that can answer from cache should stay ready when the primary is down.

Failure modes.

  • Restart storm. Liveness probes a shared dependency; it blips; all replicas fail together, restart in lockstep, and hammer the recovering dependency with cold caches and fresh connection pools. Detect with kube_pod_container_status_restarts_total: alert when a pod exceeds ~3 restarts in 10 minutes.
  • Flapping readiness. An intermittent probe failure churns the pod in and out of endpoints, resetting connections at the load balancer. Detect via endpoint add/remove events and 5xx rate during removal windows.
  • Liveness too tight. With the config above, ~30s of unresponsiveness triggers a kill. A 45s stop-the-world GC pause or a saturated connection pool does exactly that, so you restart healthy pods. Detect by correlating restarts with GC pause and pool-wait metrics.
  • Readiness that always passes. Traffic lands on pods that cannot serve, and you get 5xx with a green readiness signal. Detect by comparing 5xx rate against readiness success rate.
  • Deadlock. Only liveness catches it; readiness alone leaves the pod in endpoints forever.

Keep readiness cheap and local: deep dependency checks belong in a separate endpoint or a synthetic monitor, not in the path that gates every request.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Choose Layer 4 or Layer 7 load balancing for a service.

Answer

Core answer (first 90 seconds). Ask two things: what protocol does the service speak, and what has to be decided per request. If it is HTTP/1.1, HTTP/2 or gRPC and you need to route on Host, path or header, retry a failed request on another backend, or get per-route metrics, choose L7. If it is a non-HTTP TCP/UDP protocol, or you need TLS to terminate at the backend (end-to-end encryption), or the client's TCP connection must reach the backend unchanged, choose L4. The default for an HTTP service behind a cloud load balancer is L7 (ALB, Envoy, Nginx http); L4 (NLB, HAProxy mode tcp, Nginx stream) is the choice when the protocol is not HTTP or the proxy must stay out of the payload.

Mechanism. An L4 balancer decides once, at connection setup: it sees the SYN, picks a backend from the pool, and from then on splices bytes in both directions. It never reads the payload, so it cannot see a path, a header or an HTTP status, which is exactly why it cannot retry a request: a retry is a new request, and it does not know where one request ends. It preserves the client's source IP for free, because it is a NAT/splice, not a terminating proxy.

An L7 balancer terminates the client TCP connection, parses HTTP, then opens a separate connection to the backend. That termination is what buys the features: routing on Host/path/header, retrying a 503 on a different backend, rewriting headers, and emitting per-request latency and status metrics. The cost is that the backend now sees the balancer's IP unless you forward the client address, via PROXY protocol (HAProxy PROXY v1/v2) or X-Forwarded-For, and the proxy needs the TLS certificate if it terminates TLS.

AxisL4L7
Decision pointconnection (SYN)each request
Routing keyIP:port, 5-tupleHost, path, header, method
Retry a failed requestnoyes (idempotent only)
Client IP at backendpreserved by spliceneeds PROXY protocol or XFF
TLSpassthrough or terminateterminates (needs cert)
Added latency~0.1 ms~0.5–2 ms per request
Throughputhundreds of k conn/s per hosttens of k RPS per core

Figures are typical and hardware-dependent; measure on your own traffic.

Trace. Client sends GET https://shop.example.com/api/orders.

  • L4: SYN arrives, balancer picks B2, splices. B2 sees source = balancer IP. If B2 returns 503, the client sees 503; the balancer cannot try B3.
  • L7: balancer terminates TLS, parses the request line, matches /api/* to a pool, picks B2, opens a new connection, adds X-Forwarded-For: 203.0.113.7, gets 503, retries on B3, returns 200. Metrics record route=/api/*, upstream=B3, status=200.

Failure modes.

  • L7 parser risk: a malformed or oversized request can stall or crash the proxy. Detect a proxy 400/502 spike with no matching backend log; mitigate with request size limits and header timeouts.
  • L7 retry storm: retrying non-idempotent POSTs duplicates writes. Detect duplicate order IDs or idempotency-key collisions; retry only idempotent methods or cap with a retry budget.
  • L4 connection pinning: a long-lived connection sticks to one backend, so a slow backend accumulates connections. Detect per-backend connection-count skew; mitigate with a max connection age or least-conn balancing.

When L4 wins. Non-HTTP protocols (databases, MQTT, custom binary), TLS passthrough for compliance, or raw throughput where per-request parsing is the bottleneck.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How does TLS termination at a load balancer work, and what are the performance and security trade-offs of TLS offloading versus TLS bridging?

Answer

In TLS termination, the load balancer acts as the cryptographic endpoint for the client's TLS session. It performs the TLS handshake (typically TLS 1.3 per RFC 8446 or TLS 1.2), verifies client certificates if mutual TLS (mTLS) is configured, decrypts inbound frames into plaintext HTTP requests (RFC 9110 / RFC 9112 / RFC 9113), and inspects or mutates L7 metadata before routing.

The two downstream architectural patterns are:

  1. TLS Offloading (Termination to Cleartext): The balancer decrypts traffic and forwards standard plaintext HTTP (TCP) to backend servers over the internal network.
  2. TLS Bridging (Termination and Re-encryption): The balancer decrypts traffic to execute L7 inspection, routing, and header mutation, then establishes a separate, upstream TLS session to the backend server.

Mechanisms and Packet Trace

Client                        Load Balancer                     Upstream Backend
  |                                 |                                  |
  |--- TLS 1.3 Handshake ---------->|                                  |
  |<-- Handshake Complete --------->|                                  |
  |--- Encrypted HTTP GET --------->|                                  |
  |                                 |-- [Option A: Offload] --------->|
  |                                 |   Plaintext HTTP (TCP port 80)   |
  |                                 |                                  |
  |                                 |-- [Option B: Bridging] -------->|
  |                                 |   New TLS Handshake + HTTP/1.1/2 |

Trade-offs: Offloading vs. Bridging

DimensionTLS OffloadingTLS Bridging (Re-encryption)
Backend CPU OverheadZero cryptographic load on backend; frees CPU cycles for business logic.Backends expend CPU on upstream TLS handshakes and symmetric cipher processing.
Upstream LatencyLow: reuse of persistent plaintext TCP pools; no upstream handshake RTT.Adds 1 RTT (TLS 1.3) or 2 RTTs (TLS 1.2) on upstream pool cold start / cache miss.
L7 Visibility & PolicyFull L7 inspection at proxy only (WAF, path routing, header transforms).Full L7 inspection at proxy and end-to-end zero-trust perimeter enforcement.
Internal Network SecurityVulnerable to internal eavesdropping, packet sniffing, or VPC lateral movement.Encrypted in flight; complies with strict zero-trust, PCI-DSS, or HIPAA requirements.
Certificate LifecycleCentralized: edge certificates live exclusively on the load balancer tier.Split/Dual: public edge certs on LB; internal PKI/private CAs managed on backends.

Critical Failure Modes and Mitigations

  • Client Context Erasure / Loop Redirection: When terminating to cleartext, backends see incoming TCP on port 80. If an application inspects r.URL.Scheme and issues a 301 Moved Permanently to https://, it creates an infinite redirect loop. Mitigation: The load balancer must inject standard Forwarded (RFC 7239: Forwarded: for=198.51.100.1;proto=https;host=example.com) or de-facto X-Forwarded-Proto: https and X-Forwarded-For headers, while stripping untrusted client-supplied variants at the edge.
  • Upstream Connection Churn in Bridging: Establishing short-lived TLS upstream connections causes ephemeral port exhaustion and excessive handshake compute on backends. Mitigation: Keep persistent upstream HTTP/1.1 or HTTP/2 connection pools warm with idle timeouts aligned to backend keep-alive limits.
  • mTLS Identity Stripping: Downstream client mTLS identities (RFC 8446) are terminated at the edge. In bridging or offloading, backends cannot read the client certificate directly. Mitigation: Sanitize and forward authenticated client certificate attributes (e.g., SAN, fingerprint) via authenticated, proxy-injected HTTP headers.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Select and validate a load-balancing algorithm.

Answer

Assumptions first. This is L7 HTTP balancing across N homogeneous backends behind one service, requests are not uniform in cost, and I control the proxy config. If any of those is false (L4 only, or backends with wildly different capacity) the answer changes, and I'll say how below.

The pick. Default to least-request with power-of-two-choices: sample two healthy backends, send to the one with fewer active requests. Envoy calls this least_request and its choice_count defaults to 2; HAProxy's leastconn is the connection-count analogue. Use plain round robin only when request cost is genuinely uniform and cheap: nginx and HAProxy both default to round robin, and Envoy's default load balancer is round robin, which is why so many services inherit it without deciding. Use consistent hashing (ketama, or Maglev with its 65537-entry table) only when a cache or shard sits behind the backend and affinity is worth the remapping cost.

Why P2C, not least-loaded. True least-loaded needs a global view, which means either a shared counter (a hot spot and a failure domain) or gossip (stale). Sampling two hosts is O(1), needs no coordination, and still avoids the herd: with random placement, the max load across n bins grows like log n / log log n; with two random choices it grows like log log n. That gap is the whole reason P2C exists.

AlgorithmNeedsFails when
Round robinUniform costOne 10× request lands behind a queue
Weighted RRKnown static capacityCapacity drifts, weights go stale
Least-request (P2C)Per-host active countA slow-but-alive host accumulates requests
RandomNothingSame as RR, with worse variance
Consistent hashStable keyHot key pins one backend; churn remaps

Validation. Don't argue, replay. Mirror production traffic (or a captured mix) at 1× and 3×, and record per backend: requests/s, bytes/s, active requests, p50/p99 latency, CPU. The signal you're looking for is skew, if p99 across backends diverges by more than ~2× while CPU is even, the algorithm is mis-assigning, not the hosts. Then test churn: with modulo hashing over 10 backends, adding one remaps ~90% of keys; consistent hashing remaps ~9%. If your cache hit rate collapses on deploy, that's the number that explains it. Finally, test failure: kill one backend and confirm the proxy ejects it within its health-check interval rather than dribbling requests into timeouts.

Failure modes to name. P2C's blind spot is a host that is slow but not failing: it holds requests longer, so its active count stays high, so P2C stops sending to it, which is correct, but if it's also the only host with a warm cache you've traded latency for hit rate. Detect it with per-host p99 divergence and Envoy's outlier detection (consecutive 5xx or gateway failures eject a host). Round robin's blind spot is cost variance: a single expensive endpoint can pin one backend at 100% CPU while its peers idle. Detect it by comparing per-backend CPU against request share. Consistent hashing's blind spot is a hot key: one key can saturate one host regardless of N. Detect it by per-key request rate; mitigate with key salting or a bounded-load variant that spills to the next host when the primary exceeds a load threshold.

When not to use P2C. If requests are uniform and cheap, round robin is simpler and has no state to get wrong. If you need strict affinity, hashing wins and you accept the hot-key risk. If backends are heterogeneous, weight them, but derive weights from measured capacity, not from instance size, and re-derive when the fleet changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Use consistent hashing for a stateful cache or shard.

Answer

Core answer (first 90 seconds)

Clarify one thing before designing: is this a cache, where a miss costs a re-fetch, or a shard holding authoritative state, where a remap costs a data move? The routing mechanics are identical; the cost of a miss is not, and that decides how much churn you tolerate.

Assume N backends. Hash every key to a point on a ring of 2^32 positions, and place each backend at many points on that ring (virtual nodes). A key belongs to the first node clockwise from its hash. Adding or removing a node only reassigns the arcs that node owns, so roughly 1/N of keys move instead of nearly all of them. That is the whole point: membership change is local, not global.

Mechanism

Without virtual nodes, one point per node, the arcs are wildly uneven: a node can own 5% or 40% of the ring. Giving each physical node V points (V=128–256 is typical) averages V independent arcs, and the relative standard deviation of a node's share falls as roughly 1/√V: ~9% at V=128, ~3% at V=1024. That is why virtual nodes exist: they smooth redistribution, they do not change the 1/N property.

Python
import hashlib, bisect

def h(x: bytes) -> int:
    return int.from_bytes(hashlib.md5(x).digest()[:4], "big")  # 32-bit ring

class Ring:
    def __init__(self, nodes, vnodes=128):
        self.ring = []
        for n in nodes:
            for i in range(vnodes):
                self.ring.append((h(f"{n}#{i}".encode()), n))
        self.ring.sort()
        self.positions = [p for p, _ in self.ring]

    def node_for(self, key: str) -> str:
        pos = h(key.encode())
        i = bisect.bisect(self.positions, pos) % len(self.ring)
        return self.ring[i][1]

MD5 is what Ketama (libmemcached) uses; MurmurHash3 is Cassandra's default partitioner; xxHash is faster. None of these need to be cryptographic unless keys are attacker-controlled, then use a keyed hash (SipHash) so an adversary cannot force collisions onto one node.

Worked trace

Nodes A, B, C, V=128. Add D. D inserts 128 points and takes the arcs it lands in: about 1/4 of the ring. With 1000 keys, ~250 move to D; the other ~750 stay put. Compare hash(key) % N: going 3→4 nodes, only keys where h%3 == h%4 stay, which is 3/12 = 25%, so ~750 of 1000 keys remap. Same resize, 3× the churn.

Trade-offs

ApproachKeys moved on resizeLookupUse when
Modulo % N~75% (3→4)O(1)Fixed node count
Consistent hashing~1/NO(log V·N)Elastic membership
Rendezvous (HRW)~1/NO(N)Small N, no ring to maintain
Redis Cluster slotswhole slotsO(1)You want explicit reshard control

Consistent hashing is the wrong choice when key cardinality is tiny: a handful of keys cannot be spread evenly no matter how many virtual nodes you add, or when you can afford a directory service that assigns keys explicitly.

Failure modes

  • Hot key. One key maps to exactly one node; virtual nodes do nothing for it. Detect via per-node request skew. Mitigate by salting the key into sub-keys, request coalescing, or a local cache in front.
  • Membership flap. A node marked down then up churns the ring and spikes misses. Detect via ring-version churn and miss-rate correlation. Mitigate with a failure detector (phi-accrual) plus hysteresis before removing a node.
  • Partial control-plane views. Two clients disagree on the ring, so the same key routes to different nodes: a miss for a cache, split-brain for a shard. Detect via cross-node miss correlation. Mitigate with a versioned ring and quorum config propagation.
  • Too few virtual nodes. Load imbalance shows up as a persistently hot node. Detect by comparing each node's share against 1/N; raise V if the spread exceeds ~2/√V.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Tune a load balancer's upstream connection pools.

Answer

I'd start by clarifying what the pool is for: amortizing TCP and TLS handshakes to upstreams while keeping the number of sockets bounded and the set of endpoints fresh. The tuning knobs split into three groups: size, lifetime, and health/discovery. I'll assume Envoy as the data plane, since that's what most staff-level interviews mean by a programmable load balancer, but the same reasoning applies to NGINX or HAProxy.

Assume HTTP/1.1 or HTTP/2 to upstreams, a few hundred to a few thousand requests per second per instance, and upstreams that are mostly stable but occasionally restart or get replaced by DNS.

Size the pool from concurrency, not from request rate. For HTTP/1.1, each in-flight request needs its own connection, so max_connections should be at least the peak concurrent requests per upstream endpoint. For HTTP/2, one connection carries many streams, so you size by streams: max_connections can be small, 2 to 4 per endpoint, and max_concurrent_streams should match what the upstream can handle, typically 100 to 250. Set max_pending_requests to absorb bursts without failing fast; if it's too low you get 503s under load, too high and you queue requests until timeouts.

Lifetime matters more than most people think. Idle timeout should be shorter than the upstream's own idle timeout and shorter than any NAT or firewall idle timeout. Envoy's default idle_timeout is 1 hour, which is too long for most cloud environments where NAT drops idle TCP after 5 to 15 minutes. Set it to 60 to 120 seconds. Max lifetime, max_requests_per_connection, should force periodic re-resolution of DNS and rebalancing. Set it to 1000 to 10000 requests, or a few minutes. Without it, a connection can live for hours and keep sending traffic to an endpoint that DNS has already removed.

When DNS changes, existing connections stay open to the old IP. You need either short max lifetime or active health checking that ejects the old endpoint. Envoy's outlier detection can eject a host after a number of consecutive 5xx or connection failures; set consecutive_5xx to 5 and base_ejection_time to 30s. But outlier detection only works if you have enough hosts; with 2 to 3 upstreams, ejecting one can cause a cascade.

TLS session resumption reduces handshake cost. If you rotate certificates, the pool must be invalidated; otherwise you keep using the old cert until connections expire. Set max lifetime to less than the cert rotation interval, or trigger a drain.

The classic failure is pool exhaustion: max_connections is hit, pending requests queue, p99 latency climbs (for example, from 40 ms to 180 ms once the pool saturates at 20 connections) then timeouts. Detect it by monitoring pool wait time and pending requests. Another is stale connections after DNS change: you see traffic going to a decommissioned IP, and errors only when the old host finally dies. Detect by comparing the set of upstream IPs in the pool to the current DNS answer. A third is half-close or GOAWAY: if the upstream sends GOAWAY, the connection should be drained and not reused; if you ignore it, you get 502s. Envoy handles this, but you need to ensure max_requests_per_connection is not so high that a connection outlives a GOAWAY.

The tension is warm capacity versus freshness. More connections and longer lifetimes mean fewer handshakes and lower latency, but more sockets and staler endpoints. The deciding criteria: if your upstreams are stable and handshakes are expensive (TLS, cross-region) lean toward longer lifetimes and larger pools. If your upstreams are ephemeral (Kubernetes pods, autoscaling) lean toward short lifetimes and aggressive health checking.

Here's a starting table:

SettingStarting valueWhy
max_connections (per endpoint)2× peak concurrent requestsHTTP/1.1 needs one conn per request; HTTP/2 can be 2–4
max_pending_requests2× max_connectionsAbsorb bursts without failing fast
idle_timeout60sShorter than NAT/firewall idle (often 5–15 min)
max_requests_per_connection1000Forces DNS re-resolution and rebalancing
max_concurrent_streams (HTTP/2)100–250Match upstream capacity; too high causes head-of-line blocking
outlier detection consecutive_5xx5Eject a failing host quickly without flapping
base_ejection_time30sGive the host time to recover

That's the core. The follow-up I'd expect is how to measure it: track connection reuse ratio, handshake time, pool wait time, active streams, and reset counts. Then test backend restart, drain, DNS change, certificate rotation, idle timeout, burst, slow stream, and one connection failure.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Design layered backend health checks.

Answer

Core answer

Four layers, each answering one question, each with a different blast radius when it fails.

layerquestioncheckfailure action
livenessprocess alive, listener bound?TCP connect, or GET /livez returning 200 without touching downstreamrestart the process
readinesscan this instance take new work now?GET /readyz, 503 during startup, drain, or local resource exhaustionremove from load balancer, do not restart
local functionaldoes the app's own critical path work?bounded SELECT 1 against the DB pool with a 500ms deadlineremove from rotation
dependencyare downstreams reachable?per-dependency probe, reported not acted on fleet-widedegrade, do not eject everything

The reason to split them is blast radius. If liveness checks a dependency, a 35-second dependency blip fails liveness on every pod at once. Kubernetes defaults are periodSeconds 10, failureThreshold 3: 30s of failure triggers a restart. Restarting every pod during a dependency outage removes the capacity that would have served cached or degraded responses, and the restart storm slows the dependency's recovery.

Mechanism and settings

Kubernetes probe defaults before you tune: initialDelaySeconds 0, periodSeconds 10, timeoutSeconds 1, failureThreshold 3, successThreshold 1. A 1s timeout is aggressive for a functional probe that touches a DB; set timeoutSeconds 2–3 and failureThreshold 3 so one slow query does not flap the instance.

For the active check, pick one cheap operation with exact semantics. A TCP connect proves the listener is bound; it does not prove the handler can serve. An HTTP GET on /readyz that runs SELECT 1 with a 500ms context deadline proves the pool can hand out a connection. State the success condition exactly: HTTP 200 and body ok, anything else fails.

Passive evidence is free and catches what active checks miss. Envoy outlier detection defaults: consecutive_5xx 5, base_ejection_time 30s, max_ejection_percent 10. That last one is the guard against a shared dependency ejecting all capacity, if every instance fails the same downstream, you eject at most 10% and keep serving errors rather than serving nothing.

Trade-offs

Active vs passive: an active check costs one request per period per instance. At periodSeconds 10 and 500 instances that is 50 req/s of pure health traffic. Passive costs nothing but only sees instances that receive traffic, so a cold or newly scaled instance is never evaluated. Use passive when traffic is steady and spread; add active when instances can be idle.

Consecutive thresholds vs rate-based: consecutive counts are simple and predictable but slow to react (5 × 10s = 50s). Rate-based (50% errors over 30s) reacts faster but flaps on low-traffic instances. For low-traffic services, require a minimum request count before the rate is meaningful.

Failure modes and detection

  • Slow: p99 latency crosses the probe timeout. Compare probe latency histogram to the timeout; alert when p99 > 0.5 × timeout.
  • Partial: one shard or one replica of a dependency is down. Detect per-dependency probe results, not a single aggregate.
  • Stale: health cached from a previous check. Put a monotonic check counter in the response body; if it does not advance, the probe is cached.
  • Overloaded: the health check itself adds load. Track health-check QPS as a fraction of total; keep it under 1%.
  • Dependency-failed: downstream returns errors. Detect via passive 5xx counts; eject with the max_ejection_percent cap.
  • Flapping: instance alternates ready/not-ready. Count readiness transitions per hour; add recovery hysteresis: require successThreshold 2–3 consecutive passes before returning to rotation.

Worked trace

Instance with periodSeconds 10, timeoutSeconds 2, failureThreshold 3, successThreshold 2. DB pool saturates at 20 connections; the probe query waits 2.1s.

t=0s: probe times out (2.1s > 2s). failure count 1. t=10s: timeout. failure count 2. t=20s: timeout. failure count 3 → readiness 503, removed from LB. t=30s: pool drains, query returns in 40ms. success count 1. t=40s: success. success count 2 → back in rotation.

Removal window: 20s to 40s = 20s. Without successThreshold 2 it would return at t=30s and immediately fail again if the pool re-saturated.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design health dependency isolation.

Answer

Assumptions first. A service with N replicas behind a load balancer (Envoy, or a cloud LB), plus shared dependencies: a primary datastore, an auth service, a cache, a search index. The failure I am designing against is correlated ejection: one shared dependency blips, every replica's health check fails at the same instant, the LB removes all endpoints, and a partial degradation becomes a total outage. The design rule that follows is: health signals stay local and scoped, and ejection is capped so no single dependency can empty the pool.

Classify dependencies by blast radius, not by importance.

DependencyClassHealth signalOn failure
Primary DBhard for writespassive 5xx on write routesshed writes, serve reads from cache
Auth servicehard for authenticated routesroute-scoped /healthz/auth503 on those routes only
Search indexroute-scoped/healthz/searchdisable /search, keep the rest
Recommendationsoptionalpassive latencyreturn an empty list

Readiness must be local. A Kubernetes readiness probe that dials the DB means the kubelet marks every pod NotReady on a DB blip; endpoints drop to zero and kube-proxy has nothing to route to. Readiness should check only what the process owns: listener bound, config loaded, connection pool initialized. No shared dependency in the readiness path. Default probe timing (periodSeconds: 10, failureThreshold: 3) is fine once the check is local.

Prefer passive detection over active checks for shared deps. Envoy outlier detection ejects individual endpoints on consecutive_5xx (default 5) and is capped by max_ejection_percent (default 10%). The cap is the whole point: with 20 replicas at 10%, at most 2 are ejected and 18 keep serving. Set it to 100% and one DB blip ejects all 20. Active health checks (health_check with an interval) probe every endpoint on a timer, if that probe touches a shared dependency, all endpoints fail together, which is exactly the amplification you are trying to avoid. Use active checks only for local liveness.

The trade-off is explicit. Capping ejection trades error rate for availability: you keep sending some traffic to a sick backend. That is the right call when the alternative is zero capacity, and the wrong call for a write path where a wrong answer is worse than a 503. Decide per route, not per service.

Fallback and shedding. Envoy priority levels give a primary pool and a fallback cluster that returns a cached or degraded response. A direct_response lets the LB answer 503 with Retry-After instead of hanging when every backend is ejected: the balancer must be able to serve an error without a backend.

Failure modes and how you see them.

  • Correlated ejection: healthy-endpoint count drops below 50% while upstream 5xx is flat. Alert on the endpoint gauge, not on error rate.
  • Flapping: a dependency recovers and fails repeatedly; endpoints oscillate. base_ejection_time (default 30s) with backoff, and watch ejection churn.
  • Control-plane loss: if health depends on xDS, losing the control plane freezes the last config. Detect via config-reload staleness, not via request errors.

Test matrix: each dependency alone, a shared dependency down, a slow dependency (latency injection, not just errors), partial tenant impact, recovery flapping, and control-plane loss. Each test asserts the endpoint count stays above the cap and the surviving routes still answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Preserve client address and scheme safely through proxies.

Answer

The first 90 seconds

The questions that decide this are: how many hops do I control between the TLS terminator and the app, and is there any path that reaches the app without passing through them? A client address is trustworthy only because a hop I control put it there, so I strip every inbound Forwarded and X-Forwarded-* header at the first trusted edge, have each hop append exactly one canonical value, and read it back by counting from the right. Scheme is the same problem: X-Forwarded-Proto: https is meaningless unless the TLS terminator wrote it. And the address is a logging, rate-limiting and geo input: never an authorization decision.

Why the edge is the whole game

nginx behind an ALB, configured with set_real_ip_from 10.0.1.0/24; real_ip_header X-Forwarded-For; real_ip_recursive on;, walks the header from the right, discarding entries that fall inside trusted ranges, and sets $remote_addr to the first entry it does not trust. That is correct only because the ALB overwrote the header. If any path lets a client hand that header to nginx directly, logs, rate limits and allowlists are all attacker-controlled. Envoy expresses the same rule as xff_num_trusted_hops (count in from the right) or use_remote_address: true (ignore the header, use the connection).

Trace: client → CDN (198.51.100.0/24) → ALB (10.0.1.0/24) → nginx. The client sends X-Forwarded-For: 1.1.1.1; the CDN appends the peer it saw, the ALB appends the CDN, nginx appends the ALB:

1.1.1.1, 203.0.113.9, 198.51.100.7, 10.0.1.5

Two proxies I control sit in front of nginx, so the client is the third from the right: 203.0.113.9. The leftmost entry is whatever the attacker wrote. The hop count, not a delimiter position, is the boundary.

Strict parsing, concretely

A parser laxer than the one the WAF or the allowlist used is a bypass. All of these mean 127.0.0.1: ::ffff:127.0.0.1, its hex spelling ::ffff:7f00:1, and the bare integer 2130706433; 127.000.000.001 too, wherever leading zeros are read as octal. [::1]:443 carries brackets and a port that most parsers reject outright. RFC 7239 additionally allows for=unknown and for=_hidden, and quoted values can contain commas: splitting on , without honouring quotes truncates the list. In Go: strip brackets and port, netip.ParseAddr, then .Unmap() so the mapped form collapses to the IPv4 address and compares equal to it.

Trade-offs

mechanismcarriesclient-forgeablecost
PROXY protocol v2 (send-proxy-v2)src/dst addr+port, TLS-seen TLVno: out of band, not an HTTP headerevery hop must speak it; accept-proxy on an internet-facing bind is spoofable; no scheme
Forwarded (RFC 7239)for, proto, host, byyes, unless every hop sanitisescross-org friendly, parser variance
X-Forwarded-*de facto equivalentyesuniversal support, no standard

If I own every hop, PROXY v2 plus one assertion of proto at the terminator is hardest to forge. If I do not, I sanitise at my own edge and count from the right.

Failure modes

  • Direct-to-backend bypass: a request whose TCP peer is outside the trusted CIDRs but which carries an XFF header. Alert on it; block it at the security group. This is the bug that makes every other mitigation decoration.
  • Scheme-driven open redirect: X-Forwarded-Host and -Proto echoed into an absolute URL. Build URLs from configured base, not the header.
  • Header bloat: nginx's default large_client_header_buffers 4 8k bounds one line at 8k and rejects beyond it; without a cap a 500-entry XFF costs memory and log volume.
  • Rate limits keyed on a spoofable address are defeated by rotating it: key on the connection address or the session.

Tests: single and repeated X-Forwarded-For, mixed casing, Forwarded with quoted commas and _hidden, mapped and integer IPv6 forms, and a request straight to every backend port.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design TLS termination and upstream re-encryption.

Answer

The 90-second answer

Terminate client TLS at the edge, then open a separate TLS connection to the backend. Two handshakes, two TCP connections, two sequence spaces: the backend never sees the client's TCP stream. The edge holds the public cert and key; the backend holds its own cert and key, and the edge verifies it.

Why re-encrypt at all if the edge already authenticated the client? Because the edge authenticated the client, not the backend. Plaintext on the internal hop means any process that can reach the backend (a compromised pod, a hijacked endpoint, a node running a packet capture) reads the request body and the identity headers the edge attached. Re-encryption gives you confidentiality on that hop plus server authentication of the backend, so a rogue endpoint can't impersonate it.

Config

nginx, checked against 1.25:

location / {
    proxy_pass https://backend;
    proxy_ssl_server_name on;              # send SNI
    proxy_ssl_name backend.internal;       # SNI + verification name
    proxy_ssl_verify on;                   # default is OFF
    proxy_ssl_verify_depth 2;
    proxy_ssl_trusted_certificate /etc/ssl/backend_ca.pem;
    proxy_ssl_protocols TLSv1.2 TLSv1.3;
}

proxy_ssl_verify defaults to off: that is the single most common misconfiguration here: the edge encrypts to the backend but accepts any certificate, so re-encryption buys confidentiality and nothing else. Envoy's equivalent is an UpstreamTlsContext with auto_sni and auto_san_validation, or an explicit sni plus match_subject_alt_names.

Choosing the mode

modewhencost
terminate onlyhop is loopback or a single-tenant hostplaintext on the wire and in backend memory
terminate + re-encryptshared VPC, multi-tenant cluster, compliance boundarysecond handshake, 1 extra RTT on TLS 1.3
mesh mTLS (Istio/SPIRE)many services, need per-service identity and auto rotationsidecar CPU/memory, control-plane dependency

Identity propagation

The edge knows the client cert subject. Passing it as a plain header (X-Forwarded-Client-Cert) is forgeable by anything that can reach the backend. Two defensible options: mTLS on the upstream hop so the backend reads the peer cert, or the edge signs a short-lived JWT (SPIFFE JWT-SVID) that the backend verifies. Either way the backend must also enforce network policy so only the edge can connect.

Failure modes

  • Session resumption defeats revocation. TLS 1.3 PSK tickets let a client resume without a full handshake, so a revoked client cert keeps working until the ticket expires. Trace: client completes mTLS at t=0 and gets a ticket; cert is revoked at t=60s; client resumes at t=120s with the ticket. No cert is presented, the edge accepts. Fix: disable tickets on mTLS listeners, or cap ticket lifetime below your revocation SLA.
  • Ticket key sharing. If every edge node shares one ssl_session_ticket_key, a ticket issued by node A resumes on node B. Rotate with overlap: keep the old key for decryption, issue with the new one.
  • Downgrade. Pin TLSv1.2 TLSv1.3; TLS 1.0/1.1 are deprecated, and the fallback SCSV only protects against a broken server, not a misconfigured client policy.
  • Backend cert expiry. The edge fails closed: 502s, not a plaintext fallback. Alert on proxy_ssl_verify failures, not just on 5xx rate.
  • Direct-backend bypass. If the backend is reachable without going through the edge, everything above is optional. Network policy must make the edge the only path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Decide whether to use session affinity.

Answer

Core answer

Assume a stateless-capable app tier and a shared cache in the same region. On those assumptions, default to no affinity. Ask what state actually has to stay on one backend. If it's a session blob (user ID, cart, CSRF token) put it in Redis or DynamoDB and turn stickiness off. A same-AZ Redis GET is roughly 0.5 ms; that is cheaper than the availability you give up. If the state is a signed token the client carries, you need no affinity at all.

Use affinity when the state is too large or too hot to externalize: an in-memory game world, a WebSocket connection, a per-connection TLS session, or a legacy app whose session store you cannot change this quarter. Then affinity is a deliberate availability trade, not a default.

Why affinity breaks

The mechanism is the remap. With modulo routing, backend = hash(key) % N, removing one of N backends moves almost every key: at N=10, only keys where k mod 10 == k mod 9 stay put, which is 1/9 of them, so ~89% of sessions land on a different backend and lose their in-memory state. Consistent hashing (Envoy's ring hash or Maglev, HAProxy's stick-table) moves only the keys the dead node owned, ~1/N, so 10% at N=10. The hashing algorithm, not the cookie, decides how bad a scale event is.

nginx ip_hash hashes the first three octets of the IPv4 address, so an entire /24 shares one backend: a corporate NAT becomes a single hot key. HAProxy stick on with a stick-table gives per-key tracking and rate limits. ALB's duration-based cookie is AWSALB, configurable from 1 second to 7 days.

Trade-offs

Externalized stateSticky sessions
per-request latency+0.5–2 ms0
scale-outinstant, any backendremaps ~1/N of sessions
backend lossinvisible to clientsthose sessions lose state
ops burdenrun Redis/DynamoDBLB config only

Failure modes

  • Backend loss. Sticky clients whose cookie points at the dead target are re-routed only once the LB removes it. Detection: 5xx concentrated on one target, session-error rate. Blast radius: 1/N of sessions.
  • Drain during deploy. Deregistration delay (ALB default 300 s) must exceed the cookie TTL, or clients keep arriving at a draining target. Detection: 502/503 during deploy windows.
  • Cookie tamper. If the LB trusts a client-supplied backend ID, a client pins itself to one backend: a self-inflicted hot key, or routing to an unpatched instance. Sign the cookie with an HMAC or use an LB-generated one.
  • Hot tenant. One tenant's sessions land on one backend. Detection: per-target request-count skew in LB metrics.

Decision

Keep affinity only when the state is more than a few hundred KB per session, write-heavy, and you cannot externalize it this quarter. Otherwise externalize the state and turn stickiness off.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Balance multiplexed HTTP/2 upstream traffic.

Answer

Assume an L7 proxy (Envoy, nginx, HAProxy in HTTP mode) in front of N identical backends, and clients that multiplex: gRPC, or a browser on HTTP/2. The short answer: balance on active streams or requests per backend, not on connections, and cap how many streams one connection may carry.

Why connection counting breaks. HTTP/2 lets one TCP connection carry many concurrent streams, and RFC 7540 sets no default limit on SETTINGS_MAX_CONCURRENT_STREAMS. A round-robin or least-connections balancer sees that client as one unit of load. If it opens one connection and drives 200 streams, the backend it lands on does 200 units of work while its peers do one each.

Worked example, hypothetical numbers: 4 backends, 100 connections round-robined 25 apiece. One hot client opens a single connection and drives 200 concurrent streams. That backend now carries 200 + 24 = 224 request-units; the other three carry 25 each. Roughly 9x skew, and the loaded backend's p99 climbs from ~40 ms to several hundred ms as its queue saturates. Least-connections does not fix this: the connection count is still 1.

What to use instead. A request/stream-aware policy. Envoy's least_request with choice_count: 2 (power of two choices) samples two backends and picks the one with fewer active requests; that is the right default for multiplexed traffic. Round-robin is fine only when each connection carries roughly one request. L4 balancers (kube-proxy iptables/IPVS, HAProxy in tcp mode) cannot see streams at all; if you must keep them, terminate HTTP/2 at an L7 tier first.

policycountsmultiplexed trafficcost
round robinconnectionsnocheapest
least connectionsconnectionsnocheap
least request / P2Cactive requestsyesper-request accounting, L7 termination
hash on clientconnectionsno, and pins hot clientssticky, uneven

Settings that decide the outcome.

  • SETTINGS_MAX_CONCURRENT_STREAMS: RFC default is unlimited; nginx's http2_max_concurrent_streams defaults to 128, Go's HTTP/2 server to 250. Set it to what a backend can actually run concurrently. When the client hits the cap it queues streams or opens another connection.
  • Flow control: SETTINGS_INITIAL_WINDOW_SIZE defaults to 65,535 bytes, and the connection-level window is also 65,535 by default and shared by every stream on that connection. On a high-BDP link the connection window, not the stream window, is the throughput ceiling. Envoy raises both to 256 MiB by default; nginx leaves them at 64 KiB.
  • Connection age / max requests: recycle connections (Envoy max_requests_per_connection, nginx keepalive_requests, default 1000) so a long-lived connection does not pin a backend, but stagger the recycle or you get a handshake storm.

Failure modes and their signals.

  • Stream-limit exhaustion: backend at its cap, client queues. Detect via pending-stream gauge and RST_STREAM with REFUSED_STREAM (0x7) rate. Symptom: p99 spikes while p50 stays flat.
  • Connection-window starvation: one large response consumes the shared connection window and stalls every other stream on that connection. Detect by per-stream latency diverging from per-connection latency, connection window near zero.
  • GOAWAY race: the server sends GOAWAY with last-stream-id; streams above it were never processed and must be retried on a new connection. Detect via GOAWAY and retry counters. Cost: duplicated work if retries are not idempotent.
  • TCP head-of-line blocking: one lost packet stalls all streams on the connection. Detect by retransmit rate correlated with p99 across unrelated endpoints.

Test with one hot client driving many streams, mixed large and small responses, a slow consumer, a mid-flight connection reset, a backend drain, and a stream-limit hit: watching per-backend stream skew and tail latency, not connection counts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Calibrate heterogeneous backend weights.

Answer

Core answer (first 60–120 seconds)

Weights are relative shares of traffic, so the only defensible basis is measured sustainable capacity under the real request mix at the latency/error objective, not vCPU count, not instance type. Assumptions I'd state up front: the cohorts serve the same request mix (or I can normalize for it), the SLO is per-cohort p99, and weights are relative integers, not absolute rates.

Procedure: pick a representative request mix (top endpoints by traffic, weighted by their share), drive each cohort to its p99 objective in isolation, record sustainable RPS, and set weights proportional to that. Canary 5% of traffic and compare normalized load (rps per weight unit), p99, and error rate per cohort. If a cohort's p99 rises while its share is unchanged, its weight is too high.

Alternatives

schemebasisuse whendon't use when
Static weightsmeasured capacityfleet stable, cohorts differ by hardwarecapacity changes at runtime (cache warm, noisy neighbor)
Utilization-driven dynamicCPU/mem/conn feedbacklong-lived, homogeneous request mixrequest cost varies per endpoint: CPU ≠ capacity
EWMA / peak-EWMA (P2C)observed latency × outstanding requestsrequest cost varies, want per-request adaptationyou need a hard capacity guarantee; it reacts, it doesn't plan

Envoy's least-request is P2C over active requests (choice_count default 2). Finagle's peak-EWMA multiplies an EWMA of latency by outstanding requests: that's the variant that handles slow endpoints. Linkerd 2 defaults to P2C over an EWMA of latency.

Mechanism

Why representative request cost drives weight: a cohort's capacity is requests/sec at the SLO, and that depends on the mix. A cohort with 2× the CPU but a cache-miss-heavy endpoint may have less than 2× the capacity. Weighting by CPU over-serves the cheap-endpoint cohort.

Why oscillation: weight is both cause and effect of latency. More weight → more queueing → higher latency → lower weight → less queueing → lower latency → higher weight. That's a control loop whose delay equals your measurement window; if loop gain × delay > 1 it oscillates. Damping: EWMA the signal over a window several times the control interval, cap change per interval (e.g. ±10% per 30 s), and add a deadband so small latency differences don't move weight.

Normalization: compare cohorts on rps per weight unit at the same SLO, not raw latency. Raw latency differs because the request mix differs.

Worked check

Cohort A: 8 vCPU, measured 4,000 rps at p99 = 50 ms. Cohort B: 4 vCPU, measured 1,800 rps at p99 = 50 ms. Ratio 4000:1800 = 2.22:1, so weights 22:10 (or 11:5).

Set 1:1 by vCPU instead and total demand of 5,800 rps gives B 2,900 rps = 161% of its 1,800 rps capacity. Its queue grows, p99 goes from 50 ms to seconds, and it starts returning 5xx. That's the failure the weights exist to prevent.

Failure modes

  • Cold instance: empty cache/JIT means its first 30–60 s capacity is a fraction of steady state. Envoy's slow_start_window (default disabled) ramps weight from min_weight_percent (default 10) to full over that window; HAProxy's slowstart (default 0) does the same. Without it, a new pod takes full weight and times out.
  • Health-check flap: Envoy's healthy_panic_threshold defaults to 50%. Below that it routes to all hosts including unhealthy ones, so a flapping cohort takes traffic it can't serve. Watch the panic-mode gauge.
  • Stale weights after a deploy: a new binary with different request cost invalidates the measurement. Re-measure after runtime, config, or model changes.
  • Zone failure: losing a zone removes its capacity; weights tuned to steady state push survivors over. Keep headroom or re-derive weights automatically.

Config specifics

Envoy: load_balancing_weight per endpoint (default 1), slow_start_window, aggression (default 1.0), min_weight_percent (default 10), outlier detection base_ejection_time 30 s and max_ejection_percent 10. HAProxy: server weight default 1, range 0–256, slowstart default 0. NGINX: weight default 1, max_fails default 1, fail_timeout default 10 s.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Set a timeout hierarchy for an HTTP service.

Answer

Core answer

Clarify two things before touching a config: who owns the deadline, and is the caller user-facing? Assume a user-facing API with a 2s p99 SLO that calls one downstream service. The hierarchy is built backwards from that 2s, not forwards from each stage's comfort zone.

Reserve the cleanup margin first, 150ms to serialize the response and release the connection, leaving 1850ms of work budget. Then split that across stages using each stage's own measured tail, not its mean. A stage budget set at the median kills half your traffic; set each at roughly p99 of that stage's own latency distribution, then check the sum fits inside the total.

StageBudgetWhy this number
DNS50ms warm / 200ms coldresolver cache hit vs. a real lookup
TCP connect200mscovers SYN + one retransmit
TLS handshake200ms1-RTT plus session ticket
Upstream pool queue100mswaiting for a free connection
Request write50msheaders + small body
Response header (TTFB)800msthe downstream's own p99
Response body400msinter-chunk idle, not total
Sum1800ms50ms slack under the 1850ms work budget

Propagate an absolute deadline, not a relative timeout. gRPC carries it in the grpc-timeout header; Envoy in x-envoy-upstream-rq-timeout-ms. A request that spent 300ms queued at the gateway must arrive downstream with 1550ms left, not a fresh 1850ms.

Go
// Go 1.22
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()

tr := &http.Transport{
    DialContext: (&net.Dialer{
        Timeout: 200 * time.Millisecond, // DNS + connect, Go resolves inside Dial
    }).DialContext,
    TLSHandshakeTimeout:   200 * time.Millisecond,
    ResponseHeaderTimeout: 800 * time.Millisecond, // TTFB only, not the body
    IdleConnTimeout:       90 * time.Second,
    MaxIdleConnsPerHost:   32,
}
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)

Mechanism

Why tails. A timeout is a hard cutoff, so it must sit above the tail you intend to serve. Budgeting from the mean means the p99 request, the one your SLO is written about, is guaranteed to be cut off.

Why downstream shorter. If the caller's deadline is 2s and it calls a downstream with a 5s timeout, the caller gives up first. The downstream keeps working on a request nobody will read: wasted capacity, and the caller logs "timeout" without knowing whether the downstream was slow or dead. Downstream timeout = remaining caller budget minus the caller's own post-processing.

What exhaustion does. The stage aborts, the connection is torn down or returned to the pool, and the error must be classified: deadline exceeded vs. context canceled vs. connection reset, because retry policy differs for each. A canceled context is not retryable; a reset is.

Trade-offs

A single total timeout is simple and catches everything, but you cannot tell which stage blew or tune it. Per-stage budgets give diagnosis but leak: every stage can be individually fine while the sum exceeds the total. That is why the sum check above is mandatory.

Relative timeouts reset at each hop and quietly extend the end-to-end time; absolute deadlines survive queueing. Fail-fast is right for user-facing reads; retry-with-remaining-budget is right for idempotent writes, and the retry must consume the remaining deadline, never a fresh one.

Defaults you inherit if you set nothing: Go's http.DefaultTransport uses a 30s dial timeout, 10s TLS, 90s idle, and MaxIdleConnsPerHost: 2; Python requests has no default timeout and hangs forever; OkHttp defaults connect/read/write to 10s with callTimeout unset; nginx proxy_read_timeout is 60s; an ALB idle timeout is 60s.

Failure modes

  • Slow connect: SYN retransmits; detect via connect-duration histogram, tune tcp_syn_retries.
  • Slowloris upload: client dribbles headers; the read timeout must be per-read, not per-request.
  • Stalled body: TTFB is fine, then the body stalls. ResponseHeaderTimeout does not cover this; the body read needs its own deadline.
  • Pool queue: every stage is fast but requests wait for a connection and blow the total. Watch pool wait-time separately.
  • Cancellation race: caller times out, downstream still commits a write. Needs idempotency keys.
  • Retry overrun: retries with fresh timeouts push past the SLO; cap them at the remaining budget.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design retry policy across client, proxy, and service.

Answer

Clarify, then assume. Path is client → proxy (Envoy) → service → downstream, HTTP/1.1 or gRPC. User-facing budget is 1s p99. Reads are idempotent; writes carry an Idempotency-Key. If writes have no dedup store, the answer changes and I'd say so up front.

Core answer. One end-to-end deadline, one retry layer, one retry budget. Pick the layer that knows idempotency and sees the least amplification, and disable retries everywhere else. Propagate the deadline as a header so each hop subtracts its own time. Retry only when the failure class says the request is safe to repeat, and cap total retries as a fraction of live traffic.

Why exactly one layer. Retries multiply. Client 3× × proxy 3× × service 3× = up to 27 upstream attempts per user request. During a partial outage that is the difference between a brownout and a full outage, because the retries land exactly when the backend is already saturated. So: retry at one layer, make the others fail fast.

Which layer.

  • Proxy (Envoy): good when the route is idempotent and you want one policy for all clients, and you can lean on Envoy's retry budget. Wrong when the proxy can't distinguish idempotent from non-idempotent routes, or when clients already retry: you double up.
  • Service: good when the service owns the idempotency semantics (it knows the write is keyed) and can circuit-break its downstream. Wrong when the proxy is already retrying that route.
  • Client: good for mobile/flaky networks where the request may never have left the device. Wrong as the only layer, since you can't enforce it across client versions.

Default I'd pick: retry at the proxy for idempotent routes, disable client and service retries there; for non-idempotent writes, no automatic retry at any layer. The client retries only with the same idempotency key.

Failure classification.

failurereached server?retry?
connect refused / DNS failnoyes, any method
reset before responseunknownonly if idempotent or keyed
5xx responseyesonly if idempotent or keyed
429 / 503 + Retry-Afteryesyes, honor Retry-After
400/401/403/404yesno: deterministic

Backoff and budget. Exponential with full jitter: sleep = random(0, min(cap, base * 2^attempt)). Envoy's defaults are base 25ms, max 250ms; gRPC caps maxAttempts at 5. Cap the retry budget: Envoy's retry_budget defaults to 20% of active requests with a floor of 3 concurrent retries. That knob is what stops a retry storm.

Commit-then-timeout. The classic duplicate: the service commits the write, the response is lost, the client times out and retries. Without a dedup store you get two rows. Fix: the write is keyed by Idempotency-Key, the service stores the key and the response in the same transaction as the write, and a retry with the same key returns the stored response instead of re-executing. Stripe keeps those keys 24h; pick a window longer than your max retry span.

Failure modes to name. Retry storm on overload: detected by retry-budget exhaustion and rising 503s. Duplicate delivery: detected by idempotency-key collisions in the dedup store. Partial-body retry: never retry a streamed body mid-flight; the bytes already sent can't be un-sent, so retry only before the first byte. Retry into a dead backend: detected by outlier detection ejecting the host.

What changes the answer. No dedup store → no layer retries writes. Browser client you don't control → policy lives at the proxy. Tight budget (say 200ms) → one retry at most, and hedging (a second request in parallel after p95) is only safe for idempotent reads.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Set queue and admission policy for a proxy.

Answer

First thing I'd pin down: the proxy's job is to protect the backend, not to accept every request. So the queue is bounded and admission is deadline-aware, because a request that waits past its deadline is worse than a rejected one: it holds a connection, a worker, and a client retry slot, then fails anyway.

Assumptions I'd state out loud: HTTP/1.1 and HTTP/2 clients, backend p99 service time around 50 ms, end-to-end deadline budget 500 ms, and the proxy is the only queue in front of the backend.

Size the queue with Little's Law, L = λW. At 2,000 rps and a target p99 queue wait of 100 ms, that's 200 requests in flight. At 4 KB per request that's 800 KB of buffers: small enough to bound, big enough to absorb a 100 ms burst. Anything past that is memory you're spending to make failures slower.

Concrete starting settings, all real defaults or documented knobs:

layersettingvaluewhy
Envoy circuit breakermax_connections1024 (default)caps sockets
max_pending_requests256 (default 1024)queue depth
max_requests1024 (default)concurrent upstream
max_retries1 (default 3)retry amplification
retry_budget20% (default)caps retry storm
nginxlimit_req_zone rate50r/s per IPtenant fairness
burst100 nodelayabsorb burst, no queue delay
limit_req_status429explicit backpressure
HAProxymaxconn2000connection cap
timeout queue5sbound wait
Linuxnet.core.somaxconn4096accept backlog

Retry amplification is the arithmetic that decides max_retries: three hops each retrying 3 times is 4^3 = 64 attempts per client request. That's why I set max_retries to 1 at the edge and let the retry budget (20% of active requests, min 3 concurrent) cap the rest.

Admission order: connection limits first, then concurrency, then the queue. In the queue, evict by deadline: expected_wait = depth / service_rate; if remaining_deadline < expected_wait + service_time, reject now with 503 and Retry-After. Envoy does this with x-envoy-expected-rq-timeout-ms and the timeout_budget retry predicate.

Reserve capacity for health and control. If health checks share the data queue, a saturated queue makes the LB mark the instance unhealthy and removes it: the classic cascade. Separate listener or priority HIGH, and keep the admin port (Envoy 9901) off the data path. Envoy's overload manager does this with loadshed points: stop_accepting_connections at 95% heap, reset_high_memory_stream, disable_keepalive.

Failure modes and how I'd see them:

  • Unbounded queue: RSS climbs, OOM kill. Watch container_memory_working_set_bytes and envoy_http_downstream_rq_pending_active.
  • Queue at limit: 503s. envoy_http_downstream_rq_pending_overflow counter.
  • Retry storm: upstream_rq_retry and upstream_rq_retry_overflow; retry budget exhausted.
  • Head-of-line blocking on HTTP/1.1: a 5 MB response blocks the next request on the same keep-alive connection. Detect by splitting p99 by response size; HTTP/2 multiplexing avoids it at stream level but the 64 KiB initial flow-control window (RFC 7540) still stalls large transfers.
  • Slow consumers: write buffer fills, downstream_flow_control_paused_reading_total rises, then downstream_cx_destroy_with_active_rq.
  • Stale work: upstream_rq_timeout and upstream_rq_tx_reset climb while queue depth is high. You queued past the deadline.

Watch oldest age, not just depth. Depth can look fine while the head of the queue is 400 ms old, and that's the number that predicts timeouts. After an overload episode, drain the queue before reopening admission, or you re-enter overload on the first retry wave.

Trade-offs: rejecting at the edge is cheap and protects the backend, but wastes client work and can trip client retry budgets. Queueing absorbs bursts but adds latency and memory, and queued work can be stale. Reserving capacity protects health but shrinks the pool you can sell. Backpressure (503 + Retry-After, gRPC RESOURCE_EXHAUSTED, HTTP/2 GOAWAY ENHANCE_YOUR_CALM) is honest but shifts load to the client.

When not to queue: if the bottleneck is a shared database behind the backend, queueing at the proxy just moves the pile-up and adds a hop of latency. And if the work is deadline-bound and queue wait exceeds the deadline budget, a fast 503 beats a slow timeout every time.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design circuit breaking and load shedding.

Answer

Core answer (say this first).

Assume one service behind an L7 load balancer, HTTP and gRPC callers, multi-tenant, p99 latency SLO of 250 ms. Circuit breaking and load shedding solve opposite problems and you need both. A circuit breaker stops you from calling a dependency that is already failing, so your threads and connections aren't spent on calls that will time out. Load shedding stops you from accepting more work than you can finish, so queues don't grow until latency collapses for everyone. Both reject early, with a status the caller can act on: 503 + Retry-After for overload, 429 for a per-tenant quota, gRPC RESOURCE_EXHAUSTED (8) when shedding and UNAVAILABLE (14) when a breaker is open.

Size the limit from Little's Law, not from a guess.

L = λW: concurrency equals throughput times latency. If the service holds 200 concurrent requests at p99 250 ms, sustainable throughput is 200 / 0.25 = 800 rps. Offer 1200 rps and the extra 400 rps has nowhere to go: it queues, W rises, and L rises with it until timeouts. So the admission limit is 200 in-flight, and everything above it is shed at the edge.

ConditionSignalActionStatus
in-flight > 200concurrency countershed at edge503 + Retry-After: 1
tenant over quotatoken bucketreject that tenant429
dependency 5xx ≥ 50%breaker windowfail fastgRPC UNAVAILABLE (14)
dependency slow, no errorsp99 latencyeject host503

Circuit breaker mechanics.

Three states. Closed: calls pass, you count outcomes over a sliding window. Open: calls fail fast without touching the dependency. Half-open: a few probes decide whether to close. Resilience4j defaults: 100-call sliding window, trip at 50% failure rate, stay open 60 s, allow 10 calls in half-open. Envoy outlier detection ejects a host after 5 consecutive 5xx for 30 s, capped at 10% of the cluster. The cap matters: without it a bad window ejects every host and you've turned a partial outage into a total one.

Trace: 20 calls, 12 fail → 60% > 50% → open. 60 s later, half-open admits 3 probes; 2 succeed → close. If 2 of 3 fail → back to open, and you should jitter that 60 s so all instances don't probe together.

Trade-offs and when not to shed.

Shedding is not free: every rejected request that a client retries costs you another request. If work is cheap and the queue is bounded, queueing beats rejecting. Shed only when the queue is unbounded or the work is expensive. Prefer per-tenant token buckets over a global limit: a global limit lets one tenant consume the whole budget. Reserve capacity for health checks and control-plane traffic; if the LB's health probe gets shed, the instance is markeddead and you lose that capacity entirely.

Failure modes and how you see them.

  • Retry storm: 503s trigger client retries, request rate climbs past 3× baseline while success rate stays flat. Fix with Retry-After, jittered backoff, and a retry budget (cap retries at ~10% of requests).
  • Slow dependency that never errors: the breaker never trips because failure rate is 0. Watch p99 latency, not error rate, and eject on latency.
  • Half-open herd: dependency error rate spikes every sleep window as all instances probe at once. Jitter the window.
  • Shedding the wrong traffic: health/control requests rejected, LB drains the instance. Detect via probe failure rate; reserve a small always-admitted pool.

Measure accepted, queued, rejected, canceled, completed: the gap between accepted and completed is your real backlog.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design overload behavior for a multi-tenant edge.

Answer

The 90-second answer

Overload at a multi-tenant edge is a queueing problem, not a capacity problem. By the time CPU is pegged you are already late; what you actually control is how many requests are in flight and which ones you drop. So admission control sits in front of every backend, keyed by tenant, and the first design decision is whether a given class of traffic queues or sheds.

Assumptions I would state out loud: tenants share backends, one tenant can be 100x another's normal rate, and the edge cannot tell a retry from a first attempt unless the client tags it.

Why concurrency, not just rate

Little's Law: in-flight = arrival rate x latency. A backend serving 2,000 rps at 50 ms holds 100 requests. If latency degrades to 500 ms under load, the same 2,000 rps now holds 1,000: ten times the memory and ten times the queueing delay. A rate limit does not catch this, because the arrival rate never changed. So the primary limit is a concurrency cap per backend, with a per-tenant rate limit as a secondary guard.

The decision: shed or queue

Two credible designs, and I would pick per traffic class rather than globally.

  • Queue with a deadline. Right when work is cheap and the client can wait: batch jobs, async writes. Bound the queue and reject on queue age, not queue length, because age is what the client experiences.
  • Shed at admission. Right for interactive reads. Reject immediately with 429 for a per-tenant quota breach or 503 for global overload, and include Retry-After.

I would run both: a small queue (roughly 10 ms of work at p50) for latency-tolerant classes, immediate shed for the rest. Queueing under sustained overload is how a 200 ms blip becomes a 30-second outage: the queue absorbs the spike and then serves work nobody still wants.

Fair share versus priority

Priority shedding (Google SRE's criticality levels: CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE) protects health checks and the control plane. Fair share protects the small tenant. You need both, and they conflict: strict priority lets one tenant's CRITICAL traffic starve everyone else. So reserve a slice of capacity for health and control, divide the remainder by weighted fair share across tenants, then apply priority within each tenant's slice. A tenant cannot borrow another's slice.

Retry budget

Retries are the amplifier: three layers each retrying up to 3 times turns one request into 27. Envoy's retry budget (budget_percent, min_retry_concurrency) caps retries as a fraction of active requests. The SRE book's adaptive throttling instead rejects with probability p = max(0, (requests - 2 x accepts) / (requests + 1)), which sheds the clients that retry hardest. Both need a retry-attempt header so the edge can distinguish a first try from a fifth.

Failure modes

  • Noisy tenant: one tenant's concurrency cap saturates while others idle. Detect with per-tenant in-flight versus cap and p99 broken out by tenant. Blast radius is that tenant only if caps are per-tenant; everyone if the cap is global.
  • Retry storm: 503s trigger client retries, which raise load further. Detect by request rate rising while goodput falls, and by retry-attempt header counts climbing. The cost is that the outage outlives its trigger.
  • Slow client: a response written to a socket that never drains holds a worker. Detect via write-queue depth and connection age. Fix with a write timeout, not a bigger pool.
  • Zone failure: spillover into a healthy zone, but only after checking that zone's concurrency headroom. Otherwise you relocate the outage instead of absorbing it.

Test

Replay a noisy tenant at 10x, a slow endpoint, and a retry storm with the header set. Assert that p99 for uninvolved tenants moves less than 10%, and that after load drops no tenant stays pinned at its cap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design zero-downtime load-balancer draining.

Answer

Assumptions: HTTP/2 (or HTTP/1.1 keep-alive) behind a cloud LB or service mesh; the app owns its own shutdown; most requests are sub-second but a few are long-lived streams or batch jobs. If all traffic is short and idempotent, skip the propagation wait and kill.

The sequence, and why each step exists.

  1. Fail readiness: don't close the listener. Flip the readiness probe to failing (or call the LB's deregister API). The LB now stops selecting this backend for new connections. You must not close the listener yet: the LB's routing table is stale for a propagation window. ALB health checks run every 30 s with an unhealthy threshold of 2, so up to ~60 s pass before it stops routing. Close the listener now and those 60 s of new requests get RST.

  2. Wait out propagation. Sleep for the window: health-check interval × threshold, plus control-plane push lag for a mesh (Envoy xDS pushes are sub-second, but the endpoint update still has to reach every proxy). 15–30 s is typical.

  3. Signal no-new-work at the protocol level. Stop accepting new streams/connections without dropping in-flight ones:

ProtocolSignalEffect
HTTP/1.1Connection: close on the last responseclient won't reuse the keep-alive connection
HTTP/2 / gRPCtwo-stage GOAWAYno new streams; in-flight streams finish
WebSocketclose frame 1001 (going away)app-level close handshake
HTTP/3GOAWAY framesame semantics as HTTP/2

Two-stage GOAWAY matters: the first frame carries last-stream-id = 2^31−1 ("stop opening streams, I'll tell you the real cutoff"), then after a grace period a second GOAWAY carries the actual last processed stream id, then close. One-stage GOAWAY races: a stream opened just before the frame is silently dropped.

  1. Bound the drain. Give in-flight work a deadline, then force close. ALB's deregistration delay defaults to 300 s (0–3600 s); Envoy's listener drain_time defaults to 600 s. Pick the deadline from p99.9 request duration, not p50: if p99.9 is 2 s, a 60 s deadline is 30× headroom and saves 4 minutes per deploy versus the 300 s default. If 10-minute batch jobs share the port, 60 s drops them: move them to a separate listener or accept the longer drain.

Trade-offs.

  • Drain vs immediate kill. Drain costs capacity and deploy time; kill is instant but drops in-flight requests → 5xx. Drain when requests are non-idempotent or long; kill when the node is already failing and draining just prolongs a bad state.
  • LB-initiated vs app-initiated. LB-initiated (deregister) is centralized and works for any backend, but the LB can't see app-level work: DB transactions, background jobs. App-initiated (SIGTERM handler) knows app state but needs the LB to stop first. Do both: LB stops new selections, then the app drains its own work.
  • Deadline length. Too short drops requests; too long holds capacity and slows rollouts.

How it fails in production.

  • Half-open connections. The LB flips to unhealthy and stops routing, but existing TCP connections stay open and clients keep sending. Close the listener immediately and those get RST. Detect: connection-reset / 5xx spike during deploys.
  • Idle gRPC streams never reaped. A long-lived streaming RPC with no traffic keeps the connection alive past the deadline; the force-close kills it. Detect: stream-age histogram, count of streams older than the deadline.
  • Clients that ignore GOAWAY. Some keep opening streams; the deadline force-close is the backstop. Detect: streams opened after the first GOAWAY.
  • Process crash mid-drain. In-flight work on that backend is lost. The LB having already stopped new selections bounds the blast radius to that backend's in-flight only.

Worked check (Go 1.22, net/http):

Go
ready.Store(false)                       // 1. fail readiness

time.Sleep(20 * time.Second)             // 2. propagation window

ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()

if err := srv.Shutdown(ctx); err != nil { // 3+4. GOAWAY, drain, force close
    srv.Close()
}

Trace: ready.Store(false) makes the readiness handler return 503; the LB's next health check fails and, after threshold × interval, it removes the endpoint. The sleep covers that. srv.Shutdown closes listeners (no new TCP), sends GOAWAY on HTTP/2 connections (no new streams), and waits for active requests. If they finish within 60 s, Shutdown returns nil. If not, it returns context.DeadlineExceeded and srv.Close() force-closes what remains.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Coordinate load balancing with autoscaling.

Answer

Core answer. Assume Kubernetes behind a cloud load balancer, HPA on a custom metric, and a node autoscaler. There are two control loops: the capacity loop (HPA → scheduler → node autoscaler) and the routing loop (readiness → EndpointSlice → kube-proxy or LB target group). They touch at exactly one signal, readiness, so coordinate them by making readiness mean "can serve at full rate," by scaling on the metric the balancer actually constrains, and by budgeting headroom for the gap between the loops.

The gap is the problem. With defaults, a spike at t=0 reaches the HPA within 15s (--horizontal-pod-autoscaler-sync-period), the pod is Ready around t=45s, and the ALB then needs up to 150s more (30s health-check interval × 5 healthy threshold) before it routes to it. Capacity the scaler paid for is invisible to the balancer for ~2.5 minutes after it exists.

StageDefaultWhere it comes from
HPA metric sync15s--horizontal-pod-autoscaler-sync-period
metrics-server resolution15s--metric-resolution
Node provision~40-60s Karpenter, ~2-3 min managed node grouptypical, not a guarantee
Image pull + init + app start10-60sworkload-dependent
Readiness probeperiodSeconds 10, failureThreshold 3k8s defaults
EndpointSlice → kube-proxyup to 30s--iptables-sync-period default 30s
ALB target healthyup to 150sALB defaults
ALB slow start30starget group attribute

Three things follow.

Scale on the constraint, not on CPU. If the balancer queues, CPU stays flat while latency climbs, and a CPU-based HPA never fires. Scale on concurrency or queue depth (KEDA, or HPA on a Prometheus-adapter metric). KEDA's defaults are a 30s polling interval and a 300s cooldown: the cooldown is what stops a queue that drains in 5s from flapping the fleet.

Make readiness the handoff. A pod that passes readiness but is still warming gets traffic it can't serve. Gate it: minReadySeconds (default 0) keeps it out of the ready set for N seconds after the probe passes, and a preStop sleep covers the reverse direction. Set terminationGracePeriodSeconds ≥ the LB's deregistration delay (ALB default 300s) or scale-down kills pods the balancer is still routing to.

Asymmetric cooldown. Scale up with stabilizationWindowSeconds: 0; scale down with 300s (the HPA default). Removing capacity you'll need in two minutes is the expensive mistake.

YAML
behavior:
  scaleUp:   {stabilizationWindowSeconds: 0,   policies: [{type: Percent, value: 100, periodSeconds: 15}]}
  scaleDown: {stabilizationWindowSeconds: 300, policies: [{type: Percent, value: 100, periodSeconds: 15}]}

Trade-offs. CPU-based HPA is cheap and needs no extra pipeline, but it's blind whenever the balancer queues and useless for I/O-bound work: use it only when the app is genuinely CPU-bound and the LB doesn't backlog. Concurrency metrics track the real constraint but add a scrape pipeline (15-30s) and over-scale on a single hot shard. Predictive/scheduled scaling handles known diurnal peaks but a bad forecast over-provisions; use it as a floor, not the primary loop. Karpenter provisions in ~40-60s versus ~2-3 min for a managed node group, but only if the workload tolerates instance-type flexibility.

Failure modes and how you see them.

FailureDetection
Drain race: deregistration delay > grace period5xx spike correlated with scale-down events
Shedding hides the signal: LB 503s fast, CPU drops, HPA scales downHPA desired replicas falling while LB 5xx rate rises
Cold fleet: scale-to-zero, first request pays 10-30sp99 on the first request after a zero-replica window
Zone loss: zonal balancer, global scalerper-AZ target count and request rate diverge
Oscillation: scale-up window 0 + slow readinessreplica sawtooth with period ≈ readiness latency

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design global traffic failover using DNS.

Answer

Assume two regions, active/standby, a managed DNS provider with health checks, and an RTO measured in minutes. If the RTO is seconds, stop here: DNS is the wrong layer.

Core answer. Authoritative records with a failover routing policy: a primary record carrying a health check, and a secondary record pointing at the standby region's load balancer. Health check at a 10-second interval with a failure threshold of 3, so the endpoint is marked unhealthy roughly 30 seconds after it stops answering. Route 53's checkers are distributed globally and the endpoint counts as healthy if more than 18% of them agree: that is what stops one bad network path from failing you over. Use A/AAAA alias records so the zone apex can point at a regional load balancer without a CNAME.

Then the record changes, and the interesting part starts.

What actually delays the switch

StageDelayWhy
Health-check detection~30 s10 s interval × 3 failures
Authoritative TTL60 sa resolver holds the old answer until it expires
Resolver floor0–300 smany resolvers enforce a minimum TTL and ignore yours; a few ignore TTLs entirely
Client cache0–30 sthe JVM's networkaddress.cache.ttl defaults to 30 s; older JDKs with a security manager installed cached forever
Open connectionsminutes–hoursa keep-alive socket or gRPC stream never re-resolves

A cold client lands in the standby in about two minutes. A client with a live connection lands there when that connection dies. That gap is the honest RTO, and it is why you measure cohort shift rather than trusting the control plane.

TTL is a query-load dial. One million clients re-resolving every TTL: a 60 s TTL puts ~16.7k QPS on your authoritative servers; a 5 s TTL puts 200k QPS on them. Route 53 absorbs that; two self-hosted BIND boxes will not. Shorter TTL buys faster failover and costs query volume and resolver churn.

Alternatives, and when to skip DNS. Anycast plus BGP withdrawal fails over in seconds, but you need your own prefix and ASN and it is per-prefix all-or-nothing. A global load balancer with a single anycast VIP (GCP global external LB, Cloudflare) moves failover inside the LB, so DNS never changes and the TTL problem disappears: that is the choice when RTO is sub-minute. Multivalue answer routing, by contrast, hands clients several addresses and lets them pick; clients are not health-aware, so some fraction keeps hitting the dead IP. DNS failover is right when the failure is a whole region and minutes are acceptable.

Failure modes and how you see them

  • Stale caches. A resolver with a 300 s floor keeps sending traffic to the dead region. Detect it by measuring the actual cohort shift, per-region request counts and per-resolver-subnet query logs, not the record's value.
  • Negative caching. If the failover record is missing mid-switch, resolvers cache NXDOMAIN for the SOA minimum (RFC 2308), commonly 60–300 s, extending the outage. Alert on NXDOMAIN rate.
  • Shared-dependency health check. If the check probes a shared database or auth service, both regions go unhealthy and the name resolves to nothing. Alert on "all endpoints unhealthy".
  • Control-plane partition. If failover needs an API call, you cannot fail over when the provider's API is down. Pre-provision the secondary record so health checks drive the switch.
  • Flapping. The primary recovers, traffic returns, it fails again. Require several minutes healthy before failing back, and fail back in stages.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Operate an anycast load-balanced service.

Answer

Assumptions. One service address (a /24 for v4, a /48 for v6) originated from four PoPs. The workload is mostly stateless request/response over TCP and QUIC, with a minority of long-lived connections. You own the BGP policy and the edge; you do not own the clients' routing.

The core answer. You operate anycast by controlling three things and accepting that a fourth is not yours. You control which sites originate the prefix, how healthy a site must be to keep originating it, and how much capacity each site has for the catchment BGP hands it. You do not control which clients reach which site: the internet's routing policy decides that. You can nudge it with local preference, MED and communities, but you cannot set it. So capacity planning is about worst-case catchment, not average.

Why it behaves this way. Anycast steering is just BGP. Each site originates the same prefix, and every network on the path picks the best route by its own policy. A client in Frankfurt reaches the Frankfurt PoP because that is the shortest AS path from its ISP, not because you asked. Change one upstream's policy and the catchment moves. That is why you measure traffic shifts by region and ASN, not globally.

Health and withdrawal. Each site runs a local health check and withdraws its own prefix when it cannot serve. Do not wire a global shared-fate withdrawal: one site's bad disk should not pull the whole service. But withdrawal is slow: BGP convergence is seconds to minutes, and route flap damping (RFC 2439) can hold a flapping prefix down for tens of minutes. So for fast failure, keep the route up and stop accepting new work at the edge, return RST or a 503, while existing sessions drain. Withdraw only when the site is out for good.

Stateful vs stateless. Stateless services (DNS, NTP, connection-per-request HTTP) are the clean case: any site can answer any packet, so a reroute is invisible. Stateful ones are not. A TCP or TLS session that reroutes mid-connection lands on a site with no state and dies. QUIC's connection migration (RFC 9000) lets a client move between its own addresses, but it does not help when the route moves to a different anycast site: the new site still has no connection state. So either pin long-lived connections and accept that a site failure kills them, or replicate the state.

Failure modes and how you see them.

failuredetectioncost
Site lossper-site health check plus traffic drop by ASNcatchment shifts to survivors; N+1 sizing absorbs one loss
Route leak / hijackRPKI plus prefix monitoring (e.g. BGPStream)traffic pulled to a wrong origin; withdraw or announce a more-specific
FlappingBGP update rate per prefix; dampening countersdampening suppresses the prefix and the site goes dark
Partial app failureedge 5xx rate per site while BGP stays uproute stays, clients get errors: worse than a clean withdrawal
Asymmetric return pathtraceroute both directions; TCP retransmit ratestateful firewalls drop return traffic

Worked sizing (hypothetical). Four sites, each normally taking 25% of traffic. Size each for 1.5x its share. Lose one site: the other three take 33% each. 1.33x, fine. Lose two: 50% each. 2x, over capacity, so you shed load or serve errors. That is why you test cold failover, not just steady state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Deploy a load-balancer configuration safely.

Answer

What I'd say first

Assume an NGINX 1.25 L7 load balancer, config in Git, rendered per environment, applied by a config agent that runs nginx -s reload on each of 24 instances (8 per AZ). The safe sequence: validate the rendered artifact offline, prove the running config on one instance matches what you rendered, watch that instance's real SLOs, then widen. With an automatic abort and a last-known-good file to reload back. Each step catches a different class of failure, which is why the order matters.

Validate offline: catches syntax and include errors, not semantics

nginx -t parses the config and resolves includes; it will not tell you that a new regex location shadows an existing route. So render the full config and diff it:

nginx -t -c rendered/nginx.conf
nginx -T -c rendered/nginx.conf > rendered.dump
diff -u baseline.dump rendered.dump

nginx -T expands every include, so the diff shows what actually changes, not what the template claims.

Route precedence: the failure a syntax check misses

NGINX location matching order:

matchdirectivebeats
exactlocation = /healthall
prefix, stop regexlocation ^~ /api/regex
regex, first winslocation ~ ^/api/v[0-9]+/plain prefix
plain prefix, longestlocation /api/—

A new ~ ^/api/ regex silently steals traffic from ^~ /api/static/. Detect it with golden requests: one request per route asserting status and body, run against a local instance before deploy.

Config convergence: why before widening

After reload, run nginx -T on the box and compare to rendered.dump. If they differ, the reload didn't take: a bad include, an agent race, a read-only mount. You'd then be watching the old config's SLOs and concluding the new one is fine. Convergence is the precondition for the SLO check to mean anything.

Staged exposure and abort

Reload one instance. Blast radius is 1/24 ≈ 4.2% of capacity; the other 23 absorb it, so you need roughly 5% headroom. Abort if that instance's 5xx exceeds 1% over 60s or p99 exceeds 2× the pre-deploy baseline. Then widen AZ by AZ.

Shadow vs canary, when to use which

Shadow (mirror) copies requests to the new config without returning its responses: it validates parsing and routing under real traffic shape, but doubles backend load and can't test writes or stateful paths. Canary (one instance in rotation) tests real responses but exposes real users. Use shadow when the change is routing/TLS and backends are read-only; go straight to canary when the change affects writes or you can't isolate a single instance.

Failure modes and how you see them

failuresymptomdetection
route shadowingwrong backend for /api/v1golden request body mismatch
missing intermediate certclient handshake failuresopenssl s_client -showcerts chain length
health check catch-alldead backend stays in rotationkill one backend, assert ejection within 3× interval
empty discovery502/503 spikeassert upstream count > 0 before reload

Rollback

Keep nginx.conf.lkg on every box. nginx -s reload is graceful: old workers finish in-flight requests before exiting, so rollback drops no connections. Preserve a management route (or out-of-band SSH) so a bad route can't lock you out of the box you need to fix.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design load-balancer observability.

Answer

Core answer (first 90 seconds)

Assume an L7 proxy (Envoy, HAProxy, nginx, or an ALB) in front of N backends, and the question you actually need to answer is "which backend is failing, and is the LB or the backend the bottleneck?" The design principle: the LB is the only component that sees both sides of every request, so its job is per-backend attribution plus a latency decomposition that separates LB-induced delay from backend-induced delay. Everything else is labels.

Three signal groups, all keyed by backend endpoint (with zone, version and algorithm as bounded labels):

  1. Selection and work: requests, bytes in/out, active connections/streams, retries.
  2. LB-internal: upstream pool reuse vs new connect, pending-queue wait, which timeout stage fired.
  3. Outcome: response code class, reset/refused, latency stages, health/ejection state.

Group 2 is the one people forget, and it is the one that decides the incident.

Why the LB-internal signals matter

Decompose every request into stages; the sum should equal total request time, and a gap means you are missing a measurement (async buffering, response streaming).

stagewhere measureda spike means
client→LBTLS handshake, request readclient-side or TLS config
LB queue waittime in pending poolpool exhausted or conn limit hit: the backend never saw the request
LB→backend connectconnect timeDNS, SYN backlog, backend accept queue
backend TTFBtime to first bytebackend app or DB
response writestream duration minus the aboveslow client, backpressure

Queue wait is the discriminator. When the upstream connection pool is exhausted, requests wait inside the LB: the backend never sees them and the client just sees slow, so front-door p99 alone cannot tell you whether to scale the LB or the backend. Envoy exposes this as upstream_rq_pending; HAProxy as qtime separate from ctime/ttime.

Timeout stage is the second discriminator. An LB has connect timeout, per-try timeout, overall request timeout and idle timeout. A 504 from connect timeout is a DNS/network incident; a 504 from response timeout is a slow backend; an idle timeout is a stuck stream. Recording which stage fired tells you the fix.

Trade-off: cardinality is the budget

Labels are the cost. endpoint × zone × version × algorithm × client cohort explodes. Decide explicitly: endpoint, zone, response-code class and algorithm stay as metric labels; client cohort or key goes to logs or trace exemplars, never a metric label. A single high-cardinality label (client ID, full URL path) can take one scrape target from thousands to millions of series and OOM Prometheus.

Alternatives

LB metrics alone vs LB metrics plus OpenTelemetry traces plus backend RED metrics. Metrics are cheap, always-on and aggregate: use them for alerting and capacity. Traces give per-request causality but are sampled: use them for diagnosis. Pull (Prometheus scrape) beats push (statsd) because you get up/down detection for free.

Failure modes

  • Cardinality explosion → Prometheus OOM. Detect: series count per target, scrape duration.
  • Alerting on raw counts → a backend carrying 2× traffic looks unhealthy by error count. Normalize to error ratio.
  • Ejection cascade → outlier detection ejects a backend, traffic shifts, the rest saturate, more ejections fire. Detect: ejection count alongside per-backend concurrency.
  • Retry amplification → the LB retries 5xx against an already-overloaded backend. Detect: compare backend-received RPS to client-sent RPS. At 10k rps and a 10% error rate, 3 retries add ~1k rps (+10%); at a 50% error rate they add ~5k rps (+50%), which can push a degraded backend over the edge.

Alert on normalized capacity skew, per-backend concurrency and error ratio relative to its share of traffic, not raw counts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design the load-balancing tier's own high availability so the load balancer is not a single point of failure: how would you pair or cluster them, detect failover, handle connection state, and patch them without dropping traffic?

Answer

First question back: is this a managed LB or one I run? If it's ALB/NLB or GCP's global LB, the provider already runs it multi-AZ and I don't build redundancy: I buy it. My job there is capacity headroom in the surviving zones and correct target-group health. If I run it, I pick between a floating VIP and ECMP.

modelfailovercapacitystate to carrywhen
active-passive, VRRP/keepalived VIP~1–3 s (advert_int 1 × 3 misses)1× (standby idle)conntrack for L4 NAT; TLS ticket keyssmall tier, L4 or L7, simplest to reason about
active-active, ECMP + BGP~300–900 ms with BFD; seconds with BGP tuned to 3×3 sN×none if stateless L7; 5-tuple hash pins flowshigh throughput, stateless L7
managed LBprovider's, multi-AZprovider'snoneyou don't want to run it

Active-passive is the default I'd reach for. keepalived holds the VIP on MASTER, the standby takes it after three missed adverts and sends a gratuitous ARP:

vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 150 # standby 100 advert_int 1 # 3 missed -> ~3s takeover unicast_src_ip 10.0.1.10 unicast_peer { 10.0.1.11 } # unicast, not multicast: no split-brain virtual_ipaddress { 10.0.1.100/24 } }

State is where people get it wrong. A stateless L7 proxy has nothing to sync: the client's TCP connection dies, it reconnects to the VIP, done. An L4 NAT needs conntrackd replicating the conntrack table (~1 s interval) or every established flow resets. And if I terminate TLS on the LB, RFC 8446 session tickets are sealed with a key only the issuing LB holds; after failover clients do a full handshake unless the ticket key is shared across the pair. That's one extra RTT and a CPU spike at exactly the wrong moment.

Upgrade without dropping traffic, active-passive:

  1. Patch and restart the standby; it rejoins as BACKUP.
  2. Stop keepalived on the master: priority drops, standby takes the VIP, gratuitous ARP goes out.
  3. Clients see one RST and reconnect to the VIP. New-connection failures last as long as ARP propagation, ~1–3 s.
  4. Patch the old master, restart, rejoin as BACKUP. Fail back the same way.

Active-active is the same idea with BGP: withdraw one LB's announcement, let flows drain, upgrade, re-announce.

Failure modes I'd name. Split brain: both nodes MASTER, duplicate VIP, ARP flapping; unicast peers plus a quorum node prevent it. A health check that only proves the process is up, so I fail over onto a peer that also can't reach the backends; the check has to test upstream reachability from the LB. Gratuitous ARP not propagated by the upstream switch, leaving a stale ARP entry and a blackhole for the ARP cache timeout: minutes, not seconds. Detect all three with external VIP probes from more than one network, not from inside the tier.

Curated: · Written: · Reviewed:

Difficulty: Hard