Resilience: circuit breaker, retry, timeout, bulkhead
Mid-level Always asked 7 min
On this page
The question
How does a circuit breaker work, and what are its states?
30-second answer
It wraps calls to a dependency and counts failures over a sliding window. Closed: calls pass through. When the failure rate, or the slow-call rate, reaches a threshold, it opens: calls fail immediately, often to a fallback, which spares threads and gives the dependency time to recover. After a wait it goes half-open and lets a few trial calls through; if they succeed it closes, otherwise it opens again.
Understand it
A circuit breaker driven by the failure rate
Explore2 of the last 10 calls failed, below 50%: closed. Every call goes through to Inventory.
View as text
A row of the last 10 calls to Inventory, failed ones crossed out. Below, three states, closed, open and half-open, with arrows between them; the current state and the next move are highlighted, and a line says what callers get.
1 of the last 10 calls failed, below 50%: closed. Every call goes through to Inventory.
6 of the last 10 calls failed, at or above 50%: open. Calls fail fast for 30 s, and the fallback answers.
5 of the last 10 calls failed, at or above 50%: open. Calls fail fast for 30 s, and the fallback answers.
After 30 s, half-open lets 3 trial calls through. At 10% failing they stay under 50%, so it closes again.
After 30 s, half-open lets 3 trial calls through. At 80% failing they reach 50%, so it opens for another 30 s.
A row of the last 10 calls to Inventory, failed ones crossed out. Below, three states, closed, open and half-open, with arrows between them; the current state and the next move are highlighted, and a line says what callers get.
1 of the last 10 calls failed, below 50%: closed. Every call goes through to Inventory.
6 of the last 10 calls failed, at or above 50%: open. Calls fail fast for 30 s, and the fallback answers.
5 of the last 10 calls failed, at or above 50%: open. Calls fail fast for 30 s, and the fallback answers.
After 30 s, half-open lets 3 trial calls through. At 10% failing they stay under 50%, so it closes again.
After 30 s, half-open lets 3 trial calls through. At 80% failing they reach 50%, so it opens for another 30 s.
Takeaway: Closed lets calls through and counts failures. At the threshold it opens and fails fast, giving the service time to recover. After a wait, a few trial calls decide whether it closes or opens again.
Retries with and without jitter
CompareAll 8 clients failed together and retry every second. Their retries land at the same instants, three waves of 8 on a service that is trying to recover.
View as text
Eight client lanes on a timeline from 0 to 8 seconds, with a dot at each retry, and below them a bar chart of retries per half second.
Fixed 1 s: All 8 clients failed together and retry every second. Their retries land at the same instants, three waves of 8 on a service that is trying to recover. Peak: 8 retries at once, every second.
Backoff: Exponential backoff waits 1, 2, then 4 seconds, so there are fewer retries over time. But identical clients still retry in lockstep: the waves are as tall as before. Peak: 8 at once, waves further apart.
Backoff + jitter: Full jitter picks each wait at random between zero and the backoff. The same 24 retries spread out, and no half second sees more than 4. Peak: 4 in any half second.
Eight client lanes on a timeline from 0 to 8 seconds, with a dot at each retry, and below them a bar chart of retries per half second.
Fixed 1 s: All 8 clients failed together and retry every second. Their retries land at the same instants, three waves of 8 on a service that is trying to recover. Peak: 8 retries at once, every second.
Backoff: Exponential backoff waits 1, 2, then 4 seconds, so there are fewer retries over time. But identical clients still retry in lockstep: the waves are as tall as before. Peak: 8 at once, waves further apart.
Backoff + jitter: Full jitter picks each wait at random between zero and the backoff. The same 24 retries spread out, and no half second sees more than 4. Peak: 4 in any half second.
Takeaway: Clients that fail together and retry on the same schedule hit the recovering service in waves. Exponential backoff spaces the waves; random jitter breaks them up.
In code
@Service
class StockClient {
private final RestClient inventory;
StockClient(RestClient inventory) { this.inventory = inventory; }
@CircuitBreaker(name = "inventory", fallbackMethod = "unknownStock")
@Retry(name = "inventory")
StockLevel stock(String sku) {
return inventory.get().uri("/stock/{sku}", sku).retrieve().body(StockLevel.class);
}
// Same parameters, plus the exception: called when the breaker is open or the call fails
StockLevel unknownStock(String sku, Throwable cause) {
return StockLevel.unknown(sku); // the page shows "check availability"
}
}resilience4j.circuitbreaker.instances.inventory.sliding-window-size=10
resilience4j.circuitbreaker.instances.inventory.minimum-number-of-calls=10
resilience4j.circuitbreaker.instances.inventory.failure-rate-threshold=50
resilience4j.circuitbreaker.instances.inventory.wait-duration-in-open-state=30s
resilience4j.circuitbreaker.instances.inventory.permitted-number-of-calls-in-half-open-state=3
resilience4j.retry.instances.inventory.max-attempts=3
resilience4j.retry.instances.inventory.wait-duration=500ms
resilience4j.retry.instances.inventory.enable-exponential-backoff=true
resilience4j.retry.instances.inventory.exponential-backoff-multiplier=2
resilience4j.retry.instances.inventory.enable-randomized-wait=true
resilience4j.retry.instances.inventory.randomized-wait-factor=0.5// A timeout does not mean the charge failed: it may have gone through
@Retry(name = "payments")
Wrong Receipt charge(Order o) { return payments.post().uri("/charges").body(new ChargeRequest(o.total())).retrieve().body(Receipt.class); }
@Retry(name = "payments")
Receipt chargeOnce(Order o) {
return payments.post().uri("/charges")
Right .header("Idempotency-Key", o.id().toString()) // same key on every attempt: charged once
.body(new ChargeRequest(o.total()))
.retrieve().body(Receipt.class);
}Solve it
Inventory slows down, and Orders stops answering every request
Orders calls Inventory synchronously on checkout. One evening Inventory’s database slows down, and its answers take 30 seconds. Within a minute Orders stops answering every endpoint, even the ones that never call Inventory, and its health check fails. Explain what happened and make Orders survive the next time.
- Find the shared resource. Orders has 200 request threads. With no timeout, each checkout holds a thread for 30 seconds, so all 200 end up waiting on Inventory. Every other endpoint queues behind them.
- Bound each wait. Add a read timeout of about 2 seconds, above Inventory’s normal p99 latency. A slow call now costs 2 seconds, not 30.
- Cap the share of threads. A bulkhead allows at most 20 concurrent Inventory calls; the 21st fails at once. The other endpoints keep their threads.
- Stop calling a service that is down. A circuit breaker opens after half the recent calls fail, so checkout fails fast and Inventory gets room to recover. A fallback shows “availability unknown”.
- Check. In a test, make a WireMock stub of Inventory wait 30 seconds and load Orders: other endpoints still answer fast, and checkout answers within 2 seconds.
@Bean
RestClient inventory(RestClient.Builder builder) {
var factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofMillis(500));
factory.setReadTimeout(Duration.ofSeconds(2)); // a slow call costs 2 s, not 30
return builder.baseUrl("http://inventory").requestFactory(factory).build();
}
// resilience4j.bulkhead.instances.inventory.max-concurrent-calls=20
// resilience4j.bulkhead.instances.inventory.max-wait-duration=0
@Bulkhead(name = "inventory", fallbackMethod = "unknownStock") // at most 20 threads wait here
@CircuitBreaker(name = "inventory", fallbackMethod = "unknownStock")
StockLevel stock(String sku) {
return inventory.get().uri("/stock/{sku}", sku).retrieve().body(StockLevel.class);
}
StockLevel unknownStock(String sku, Throwable cause) { return StockLevel.unknown(sku); }How to answer
- It fails fast instead of making every caller wait for a timeout.
- It protects the struggling service from more load while it recovers.
- Window size, minimum calls, threshold and open duration are the settings to tune.
- In Resilience4j, an open breaker throws CallNotPermittedException, which the fallback can catch.
Common mistakes
- Describing the states backwards, as if open meant calls flow. Open is like an open electrical circuit, so nothing passes.
- Using a circuit breaker without a timeout, so slow calls never count as failures and threads still pile up.
Follow-up questions
How should a service retry a failed call to another service?
Retry only transient failures, such as timeouts, connection errors and 503, never a 400. Limit the attempts, to three or so. Wait longer each time, with exponential backoff, and add random jitter so clients that failed together do not retry together. Retry only idempotent operations, or send an idempotency key. And keep the total time within the caller's own timeout.
- Retries multiply load; retrying at every layer of a five-service chain can multiply it many times over.
- A retry budget caps retries at a share of normal traffic.
- Put the retry outside the circuit breaker, so an open breaker stops the retries too.
What is the bulkhead pattern?
It isolates resources per dependency, like the watertight compartments of a ship, so one failing dependency cannot sink the whole service. In practice it caps concurrent calls to each dependency, with a semaphore or a separate thread pool. When Inventory is slow, at most 20 threads wait on it; the 21st call is rejected at once, and the threads serving other endpoints stay free.
- Resilience4j offers a semaphore bulkhead and a thread pool bulkhead.
- Size it from expected throughput times latency, plus headroom.
- Separate pools, or even separate deployments, isolate critical from batch traffic.
See it in the infographic: A circuit breaker driven by the failure rate
What makes a good fallback when a call to another service fails?
A fallback returns something useful without the dependency: a cached value, a default, a reduced answer, or a clear error the client can act on. For product recommendations, show bestsellers; for stock, show "availability unknown"; for a payment, there is no safe fallback, so fail clearly. It must be cheap and must not call another fragile service, or it fails too.
- Make degraded answers visible to the user or the caller, not silently wrong.
- Decide per feature whether failing open or closed is safe.
- Count fallback use in metrics; frequent fallbacks hide an outage.
See it in the infographic: A circuit breaker driven by the failure rate
What does Resilience4j give a Spring Boot service, and how are its parts combined?
Resilience4j is a lightweight library with CircuitBreaker, Retry, TimeLimiter, Bulkhead and RateLimiter modules. In Spring Boot you annotate a method, configure each named instance in properties, and get metrics through Actuator and Micrometer. When several annotations apply, the default order is Retry outermost, then the circuit breaker, rate limiter, time limiter and bulkhead around the call. It replaced Netflix Hystrix, now in maintenance.
- The fallbackMethod takes the same parameters plus a Throwable.
- Annotations work through Spring proxies, so self-invocation skips them.
- Spring Cloud Circuit Breaker offers a neutral API over Resilience4j.
See it in the infographic: A circuit breaker driven by the failure rate See it in the infographic: Retries with and without jitter
A service calls three others with no timeouts. Why is that dangerous, and how do you pick the values?
Without a timeout, a dependency that hangs holds the caller's threads forever, and the caller hangs too: one slow service brings down its callers. Set a connect timeout of a few hundred milliseconds and a read timeout just above the dependency's normal p99 latency. Make the timeouts along a chain shrink downstream, so the caller never gives up before the services it waits on.
- Default HTTP client timeouts are often infinite or very long.
- A deadline passed along the chain, as gRPC does, keeps all hops within budget.
- A timed-out call may still succeed on the other side, so retries need idempotency.
See it in the infographic: A circuit breaker driven by the failure rate
What counts as a failure for the breaker?
By default in Resilience4j, any exception the call throws. You narrow it with recordExceptions and ignoreExceptions, because a 404 or a validation error says nothing about the dependency's health. Slow calls can also count: past slowCallDurationThreshold, they raise the slow-call rate, which has its own threshold.
Where should the circuit breaker live, in the caller or the callee?
In the caller, one per dependency, because its job is to protect the caller's resources and stop it from hammering the callee. The callee protects itself with rate limiting and load shedding. A service mesh can apply breakers in the sidecar instead of in code.
Check yourself
Show answers
- It fails immediately without calling Inventory, and the fallback runs: Correct. Open means no calls pass until the wait ends.
- It goes through to Inventory as usual: Incorrect. That is the closed state.
- It waits until Inventory recovers: Incorrect. Waiting is what the breaker exists to avoid.
Show answers
- So clients that failed together do not retry at the same moment: Correct. Jitter breaks the lockstep that makes retries arrive in waves.
- So each client makes fewer retries: Incorrect. Jitter changes when retries happen, not how many.
- So the first retry always happens sooner: Incorrect. Full jitter can make a retry sooner or later; spreading is the goal.
Show answers
- It opens again for another wait: Correct. Trials at or above the threshold send it back to open.
- It closes, because the wait is over: Incorrect. It closes only if the trial calls succeed.
- It stays half-open and lets every call through: Incorrect. Half-open allows only a few trial calls.