Distributed patterns and operations

Circuit breakers and bulkheads

Stop one failing dependency from taking down every service above it by failing fast, isolating resources per dependency and shedding load you cannot serve.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

An online shop has a product service with 200 worker threads, which is Tomcat’s default maximum. To render a page it calls pricing, inventory and recommendations. The first two are essential. Recommendations is a nice extra.

One day the recommendations service becomes slow and answers in 10 seconds instead of 20 ms. The product service’s timeout for that call is 10 seconds. At 100 page views per second, each request now holds a thread for 10 seconds, which would need 1,000 threads. There are 200. Within 2 seconds every thread is waiting on recommendations. Pricing and inventory are healthy, but no thread is free to call them. The product page is down, and the services that call the product service start to fill up in the same way.

This is a cascading failure. An optional feature took down the whole shop, because callers shared one pool of threads and kept waiting.

The team shortens the timeout to 300 ms. That helps: 100 requests per second for 0.3 seconds is about 30 busy threads. But every page is now 300 ms slower, and the product service still sends 100 requests per second, plus retries, to a service that cannot answer them.

Two more ideas are needed. Stop calling something that is clearly broken, which is a circuit breaker. Limit how much of the caller any one dependency can occupy, which is a bulkhead. Michael Nygard described both in his book Release It! (2007), and Netflix’s Hystrix library, open-sourced in 2012, made them standard in microservice systems. Hystrix has been in maintenance mode since 2018. Resilience4j, Envoy and service meshes carry the ideas on.

The circuit breaker

A circuit breaker wraps calls to one dependency and tracks their outcomes. It has three states.

A circuit breaker opening and recovering5 components: Users, Product service, Circuit breaker, Recommendations, Fallback. Connections: Users to Product service; Product service to Circuit breaker (every call); Circuit breaker to Recommendations (while closed); Product service to Fallback (when rejected).UsersProduct service200 worker threadsCircuit breakerinside the client libraryCLOSED, 0% failingRecommendationsthe dependencyhealthyFallbackcached best sellersevery callwhile closedwhen rejected

Step 1 of 8

The product service calls the recommendations service through a circuit breaker. The breaker is closed, so every call passes through, and it records whether each one succeeded. Calls return in about 20 milliseconds.

Read the steps as text
  1. The product service calls the recommendations service through a circuit breaker. The breaker is closed, so every call passes through, and it records whether each one succeeded. Calls return in about 20 milliseconds.
  2. A bad deploy makes recommendations slow. Calls now hit the 300 millisecond timeout and count as failures. Each one holds a product service thread for the full 300 milliseconds, so threads start to run short.
  3. The breaker is configured to open when at least half of the last 20 calls failed. The failure rate crosses 50 percent, so the breaker opens.
  4. While the breaker is open, calls fail immediately without touching the network. The product service shows cached best sellers as a fallback. Pages load quickly again, and recommendations receives no traffic, which gives it room to recover.
  5. After a 30 second wait, the breaker moves to half-open. It lets a small number of trial calls through and keeps rejecting the rest.
  6. The trial calls time out, because the bad deploy has not been rolled back yet. The breaker returns to open and starts another 30 second wait. Users still see the fallback.
  7. The deploy is rolled back. At the next half-open check the trial calls succeed, so the breaker closes, resets its counters and lets all traffic through again.
  8. The breaker did not repair anything. It turned slow failures into fast ones, which protected the caller's threads and stopped the caller from adding load to a struggling dependency. It only helps users if there is a fallback or a clean error to show.
A circuit breaker opening and recovering
  • Closed. Calls pass through. The breaker records successes and failures.
  • Open. The failure threshold was crossed. Calls are rejected immediately, without touching the network, until a wait period ends.
  • Half-open. A small number of trial calls are allowed. If they succeed, the breaker closes. If they fail, it opens again.

The effect is to replace slow failure with fast failure. The caller gets its threads back, and the dependency gets a pause in which to recover instead of a stream of requests and retries.

Choosing thresholds

  • Trigger on a failure rate over a sliding window, with a minimum number of calls so that one failure out of two does not open the breaker. A count of consecutive failures is simpler but erratic under partial failure, because a single success resets it.
  • Decide what counts as failure. Timeouts, connection errors and 5xx responses count. A 4xx response is the caller’s mistake and should not. Some libraries can also treat slow successes as failures.
  • Set the open wait to match recovery time. Too short and you hammer a service that is restarting. Too long and you serve fallbacks after it is healthy again.
  • Scope it narrowly. One breaker per dependency is the minimum. If one of 20 instances is bad, the failure rate is 5% and a service-wide breaker stays closed. Removing a single bad instance is the job of health checks and outlier detection in the load balancer. Likewise, one breaker in front of a sharded database opens for every user when a single shard fails, so scope it per shard.

Fallbacks

An open breaker still has to return something. The options, roughly from best to worst for the user:

  • a cached or slightly stale value
  • a sensible default, such as best sellers in place of personal recommendations
  • a reduced page with the feature hidden
  • a fast, clear error

Some calls have no honest fallback. You cannot invent a successful payment. In that case fail fast, tell the user, or accept the request and queue it for later if the business allows.

A fallback must be simpler and more reliable than the thing it replaces. One that calls another remote service can fail too, and one that sends all cache misses to the database can overload it. See cache stampedes.

Bulkheads

A ship’s hull is divided into watertight compartments so that one breach floods one compartment. In software, a bulkhead gives each dependency its own bounded share of the caller’s resources.

Bulkheads, one bounded pool per dependency7 components: Checkout service, Payments pool, Inventory pool, Reviews pool, Payments, Inventory, Reviews. Connections: Checkout service to Payments pool; Checkout service to Inventory pool; Checkout service to Reviews pool (rejected when full); Payments pool to Payments; Inventory pool to Inventory; Reviews pool to Reviews (5 calls stuck).CheckoutservicePayments pool20 slots, 6 in useInventory pool20 slots, 4 in useReviews pool5 slots, all in usePaymentshealthyInventoryhealthyReviewsslow, 10 s responsesrejected when full5 calls stuck
Bulkheads, one bounded pool per dependency

In the diagram, the reviews service can hold at most 5 of the checkout service’s slots. When they are full, further calls to reviews are rejected at once, and payments and inventory are untouched.

Bulkheads take several forms:

  • Thread pool per dependency. Calls run on a dedicated pool. This isolates well, and a stuck call can be abandoned on timeout, at the cost of extra threads and context switches. It was Hystrix’s default.
  • Semaphore. A counter of calls in flight. It is cheap and works with asynchronous I/O.
  • Separate connection pools, queues and workers for each dependency, job type or priority, so that a flood of slow report jobs cannot starve order processing.
  • Per-tenant quotas, so one noisy customer cannot use the capacity of the rest. See rate limiting.
  • Separate deployments for critical and batch traffic.

Size a pool from the load it should carry: peak requests per second times p99 latency, plus headroom. At 50 calls per second and 100 ms, about 5 calls are in flight, so 10 slots is generous.

The price is fragmentation. Spare slots in one pool cannot help a busy one, and every pool is another number to tune.

Load shedding

Breakers and bulkheads protect a caller. Load shedding protects a server. When requests arrive faster than they can be served, a queue only delays the failure: requests wait, clients time out and retry, and the server finishes work nobody will read. It is better to reject the excess early with a 503 or 429 and serve the accepted requests quickly.

Bound every queue. Limit concurrent requests. Drop the least important traffic first, so a background sync is refused before a checkout. Check the request’s deadline before starting work. Backpressure applies the same thinking to queues and streams.

How the pieces fit together

Mechanism Handles Without it
Timeout One call that hangs Threads wait forever, and the breaker sees no failures
Retry with backoff and jitter A brief, isolated fault Transient errors reach users
Circuit breaker A fault that lasts Callers keep paying the timeout and feeding load to a broken service
Bulkhead Slowness below the breaker’s threshold One dependency can still hold every thread
Load shedding Overload on the server Queues grow until everything times out

The interactions matter. A rejection from an open breaker should not be retried. Each retry attempt should be counted by the breaker. Timeouts and retries covers the first two rows.

When to choose it and when not to

Use a circuit breaker on synchronous calls to a dependency that can fail on its own, where a fallback or a fast error is better than a slow one. Use bulkheads when one service calls several dependencies of different importance, or serves several tenants.

Be cautious in these cases:

  • Low-traffic paths. With a few calls per minute the window never has enough samples, so the breaker either never opens or flaps.
  • A dependency with no fallback and no alternative. Failing fast still frees threads, but users see errors either way, so the gain is smaller.
  • Queue consumers. Pausing consumption and letting the queue buffer is usually the better response to a failing downstream.
  • Very small systems. Two services and one database need timeouts and sensible pool sizes before they need a breaker library.

In the interview

Raise this when the interviewer asks what happens if a dependency is slow, or when your design has one service fanning out to several others.

A strong answer in a minute: slow is worse than down, because callers block and exhaust shared threads, and the failure cascades. Put a timeout on every call. Wrap each dependency in a circuit breaker that opens on a failure rate over a window, rejects fast while open and probes in half-open. Say what the fallback is for this specific call. Give each dependency a bounded pool so that optional features cannot starve critical ones, and shed load at the server when queues grow. Finish by separating critical dependencies from optional ones in your own design.

Key takeaways

  • Cascading failure happens when callers keep waiting on a slow dependency and run out of shared threads or connections.
  • A circuit breaker has three states. Closed passes calls and counts failures, open rejects calls at once, and half-open lets a few trial calls test for recovery.
  • Open on a failure rate over a sliding window with a minimum number of calls, and count timeouts and 5xx responses but not 4xx.
  • A breaker only helps users if there is a fallback or a clean, fast error to return.
  • A bulkhead gives each dependency or tenant its own bounded pool, so the worst case is losing that pool and nothing more.
  • Load shedding protects the server side by rejecting excess requests early instead of queueing work nobody will wait for.

Check yourself

1. A service has 200 worker threads and receives 100 requests per second. Every request calls a dependency that has started taking 10 seconds, and the call timeout is 10 seconds. What happens?
2. What does a circuit breaker do in the half-open state?
3. A breaker opens when at least 50 percent of the calls in its window failed, with no minimum number of calls. At night the service makes about two calls a minute. What goes wrong?
4. Which problem does a bulkhead solve that a circuit breaker on its own does not?
5. A server is receiving more requests than it can process. Why is rejecting the excess immediately better than queueing it?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is a cascading failure?

A failure that spreads from one component to its callers, usually because they block on it and exhaust shared resources such as threads or connections.

Name the three circuit breaker states.

Closed (calls pass, failures are counted), open (calls are rejected immediately for a set wait), half-open (a few trial calls decide whether to close or reopen).

What should count as a failure for a circuit breaker?

Timeouts, connection errors and 5xx responses. Not 4xx responses, which are the caller's mistake and say nothing about the dependency's health.

What is a bulkhead?

A bounded, separate pool of threads, connections, queue slots or quota for each dependency or tenant, so that one of them can exhaust only its own pool.

What is load shedding?

A server deliberately rejecting excess requests early, usually with 503 or 429, so that the requests it accepts still complete quickly.

Why does a circuit breaker depend on timeouts?

Without a timeout, calls to a hung dependency never fail, they just wait. The breaker sees no failures to count and never opens.

Review the deck