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.
Describe an end-to-end connection draining strategy for a deployment where the traffic mix includes both short HTTP requests and long-lived WebSocket connections, from the moment an instance is marked for removal to the point it's safe to terminate. How would you measure and validate a safe drain duration in staging before trusting it in production?
Sample Answer
Direct answer
Draining safely with a mix of short HTTP and long-lived WebSocket connections means stopping admission of new work immediately (fail readiness, deregister), letting in-flight HTTP finish naturally since it is already short, and giving WebSocket connections an explicit grace period bounded by a measured drain timeout, after which any still-open connection is force-closed. The timeout itself should not be a guess: measure the real duration distribution of long-lived connections in staging, pick a percentile with a safety margin, and validate that choice by re-running the drain and checking how many connections it actually force-closes.
Structured elaboration
- Stop new traffic first. Flip readiness to failing (or deregister from the load balancer's target pool) before doing anything else, so no new HTTP request or WebSocket upgrade attempt lands on the draining instance. New upgrade attempts should get a fast rejection (503), not a connection that immediately gets drained.
- Let short HTTP finish on its own. In-flight HTTP requests are typically done within seconds; rely on the load balancer's own connection-draining or deregistration-delay setting to keep the instance reachable for just those existing connections, not new ones.
- Give WebSockets a bounded grace period. Send a close frame with a reason and, where the client supports it, a suggested reconnect delay. Track how many WebSocket connections remain open and how long the drain has been running; when the timeout is reached, force-close whatever is left rather than draining indefinitely.
- Measuring the timeout in staging. Generate a realistic connection-duration distribution under staged load (not just connection count, the actual spread of session lengths), trigger a controlled drain, record how long each connection was open, and compute a high percentile (for example p90 or p99) of that distribution as the timeout floor before adding a safety margin.
stateDiagram-v2
[*] --> InRotation
InRotation --> Draining: marked for removal, readiness fails
Draining --> Draining: HTTP finishes naturally; WS gets close frame
Draining --> SafeToTerminate: HTTP count = 0 and WS count = 0
Draining --> ForceClose: drain timeout reached
ForceClose --> SafeToTerminate
SafeToTerminate --> [*]
Worked example
A staging drain test records 10 WebSocket session durations in seconds (fully specified for this example): 12, 15, 20, 22, 30, 35, 40, 55, 90, 240. Already sorted ascending, with n=10.
Using the nearest-rank method, the 90th percentile index is:
rank=⌈0.90×10⌉=9The 9th value in the sorted list is 90 seconds, so p90=90 s.
Add a 20% safety margin and round to a configuration-friendly value:
90×1.2=108⇒drain timeout=110 sValidate by re-running the same drain with the 110-second timeout: only the 240-second session exceeds it, so exactly 1 of 10 sessions would be force-closed, a 1/10=10% forced-close rate in this sample. If the team's tolerance for forced WebSocket closures during a deploy is, say, under 5%, this result fails validation and the timeout needs to go higher, or the long tail needs a real fix (session handoff and client-side reconnect) instead of a longer wait.
Autoscaling context. The same drain path fires on scale-in, not just deploys. If sticky routing pins long-lived sessions to specific pods, a scale-in event has to drain those pinned sessions the same way, and frequent autoscaling churn means paying this drain cost far more often than a deploy cadence would; that is a real argument for moving session state out of the pod (a shared store) rather than tuning the drain timeout ever higher to compensate.
Trade-offs & pitfalls
- Too-short a timeout forces out legitimate long sessions and shows up as user-visible disconnects; too-long a timeout slows every deploy and scale-in and holds resources the orchestrator thinks it already reclaimed.
- A percentile chosen from a staging dataset is only as good as how representative that dataset's traffic mix and connection-duration shape are; validate against real production duration distributions periodically, not once at design time.
- Common wrong turn: reusing the same drain timeout for HTTP and WebSocket paths. HTTP's tail is usually seconds; WebSocket's tail can be minutes to hours, and forcing HTTP to wait for the WebSocket-sized timeout just slows every deploy for no benefit.
- Session handoff or reconnect logic on the client is what actually solves the extreme tail (a connection open far longer than any reasonable timeout); a timeout alone only bounds how long you wait before giving up on it.
Design a monitoring and alerting setup for a load balancer tier so you catch unhealthy backends before users see errors. Which metrics would you include and why, what alert thresholds would you propose, and how would you differentiate severity to avoid alert fatigue?
Sample Answer
Direct answer
Catching unhealthy backends before users notice means monitoring the LB tier along four angles: traffic, latency, and errors as seen from the LB itself (the RED metrics), backend health signals independent of user-facing symptoms, saturation and capacity of the LB tier, and TLS/connection-layer health, then tying alert severity to how much of the user-facing error budget (the amount of failure your reliability target still allows before you've broken your promise to users) is actually being consumed rather than to a single static threshold, so a brief blip and a sustained outage don't page the same way.
The metric set
| Category | Metric | Why it matters |
|---|---|---|
| Traffic | Requests per second, overall and per backend pool | Baseline for interpreting every other metric; a rate change can explain an error-rate change |
| Latency | p50 / p90 / p95 / p99, split into LB-processing time and end-to-end time | Percentiles catch tail degradation that an average hides; splitting LB time from backend time tells you where the slowdown is |
| Errors | 4xx vs 5xx rate, and whether 5xx originated at the LB (no healthy backend) or was passed through from a backend | A 5xx-at-the-LB spike usually means capacity loss, not an application bug |
| Backend health | Per-backend health-check pass/fail rate and consecutive-failure counts | The direct signal for whether a specific node is about to be pulled |
| Connections | Active connections and connection churn (opens/closes per second) | A churn spike often precedes a latency or error spike |
| Capacity | LB-tier CPU, memory, socket/file-descriptor usage | The LB tier itself can become the bottleneck, not just the backends |
| TLS | Handshake failure rate, certificate expiry countdown | Silent failure mode: expired certs or handshake issues look like "backend is fine but nobody can connect" |
| Traffic shaping | Rate-limit rejections, circuit-breaker open/close events | Leading indicators: a circuit breaker tripping on a backend is an early warning before that backend fails health checks outright |
Alert severity: tie it to error-budget burn, not just a raw threshold
A raw threshold ("page if 5xx rate > 1%") treats a 10-minute blip the same as a slow multi-hour decline, a common cause of alert fatigue in either direction: it either pages on noise or is set so loose it misses real problems. The more robust approach expresses the threshold as a multiple of your error-budget burn rate: if you're consuming your monthly error budget faster than the rate at which "consume it evenly over 30 days" would, page proportionally to how much faster.
Worked example
Suppose the LB tier's SLO (service-level objective, the reliability target you've committed to, here 99.9% of requests succeeding) is 99.9% success rate over a 30-day window. The allowed error budget is 0.1% of requests, equivalently, 0.1% of the 30-day window can be fully down and still meet the SLO:
- 30 days in minutes: 30×24×60=43,200 minutes.
- Budget: 43,200×0.001=43.2 minutes of full-downtime-equivalent for the entire month.
Now suppose the current 5xx rate over the last hour is holding at 2%, against an objective of 0.1%. The burn rate is:
burn rate=0.1%2%=20×At 20 times the sustainable rate, the entire month's budget would be exhausted in:
2030 days=1.5 daysA burn rate that would exhaust the monthly budget in 1.5 days is unambiguously page-worthy; a burn rate of, say, 1.2 times sustainable is not, it just needs tracking. That is the difference between a severity-1 page and a low-priority ticket, expressed in the same unit (budget consumption), not two arbitrarily different percentage cutoffs.
Avoiding alert fatigue
- Tier severity by projected budget-exhaustion time (minutes-to-exhaust pages immediately, weeks-to-exhaust becomes a ticket), rather than by a single static percentage.
- Deduplicate and correlate: a health-check-flapping alert and a 5xx-rate alert firing from the same underlying cause should collapse into one incident, not page twice.
- Route by audience: on-call needs the actionable, current-state view (which backend, since when); a weekly review needs the trend (is health-check-induced churn increasing over time).
- Require every page-level alert to link directly to a runbook step; an alert with no clear next action trains people to ignore it.
Trade-offs and pitfalls
Over-indexing on system-level metrics (CPU, connections) without a user-facing correlate risks paging on things users never notice; conversely, only alerting on aggregate error rate can hide a problem affecting one backend pool or one tenant while the aggregate stays healthy. Circuit-breaker and rate-limit rejection counts are easy to skip because they're not "errors" in the traditional sense, but they're often the earliest signal, by the time health checks start failing outright, the circuit breaker has usually already tripped.
A client asks you to choose between a managed cloud load balancer (like AWS ALB/NLB), an open-source proxy (NGINX/HAProxy), and an Envoy-based service mesh. Build a selection rubric covering scalability, supported protocols and features, management overhead, and cost, and recommend an approach for a 200-service enterprise.
Sample Answer
Direct answer
Build the choice as a scored rubric across scalability, protocol/feature support, management overhead, and cost, then let the traffic pattern decide the split: use a managed cloud LB at the edge for north-south traffic regardless of the rest of the answer, and reserve the OSS-vs-mesh decision for east-west, service-to-service traffic, since the three options aren't really mutually exclusive at 200-service scale, they're complementary layers.
Structured elaboration: the selection rubric
Score each option 1 (weak) to 5 (strong) per dimension for the specific environment (here: multi-AZ cloud deployment, moderate-to-high east-west traffic, mTLS and fine-grained observability required, team can grow SRE capacity but wants cost discipline):
| Dimension | Managed cloud LB (ALB/NLB) | OSS proxy (NGINX/HAProxy) | Envoy-based mesh |
|---|---|---|---|
| Scalability | 5, autoscaled by the provider, no capacity planning | 3, scales well but you own the capacity planning and HA | 4, scales roughly linearly with services, but the control plane needs its own scaling plan |
| Protocol/feature support | 4, HTTP/1.1, HTTP/2, WebSocket, basic L7 routing; limited deep app-level policy | 4, rich routing and scripting (e.g. Lua), broad protocol support, config is fully in your hands | 5, first-class gRPC/HTTP2, retries, timeouts, circuit breakers, fault injection, weighted/subset routing |
| Management overhead | 5, lowest, provider-operated | 2, you own deployment, scaling, patching, and config management end to end | 3, moderate to high: control plane (the centralized system that computes and pushes routing/policy configuration out to every proxy) and sidecar (a small proxy process deployed alongside each service instance that the mesh routes traffic through, instead of the app talking to the network directly) lifecycle, certificate rotation, upgrade coordination |
| Security | 4, TLS at the edge, WAF (web application firewall, which filters malicious HTTP requests) integration available | 3, you manage TLS termination and rotation yourself | 5, mTLS (mutual TLS: client and server both authenticate each other via certificates) and per-service identity largely by default |
| Observability | 3, access logs and aggregate metrics, no per-call tracing without app-level work | 3, custom metrics/logs, requires your own instrumentation | 5, distributed tracing, per-route metrics, service maps near-automatically |
| Cost (TCO) | 4, higher per-request pricing offset by near-zero ops cost | 4, low infrastructure cost, higher people cost | 3, sidecar CPU/memory overhead per instance plus control-plane and ops investment |
Worked example: scoring the recommendation
Summing the six dimensions above (unweighted, for illustration; a real rubric would weight dimensions by what the org actually cares about):
ALB/NLB total=5+4+5+4+3+4=25 NGINX/HAProxy total=3+4+2+3+3+4=19 Envoy mesh total=4+5+3+5+5+3=25The tie between the managed LB and the mesh is the point, not a coincidence: they score highest on different dimensions (ops simplicity vs. observability and policy control) because they solve different problems. That's the argument for a hybrid rather than picking a single winner from the sum.
Recommendation for a 200-service enterprise
- Edge (north-south): managed cloud LB (ALB/NLB). Handles TLS termination, WAF, and DDoS protection with near-zero operational burden, this is not where the interesting trade-off is.
- East-west (service-to-service): Envoy-based mesh, adopted incrementally. This is where the mesh's mTLS-by-default, fine-grained retry/circuit-breaker policy, and automatic tracing earn their operational cost at 200-service scale, a scale where manually wiring TLS and tracing per service would be far more expensive than the mesh control plane.
- Reserve plain NGINX/HAProxy for specific pockets: legacy monoliths not yet mesh-integrated, or workloads needing custom scripting the mesh's policy surface doesn't cover.
Rollout plan to bound risk:
- Pilot the mesh on 10 to 20 non-critical services first; validate mTLS, tracing, and latency overhead against real traffic before wider rollout.
- Automate sidecar injection and policy-as-code so config changes are reviewed the same way application code is.
- Watch sidecar CPU/memory overhead and control-plane push latency as adoption grows past the pilot, this is the axis most likely to surprise a team scaling past a few dozen services: at 200 services averaging 20 instances each, a naive full-state config push touches roughly all 4,000 sidecars (200 x 20) on every single endpoint change, so a mesh control plane needs incremental, delta-only pushes, or a routine pod restart anywhere in the fleet turns into a mesh-wide config storm.
Trade-offs and pitfalls
- A rubric with unweighted dimensions can mislead. The 25-25 tie above only makes sense once you decide which dimensions actually matter for this org, a security-and-compliance-heavy environment should weight the security and observability rows far higher than the raw sum suggests.
- "Managed" reduces ops burden but also reduces control. A managed LB's feature roadmap and support SLAs become dependencies you don't own; that's a real cost even when it doesn't show up as a rubric number.
- Mesh adoption cost is back-loaded, not front-loaded. The pilot phase looks cheap; the real cost shows up in certificate lifecycle management, control-plane HA, and upgrade coordination once hundreds of services depend on the mesh being correct.
- Don't let the rubric replace a pilot. Scores are directional; only a real pilot against production-shaped traffic reveals whether the latency overhead and operational load are actually acceptable for this specific org.
Explain the differences between the common rate-limiting algorithms: fixed window, sliding window, token bucket, and leaky bucket. For each, describe a typical use case, its strengths and weaknesses, and how it handles bursts and fairness across clients.
Sample Answer
Direct answer
All four algorithms answer the same question, "has this client used too much capacity", but they differ in what they track (a count in a time bucket vs a bank of tokens vs a queue) and in how they treat bursts. Token bucket and leaky bucket are the two production workhorses, though the specific tool decides which: nginx's limit_req module implements leaky bucket by its own documentation, while Envoy's local rate limit filter and most API gateways default to token bucket; fixed window is the simplest and the one with the well-known boundary flaw; sliding window is the fix for that flaw at some extra cost.
How each algorithm works
| Algorithm | How it tracks usage | Typical use case | Burst behavior | Main weakness |
|---|---|---|---|---|
| Fixed window | Count per client in a hard time bucket (e.g. a minute boundary), reset each window | Simple quota tiers, dashboards | Allows a full limit's worth of requests right before AND right after a boundary | Boundary spike (see worked example) |
| Sliding window (log or counter) | Either a timestamped log of recent requests, or a weighted blend of the current and previous fixed windows | Enforcement where boundary spikes are unacceptable | Smooths the boundary case; still allows up to the limit in any rolling interval | Sliding log costs memory proportional to request volume; sliding counter is an approximation |
| Token bucket | Tokens accrue at a steady refill rate up to a capacity; each request spends a token | API gateways, network shapers, anywhere you want an average rate with tunable burst headroom | Bursts up to bucket capacity, then throttled to the refill rate | Needs separate tuning of capacity vs refill rate |
| Leaky bucket | Requests queue and drain at a fixed rate; queue has a max depth | Shaping outbound traffic to a fixed-rate downstream consumer | Does not allow bursts past queue depth; excess is queued or dropped | Adds queuing latency, can drop legitimate bursts |
Fairness in all four comes from your key, not the algorithm: per-client buckets/counters are fair, a shared global counter or queue lets one aggressive client crowd out the rest. Leaky bucket is the exception worth calling out, since a single shared queue is the one case where "fair" requires a deliberate per-client sub-queue design, not just a per-client key.
Worked example: the fixed-window boundary spike, bounded by token bucket
Take a limit of L=100 requests per minute (T=60s).
Fixed window: nothing stops a client from sending its full limit in the last instant of window k and its full limit again in the first instant of window k+1, since the counter resets at the boundary regardless of timing. The worst-case burst that can land in an arbitrarily short span straddling a boundary is:
Bfixed=2L=200 requeststwice the nominal per-minute limit, with no time gap required between them.
Token bucket, configured with capacity C=L=100 and refill rate
r=TL=60100≈1.667 tokens/scannot exceed C tokens instantaneously no matter when the burst lands, because tokens only exist if they were refilled or never spent. Its worst-case burst is bounded by the bucket's own capacity:
Btoken=C=100 requestsa strictly tighter and, crucially, tunable bound (shrink C for stricter burst control, or grow it for more headroom) that fixed window cannot offer without a redesign.
Trade-offs and pitfalls
- Fixed window is cheap (one counter, one TTL) but the 2L boundary spike is a real production failure mode, not a theoretical one; it shows up as bursty traffic right at minute or hour boundaries.
- Sliding window counter (the common production approximation) trades exactness for cheap, fixed-size storage by blending the previous window's count, weighted by how much of it still overlaps the current interval; the sliding log is exact but its memory grows with request volume, which matters at high request rates per client.
- Token bucket's two knobs, capacity and refill rate, are independent: capacity controls burst tolerance, refill rate controls sustained average. Conflating them (e.g. setting capacity to one second's worth of the sustained rate) either kills legitimate bursts or defeats the limit.
- Leaky bucket is the right choice when you must protect a downstream that cannot absorb bursts at all (a fixed-rate consumer), but adding a queue trades burst-drop for burst-delay; a queue that's too deep just turns a rate-limit problem into a latency problem.
- Distributed enforcement (the same client hitting many nodes) is the pitfall every one of these hits eventually: none of the four is inherently safe for a multi-instance deployment without a shared store or an approximation scheme layered on top.
Compare consistent hashing and rendezvous (highest-random-weight) hashing. How does each handle node addition and removal, what is the cost of rebalancing, and which would you use for cache routing versus partitioned storage with heterogeneous node weights?
Sample Answer
Direct Answer
Consistent hashing (CH) places nodes and keys on a hash ring and routes each key to the next node clockwise; rendezvous hashing (also called highest-random-weight, HRW) scores every node for a given key with an independent hash and routes to the node with the highest score. Both move only a small, bounded fraction of keys when the node set changes, but they differ in what they need to operate: CH needs a maintained ring data structure (and virtual nodes to balance load), while HRW needs nothing shared at all, it recomputes from scratch on every lookup. That operational difference, not raw performance, usually decides which one you pick.
How Each Handles Node Changes
Consistent hashing. Nodes (or their virtual tokens) occupy positions on a ring. A key is owned by the first node clockwise of its hash position. Adding a node inserts a new position and reassigns only the keys that fall in the arc between the new node and its counterclockwise neighbor. Removing a node deletes its position, and in a plain single-token ring, every key that node owned is reassigned entirely to its clockwise successor. That successor absorbs the whole load, it is not spread across the rest of the cluster. This is why production consistent-hash rings almost always use virtual nodes: giving each physical node many tokens scattered around the ring means a removal's load lands on many different successors instead of one.
Rendezvous hashing. For a key, each node's score is an independent draw from a hash function, and the node with the maximum score wins. Adding a node adds one more independent score into the comparison; only keys where the new score happens to be the maximum move, and they move only to the new node. Removing a node drops one score out of the comparison; for every key that node used to win, the new winner is whichever of the remaining nodes had the second-highest score, which, because all scores are independently drawn from the same distribution, is uniformly distributed across the survivors. Rendezvous hashing gets even redistribution on removal for free, without virtual nodes.
Cost of Rebalancing
| Operation | Consistent hashing (single-token) | Consistent hashing (with V virtual nodes/node) | Rendezvous hashing |
|---|---|---|---|
| Node join | Only the new node's arc moves | Only the new node's arc(s) move | Only keys where the new score wins move |
| Node leave | All of the removed node's keys land on one successor | Removed node's keys spread across roughly V nearby successors | Removed node's keys spread uniformly across all survivors |
| Lookup cost | O(log T) with T ring tokens (binary search) | O(log T), T grows with V | O(N) hash evaluations per key, N = node count |
| Metadata to maintain | Sorted ring of N positions | Sorted ring of N*V positions | None beyond the current node list |
Worked Example
Take a cluster of N=10 nodes holding keys uniformly on the ring, so each node owns an expected 101 of the keyspace.
Join (both schemes). Adding one node makes it 1 of 11 exchangeable ring owners (CH) or 1 of 11 exchangeable score-holders (HRW). By symmetry, the new node's expected share is:
N+11=111≈9.1%and every other node's share is unaffected in expectation, for both schemes.
Leave, plain single-token consistent hashing. The removed node held N1=101=10% of keys. All of it moves to one clockwise successor, whose share becomes:
101+101=102=20%That successor now carries double its prior load, a hotspot, while the other 8 surviving nodes are untouched.
Leave, rendezvous hashing (or CH with enough virtual nodes to approximate it). The removed node's 10% share spreads uniformly across the 9 survivors. Each survivor's new share:
101+10×91=909+1=91≈11.1%which is exactly the uniform N−11 share you would expect if the whole keyspace were freshly and evenly split across 9 nodes. This algebra generalizes: N1+N(N−1)1=N−11, confirming that rendezvous hashing (and a well-provisioned virtual-node ring) reach the ideal uniform post-removal distribution automatically, while a plain single-token ring does not.
Which to Use
For cache routing (many roughly similar-capacity nodes, request-level lookups, simplicity matters, weights may differ per node's memory size), rendezvous hashing is usually the simpler choice: no ring to maintain, exact per-node weighting by scaling scores, and even load redistribution on failure without tuning a virtual-node count. The O(N) lookup cost is rarely the bottleneck unless N reaches the high hundreds or thousands of cache nodes.
For partitioned storage with a large number of partitions (sharded databases, distributed key-value stores), consistent hashing with virtual nodes is usually preferred: ownership maps to contiguous ranges, which supports range scans and simple "move this token's range" rebalancing tooling, and lookup stays O(log T) even as the ring grows large. Heterogeneous weights are handled by giving higher-capacity nodes proportionally more virtual nodes, though that is a discrete approximation rather than an exact ratio.
Trade-offs and Pitfalls
- The single-token consistent-hashing hotspot on removal (shown above) is a frequent interview trap: candidates who describe CH without mentioning virtual nodes are implicitly describing a scheme with an uneven-failover problem.
- Rendezvous hashing's O(N) per-lookup cost is a real scaling limit for very large node counts; production systems mitigate it with a hierarchical or bounded-candidate variant rather than switching to CH purely for that reason.
- Weighting is exact and continuous with rendezvous hashing (scale each node's score by its weight) but only approximate with CH virtual nodes (weight is quantized by how many tokens you assign).
- Neither scheme is free of the "every key touches every node during full re-sharding" cost if you ever need to change the hash function itself (e.g., migrating hash algorithms); that requires a coordinated dual-write or shadow-ring migration regardless of which scheme you use.
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.