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 the common load balancing algorithms: round robin, weighted round robin, least connections, and consistent hashing. For each, explain how it behaves under variable request latencies, long-lived connections such as WebSockets, and heterogeneous backend capacity, and give one production use case and one drawback. When would health checks and session affinity change which algorithm you pick?
Sample Answer
Direct answer
Round robin, weighted round robin, least connections, and consistent hashing differ mainly in what signal they use to pick a backend: round robin uses none (pure sequence), weighted round robin uses a static capacity ratio, least connections uses live connection counts, and consistent hashing uses a deterministic key (session id, user id) rather than load at all. That difference in signal is exactly why they behave so differently under variable request latency, long-lived connections, and mixed backend capacity.
Structured elaboration
| Algorithm | Behavior | Variable request latency | Long-lived connections (WebSockets) | Heterogeneous capacity | Production use case | Main drawback |
|---|---|---|---|---|---|---|
| Round robin | Cycles requests through servers in fixed order | Poor: ignores how long a prior request is taking | Poor: a server holding several long connections still gets the next new one | Poor: treats all servers as equal capacity | Homogeneous fleet, short uniform requests (static assets) | Blind to actual load; one slow server keeps getting new work |
| Weighted round robin | Same cycle, but servers get requests proportional to a static weight | Same blind spot as round robin, just scaled by weight | Same as round robin, scaled by weight | Good, if weights reflect real capacity | Mixed instance sizes with known, stable capacity ratios | Weights are static; does not react to a live spike |
| Least connections | New request goes to the server with fewest active connections | Good: naturally favors servers not stuck on slow requests | Good: avoids piling more work on a server already holding many long sessions | Needs weighting; assumes equal cost per connection otherwise | Variable-duration requests, streaming, WebSocket-heavy services | Needs an accurate, ideally shared, connection count; degrades to round robin if counts are only local per LB replica |
| Consistent hashing | Deterministic key (e.g. session id) maps to a server via a hash ring (both servers and keys are hashed onto points on a circle; a key is served by whichever server's point comes first walking clockwise from the key's own point) | Neutral: does not react to load at all | Excellent: same client always lands on the same server without a central session store | Needs virtual nodes weighted by capacity | Caches, CDNs, or any workload that needs strong affinity without a session store | Balances key placement, not load; a single hot key still lands entirely on one node |
When health checks and session affinity change the pick: if backends must hold session state without an external store, consistent hashing (or cookie-based affinity layered on any of the other three) becomes close to mandatory regardless of its load-balancing weaknesses. If health checks are slow to detect a failing node, least connections is more forgiving than round robin because it naturally routes fewer new requests to a node that is already accumulating unanswered connections, buying time until the health check catches up.
Worked example
Two backends, A and B, where A has twice the capacity of B (weight ratio 2:1). A weighted round robin scheduler realizing that ratio with a repeating pattern of period 3, "A, A, B", sent over 9 requests: A, A, B, A, A, B, A, A, B. Counting assignments: A receives requests 1, 2, 4, 5, 7, 8 (6 total), B receives requests 3, 6, 9 (3 total). That is 6:3, which simplifies to 2:1, exactly matching the configured weight, with no need to observe live load at all.
Consistent hashing, traced the same way: using a simplified illustrative hash (real systems use SHA-256 or similar, not this), sum a key's ASCII codes and take the result mod 100 to place it on a 0-99 ring. Three servers sit at fixed ring positions: X = 25, Y = 60, Z = 90 (a key is served by the first server whose position is at or after the key's hash, walking clockwise and wrapping to X if the hash is past the last position).
| Key | ASCII sum | mod 100 | Routed to |
|---|---|---|---|
| "session-42" | 919 | 19 | X (25) |
| "session-77" | 927 | 27 | Y (60) |
| "session-3" | 868 | 68 | Z (90) |
Now remove X from the ring (a node failure or a planned decommission): "session-42" (hash 19) has no server at or after position 19 until Y at 60, so it remaps from X to Y. "session-77" and "session-3" are untouched, since Y and Z were never X's successor for their hashes. This is the traced version of the bounded-remap claim in the table above: removing one of three nodes only disturbs the keys that node actually owned, not the whole ring.
Trade-offs & pitfalls
- Least connections needs an accurate, ideally shared, view of active connections per backend. Behind multiple load balancer replicas each keeping its own local count, the counts are only approximations, and the algorithm's advantage over round robin shrinks.
- Consistent hashing balances key placement, not load. A single popular key still lands entirely on one node no matter how good the hash function is; that is a cache-hot-key problem, not something the algorithm fixes.
- Common wrong turn: reaching for consistent hashing "for scalability" when the actual requirement is even load distribution. It solves affinity and cache locality, not general load balancing; without capacity-weighted virtual nodes it can be less balanced than plain least connections.
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 active-active and active-passive architectures for making the load balancer layer itself highly available. Describe failure detection, how DNS and anycast fit into each approach, state-synchronization requirements, and the trade-offs in cost, complexity, and recovery time.
Sample Answer
Direct answer
Active-active runs multiple load balancers serving traffic simultaneously, giving near-instant failover since the survivors are already warm and already receiving traffic, at the cost of needing to handle state consistency across them. Active-passive keeps a standby idle until a failure is detected, which is operationally simpler and cheaper but has strictly worse recovery time, since the standby has to actually take over, not just absorb more of a load it was already serving.
Comparison
| Dimension | Active-active | Active-passive |
|---|---|---|
| Failure detection | Health checks and heartbeats among peers; a failed node's traffic share is redistributed to already-running peers | Heartbeat/cluster arbitration (e.g. VRRP, the Virtual Router Redundancy Protocol that lets a standby take over a shared virtual IP, or keepalived, a common Linux implementation of it) with quorum or fencing (forcibly cutting off a misbehaving node's power or network access so it truly can't serve) to avoid two nodes both believing they're primary (split-brain) |
| Role of DNS/Anycast | Anycast fits naturally: an identical IP announced from multiple active locations, the nearest healthy one wins at the routing layer | DNS failover (short TTL, single active record) is common; VRRP-style IP takeover is faster than DNS when both nodes share an L2 segment |
| State synchronization | Needs either stateless design or active replication (a shared session store, consistent hashing for locality), since more than one node is live at once | Simpler: only one node is authoritative at a time, replication to standby can be asynchronous since it isn't concurrently serving |
| Recovery time | Fast, often sub-second to a few seconds, since capacity is already running | Slower: bounded by detection time plus promotion time (VRRP takeover is quick, DNS-based failover is slow due to caching) |
| Cost | Higher: standby capacity isn't idle, it's paying its way as active capacity, but that means paying for redundancy at all times | Lower: standby sits idle until needed, but idle capacity is capacity you're paying for and not using day to day |
| Complexity | Higher: consistency, routing, and monitoring all have to account for concurrent writers/servers | Lower: one active path to reason about at a time; correct failover logic is the main thing that has to work |
When to choose which
Choose active-active when the recovery-time budget is tight (seconds, not minutes) and the service can either be made stateless at the LB layer or afford real-time state replication. Choose active-passive when the service's state is genuinely hard to keep consistent across concurrent writers, or when the cost of standing up full duplicate active capacity isn't justified by the actual availability requirement; a slightly slower failover is a legitimate trade-off, not a compromise, if the SLA allows for it.
Worked example
Take a 2-node pair using VRRP with a 1-second heartbeat and a 3-missed-heartbeat failure threshold. In active-passive, the standby only notices the active node is gone after 3×1s=3s of missed heartbeats, then needs roughly 1s more to take over the shared IP, so client-visible downtime is about 3+1=4s. In active-active with the same 3s detection window, the survivor is already serving traffic, so that window doesn't cause an outage, it just means the failed node's share has to shift over. If 10,000 RPS was split evenly across the pair (5,000 RPS each), the survivor's load roughly doubles to 10,000 RPS the moment the shift completes: active-active trades a ~4s outage for a ~4s capacity spike that the survivor must already be provisioned to absorb.
Trade-offs and pitfalls
- Split-brain is the active-passive failure mode that active-active sidesteps by construction, since there's no single "the" primary to disagree about; any active-passive design needs real fencing (forcibly cutting off a misbehaving node so it truly can't serve) or quorum, not just a heartbeat timeout, or a network partition can leave two nodes both serving as primary.
- Active-active's biggest hidden cost is usually not the LB layer itself but what's behind it: if the backends and session store aren't also built for concurrent multi-region writes, active-active load balancing in front of a single-writer database just moves the bottleneck, it doesn't remove it.
- DNS-based failover for active-passive is bounded by TTL in theory but by resolver and client caching behavior in practice; some clients and corporate resolvers ignore short TTLs, so don't treat a TTL setting as a guaranteed failover time.
- Testing failover regularly, not just designing for it, is what separates a working active-passive setup from one that fails silently the one time it's needed; an untested standby is a hypothesis, not a plan.
Design a high-throughput traffic mirroring pipeline that copies a sample of production requests to a staging cluster without adding latency to the production path. Cover asynchronous delivery, sampling strategy, masking of sensitive data, and how you would prevent a mirrored write from causing a real side effect in the staging system.
Sample Answer
Direct answer
Make the mirroring decision and enqueue non-blocking at the edge so production latency is unaffected, ship the sampled copy asynchronously through a durable stream to staging, and prevent side effects by treating the staging path as read-only by construction: either point it at a storage layer that discards or isolates writes, or convert write methods before they reach a real backend. Sensitive data gets masked before it leaves the edge, not after it lands in staging, since "after" means it already left the trust boundary.
Structured elaboration
- Decision point stays fast. At the edge or sidecar, evaluate sampling rules against cheap, already-available data (route, a few headers) and enqueue a copy into a local, bounded, in-memory buffer. The enqueue is fire-and-forget: on a full buffer, drop and increment a counter, never block the production request.
- Asynchronous transport. A background worker drains the local buffer into a durable, high-throughput stream (for example Kafka or Kinesis), batching and compressing for efficiency. This decouples production's request rate from staging's actual processing rate.
- Masking at the edge, not in staging. Redact or tokenize PII fields and strip auth secrets in the same process that decides to mirror, before the copy is serialized onto the stream. Waiting until staging to redact means an unredacted copy already crossed a trust boundary and sat in a durable log.
- Preventing write side effects. The staging ingress recognizes mirrored traffic (a shadow-mode header) and routes it through an adapter that either discards writes, redirects them to an isolated namespace or database, or serves reads from a replica while writes are stubbed. Add an idempotency key (a unique id attached to a request so the receiving system can recognize and discard a duplicate instead of applying it twice) to every mirrored request so retries in the pipeline itself cannot double-apply a write that did slip through.
- Fidelity validation. A comparator service consumes both the mirrored request and the staging response (correlated by an original trace ID carried in a header) and checks response-shape agreement (status code family, latency distribution, schema) against production, without needing a human to eyeball individual requests. This is what tells you the shadow environment is representative, not just quiet.
graph LR
Prod[Production request] --> Edge[Edge: sample + mask + async enqueue]
Edge --> Serve[Continue serving production, no wait]
Edge -.-> Buffer[Bounded local buffer]
Buffer --> Stream[Durable stream: Kafka/Kinesis]
Stream --> Consumer[Mirror consumer]
Consumer --> Ingress[Staging ingress: shadow-mode adapter]
Ingress --> Staging[Staging services, writes isolated]
Consumer --> Comparator[Comparator: prod vs staging fidelity]
Worked example
Production ingress runs at 50,000 rps. A 2% sampling target sends 50000×0.02=1000 rps into the mirroring pipeline. Staging is provisioned with 20% headroom over that mirrored rate: 1000×1.2=1200 rps of capacity.
If a single stream partition sustains 5,000 rps of small messages, one partition is technically enough for 1,000 rps (⌈1000/5000⌉=1), but the pipeline is provisioned with 4 partitions so 4 consumers can process in parallel; each partition then carries an average of 1000/4=250 rps, well under its 5,000 rps ceiling, leaving headroom for an uneven key distribution across partitions without any single consumer falling behind.
Trade-offs & pitfalls
- Fail-open is the only safe default: if the stream backs up or the buffer fills, drop mirrored traffic and keep counting drops, never apply backpressure (forcing an upstream sender to slow down or block because a downstream consumer can't keep up) to the production request path itself.
- Converting writes at the staging ingress (stubbing them out) keeps staging's data pristine but can make staging diverge functionally from production over time, since write-triggered side effects never happen there; using a read-only replica plus stubbed writes downstream keeps closer functional parity at the cost of extra infrastructure.
- Redacting at staging instead of at the edge is the single most common mistake in shadow-traffic designs: an unmasked copy sitting in a durable stream, even briefly, is a real data-exposure surface, not a theoretical one.
- Sampling and mirroring add real infrastructure cost (stream, consumers, staging capacity) proportional to sampled volume; treat the sampling rate as a cost dial, not just a load-control dial.
You manage a pool of stateless web servers behind a single load balancer that sees bursty traffic and heterogeneous server capacity. Compare round robin, least connections, and weighted load balancing for this situation: how does each pick a server, and which would you choose?
Sample Answer
Direct answer
Round robin, least connections, and weighted load balancing differ in what information they use to pick a server. Round robin uses none, it just cycles through the pool. Least connections uses current load (active connection count) but assumes every server has equal capacity. Weighted load balancing (typically combined with one of the other two, giving weighted round robin or weighted least connections) uses declared server capacity. For a pool with bursty traffic and heterogeneous capacity, weighted least connections is the right default, because it is the only one of the three that reacts to both current load and known capacity differences.
How each one picks
| Algorithm | Selection rule | Reacts to load? | Reacts to capacity? |
|---|---|---|---|
| Round robin | Next server in a fixed rotation | No | No |
| Least connections | Server with fewest active connections | Yes | No (treats all servers as equal) |
| Weighted (least connections) | Server with the lowest active-connections-to-weight ratio | Yes | Yes |
Why plain round robin and plain least connections both fall short here
Round robin sends the same share of traffic to every server regardless of what it can handle, so a small server gets hit exactly as often as a large one and becomes the bottleneck under burst. Least connections is an improvement, since it avoids piling more work onto an already-busy server, but it still treats a 2-vCPU box and an 8-vCPU box as equally capable: an equal number of active connections is not an equal amount of work when the servers are different sizes.
Worked example: weighted least connections in action
Say the pool has three servers with declared capacity weights 4, 2, and 1 (roughly matching, say, an 8-vCPU, 4-vCPU, and 2-vCPU box). Weighted least connections picks, for each new request, whichever server minimizes:
scorei=wiciwhere ci is server i's current active connection count and wi is its weight. Ties are broken toward the higher-weight server. Tracing 7 back-to-back requests (a burst, so nothing completes mid-trace):
| Request | Scores (S1, S2, S3) | Picked | Active after |
|---|---|---|---|
| 1 | 0, 0, 0 (tie) | S1 | S1=1, S2=0, S3=0 |
| 2 | 0.25, 0, 0 (tie) | S2 | S1=1, S2=1, S3=0 |
| 3 | 0.25, 0.5, 0 | S3 | S1=1, S2=1, S3=1 |
| 4 | 0.25, 0.5, 1.0 | S1 | S1=2, S2=1, S3=1 |
| 5 | 0.5, 0.5 (tie), 1.0 | S1 | S1=3, S2=1, S3=1 |
| 6 | 0.75, 0.5, 1.0 | S2 | S1=3, S2=2, S3=1 |
| 7 | 0.75, 1.0, 1.0 | S1 | S1=4, S2=2, S3=1 |
After 7 requests the split is S1=4, S2=2, S3=1, exactly proportional to the declared weights of 4:2:1, even though every request arrived back-to-back with no completions in between. Plain round robin would have sent requests 1-7 as S1,S2,S3,S1,S2,S3,S1 (a 3:2:2 split), overloading S3 relative to its actual capacity.
Trade-offs and pitfalls
Weighted least connections needs two things plain least connections does not: accurate weights (usually derived from instance size or a load test, not guessed) and a mechanism to keep them current as capacity changes (autoscaling, degraded instances). It is also more stateful, the balancer has to track active connections per server accurately, which matters less for round robin. If request cost varies wildly and isn't reflected by connection count (a handful of expensive long-running requests versus many cheap ones), even weighted least connections can misjudge load, at which point request-cost-aware balancing or queuing becomes worth considering.
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.