How do you stop one slow dependency from crashing your API?
Question
Your store API runs a shared pool of 40 worker threads for both critical /checkout (50 ms) and optional /recommendations (20 req/s calling recs-svc, normally 40 ms). Today recs-svc starts hanging for 30 seconds, and the HTTP client has no timeout and no concurrency cap.
- How fast does
/recommendationsexhaust all40workers, and why does/checkoutgo down too? - Why is adding a
200 mstimeout necessary, yet still not enough during a traffic spike? - Combine timeouts, a bulkhead, a circuit breaker (
Closed,Open,Half-Open), and a fallback so/checkoutstays healthy.
Show hints (3)
- "COUNT PINNED WORKERS"
Multiply arrival rate (
20 req/s) by hang duration (30 s), and see how many seconds it takes to pin all40workers. - "CAP CONCURRENT CALLS"
A bulkhead limits
recs-svcto a fixed slice (say8slots), leaving at least32of the40workers always free for/checkout. - "FAIL FAST WHEN OPEN"
A circuit breaker trips to
Openafter repeated failures, skips upstream calls during cooldown, and tests recovery inHalf-Open.
Show checked explanation
At 20 req/s with no timeout, hanging recs-svc calls fill all 40 workers in 2 seconds, starving /checkout on the shared pool. Pair a strict 200 ms timeout with a bulkhead capping recs-svc (for example 8 of 40 slots), a circuit breaker (Closed -> Open -> Half-Open), and a fast degraded fallback.
class Breaker: def __init__(self, limit=3, wait=30): self.limit, self.wait = limit, wait self.state, self.fails, self.until = "closed", 0, 0 def call(self, fn, now): if self.state == "open" and now < self.until: return "fallback:open" if fn(): # closed call, or half-open probe once wait passes self.state, self.fails = "closed", 0 return "live:closed" self.fails += 1 if self.state == "open" or self.fails >= self.limit: self.state, self.until = "open", now + self.wait return f"fallback:{self.state}" cb = Breaker(3, 30) for t, ok in ((1, 0), (2, 0), (3, 0), (10, 1), (33, 1)): print(t, cb.call(lambda v=ok: bool(v), t))
1 fallback:closed 2 fallback:closed 3 fallback:open 10 fallback:open 33 live:closed
Ran the Python 3.12 circuit breaker code, Little's Law calculations, and a real 40-worker bulkhead ThreadPoolExecutor simulation on CPython 3.12.10. Checked by an editor other than the author.
Walkthrough
Normally /recommendations uses almost zero capacity: by Little's Law (concurrency = rate * latency), 20 req/s * 0.04 s = 0.8 workers. The moment recs-svc hangs for 30 s, steady-state demand jumps to 20 * 30 = 600 workers. In 40 / 20 = 2 seconds, every worker in the shared pool is blocked waiting on recs-svc, so /checkout requests queue and time out even though checkout never touches recs-svc.
Layer four defenses so one optional dependency cannot sink the service:
| Defense | Setting here | Workers held under hang | What it prevents |
|---|---|---|---|
| None | No timeout, shared 40 | 40/40 in 2 s | Full API outage |
| Timeout only | 200 ms connect+read | 4 at 20 req/s, 40 at 200 req/s | Slow hangs, not spikes |
| Bulkhead | Max 8 slots (BoundedSemaphore) | At most 8/40 (32 free) | Cross-endpoint starvation |
| Circuit breaker | Open after 3 fails, 30 s wait | 0 while open | Repeated 200 ms waits |
- Per-call timeout: Always set both connect and read timeouts (here
200 ms). At20 req/s, concurrency drops from600to4workers. Yet a 10x burst (200 req/s * 0.2 s = 40workers) still fills the pool if calls are unbounded. - Bulkhead (concurrency cap + separate pool): Give
recs-svcits own connection pool and a bounded concurrency cap of8slots (fail immediately if full). That guarantees at least32workers (80%) remain free for/checkoutunder any traffic spike. - Circuit breaker: Track failures in
Closed. After3consecutive failures (or a rolling error-rate threshold), trip toOpenfor30 s: requests skipfn()and return fallback in0 ms. Att = 33, transition toHalf-Openand send a limited probe. If the probe passes, return toClosed; if it fails, immediately re-open for another30 s. - Degraded fallback: Return cached popular items (or an empty list with
degraded: true) so product pages keep loading cleanly whilerecs-svcrecovers.
Common mistakes
- Leaving the HTTP client timeout unset. Python's
urllibandrequestsdefault to no timeout, letting one hung socket pin a worker thread indefinitely (or for hours even with TCP keepalive enabled). - Sharing one giant connection pool and thread pool across critical
/checkoutand optional/recommendations. A spike on optional features then starves revenue-critical traffic. - Letting every waiting request stampede through
Half-Openat once when cooldown ends. Permit only one or a small capped number of probe requests. - Tripping a circuit breaker on
400or404caller errors. Count only dependency faults such as timeouts, connection failures, and5xxresponses.
Follow-up questions
- "How do you pick the timeout and bulkhead limit for a downstream service?" Set the timeout slightly above the dependency's healthy p99 latency and inside the caller's own deadline budget. Size the bulkhead from peak expected rate times timeout (
rate * timeout), capped well below total API workers so critical routes keep headroom. - "What if a dependency is critical, like payment authorization on /checkout, so no cached fallback exists?" Still keep strict timeouts, a bulkhead, and a circuit breaker so failing payment calls do not crash login, cart, or order history endpoints. When the breaker opens, fail
/checkoutfast with503 Service UnavailableandRetry-After. - "Why can per-instance in-memory circuit breakers behave differently across 20 API pods?" Each pod tracks its own failure counter, so low-traffic pods trip later or probe at staggered times. That staggering actually protects the downstream service from synchronized probe spikes, and avoids adding a shared Redis dependency to the breaker path.
What a strong answer covers
Computes the 2-second pool exhaustion via Little's Law and shows why timeouts alone fail under spikes. Combines strict connect/read timeouts, a bounded bulkhead keeping 80% of workers for /checkout, a Closed/Open/Half-Open breaker, and degraded fallback.
Open in interactive practice deck →