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.
When designing a load balancer's health checks for a backend service, which check types would you reach for and why? How do check frequency, timeout, and failure threshold influence failover sensitivity and false positives, and how would you adapt the checks for a service with a slow startup?
Sample Answer
Direct answer
For a backend service's health checks, reach for the cheapest check that actually proves what you care about: a TCP connect check to confirm the port is open, a TLS handshake check when the service terminates TLS itself, an HTTP(S) status and body check for a general web service, and an application-level readiness endpoint, including gRPC's dedicated health-checking protocol for gRPC services, when you need to know the instance can correctly serve a request right now, not just that the process is running.
Structured elaboration
| Check type | What it verifies | Cost | Blind spot |
|---|---|---|---|
| TCP connect | The port is open and accepting connections | Very low | Says nothing about application correctness; a hung process can still accept connections |
| TLS handshake | The service can negotiate TLS and present a valid certificate | Low | Confirms the TLS stack, not the application behind it |
| HTTP(S) status and body check | A specific endpoint returns an expected status code, and optionally a body pattern | Moderate | Only as good as the endpoint it hits; a shallow endpoint can pass while real routes fail |
| Application readiness endpoint (including gRPC health protocol) | The application itself reports whether it is ready to serve, can include dependency checks | Moderate to higher, depending on what it checks internally | An endpoint that checks too much (e.g. a slow downstream) becomes a source of false positives |
Frequency, timeout, and failure threshold interact to set failover sensitivity. In the worst case, a failure starts right after a successful check, so detection is bounded by how often the balancer checks and how many consecutive failures it demands before acting:
worst-case detection latency≈interval×thresholdWith a 5-second interval and a 3-failure threshold:
5×3=15 (seconds, worst case)Tightening the threshold to 2 failures with the same interval:
5×2=10 (seconds, worst case)The 10-second configuration fails over faster but reacts to two consecutive blips instead of three, so it is more exposed to a single transient network hiccup being read as a real outage. Timeout works the same way from the other side: a timeout shorter than the service's genuine worst-case response time will misclassify a slow-but-alive backend as failed.
Adapting for a service with a slow startup: point the load balancer's check at a readiness endpoint that returns unhealthy until initialization finishes, rather than reusing the liveness check. Where the platform supports a distinct startup probe, use it to give the service a longer grace period before liveness checks even begin, so a legitimately slow boot (schema checks, cache warm-up) is never mistaken for a crash.
Trade-offs & pitfalls
- Putting a heavy dependency check inside a liveness-style probe means a slow downstream can trigger unnecessary restarts of an otherwise-healthy process; keep checks that can restart a process local and cheap.
- Tightening thresholds "for safety" often produces more incidents from flapping and restart churn than the failure category it was meant to catch quickly; tune against the service's actual latency variance, not a default.
- Reusing one endpoint for both a shallow liveness-style check and a deep readiness check makes it impossible to tune the two independently; keep them as separate endpoints even if they share code internally.
Design an automated control loop that shifts a percentage of production traffic to a canary over a fixed window and rolls back automatically on an SLO breach. Cover how you would smooth the weight changes, what guardrails you'd set (minimum observation windows, maximum error thresholds), and how the rollback itself executes quickly and safely.
Sample Answer
Direct answer
An automated canary control loop is a periodic process that increases a canary's traffic weight in small, guarded steps, checks health metrics against the baseline after every step using a minimum-observation window, and holds or immediately rolls back to zero on an SLO breach (a violation of the service-level objective, the reliability target you've committed to, such as 99.9% success rate). The design problem is really about the guardrails and the rollback path, not the ramp itself.
Structured elaboration
Components:
- A traffic router (Envoy, an ingress controller, or a cloud LB) that supports weighted routing and an instant weight-update API.
- A telemetry pipeline producing short and long rolling windows of error rate, latency, and request volume, split by canary vs. baseline.
- A stateless controller that runs the step/check/decide loop and calls the router's weight API.
- A rollback path that can zero out canary weight immediately, independent of the step loop.
Guardrails (the part that actually matters):
| Guardrail | Purpose | Example setting |
|---|---|---|
| Minimum observation window | Prevents decisions on too little data | require >= 100 canary requests in the last 60s before advancing |
| Short window (fast signal) | Catches sharp regressions quickly | 60s rolling window |
| Long window (stability) | Filters transient noise, confirms sustained breach | 300s rolling window |
| Max error delta | Hard stop on quality regression | canary error rate > baseline + 0.5 pp |
| Max latency ratio | Hard stop on tail-latency regression | canary p99 > baseline p99 x 1.2 |
| Monotonic ramp | Never sneak weight back up after a hold | only increase, decrease only via rollback |
| Cooldown after rollback | Prevents a flapping loop from re-triggering immediately | 30 minute freeze + incident ticket |
Smoothing the weight changes. Compute a fixed step size from the target ramp, then apply the step in small sub-increments at the router level (e.g. over a few seconds) so a single jump doesn't itself cause a connection-pool or cache-warming spike.
Worked example
Target: shift 10% of production traffic to canary over a 10 minute (600s) window, checking every 30s.
steps=30s600s=20 step size=2010%=0.5% per stepSo the loop runs 20 times, adding 0.5 percentage points of canary weight each pass, provided the guardrails above all pass. If step 12 (weight = 6%) shows canary p99 = 340ms against a baseline p99 of 260ms:
260340≈1.31>1.2That exceeds the 1.2x latency-ratio guardrail, so the controller does not advance to step 13. It instead sets weight back to 0% immediately (not a gradual decrease), opens an incident, and freezes further attempts for the cooldown period.
# runs every 30s
current = get_current_weight()
target = min(10, current + 0.5)
m = fetch_metrics(short=60, long=300)
if m.canary_requests_short < 100:
return # not enough signal yet, hold at current weight
if m.error_rate_canary > m.error_rate_baseline + 0.005 or \
m.p99_canary_long > m.p99_baseline_long * 1.2:
set_weight(0) # immediate rollback, not gradual
open_incident(m)
start_cooldown(minutes=30)
else:
set_weight(target) # router ramps this smoothly over a few seconds
Extensions: downstream capacity and CI/CD integration
Downstream-capacity-constrained ramp. The guardrails above are all canary-side (error rate, latency). A canary can look perfectly healthy on its own metrics while the traffic it forwards saturates a downstream dependency, a connection pool, a queue, or a rate-limited third-party API, before that dependency's own health signal even reflects the problem. Add a downstream capacity ceiling as its own guardrail: before each step, check the downstream dependency's current utilization (connection-pool saturation, queue depth, or a published capacity headroom number) and cap the canary weight so its incremental load stays under that ceiling, independent of what the canary's own error and latency metrics say. In practice the step size becomes the smaller of the scheduled step and the downstream headroom divided by requests-per-weight-point, and downstream saturation becomes its own rollback trigger alongside the error and latency guardrails, since the canary's own SLOs will not catch a downstream problem until it is already failing.
CI/CD pipeline integration. The loop is usually not a standalone daemon, it is a stage in the deploy pipeline. A build that passes its test stage triggers the deploy, which starts the canary at 0% weight and hands control to this loop; the pipeline blocks promotion to the next stage (wider rollout, or the next environment) until the loop reports a verdict, not a fixed timer. On success the loop reports pass and the pipeline proceeds to full rollout. On a guardrail breach, the loop's immediate zero-weight rollback from the worked example above is reported back as a failed pipeline stage: the deploy is marked failed, the previous version stays serving at 100%, and the pipeline stops rather than continuing to the next stage. That makes the human's only manual step reviewing the failure, not remembering to check on the canary.
Trade-offs and pitfalls
- Short windows are noisy, long windows are slow. A short-only window trips on transient blips; a long-only window lets real regressions run for minutes before anyone notices. Using both, and requiring the long window to confirm, is the standard resolution.
- Rollback must never itself be a slow ramp. The instinct to "gradually" bring weight back down defeats the purpose; on breach, cut to zero immediately and investigate after.
- Minimum-request guardrails matter more for low-traffic services. A service doing 50 RPS total needs a longer observation window or a lower canary weight cap just to get statistically meaningful samples per step.
- Business metrics can lag system metrics. A checkout canary can look perfectly healthy on latency and error rate while conversion silently drops; if the metric that matters is business-level, it needs its own window and threshold, not just infra SLOs.
- This is inherently single-service. Running the same loop concurrently across many dependent services without coordination risks compounding partial failures across a call graph; large orgs typically centralize this into a shared canary-analysis service rather than one loop per team.
Compare the architectural implications of an external load balancer versus a sidecar-based service mesh (for example Envoy) for intra-cluster traffic. For a large microservices environment, discuss trade-offs in routing flexibility, observability, latency overhead, and operational complexity, and how traffic distribution patterns change when you introduce a mesh.
Sample Answer
Direct answer
An external load balancer is a single centralized hop that all traffic passes through; a sidecar-based service mesh (Envoy) puts a proxy next to every workload instance, decentralizing routing decisions to the edge of each service. The trade is centralized simplicity and lower per-call overhead against distributed per-call policy control and much richer observability, at the cost of running and operating a control plane.
Structured elaboration
graph LR
subgraph ExternalLB [External Load Balancer Model]
C1[Client] --> LB1[External LB]
LB1 --> S1[Service A]
LB1 --> S2[Service B]
end
subgraph Mesh [Sidecar Mesh Model]
S3[Service A] --> P3[Envoy Sidecar A]
P3 --> P4[Envoy Sidecar B]
P4 --> S4[Service B]
end
Control plane vs. data plane. A mesh formally separates the two: sidecars (data plane) enforce routing, retries, timeouts, and circuit-breaker policy on every call; a control plane (e.g. an xDS server, Envoy's discovery-protocol API for pushing routing and policy config out to proxies) pushes that configuration out to every sidecar. An external LB usually collapses both into one component. This separation is what makes per-route policy (canary weight, retry budget, header-based routing) something you can change centrally without touching a single service's code, but it's also the piece most likely to become a scale bottleneck.
| Dimension | External load balancer | Sidecar-based mesh (Envoy) |
|---|---|---|
| Routing flexibility | Coarse-grained: host, path, header at the edge | Fine-grained per-call: per-route retries, timeouts, circuit breakers, weighted/version-based routing, fault injection |
| Observability | Centralized access logs and aggregate metrics; blind to service-internal call graph unless apps propagate trace headers themselves | Distributed tracing, per-route metrics, and service maps largely for free, since every hop passes through an instrumented proxy |
| Latency overhead | One network hop, lowest added latency | Two extra hops per call (local sidecar out, remote sidecar in); a well-tuned Envoy typically adds low single-digit milliseconds of proxy overhead, but this is workload- and config-dependent, treat any specific number as something to measure, not assume |
| Operational complexity | Low: one component to run, scale, and reason about | High: certificate/mTLS lifecycle, sidecar injection and upgrades, control-plane HA, config-push correctness at scale |
| Traffic distribution pattern | Centralized decision at the LB; often coarse hashing or round-robin at the VIP level | Client-side load balancing at each sidecar (least-request, ring hash, subset routing by version/zone), which tends to spread load more evenly across instances |
| Where it fits naturally | North-south (edge) traffic | East-west (service-to-service) traffic |
How traffic distribution patterns change with a mesh. Without a mesh, load-balancing decisions concentrate at the LB, often coarse (round-robin or least-connections over a VIP). With a mesh, every calling service's sidecar makes its own load-balancing decision against the live, health-checked endpoint set for the callee, enabling patterns that are awkward at a centralized LB: zone-local routing to reduce cross-AZ cost, subset routing that only sends canary traffic to pods carrying a specific version label, and per-call hedging or retry budgets that a single shared LB cannot reasonably apply per-caller.
Worked example: a 200-service rollout
At 200 services, a single Envoy control plane pushing full configuration to every sidecar on every change is the concrete bottleneck to plan for. If each config push must reach, say, 4,000 total sidecar instances (200 services x an average 20 instances each) and the control plane naively recomputes and re-pushes full config on every endpoint change anywhere in the mesh:
pushes per topology change=4,000At this scale, a mesh implementation without incremental (delta) config distribution, pushing only what changed to only the sidecars that care, turns a single pod restart anywhere in the fleet into a full-mesh config storm. This is why production mesh control planes (Istio's istiod, for example) implement scoped, incremental xDS updates rather than full-state pushes; it's the single most common cause of "the mesh worked fine in the pilot and fell over at scale" reports.
Trade-offs and pitfalls
- Don't treat this as all-or-nothing. A common, lower-risk pattern is to keep an external LB at the edge for north-south traffic (TLS termination, WAF, DDoS protection) and introduce the mesh only for east-west traffic, incrementally by namespace or team, to bound blast radius while the team builds operational maturity.
- The retry and circuit-breaker policy surface a mesh exposes is also a footgun surface. Misconfigured retries (no budget, no jitter) at the sidecar layer can amplify a downstream outage into a retry storm across the whole mesh; policy-as-code review and conservative defaults matter as much as the feature itself.
- mTLS (mutual TLS, where both client and server present certificates to authenticate each other, not just the server) by default is a real security upgrade, but certificate rotation and identity issuance become mesh-critical infrastructure; an outage in the certificate authority path is now an availability incident, not just a security one.
- Measure before generalizing about latency overhead. Sidecar proxy cost depends heavily on payload size, TLS handshake reuse, and filter-chain complexity; a number that's fine for a JSON API can be very different for a large-payload streaming workload.
What is traffic mirroring (shadowing) at the load balancer level? Explain a safe approach to mirror production traffic to a staging cluster for testing, how you would sample it to limit load, and the risks, such as side effects in downstream systems or data contamination.
Sample Answer
Direct answer
Traffic mirroring (also called shadowing) copies live production requests and sends a duplicate to a second target, usually a staging or canary cluster, without ever returning that target's response to the real client. It lets you exercise new code with real traffic shapes and volumes before it serves anyone, with zero risk to the production response path.
Structured elaboration
Mechanism. The load balancer or a sidecar proxy (a small proxy process deployed alongside each service instance, rather than centralized in the LB tier: Envoy's request_mirror_policy, NGINX mirror, or an application-level fan-out) forwards a copy of the request asynchronously, fire-and-forget. The production request path never waits on the mirror's response, so mirror latency or errors cannot affect real users.
Safe rollout approach:
- Isolate the mirror target. It must not share a production database or write path. Point it at a replica or a sandboxed data store so any writes it performs cannot corrupt live data.
- Sanitize before forwarding. Strip or mask PII, auth tokens, and session cookies, or route through a sanitizing proxy layer, since the mirror environment is held to a lower trust bar than production.
- Suppress side effects. Anything that is not idempotent, payments, emails, third-party webhooks, external API calls, must be stubbed or short-circuited in the mirror environment. This is the single most important safety control.
- Tag mirrored traffic. Add a header or trace attribute (e.g.
x-mirrored: true) so logs, metrics, and alerting pipelines can separate mirror noise from real signal. - Sample instead of mirroring 100%. Use deterministic hashing on a stable key (user id or request id) so the same entities are consistently included or excluded, which keeps A/B-style comparisons stable across requests from the same user.
Worked example
Assume production runs at 50,000 requests per second (RPS) and you want to validate a new service version without over-provisioning staging.
Sampling at 2% (hash of user id, keep if hash(user_id) mod 100 < 2):
To avoid the mirror cluster itself becoming a bottleneck, provision it with headroom, say 1.5x the expected mirrored load:
staging capacity=1,000×1.5=1,500 RPSThat is a cluster sized for 1,500 RPS instead of one sized for the full 50,000 RPS production load, a large cost saving while still exercising a statistically meaningful, consistently-sampled slice of real traffic.
Trade-offs and pitfalls
- Async mirroring is the default for a reason. Synchronous (blocking) mirroring couples production latency to the mirror's health, which defeats the point; always fire-and-forget.
- Data contamination is the top real-world failure mode. A mirrored write that reaches a shared resource (a shared cache, a shared queue, a third-party API) is the most common way mirroring causes a production incident.
- Mirroring is not free. It roughly doubles egress and backend load for the sampled slice, so uncapped 100% mirroring at scale is rarely justified; sample deliberately.
- Mirror-cluster failures should never alert on-call for production. Route mirror telemetry to its own dashboards and alert channels, or a slow-to-fail staging service will generate noisy pages for a system nobody's users are touching.
Compare Layer 4 (TCP) and Layer 7 (HTTP) load balancers using the equivalent products on the major clouds (for example AWS NLB vs ALB, GCP Network vs HTTP(S) Load Balancer, Azure Standard Load Balancer vs Application Gateway). Which features would you use each for: TLS termination, path-based routing, health checks, or session stickiness?
Sample Answer
Direct answer
Every major cloud offers the same L4-versus-L7 split under different product names: a transport-layer balancer that forwards TCP/UDP by IP and port, and an application-layer balancer that understands HTTP and can route on path, host, or headers. Pick the L4 product when you need raw throughput, non-HTTP protocols, or TLS passthrough to the backend; pick the L7 product when you need TLS termination, path- or host-based routing, or cookie-based stickiness.
Cloud product lines
| Cloud | L4 (transport) product | L7 (application) product |
|---|---|---|
| AWS | Network Load Balancer (NLB) | Application Load Balancer (ALB) |
| GCP | Network Load Balancer | External HTTP(S) Load Balancer |
| Azure | Standard Load Balancer | Application Gateway |
Feature comparison
| Feature | L4 product | L7 product |
|---|---|---|
| TLS termination | Generally passthrough; AWS NLB is the exception and can terminate TLS at an L4 listener, but it still never parses HTTP, so termination there does not unlock routing | Terminates centrally with managed certificates and SNI (Server Name Indication: a TLS extension that lets a client specify which hostname it wants before the handshake completes, so one balancer can serve certificates for many hostnames off a single IP) (ALB via ACM, AWS Certificate Manager, which issues and auto-renews TLS certificates; GCP-managed certs; App Gateway) |
| Path/host based routing | Not possible, the balancer never reads the HTTP request | Core feature: route by path, hostname, or header to different backend pools |
| Health checks | TCP or basic port reachability | HTTP-aware: status code, path, response body match |
| Session stickiness | Source-IP hash where supported (NLB, Azure Standard LB) | Cookie-based affinity (ALB application cookies, GCP backend-service affinity, App Gateway cookie affinity) |
| Best for | Raw TCP/UDP, gRPC over TLS passthrough, extreme low latency, preserving client source IP | HTTP APIs needing content-aware routing, centralized TLS, WAF, per-tenant or per-path policy |
Worked example
Say the multi-tenant API has two needs: (1) terminate TLS once and route /v1/images/* to an image-serving pool and everything else to the core API pool, and (2) proxy an internal gRPC service that requires end-to-end mTLS (mutual TLS, where both client and server present certificates and verify each other, not just the client verifying the server) between client and backend. Need (1) is a textbook L7 case: deploy an ALB (or GCP HTTP(S) LB, or App Gateway) with two path-based rules, one target group per pool, and centralized certificate management. Need (2) is a textbook L4 case: an NLB (or GCP Network LB, or Azure Standard LB) in TCP passthrough mode, since terminating TLS at the balancer would break the mTLS handshake the backend expects to see directly from the client.
Trade-offs and pitfalls
A common mistake is defaulting to L7 everywhere because it has more features: for pure TCP/UDP workloads or extreme connection-count scale, the extra parsing cost of L7 is pure overhead with no benefit. The reverse mistake is defaulting to L4 for an HTTP API and pushing routing logic (path dispatch, header inspection) into application code or a sidecar, which duplicates what the L7 product already does centrally and loses the unified observability an L7 balancer gives you. It is also common to chain them: an L4 balancer in front for connection-level scale and DDoS absorption, with L7 balancers or an API gateway behind it for the actual routing decisions.
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.