download

How do you stop one slow dependency from crashing your API?

Backend~12 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. How fast does /recommendations exhaust all 40 workers, and why does /checkout go down too?
  2. Why is adding a 200 ms timeout necessary, yet still not enough during a traffic spike?
  3. Combine timeouts, a bulkhead, a circuit breaker (Closed, Open, Half-Open), and a fallback so /checkout stays healthy.
Show hints (3)
  1. "COUNT PINNED WORKERS"

    Multiply arrival rate (20 req/s) by hang duration (30 s), and see how many seconds it takes to pin all 40 workers.

  2. "CAP CONCURRENT CALLS"

    A bulkhead limits recs-svc to a fixed slice (say 8 slots), leaving at least 32 of the 40 workers always free for /checkout.

  3. "FAIL FAST WHEN OPEN"

    A circuit breaker trips to Open after repeated failures, skips upstream calls during cooldown, and tests recovery in Half-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.

"SOLUTION · PYTHON"
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))
"OUTPUT"
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:

DefenseSetting hereWorkers held under hangWhat it prevents
NoneNo timeout, shared 4040/40 in 2 sFull API outage
Timeout only200 ms connect+read4 at 20 req/s, 40 at 200 req/sSlow hangs, not spikes
BulkheadMax 8 slots (BoundedSemaphore)At most 8/40 (32 free)Cross-endpoint starvation
Circuit breakerOpen after 3 fails, 30 s wait0 while openRepeated 200 ms waits
  1. Per-call timeout: Always set both connect and read timeouts (here 200 ms). At 20 req/s, concurrency drops from 600 to 4 workers. Yet a 10x burst (200 req/s * 0.2 s = 40 workers) still fills the pool if calls are unbounded.
  2. Bulkhead (concurrency cap + separate pool): Give recs-svc its own connection pool and a bounded concurrency cap of 8 slots (fail immediately if full). That guarantees at least 32 workers (80%) remain free for /checkout under any traffic spike.
  3. Circuit breaker: Track failures in Closed. After 3 consecutive failures (or a rolling error-rate threshold), trip to Open for 30 s: requests skip fn() and return fallback in 0 ms. At t = 33, transition to Half-Open and send a limited probe. If the probe passes, return to Closed; if it fails, immediately re-open for another 30 s.
  4. Degraded fallback: Return cached popular items (or an empty list with degraded: true) so product pages keep loading cleanly while recs-svc recovers.

Common mistakes

  • Leaving the HTTP client timeout unset. Python's urllib and requests default 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 /checkout and optional /recommendations. A spike on optional features then starves revenue-critical traffic.
  • Letting every waiting request stampede through Half-Open at once when cooldown ends. Permit only one or a small capped number of probe requests.
  • Tripping a circuit breaker on 400 or 404 caller errors. Count only dependency faults such as timeouts, connection failures, and 5xx responses.

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 /checkout fast with 503 Service Unavailable and Retry-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 →

Original OfferVibe question. Google SRE: Addressing Cascading Failures · Google SRE: Handling Overload · Azure Architecture: Circuit Breaker · Azure Architecture: Bulkhead.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.