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.
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.
Your L7 proxy tier (for example Envoy) is CPU-saturated under load. Walk through the failure modes you'd expect to see and how you'd confirm them, and lay out your mitigation plan to bring the tier back to healthy.
Sample Answer
Direct answer
When an L7 proxy tier like Envoy is CPU-saturated, the symptoms show up everywhere at once because CPU is the shared resource behind accept handling, filter processing, and control-plane config updates: rising accept-queue depth, growing request tail latency, and stale/delayed configuration from xDS (Envoy's config-discovery protocol, the channel that streams routing and policy updates out to the proxy) all point back to the same root cause. Confirming it means correlating kernel-level signals (accept backlog, run-queue length) with Envoy's own worker and listener stats, not just watching request latency in isolation. Mitigation is layered: immediate load-shedding and horizontal scale-out to stop the bleeding, then runtime tuning (worker count, filter chain cost, TLS offload) to fix the actual bottleneck.
Failure modes and how to confirm them
| Symptom | What to check | Why it happens |
|---|---|---|
| Accept queue / SYN backlog growth | Kernel accept queue (ss -l), net.core.somaxconn (the kernel's cap on completed-but-unaccepted connections waiting in queue), net.ipv4.tcp_max_syn_backlog (the cap on half-open connections still completing the TCP handshake), Envoy's listener.<name>.downstream_cx_active vs total | Worker threads can't call accept() fast enough because they're CPU-busy elsewhere; new connections queue in the kernel instead of being picked up |
| Rising tail latency (p50 stable, p99 diverging) | upstream_rq_time / downstream_rq_time histograms | CPU contention causes intermittent scheduling delay for some requests while most still complete fast; this is a leading indicator before p50 moves |
| Filter chain processing delay | Per-worker CPU and run-queue length, custom filter timing stats if instrumented | Synchronous, CPU-heavy filters (deep inspection, heavy logging, inline crypto) block the worker thread for the whole request |
| Control-plane (xDS) lag | ADS stream latency, time since last successful config apply | The management/main thread is starved of CPU alongside the workers, so config updates queue behind request processing |
| Secondary amplification | Retry rate, connection churn, memory growth | Slow/failed requests trigger client and internal retries, adding more load on top of an already CPU-bound tier |
The confirming signal is a rising kernel run-queue length and accept-queue depth together with Envoy-reported worker CPU near 100%, not just high request latency alone, since request latency can rise for many unrelated reasons (slow upstreams, network issues).
Root causes worth checking
- Worker/thread count misconfigured relative to available vCPUs, or a container CPU limit lower than what Envoy's
--concurrencyassumes. - CPU-heavy work on the hot path: TLS handshake/crypto without session reuse, verbose access logging, or a custom filter doing synchronous, expensive work per request.
- High-frequency xDS config churn competing with the request path for the same CPU.
Mitigation plan
Immediate (stop the bleeding):
- Shed load explicitly (local or global rate limiting, or return 503 for non-critical routes) rather than letting the kernel accept queue silently grow.
- Disable or bypass the most expensive optional filters (deep inspection, verbose logging) to buy back CPU.
- Scale out horizontally (add replicas) so aggregate CPU capacity matches offered load; this is the correct lever specifically because the bottleneck is CPU, not memory or network.
Runtime tuning (fix the underlying cost):
- Right-size
--concurrencyto available vCPUs and confirm the container's CPU limit isn't throttling below that. - Enable TLS session resumption and consider offloading TLS termination to a dedicated tier or hardware accelerator if crypto is the dominant cost.
- Reduce logging verbosity and stats cardinality on the hot path.
- Rate-limit or batch xDS updates so config churn doesn't compete with request processing during a load event.
Architectural (prevent recurrence):
- Set circuit breakers (
max_connections,max_pending_requests,max_requests) so an overloaded proxy tier fails fast instead of queuing and amplifying retries. - Maintain standing CPU headroom and autoscale on a leading indicator (accept-queue depth or worker CPU) rather than solely on request latency, which lags.
Worked example
Suppose load testing established that each Envoy worker (one per vCPU) safely sustains 3,000 RPS at around 70% CPU before tail latency degrades, and the current fleet is 20 instances of 8 vCPUs each:
CinstCfleet=W×Rworker=8×3,000=24,000 RPS=M×Cinst=20×24,000=480,000 RPSIf telemetry during the incident shows offered load of 620,000 RPS, that's 29% over the fleet's safe capacity, which is consistent with observed CPU saturation and explains the accept-queue growth. To restore headroom at the same per-instance ceiling, with a further 15% buffer against continued growth:
NneededNprovisioned=⌈CinstL⌉=⌈24,000620,000⌉=26=⌈26×1.15⌉=30So scaling from 20 to 30 instances (10 additional replicas) restores safe headroom against the observed load, assuming the per-instance ceiling holds, i.e. that CPU (not some other resource) really is the binding constraint at the new scale too.
Trade-offs and pitfalls
- Aggressive load shedding protects the tier but trades away availability for non-critical traffic; it should be scoped (by route or priority) rather than uniform where possible.
- TLS offload reduces proxy CPU but adds a new component and a new trust boundary to operate and secure.
- Horizontal scaling only helps if CPU really is the bottleneck; if the real constraint turns out to be memory, NIC bandwidth, or a downstream dependency, adding replicas burns cost without fixing the incident, which is why confirming the failure mode (not just reacting to "latency is up") matters before choosing a mitigation.
- Scaling reactively off request latency alone is slower than scaling off accept-queue depth or worker CPU, since latency is a lagging signal.
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.
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.
Tell me about a time you managed a failover or incident where the load balancer or a failover mechanism didn't behave as expected. Walk me through the situation, what you were responsible for, the actions you took during the incident, the results (including mitigation and root cause), and what you changed afterward.
Sample Answer
Direct answer
Use STAR: set up the situation and your role in one or two sentences, describe concretely what you did during the incident (not what "the team" did), state the outcome and what changed afterward, and end with the lesson. The strongest signal an interviewer is listening for is not the outage itself, it is whether your actions were deliberate and whether the fix addressed the root cause rather than just the symptom.
Structured elaboration
Situation: Name the system, the trigger, and the specific way the load balancer or failover mechanism misbehaved (routed to a dead node, failed to detect an unhealthy backend, split-brained across regions, flapped between healthy/unhealthy). Vague ("a server went down") is weak; specific ("health checks marked degraded instances as healthy because the probe timeout was shorter than the instance's real response time under load") is strong.
Task: State your role and scope of ownership plainly, on-call engineer, service owner, incident commander, so the interviewer knows what you controlled versus what you coordinated.
Action: This is the section to spend the most time on. Structure it in the order things actually happened:
- Immediate containment: what you changed to stop user impact (pulled a node/region from rotation, rolled back a config, manually failed over).
- Diagnosis: how you found the actual cause, not just the symptom (log correlation, comparing healthy vs unhealthy instance behavior, checking recent changes).
- Communication: who you told, how often, and why that mattered for a coordinated response.
Result: State the outcome honestly and in terms you can actually defend if asked to go deeper: service impact was contained, the specific fix that resolved it, and what changed in the system or process afterward (a corrected health-check timeout, an added synthetic probe, a canary requirement for load-balancer config changes). If you do not have precise numbers from memory, describe the outcome qualitatively (restored to normal operation, contained to a subset of traffic) rather than inventing statistics. An interviewer who probes "how many users were affected" and gets a fabricated number will trust the rest of the story less, not more.
Worked example
A representative version of this story, deliberately written without invented precision so it illustrates structure rather than fake data:
Situation: A payment service ran active-active across two regions behind a global load balancer. During a regional network blip, the load balancer's health checks did not fail the degraded region out of rotation, so a meaningful share of traffic kept landing on instances that were timing out.
Task: As the on-call engineer, I owned containing user impact and driving the fix.
Action: I manually pulled the degraded region from the load balancer's pool through the control plane rather than waiting for automatic health-check convergence, which was clearly not going to trigger in time. In parallel, I checked what changed recently and found that a prior change had shortened the health-check probe timeout below the instance's real p99 response time under load, so probes were failing even on instances that were still serving most requests correctly, the health check itself was miscalibrated, not just unlucky timing. I posted incident updates on a fixed cadence so stakeholders were not pinging for status mid-fix.
Result: Traffic normalized once the region was pulled and the timeout was corrected; the underlying fix was reverting the probe timeout to its previous value and adding a synthetic cross-region probe that exercises the failover path continuously (rather than only during real incidents) so a miscalibrated health check would be caught before the next config change shipped, not during the next real outage.
What I learned: A load balancer's failover is only as good as its health check's ability to distinguish "genuinely unhealthy" from "temporarily slow"; changes to health-check parameters deserve the same review rigor as changes to the service itself, because they directly control blast radius during a real failure.
Trade-offs and pitfalls
- Do not narrate what "we" did when the question asks what you did. Interviewers are listening for your specific decisions and reasoning, not a team summary.
- Avoid ending at "it got fixed." The strongest answers name the systemic change that makes the same failure mode structurally harder to repeat.
- Do not manufacture precision you do not have. A specific, remembered detail (which config changed, what the health check was checking) is more credible than an invented percentage or timestamp, and it holds up better under a skeptical follow-up.
- Watch for blame framing. A root cause that reads as "someone else misconfigured it" without acknowledging what allowed that misconfiguration to ship (no canary, no review gate) reads as less senior than one that owns the systemic gap.
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.