skip to content
jaeaeichsysdes

Load Balancing & Circuit Breakers

Routing traffic past slow nodes with Power of Two Choices and stopping cascading failures with circuit breakers, timeouts, and bulkheads.

Running 10 replicas eliminates a hard SPOF, but one degraded node taking 500ms instead of 20ms (a gray failure from GC pauses, thermal throttling, or noisy neighbors) still spikes p99 latency and exhausts upstream thread pools. Load balancers route around slow replicas; circuit breakers stop callers from hammering a broken dependency.

L4 (TCP) vs L7 (HTTP) load balancing

  • L4 (TCP / UDP): routes by IP + port for the lifetime of a TCP connection — cheap and fast because it skips TLS termination and HTTP parsing.
  • L7 (HTTP / gRPC): terminates TLS, parses each request, and routes by URL path, headers, or live queue depth.

note

HTTP/2 & gRPC trap: gRPC multiplexes thousands of RPCs over one long-lived TCP connection, so an L4 balancer pins all traffic from a client to one pod even after scaling out. Use L7 or client-side load balancing for HTTP/2 and gRPC.

Why Round-Robin fails with slow nodes

Round-Robin assumes equal speed. If Backend B slows from 20ms to 500ms (25× slower), Round-Robin still sends it one-third of traffic — its in-flight queue grows unbounded and tail latency explodes.

  • Least Connections: routes to the fewest in-flight requests, but multiple independent LBs all pick the same “least loaded” node at once (herd storms).
  • Power of Two Choices (P2C) (default in Envoy, NGINX, Linkerd): O(1), zero coordination — pick 2 random backends, compare in-flight queue depth (or EWMA latency), and route to the shallower one. Drops max queue depth across n servers from O(log n / log log n) to O(log log n) without herd storms.

Compare round-robin and power of 2 choices below while Backend B runs at 500ms.

interactive · switch strategy and send traffic while Backend B is degraded (500ms)

Backend A20ms
in-flight: 0routed: 4
Backend B500ms · slow
in-flight: 1routed: 4
Backend C20ms
in-flight: 1routed: 4

Backend B queue: 1 in-flight · total 12switch to P2C to route around slow B

Cascading failures and Circuit Breakers

When an entire downstream service hangs for 2 seconds at 500 req/s, 1,000 upstream worker threads saturate in 2 seconds flat — crashing unrelated endpoints sharing the pool. A circuit breaker stops the bleed with three states:

CLOSED

normal traffic · count failures

OPEN

fail fast in 1ms · protect threads

HALF-OPEN

1 probe after cooldown

  • Closed: normal traffic; trips Open when consecutive failures or rolling error rate cross a threshold.
  • Open: fails fast locally in ~1ms with a fallback or cached value, freeing upstream threads.
  • Half-Open: after cooldown, sends one probe — success resets to Closed, failure snaps back to Open.

Toggle downstream health below, trip the breaker, and click cooldown elapsed to watch the half-open probe.

interactive · toggle backend health, send requests to trip OPEN, then run a half-open probe

CLOSEDtraffic flows
OPENfail fast (1ms)
HALF-OPEN1 probe request
req #4FAST-FAIL · 1msrejected locally · 0 downstream threads blocked
req #3FAIL · 2000msfailure 3/3 · tripped OPEN
req #2FAIL · 2000ms503 timeout · failure 2/3
req #1FAIL · 2000ms503 timeout · failure 1/3

state: OPEN · fast-failed: 1click cooldown elapsed to test half-open probe

Timeouts, retries with jitter, and bulkheads

Pair circuit breakers with three companion defenses:

  • Tight timeouts: bound both connect (e.g. 200ms) and read timeouts so hung sockets never leak threads.
  • Bounded retries with jitter: retry only idempotency-safe calls, cap attempts (e.g. 2), and add randomized exponential backoff (jitter) to avoid 3×–5× synchronized retry storms.
  • Bulkheads: isolate dependencies into separate thread/connection pools so a saturated Recommendations pool never starves Checkout.
  • Backpressure & load shedding: return 503 Service Unavailable at the edge once queues exceed budget instead of accepting doomed work.

System design decision matrix

Failure mode Best mechanism Why
One pod has GC pauses or slow disk (gray failure) Power of Two Choices (P2C) + EWMA Automatically routes traffic to faster peers without waiting for health-check failure
Long-lived gRPC / HTTP/2 connections pin to one pod L7 load balancer (Envoy / client-side LB) Balances per RPC stream instead of per TCP handshake
Entire downstream dependency hangs or times out Circuit breaker + tight timeouts Fails fast in 1ms so upstream worker threads do not pile up waiting on dead sockets
Slow non-critical feature starves critical checkout path Bulkhead isolation Dedicated connection/thread pools keep failures contained to one compartment

Where this shows up in system design

  • Edge API Gateways / Envoy / NGINXL7 proxies terminate TLS, route HTTP/2 requests with Power of Two Choices, and shed excess load at the perimeter.
  • Microservice payment / auth callsCircuit breakers, strict timeouts, and idempotent retries with jitter stop third-party gateway outages from crashing checkout.
  • Streaming media originsL4 anycast + L7 origin shields steer viewers around degraded edge POPs before rebuffering spikes.
  • High-traffic checkout degradationBulkheads isolate recommendations and loyalty points so checkout falls back gracefully when auxiliary services open their breakers.

Check yourself: system design scenarios

interactive · pick an architecture for each prompt to test your intuition

1. gRPC service stays hot on 2 pods after scaling to 10

gRPC / HTTP/2 · L4 load balancer · existing clients

Your team scales a gRPC backend from 2 pods to 10 pods during a traffic spike, behind a standard L4 TCP load balancer. CPU on the original 2 pods stays at 95% while the 8 new pods sit at 0%. What is the root cause?

2. Retry storm turns a 5-second blip into a 20-minute outage

retry storm · cascading failure · fast recovery

A payment microservice hiccups for 5 seconds. Every caller immediately retries 5 times in a tight loop with no circuit breaker. Even after the DB recovers, the payment service stays down for 20 minutes. What combination fixes this?

3. Slow recommendations engine takes down checkout

mixed criticality · shared API server · graceful degradation

Your product page calls both `inventory-svc` (critical) and `recommendations-svc` (optional) from the same API server. When `recommendations-svc` hangs, users can no longer check out. How do you isolate checkout?

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme