Circuit breakers, bulkheads & backpressure
Contain failures so one slow dependency doesn't take down the system.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
Resilience patterns stop one slow or failing dependency from dragging the whole system down. Circuit breakers fail fast, bulkheads isolate resources, and backpressure and load shedding keep overload from spreading.
Think of it like this: A circuit breaker in your house cuts power before a fault burns everything.
Explained simply
In a big system, services call other services. If one of them becomes slow or broken, the callers can get stuck waiting, then their callers get stuck, and soon everything is down. This chain reaction is called a cascading failure. Resilience patterns are tricks that stop the damage from spreading.
A circuit breaker watches calls to a dependency. When too many fail, it trips and stops calling for a while, returning an error or a fallback answer at once. A bulkhead, named after the walls that divide a ship into watertight sections, gives each dependency its own limited pool of resources, so one leak cannot sink the whole ship.
Backpressure means telling the sender to slow down when you cannot keep up, instead of quietly piling up work. Load shedding means politely refusing some requests when overloaded, so the ones you accept still get served well. A fast no is better than a slow maybe.
Together, these patterns keep a problem small. One slow recommendation service should mean the product page has no recommendations, not that the whole shop is down.
Press Play on a diagram to walk through it one step at a time.
- 1Closed
Requests flow, failures are counted
- 2Open
Failure threshold hit, calls fail fast
- 3Half-open
After cooldown, allow a few trial calls
- 4Close or reopen
Successes close it, failures reopen it
- Back to step 1
- Stops calling a failing dependency
- Fails fast with fallback
- Gives it time to recover
- Separate pools per dependency
- One slow call cannot take all threads
- Limits blast radius
- Signal producers to slow down
- Bounded queues, shed excess
- Prefer 503 over collapse
- Caller to Breaker: Calls pass while closed1Calls pass while closed
- Breaker to Dependency: Requests time out repeatedly2Requests time out repeatedly
- 3Failure rate over 50%: openBreaker to Breaker: Failure rate over 50%: open
- Caller to Breaker: New call4New call
- Breaker to Caller: Fail fast with fallback5Fail fast with fallback
- Breaker to Dependency: After 30 s: one trial call (half-open)6After 30 s: one trial call (half-open)
- Dependency to Breaker: Success: close again7Success: close again
- 1Edge rate limits
Stop abusive or excess traffic early
- 2Load shedding
Reject what the server cannot finish
- 3Bulkhead per dependency
Cap concurrent calls
- 4Timeout and retry budget
Bound how long and how often
- 5Circuit breaker and fallback
Stop calling, serve a default
In depth
Why slow is worse than down
A dependency that is down fails fast: you get a connection error in milliseconds and move on. A dependency that is slow holds your threads, connections and memory while you wait. Little's Law shows how fast this goes wrong: requests in flight = arrival rate x time per request. At 1,000 requests per second and 50 ms each, about 50 requests are in flight. If the dependency slows to 5 seconds, 5,000 are in flight. A server with a pool of 200 threads is full in a fraction of a second, and now even requests that never touch the slow dependency cannot get a thread.
This is how one slow database query or one sluggish third-party API takes down services that have nothing to do with it. Timeouts limit how long each request can hold resources, and the other patterns limit how many can.
- 1Dependency slows
Latency 50 ms to 5 s
- 2Requests pile up
In flight grows 100x
- 3Pool exhausted
All threads waiting
- 4Healthy paths fail too
No free threads for anything
- 5Callers time out and retry
Failure moves upstream
Tuning a circuit breaker
A breaker needs a few settings. Failure rate threshold: open when, say, 50% of calls fail. Sliding window: measure over the last 100 calls or the last 10 seconds. Minimum calls: do not judge on 3 calls; require at least, say, 20 in the window. Slow-call threshold: count calls slower than a limit (like 2 seconds) as failures, because slowness is the real danger. Open duration: stay open for, say, 30 seconds, then go half-open and allow a few trial calls.
Scope matters. One breaker per dependency, and sometimes per endpoint or per host, so one bad replica does not block calls to healthy ones. Libraries implement all of this: Resilience4j for Java, Polly for .NET, and service meshes like Envoy offer outlier detection, which ejects failing hosts from the load-balancing pool. Expose breaker state as a metric so you can see when and why it opened.
- Count slow calls, not just errors
- Require a minimum number of calls before tripping
- One breaker per dependency (or host)
- Alert on breaker state changes
Bulkheads in practice
A bulkhead caps the resources any one dependency can use. The simplest form is a separate connection pool or thread pool per dependency, or a semaphore that limits concurrent calls. If the payment service may use at most 30 concurrent calls, a slow payment provider can tie up 30 slots and no more; requests for search, login and browsing keep their own capacity.
The same idea works at larger scales. Separate worker pools for interactive requests and batch jobs keep a big export from slowing the website. Per-tenant limits stop one noisy customer from starving others. Cell-based architecture splits the whole system into independent copies (cells), each serving a subset of customers, so a bad deploy or overload hits one cell, not everyone. In Kubernetes, CPU and memory limits are a bulkhead between pods on the same node.
Backpressure and load shedding
When work arrives faster than you can process it, it must go somewhere. An unbounded queue just hides the problem: latency grows, memory grows, and requests time out after you have spent effort on them. So bound every queue, and when it is full, push back.
Backpressure signals the producer to slow down: a full bounded queue blocks the producer, TCP flow control slows a sender, or Kafka consumers simply read more slowly. At an HTTP edge, the signal is a fast 503 or 429 with a Retry-After header.
Load shedding chooses what to drop. Drop low-priority work first (analytics, prefetches) before checkout. Drop requests whose deadline has already passed, since nobody is waiting for them. Adaptive concurrency limiters, like Netflix's concurrency-limits library or Envoy's adaptive concurrency filter, watch latency and lower the number of in-flight requests automatically when it rises.
- 1Request arrives
With priority and deadline
- 2Deadline passed?
Yes: drop, nobody is waiting
- 3Over concurrency limit?
Yes: shed low priority first
- 4Return fast 503
With Retry-After
- 5Otherwise serve
Accepted work stays fast
Fallbacks and graceful degradation
When a breaker is open or a call fails, return something useful instead of an error. Options include cached data (yesterday's recommendations), a default (a generic top-sellers list), a reduced feature (hide the reviews widget), or queuing the action for later (accept the order, process it when the payment provider recovers).
Good fallbacks are simple and independent. A fallback that calls another service, or the same database, can fail at the same moment as the main path. And some operations have no safe fallback: you cannot pretend a payment succeeded. In those cases, fail clearly and fast.
Decide fallbacks per feature ahead of time, and test them. Many teams run game days where they block a dependency on purpose and check that pages still load. A fallback that is never exercised tends to break quietly.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Explain the circuit breaker pattern~40m
- 2Isolate resources with bulkheads~40m
- 3Apply backpressure and load shedding~40m
Key points
- Slow dependencies are more dangerous than dead ones because they tie up threads.
- Open circuits should return a fallback such as cached or default data.
- Bulkheads give each dependency its own connection or thread pool.
- Unbounded queues hide overload until memory runs out.
- Shed low-priority traffic first during overload.
Key terms
Tap a card to flip it. 0/5 known
Examples
A minimal circuit breaker
This class counts consecutive failures. After 5 in a row it opens and rejects calls for 30 seconds by raising at once. After that it allows one trial call (half-open): success closes it, failure reopens it. Real libraries use failure rates over a sliding window and count slow calls, but the state machine is the same. The caller catches CircuitOpen and serves a fallback.
import time
class CircuitOpen(Exception): pass
class Breaker:
def __init__(self, limit=5, cooldown=30):
self.limit, self.cooldown, self.fails, self.opened = limit, cooldown, 0, None
def call(self, fn):
if self.opened and time.monotonic() - self.opened < self.cooldown:
raise CircuitOpen()
try: result = fn()
except Exception:
self.fails += 1
if self.fails >= self.limit or self.opened: self.opened = time.monotonic()
raise
self.fails, self.opened = 0, None
return resultSizing a bulkhead with Little's Law
The product page calls a reviews service at 400 requests per second with a normal latency of 40 ms. Step 1: normal concurrency = 400 x 0.04 = 16 calls in flight. Step 2: allow headroom for bursts and p99 latency of 150 ms: 400 x 0.15 = 60. Step 3: set the bulkhead to 60 concurrent calls and the timeout to 300 ms. Step 4: if reviews slow to 5 seconds, only 60 slots are tied up; extra calls are rejected at once and the page renders without reviews. Without the cap, 400 x 5 = 2,000 requests would wait and could exhaust the whole server.
Quick reference
- Little's Law: requests in flight = arrival rate x latency
- Breaker: open at about 50% failures over a window, with a minimum call count
- Count slow calls as failures; slowness is what exhausts pools
- One pool or semaphore per dependency is a bulkhead
- Bound every queue; an unbounded queue is a hidden outage
- Shed load with a fast 503 or 429 plus Retry-After
- Drop requests whose deadline already passed
- Fallbacks: cached data, defaults, hide the feature, or queue for later
Common mistakes
- Sharing one thread pool for all outbound calls.
- Circuit breaker with no fallback, so users still see errors everywhere.
- Queues with no size limit.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
For a news site's article page, name a fallback for each failing dependency: comments service, recommendation service, ad server, article database.
- Exercise 2medium
Implement a bulkhead in Python with a semaphore that allows at most 20 concurrent calls and rejects immediately (no waiting) when full.
- Exercise 3hard
During a sale, checkout latency rises and the site starts failing. Design a load-shedding policy with three priority classes and describe what the server does at 80%, 95% and 100% of its concurrency limit.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a circuit breaker and a retry?
- A retry tries again hoping the next attempt works. A circuit breaker stops trying for a while when failures are frequent. They work together: retry a little, and let the breaker stop retries when a dependency is clearly down.
- Do I need these patterns if I use a service mesh?
- A mesh like Istio or Linkerd can provide timeouts, retries, outlier detection and connection limits without code changes. You still need application-level fallbacks, because only your code knows what a sensible default answer is.
- What is the difference between rate limiting and load shedding?
- Rate limiting enforces a fixed allowance per client, such as 100 requests per minute, even when the server is idle. Load shedding reacts to the server's actual condition and rejects work only when it is overloaded.