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.
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.
A backend instance recovers after being marked unhealthy, and a flood of clients reconnect immediately and overwhelm it (thundering herd). What mitigations would you apply at the load balancer and application level to prevent this?
Sample Answer
Direct answer
The fix has to work at both layers: the load balancer should bring a recovered instance back into rotation gradually (slow-start / weight ramp) rather than at full weight immediately, and clients should retry with jittered exponential backoff rather than reconnecting in lockstep the moment they see the instance healthy again. Neither alone is sufficient: LB-side ramping protects against a coordinated flood, but internal callers that bypass client backoff will still hit the instance hard once its weight is nonzero, so admission control (a hard per-instance connection/request cap) is the backstop that holds regardless of what clients do.
Load balancer mitigations
- Slow-start / weighted ramp-up: on transition to healthy, start the instance's LB weight near zero and increase it on a schedule (linear or exponential) instead of jumping to full share immediately.
- Health-check hysteresis: require several consecutive successful probes, not one, before even starting the ramp, so a flapping instance doesn't repeatedly trigger fresh thundering-herd events.
- Hard admission caps: independent of weight, enforce a per-instance connection/request ceiling at the LB so the ramp schedule isn't the only thing standing between the instance and overload.
- Sticky-routing caution: if session affinity is in use, avoid re-establishing it fully during ramp-up, since affinity can concentrate a disproportionate share of long-lived clients onto a still-warming instance.
Application-level mitigations
- Jittered exponential backoff on clients: spread reconnect attempts in time instead of retrying immediately or on a fixed interval that resynchronizes across clients.
- Admission queueing with a bound: the instance itself accepts up to a limit and returns 429/503 with
Retry-Afterbeyond that, rather than accepting everything and falling over. - Circuit breakers upstream of the instance: if error/latency crosses a threshold during ramp-up, upstream callers back off automatically instead of continuing to hammer it.
Worked example
Suppose the recovered instance's established safe steady-state capacity is C=5,000 RPS, and the pent-up demand specifically targeting it (clients that were failing over away from it and are now retrying) is D=50,000 RPS, 10x its safe capacity. The LB ramps its weight starting at w0=1%, doubling every 10 seconds:
w(t)=min(1,w0⋅2t/10),admitted(t)=min(w(t)⋅D,C)| t (s) | weight | w(t)*D (RPS) | admitted (RPS, capped at C) |
|---|---|---|---|
| 0 | 1% | 500 | 500 |
| 10 | 2% | 1,000 | 1,000 |
| 20 | 4% | 2,000 | 2,000 |
| 30 | 8% | 4,000 | 4,000 |
| 40 | 16% | 8,000 | 5,000 (capped) |
| 50 | 32% | 16,000 | 5,000 (capped) |
By t=40s the instance is already running at its full safe capacity even though the LB weight is still far below 100%; from that point on, the hard admission cap (not the weight ramp) is what's actually protecting it, and the ramp continuing upward just determines when the instance starts absorbing a "fair" share once the herd's backlog (D) has drained through the rest of the pool. This is the concrete reason both mechanisms are needed: the ramp controls the early window when D is far above C, and the hard cap controls everything after, once weight alone would otherwise overshoot.
Trade-offs and pitfalls
- Slow-start delays how quickly the pool's overall capacity recovers, which matters if the rest of the pool is itself under strain; the ramp duration is a real trade-off between protecting the recovering instance and relieving the rest of the fleet faster.
- Implementing only client-side backoff misses internal service-to-service callers that don't go through the same retry library; implementing only LB-side ramping misses the fact that a fixed weight schedule can still be overwhelmed if pent-up demand is large enough relative to the ramp rate, which is exactly why the hard admission cap has to exist independent of the ramp.
- A common failure in postmortems is tuning the ramp curve without ever computing whether the ramp rate can plausibly outrun realistic pent-up demand (as in the worked example above); a ramp that's too slow relative to D just delays the herd, and one that's too fast relative to C doesn't protect the instance at all.
Describe DNS-based load balancing strategies: round-robin DNS, weighted DNS, and GeoDNS. What are their pros and cons for global traffic distribution, and how do DNS TTL and resolver caching affect failover speed and consistency? How would you design TTLs for fast failover without overloading your authoritative nameservers?
Sample Answer
Direct answer
Round-robin, weighted, and GeoDNS are all ways an authoritative DNS server chooses which IP to hand back for the same hostname, they differ only in the selection rule (rotate, weighted-random, or client-location-based), and all three inherit the same fundamental limitation: once a resolver caches an answer, DNS has no way to recall it. Failover speed is bounded entirely by TTL and by how faithfully resolvers respect it.
Structured elaboration
| Strategy | How it picks | Strength | Weakness |
|---|---|---|---|
| Round-robin DNS | Rotates through a fixed list of A/AAAA records per query | Trivial to set up, no extra infrastructure | No health awareness at all; an unhealthy endpoint keeps getting served until manually removed |
| Weighted DNS | Returns records probabilistically according to assigned weights | Coarse traffic-split control (e.g. 70/30 between two regions) | Still not health-aware by itself; actual observed split drifts because of resolver-side caching, not a live probability draw per real user |
| GeoDNS | Returns the record for the region nearest the resolver's (not necessarily the client's) location | Lower latency, keeps traffic and egress cost regional | IP-to-geo mapping is imperfect, especially for clients behind large/shared corporate or ISP resolvers |
None of the three is health-aware on its own. In practice all three are paired with active health checks (e.g. Route 53 health-checked records, a GSLB, Global Server Load Balancing: DNS that also factors in live health checks, so it can steer traffic away from an unhealthy region instead of rotating blindly) that add or remove a record from the pool based on liveness, the DNS strategy alone only decides selection among whatever is currently in the pool.
Worked example: TTL vs. authoritative query load
Assume roughly 1,000,000 independently-caching clients (accounting for resolver fan-out, this is "cache entries," not literal end users) issuing steady lookups for the hostname. Because each client re-queries only when its cached TTL expires, the sustained query rate the authoritative server sees is approximately:
QPSauthoritative≈TTL (s)unique caching clients TTL=300s⇒3001,000,000≈3,333 QPS TTL=60s⇒601,000,000≈16,667 QPS TTL=30s⇒301,000,000≈33,333 QPSDropping TTL by 10x (300s to 30s) multiplies authoritative query load by 10x for the same client population. Designing TTL is therefore a direct trade between failover speed and nameserver load, not a free lunch: pick the lowest TTL that (a) your authoritative infrastructure (typically anycast-backed managed DNS) can sustain at expected client scale, and (b) actual public resolvers will honor, many ISP and public resolvers apply a practical floor around 30 to 60 seconds regardless of the record's stated TTL.
Trade-offs and pitfalls
- Negative caching is caching too. An NXDOMAIN or SERVFAIL response gets cached according to the zone's SOA minimum TTL, a botched record removal can produce a resolvable-but-wrong period followed by an unexpectedly long "not found" period.
- Very low TTLs are not guaranteed to help. Below the resolver's practical floor, requesting a 5s TTL buys nothing while still multiplying real query volume against the servers that do honor it.
- DNS is a request for a new answer, not a push. A client that already opened a connection or cached the resolution client-side (browser, HTTP client, container DNS cache) is unaffected by a DNS change until it does a fresh lookup, so DNS TTL bounds resolver-level staleness, not necessarily client-visible staleness.
- A common practical pattern: keep a stable, moderate TTL (e.g. 300s) in steady state to protect the authoritative servers, and only drop to a low TTL (e.g. 30 to 60s) proactively ahead of a planned migration or maintenance window, since a TTL change itself only takes effect after the previous TTL expires.
How does weighted round robin differ from applying weights to least-connections? Sketch how you would distribute requests proportional to backend weight under each approach, and describe when you would adjust weights dynamically, for example during autoscaling or when an instance is degraded.
Sample Answer
Direct answer
Both are ways to make an algorithm capacity-aware, but they optimize different things. Weighted round robin (WRR) distributes a fixed pattern of requests proportional to weight, without looking at current load: it is a scheduling problem, solved up front. Weighted least connections picks, per request, whichever server has the lowest connections-to-weight ratio: it is a live load-balancing decision that reacts to what's actually happening on each server right now. WRR is cheaper and predictable; weighted least connections is more adaptive when request duration varies.
Weighted round robin mechanics
A naive WRR just repeats each server in the rotation list a number of times equal to its weight (weight 5, 1, 1 becomes the list [A,A,A,A,A,B,C]), which is simple but bursty, all of A's requests land in a clump. The standard fix is smooth weighted round robin, used by nginx and others: each server keeps a running counter, and at every request:
then the server with the highest counter is selected, and only that server's counter is reduced by the total weight:
ci∗(t+1)=ci(t+1)−W,W=j∑wjWorked trace: weights A=5, B=1, C=1 (W=7)
| Step | Counters after add (A, B, C) | Selected | Counters after subtract |
|---|---|---|---|
| 1 | 5, 1, 1 | A | -2, 1, 1 |
| 2 | 3, 2, 2 | A | -4, 2, 2 |
| 3 | 1, 3, 3 (tie B/C, broken alphabetically) | B | 1, -4, 3 |
| 4 | 6, -3, 4 | A | -1, -3, 4 |
| 5 | 4, -2, 5 | C | 4, -2, -2 |
| 6 | 9, -1, -1 | A | 2, -1, -1 |
| 7 | 7, 0, 0 | A | 0, 0, 0 |
Sequence: A, A, B, A, C, A, A. Final counts: A=5, B=1, C=1, exactly matching the declared weights, and after 7 steps every counter returns to 0, so the pattern repeats cleanly. Compare this to the naive list [A,A,A,A,A,B,C]: smooth WRR interleaves B and C between A's turns instead of clumping them at the end.
Weighted least connections mechanics
Instead of a precomputed pattern, each request goes to whichever server minimizes:
scorei=wiciwhere ci is current active connections. This needs live state (the balancer must track connection counts accurately) but it self-corrects when request durations vary: if one of A's requests is unusually slow and its connection count stays elevated, weighted least connections routes around it immediately, while WRR would keep sending A its scheduled 5-out-of-7 share regardless.
When to adjust weights dynamically
- Autoscaling: when an instance joins or leaves the pool, recompute weights from the group's new capacity (commonly proportional to vCPU count or a load-tested throughput figure), otherwise new instances sit idle while old ones stay pinned to stale weights.
- Degraded instance: on failed or borderline health checks, reduce the instance's weight toward zero (a soft drain) rather than hard-removing it, so in-flight requests finish before it stops receiving new ones.
- Heterogeneous hardware: base weights on measured throughput under load, not just instance-type labels, since two "same size" instances can have different real capacity due to noisy neighbors or different hardware generations.
- Oscillation risk: reacting to every latency blip by changing weights can cause a feedback loop (a server's weight drops, it gets less traffic, its metrics improve, weight goes back up, traffic returns, metrics degrade again). Apply a decay or minimum-dwell-time before a weight change takes effect.
Trade-offs and pitfalls
WRR is stateless and cheap to run at very high request rates because it never inspects live connection counts, but it is blind to reality: if a server silently starts responding slowly, WRR keeps sending it its full scheduled share. Weighted least connections fixes that but needs accurate, low-latency visibility into connection counts across the fleet, which is harder in a distributed balancer with multiple LB instances that don't share state. A common middle ground is weighted least connections with a smoothing factor so weight changes and connection counts don't cause the oscillation described above.
Case study: during a region failover, traffic was redirected to another region, which then became overloaded and failed too. How would you investigate the cascade using metrics, logs, and traces to identify the contributing factors, and what short-term and long-term changes would you propose?
Sample Answer
Direct answer
Treat the cascade as a causal chain to reconstruct, not a single event: build a timeline correlating the failover trigger (DNS/LB cutover) against the target region's saturation signals, then look specifically for the amplifying mechanism that turned a redirect into a second outage, whether that's insufficient headroom, retries piling on top of already-degraded capacity, or slow autoscaling. The single highest-value question in the investigation is usually: was the surviving region ever provisioned to absorb the failed region's full traffic, or only a fraction of it?
Investigation approach
| Signal type | What to pull | What it tells you |
|---|---|---|
| Metrics | RPS, CPU, queue depth, connection count, per-region and per-service, before/during/after cutover | Whether the target region was already near capacity before absorbing the failed region's traffic |
| Logs | LB/gateway logs, DNS/CDN logs, autoscaler events, error codes (502/504/429) | The exact timeline of the cutover and whether errors preceded or followed the traffic shift |
| Traces | Distributed traces during the overload window | Whether fan-out amplified the load (one failed request triggering multiple downstream calls) and where tail latency concentrated |
| Control plane | DNS TTL, health-check config, routing/weight change history | Whether the cutover was instantaneous or overlapped (old region still receiving some traffic during transition, compounding total demand briefly) |
Build the timeline first, then work backward from the second region's failure point to find what was different about the moment it tipped over: a specific traffic level, a specific downstream dependency saturating, or a specific automation event (autoscaler decision, config push).
Common contributing factors
- No global rate limiting, so the surviving region absorbed 100% of demand instead of shedding the excess.
- Autoscaling too slow to react within the failover window, so capacity lagged the traffic shift.
- DNS TTL or connection-draining overlap meaning the "instant" failover wasn't actually instant, briefly inflating total concurrent demand across both regions.
- Retries from clients and internal services amplifying load on top of an already-degraded region rather than backing off.
- Regional headroom sized for local (within-region) redundancy, not for absorbing a peer region's entire traffic.
Worked example
Suppose pre-incident traffic is 100,000 RPS total, split 60/40 between Region A and Region B, and each region carries standard N+1-style headroom (provisioning one extra unit of redundant capacity beyond what's needed for steady-state load) of 1.3x its own steady share:
DACALBfailoverdeficit=0.6D=60,000 RPS,DB=0.4D=40,000 RPS=1.3DA=78,000 RPS,CB=1.3DB=52,000 RPS=DA+DB=100,000 RPS=CBLBfailover−CB=52,000100,000−52,000≈0.923 (92.3% over capacity)Region B was provisioned with a comfortable 30% margin over its own normal share, but a full regional failover requires it to absorb Region A's traffic on top of its own, roughly double what its headroom was ever sized for. This is the analytical version of "the surviving region became overloaded and failed too": the headroom math was correct for local redundancy and simply never accounted for full peer-region failover, which is a sizing decision, not a runtime bug.
Short-term response
- Shed or throttle low-priority traffic in the surviving region immediately to bring load back under its safe ceiling.
- Apply global (not per-region) rate limits so no single region can be driven past capacity by a redirect.
- If a third region or emergency capacity exists, spread the failed-over traffic further rather than concentrating it on one target.
Long-term changes
- Provision each region's headroom against "can absorb a full peer failover," not just local N+1, or explicitly accept and design for graceful degradation (shed low-priority traffic) as the intended behavior under full failover instead of assuming full capacity will always be there.
- Add global rate limiting/quotas so a cutover can't silently push one region past its ceiling.
- Rehearse failover under load (game days) so the deficit above is discovered in a drill, not during a real incident.
- Tighten the cutover mechanism (shorter TTLs, coordinated draining) to avoid the transition period itself briefly inflating total demand.
Trade-offs and pitfalls
- Provisioning every region to absorb 100% of peer traffic (true N+1 at the global level) is expensive; the alternative is explicit, tested graceful degradation, which is cheaper but requires deciding in advance what gets shed and validating that decision under real load, not assuming it during the incident.
- A postmortem that stops at "Region B got overloaded" without asking whether B's headroom was ever meant to cover 100% of A's traffic will produce the wrong fix (e.g. "scale B faster") instead of the real one (headroom policy was undersized for the failure mode that actually occurred).
- Retries and fan-out amplification can make the root cause look like "the region couldn't handle X RPS" when the real offered load, once amplified, was meaningfully higher than X; traces are what separate offered load from amplified load.
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.