Load Balancing and Traffic Management Questions
Distributing requests across capacity: load-balancing algorithms (round-robin, least-connections, consistent hashing), L4 versus L7 balancing, health checks, and traffic shaping. Covers sticky sessions, canary and blue-green routing, rate limiting, and graceful draining. The traffic-distribution layer that keeps a scaled system balanced and available.
Design a plan to migrate a stateful web application away from sticky sessions to a stateless architecture. Compare an external session store (for example Redis or DynamoDB), signed JWTs, and client-encrypted cookies, weighing latency, security (revocation), and operational complexity. What rollout and rollback plan would you use to do this without a downtime or data-loss incident?
Sample Answer
Direct answer
Moving off sticky sessions means moving the session state somewhere every backend can reach, so the LB no longer needs to remember which instance served a user. The three options, an external store (Redis or DynamoDB), a signed JWT, or a client-encrypted cookie, trade off differently on latency, revocation, and operational complexity, and the safest rollout treats this as a staged migration with a working rollback at every step, not a single cutover.
Comparing the three approaches
| Approach | Latency impact | Revocation | Operational complexity |
|---|---|---|---|
| External store (Redis / DynamoDB) | One extra network round-trip per request that needs session data; mitigated with a local read cache | Immediate: delete or expire server-side, takes effect on the next lookup | Medium to high: run and operate a highly-available store, plan for its own failover and backup |
| Signed JWT | None, validated locally from the request, no network call | Hard: valid until expiry unless you add a blocklist (which reintroduces an external store for exactly the sessions you need to revoke) | Low for issuance and validation; grows if you add key rotation and a blocklist |
| Client-encrypted cookie | None, decrypted locally | Same limitation as JWT unless you track issued session IDs server-side | Medium: must manage encryption key rotation (typically via a KMS, a managed service that stores and rotates encryption keys for you) and cookie size limits |
A common pattern that resolves the tension: short-lived JWTs (or encrypted cookies) for the common case, backed by a lightweight server-side store used only for the sessions that actually need early revocation (a logout, a compromised-account response), instead of paying store latency and store operational cost on every single request.
Worked example: capacity planning for the store option
If the API currently handles 5,000 requests per second at peak and every one of them will look up session state after migration, the session store has to sustain at least that read rate. Provisioning with headroom (a common starting point is 50%) gives a capacity target of:
5,000×1.5=7,500 ops/secThat is the number to load-test the store against before cutover, not the number you discover you needed during the first real traffic spike after migration.
Rollout plan
- Dual-write, keep stickiness on. Introduce the new session store (or start issuing tokens) alongside the existing sticky-session behavior, so nothing user-facing changes yet, but you can validate correctness (does the store have what the in-memory session had) and measure latency and store load under real traffic.
- Canary read path. Route a small percentage of traffic (start around 1%, a percentage you can quickly widen or zero out) to read from the new session mechanism instead of relying on affinity, while stickiness stays on as a safety net for everyone else. Compare error rates and session-consistency between the canary cohort and the control group.
- Widen gradually. Step the canary percentage up (1% to 10% to 50% to 100%) only after each step holds steady, with an explicit rollback trigger: if the canary cohort's error rate or session-mismatch rate exceeds the control group's by a meaningful margin, drop back to the previous percentage immediately rather than investigating first.
- Disable stickiness. Once 100% of traffic is confirmed reading correctly from the new mechanism, turn off session affinity at the LB. Keep the old in-memory session path dark (deployed but unused) for one more cycle so it's a one-line revert, not a redeploy, if something surfaces late.
- Remove the old path. Only after that final safety window, delete the in-memory session code so there's no drift between what's live and what's supported.
Throughout, connection draining matters more, not less: once affinity is off, any instance can be taken out of rotation for a deploy at any time, so graceful shutdown (finish in-flight requests, stop accepting new ones) has to be solid before you rely on it as the normal operating mode instead of an edge case.
Trade-offs and pitfalls
The most common mistake is cutting over all at once because the change "looks simple" (swap a cookie mechanism), which skips the chance to catch a subtle bug, like a field that existed in the in-memory session but was never migrated to the new store's schema, before it affects 100% of users. Another pitfall specific to the token-based paths: teams discover mid-migration that a session held more state than fits comfortably in a JWT or encrypted cookie (shopping cart contents, multi-step form progress), at which point the honest fix is usually to keep that specific state server-side (the external-store option) rather than growing the token past a size where it adds real latency and cookie-size problems. Revocation is the other recurring gap: if the product needs "log out everywhere" or a fast response to a compromised session, a pure JWT approach without any server-side tracking cannot deliver that without a redesign.
A downstream service starts returning intermittent errors, and your clients retry aggressively, overloading other components as a result. What is your immediate mitigation plan to stop the cascade, and what architecture changes would you make afterward to prevent it recurring?
Sample Answer
Direct answer
Stop the retry amplification first: shed load at the edge (cap or disable client retries, open a circuit breaker toward the failing dependency) so the retries stop compounding faster than the mitigation. Only once the bleeding is stopped do you dig into root cause. Afterward, the fix is structural: circuit breakers, bulkheads, and bounded retry budgets so this class of failure cannot cascade again, not just a one-off cleanup.
Structured elaboration
Immediate containment (first minutes):
- Cut the amplification loop, not the symptom. A retry storm is a positive feedback loop: errors trigger retries, retries add load, added load causes more errors. The fastest lever is at the edge (API gateway, service mesh, or client library), where you can globally cap or pause retries without a code deploy.
- Open a circuit breaker toward the failing downstream so callers fail fast (return a fast error or a cached/degraded response) instead of queuing and retrying against a dependency that is already struggling.
- Shed non-critical load: rate-limit or reject low-priority traffic first, protect the critical path.
- Make failure cheap for callers: return
503withRetry-Afterso well-behaved clients back off instead of retrying immediately.
Root-cause-directed long-term changes:
- Circuit breakers (client-side and at the gateway): trip on an error-rate threshold over a rolling window, fail fast while open, probe with limited traffic in half-open state before fully closing.
- Bulkheads: give each downstream dependency its own connection pool, thread pool, or queue so one degraded dependency cannot exhaust resources shared with healthy ones.
- Retry budgets with jittered exponential backoff: bound total retry traffic to a fixed fraction of primary request volume (a token-bucket style budget), require idempotency for anything retried, and always jitter backoff so retries do not resynchronize into a new spike.
- Backpressure (letting a struggling downstream signal or force upstream producers to slow down, rather than silently accepting more work than it can handle) over synchronous retries: for non-latency-critical paths, replace "retry immediately" with a durable queue so producers are decoupled from the downstream's instantaneous capacity.
Worked example
Retries are dangerous because they multiply load, and the multiplier grows non-linearly as the error rate rises. If a downstream fails a request with probability p and a client retries up to r times (each retry only happens after the previous attempt failed), the expected number of attempts per logical request is a finite geometric series:
E[attempts]=i=0∑rpi=1−p1−pr+1At a moderate error rate (p=0.3) with 3 retries:
E[attempts]p=0.3, r=3=1+0.3+0.09+0.027=1.417That is only 42% extra load. But during real distress (p=0.7, the same 3 retries):
E[attempts]p=0.7, r=3=1+0.7+0.49+0.343=2.533Load to the downstream more than doubles from the retries alone, on top of whatever caused the original errors. If retries are not capped at all, the series is unbounded and converges to:
r→∞limi=0∑rpi=1−p1so at p=0.9, an uncapped retrying client sends 10x its normal load into an already-failing dependency, which is exactly how a partial outage becomes a total one. And this compounds across a call chain: if 3 dependent hops each independently retry at p=0.3,r=3 (a 1.417x multiplier per hop), the multiplier reaching the origin is:
1.4173≈2.845This is why bulkheads are per-hop, not just at the edge: an unprotected chain amplifies retries multiplicatively with depth.
flowchart LR
Client -->|retries| GW[API Gateway]
GW --> RL[Rate limiter and retry budget]
RL --> CB[Circuit breaker]
CB -->|open: fail fast| Deg[Return 503 with Retry-After]
CB -->|closed: allow| BHA[Bulkhead: pool A]
CB -->|closed: allow| BHB[Bulkhead: pool B]
BHA --> Down[Downstream service]
BHB --> Other[Other backend]
Trade-offs and pitfalls
- Circuit breaker thresholds are a tuning problem, not a one-time setting. Too sensitive and you trip on normal noise (self-inflicted outage); too lax and it never protects anything. Validate thresholds against real traffic variance before trusting them in production.
- Bulkheads cost resources. Partitioning pools per dependency means some pools sit idle while others are saturated; this is a deliberate isolation-versus-utilization trade, not a free lunch.
- Retries must be idempotency-safe. A retry budget that resends non-idempotent writes turns a latency problem into a data-corruption problem; this has to be solved before any retry policy is trusted.
- Hidden retries are the most common miss. SDKs, ORMs, and infrastructure clients (HTTP clients, gRPC stubs, connection pools) often retry internally by default; a mitigation plan that only touches application-level retry code can still leave an amplification loop running underneath it.
- Jitter is not optional. Synchronized backoff without jitter just delays the storm and re-synchronizes it into a new spike at the same instant.
Root cause analysis exercise: after a partial outage, your system experienced a retry storm and cascading failures. Lay out a postmortem plan: what logs, metrics, and traces would you collect, how would you determine the source of the retries, and what short-term and long-term controls would you add to prevent recurrence?
Sample Answer
Direct answer
A retry storm postmortem has two distinct jobs: find exactly where in the call chain retries originated (which service, whether it had backoff/jitter, whether its timeout was shorter than the downstream's real processing time), and quantify how much the retries amplified load as they fanned out through the system, since that amplification is usually what turned a partial outage into a full cascade. Short-term you throttle or disable the offending retries and roll back any recent change that touched timeout or retry config; long-term you replace uncoordinated per-hop retries with a single, budgeted retry policy enforced centrally.
Data to collect
| Category | What to pull |
|---|---|
| Logs | Application error/warn logs with correlation/request IDs, LB/gateway logs, upstream and downstream service logs, recent deploy/config-change logs |
| Metrics | Request rate, error rate (4xx/5xx), latency percentiles, retry counts per client/service, queue depth, circuit-breaker state transitions, rate-limit counters |
| Traces | End-to-end spans showing parent-child relationships, so repeated retries of the same logical request are visible as siblings under one trace |
| Timeline | Alert timestamps, operator actions, autoscaler events, correlated against the first error spike |
Finding the source of the retries
- Use traces to find the first hop issuing repeated retries: look for spans with the same parent trace and an increasing retry count.
- Correlate logs by request ID to identify the originating client or service.
- Check whether the retrying layer's timeout is shorter than the downstream's actual (degraded) processing time; a timeout misconfigured relative to real latency causes retries even when the downstream would have eventually succeeded.
- Check whether retries use exponential backoff with jitter or fire immediately/on a fixed interval, since immediate/fixed retries are what synchronize into a flood rather than spreading out.
- Check recent deploys or config changes that touched retry policy, timeouts, or error handling around the incident start time.
Worked example: why retries amplify
Consider a call path Client -> Gateway -> Service A -> Service B, where each hop independently retries up to r times on failure, with no shared retry budget. One original client request can result in up to r attempts from the client, each retried up to r times by the gateway, each retried up to r times by Service A, before reaching Service B:
Amax=rh=33=27With r=3 retries at each of 3 retrying hops, a single client intent can turn into up to 27 actual attempts hitting Service B. This is why a moderate, transient error at Service B (say, a brief GC pause or a single bad deploy) can explode into a full retry storm purely from independent, uncoordinated retry layers, without Service B's underlying problem ever getting worse on its own.
The standard fix is a single retry budget enforced at one point (commonly the edge or gateway) instead of per-hop retries: if the budget allows retries up to 10% of normal traffic (b=0.10), the worst-case amplification is capped at:
Abudget=1+b=1.10regardless of how many hops exist downstream, because only the budgeted layer is allowed to retry at all; downstream hops propagate failures instead of retrying independently.
Short-term controls
- Disable or cap retries at the identified source hop immediately, or apply rate limiting at ingress.
- Roll back the recent change if one is implicated.
- Open circuit breakers on the overloaded downstream to fail fast rather than let retries keep queuing against it.
Long-term controls
- Replace independent per-hop retries with a single retry budget enforced at one layer, sized like the example above.
- Standardize retry libraries across services to always use exponential backoff with jitter, never immediate or fixed-interval retries.
- Align timeout hierarchies so client timeouts exceed realistic downstream processing time, including under degraded conditions, not just the happy path.
- Add chaos/failure-injection tests that specifically simulate partial downstream failure and verify retry amplification stays bounded.
- Add alerting on retry-rate spikes as a leading indicator, not just on the resulting error rate.
Trade-offs and pitfalls
- A shared retry budget requires either centralized enforcement (a single layer allowed to retry) or shared state (a token bucket every hop checks), both of which add coordination cost compared to each service just retrying independently; the payoff is that amplification is bounded by construction instead of by hoping every team tunes their retry count conservatively.
- Circuit breakers can false-open under legitimate bursty traffic if thresholds are tuned too aggressively, trading availability for protection; the threshold should be validated against real traffic variance, not just incident replay.
- Testing a fix by replaying incident traffic in staging is valuable but easy to get wrong if the replay doesn't preserve the original timing/burstiness, since retry storms are fundamentally a timing phenomenon (synchronized floods), not just a volume phenomenon.
Compare connection management for HTTP/2 and gRPC traffic behind a Layer 7 load balancer: long-lived multiplexed connections versus ephemeral short-lived ones. How does connection pooling and multiplexing change throughput and resource usage compared to HTTP/1.1 keep-alive, what per-connection limits would you tune, and how should the load balancer measure load and apply backpressure to avoid head-of-line effects?
Sample Answer
Direct answer
HTTP/1.1 keep-alive needs roughly one TCP connection per concurrent in-flight request, so an L7 balancer scales by managing connection count. HTTP/2 and gRPC multiplex many concurrent streams over a small number of long-lived connections, so the balancer has to scale by managing stream concurrency within a connection instead, and load signals that were adequate for HTTP/1.1 (active connection count) become nearly useless. The practical consequence: fewer sockets and less TLS/TCP handshake overhead, but a new failure mode where one connection getting stalled or overloaded can degrade every stream multiplexed on it (head-of-line effects), which the balancer has to actively guard against.
Connection model comparison
| Dimension | HTTP/1.1 keep-alive | HTTP/2 | gRPC (HTTP/2 framing) |
|---|---|---|---|
| Connection lifetime | Reused per client, but 1 request in flight per connection (no multiplexing) | Long-lived, multiplexes many streams | Long-lived, same as HTTP/2 plus persistent bidirectional streaming RPCs |
| Concurrency unit the LB should track | Connection count | Streams per connection | Streams per connection, plus per-RPC deadlines |
| Typical tuning knob | max connections per backend, idle timeout, pool size | max_concurrent_streams per connection, connection pool size (few per backend), flow-control window | Same as HTTP/2, plus keepalive ping interval for long-idle streaming RPCs |
| Resource cost per unit of throughput | Higher: 1 TCP handshake + TLS handshake per request burst, more open sockets | Lower: handshake cost amortized across many streams, fewer sockets | Lower, same amortization; adds framing/serialization overhead per message |
| Head-of-line risk | None at the LB (each request has its own connection) | Yes: a stalled connection (e.g. TCP loss) blocks every multiplexed stream on it until retransmit | Yes, same mechanism, worse impact if a stream is a long streaming RPC holding the connection open |
Per-connection limits to tune
- HTTP/1.1: max connections per backend (bounds concurrency directly), idle keep-alive timeout (frees sockets from clients that went quiet), and pool size on the LB's upstream side.
- HTTP/2 / gRPC:
max_concurrent_streamsper connection (how many in-flight requests one connection may carry, commonly capped well below the protocol's theoretical maximum to bound blast radius), a small upstream connection pool per backend (a handful, not one) so a single stalled connection doesn't take out all traffic to that backend, per-stream flow-control window size (the amount of unacknowledged data a stream may have in flight before the sender must pause), and a keepalive ping interval to detect a half-open connection before streams queue behind a dead peer.
Load measurement and backpressure
Connection count stops being a useful load signal once multiplexing is in play: a backend with 4 connections and 400 streams looks identical to one with 4 connections and 4 streams if you only count sockets. Instead:
- Measure in-flight streams per backend (or
max_concurrent_streams - current_streamsas available capacity) and use that as the weighting signal for load-aware routing. - Track per-stream and per-connection latency percentiles separately; a rising per-connection tail with stable per-stream counts points at connection-level contention (CPU, flow-control), not request volume.
- Apply admission control at the stream level: reject new streams past a concurrency threshold with a fast, typed backpressure signal (gRPC
RESOURCE_EXHAUSTED, HTTP 429) rather than accepting and queuing, which just moves the head-of-line problem later. - Detect stalled streams (no progress against their flow-control window) and reset them individually instead of tearing down the whole connection, so one bad stream doesn't punish every other stream sharing it.
Worked example
Suppose the LB maintains a pool of 4 HTTP/2 connections to a backend, each configured with max_concurrent_streams = 100:
That backend can serve 400 concurrent RPCs using 4 sockets. Reaching the same 400 concurrent in-flight requests under HTTP/1.1 keep-alive would require roughly 400 separate TCP+TLS-established connections (one per in-flight request), which is exactly the socket and handshake overhead multiplexing removes. The other side of that number: if one of those 4 connections stalls, up to 100 of the 400 in-flight requests (25%) can be head-of-line blocked simultaneously, which is why the pool size (not just 1 connection) and per-stream stall detection both matter.
Trade-offs and pitfalls
- Fewer, fatter connections are more efficient but concentrate risk: a single TCP-level packet loss stalls every stream on that connection at the transport layer, even though the streams are logically independent at the application layer. This TCP-level head-of-line blocking is a known limitation of running multiplexing over TCP (it's the reason HTTP/3/QUIC exists), but that's depth beyond what most interviews expect; the interview-relevant point is just that a small connection pool, not a single connection, bounds the blast radius.
- A common mistake is reusing HTTP/1.1-era LB health/load metrics (connection count, connections-per-second) unchanged for HTTP/2 backends; they will systematically under-detect overload because a backend can look "quiet" on connections while being saturated on streams.
- Setting
max_concurrent_streamstoo high trades efficiency for blast radius; setting it too low defeats the purpose of multiplexing and pushes you back toward connection-count scaling.
Explain consistent hashing in the context of traffic distribution and distributed caches. Describe the hash ring, why virtual nodes are used, and how it minimizes remapping compared to plain modulo hashing when a node is added or removed. Walk through a small example.
Sample Answer
Direct answer
Consistent hashing maps both servers and keys onto the same hash space, conceptually a ring, so that a key belongs to the first server found going clockwise from the key's hash position. Unlike plain modulo hashing, where server = hash(key) mod n, changing the number of servers under consistent hashing only moves the keys sitting in the arc next to the server that was added or removed; every other key stays put. Virtual nodes, where each physical server is hashed to many points on the ring instead of one, are used to smooth out the otherwise lumpy arcs that a small number of real servers would create.
Structured elaboration
- The hash ring. Hash both server identifiers and keys into the same range, for example 0 to 255, and think of that range as a circle. To find the owner of a key, hash the key and walk clockwise until you hit the first server position.
- Why it minimizes remapping. When a server is added or removed, only the keys between that server's position and its predecessor's position need to move. Everything else still maps to the same server it did before, because no other server's position on the ring changed.
- Why virtual nodes. With only a handful of real servers placed at a few random points, the arcs between them can be very unequal by chance, so one server ends up owning a disproportionate share of keys. Giving each physical server many virtual positions (commonly 100 to a few hundred) averages this out and also means a removed server's keys spread across many surviving servers instead of dumping them all on one neighbor.
How much remapping this actually saves, comparing consistent hashing to naive modulo hashing when going from n to n+1 servers:
With consistent hashing, the new server claims a share of the ring and only those keys move; the expected fraction of the keyspace that moves is:
fraction moved (consistent hashing)=n+11With naive modulo hashing, a key keeps its server only when hmodn=hmod(n+1). Since n and n+1 share no common factor, that equality holds for exactly n values out of every n(n+1) consecutive hash values, so the fraction of keys that keep their server is 1/(n+1), and the fraction that must move is:
fraction moved (naive modulo)=n+1nWorked example
Small ring walkthrough. Three servers A, B, C hash to positions 10, 50, 200 on a 0-255 ring. Key k1 hashes to 20: walking clockwise from 20, the first server position is B at 50, so k1 maps to B. Key k2 hashes to 180: the first server position clockwise is C at 200, so k2 maps to C. Key k3 hashes to 230: there is no server position at or above 230, so the walk wraps around to the smallest position, A at 10, and k3 maps to A.
Now remove C. Only keys that previously mapped to C, meaning keys hashing into (50, 200], need to move. k2 (180) is in that range: walking clockwise from 180 with C gone, there is no server until the wrap to A at 10, so k2 now maps to A. k1 (20, maps to B) and k3 (230, already wrapping to A) are both unaffected, exactly as the fraction-moved formula predicts: only the keys in C's old arc move.
Numeric scale. With n=10 servers and K=1000000 keys, adding an 11th server:
keys moved (consistent hashing)=K×n+11=1000000×111≈90909 keys moved (naive modulo)=K×n+1n=1000000×1110≈909091Consistent hashing moves roughly 9.1% of the keyspace; naive modulo hashing moves roughly 90.9%, which for a cache means the equivalent of a near-total cold start on every capacity change.
Trade-offs & pitfalls
- Virtual node count is a real tuning knob: too few and load is lumpy across whichever real nodes happen to own the largest arcs; too many and every lookup and rebalance touches more ring entries and more memory.
- A perfectly balanced ring does not protect against a hot key: hashing spreads keys evenly, not access frequency, so one very popular key can still overload the single node that owns it.
- Weight servers by capacity through proportional virtual node counts (a server with twice the capacity gets twice the virtual nodes), rather than assuming uniform hashing will "even out" heterogeneous hardware on its own.
Unlock Full Question Bank
Get access to all Load Balancing and Traffic Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.