System Design Part 6 Reliability

Circuit Breakers and Bulkheads: Keep One Broken Downstream from Taking Down the Whole System

Bill.Lin 15 min read

System Design series Part 6-3 | Previous: Timeouts, Retries, Backoff, and Jitter | Next: Rate Limiting | Series map

Read first: Part 6-2 Timeouts, Retries, Backoff, and Jitter.

Scenario and problem

The previous post gave the payment call a 1-second timeout and retries with a budget. The next time the payment service failed, the sign-up service no longer hung, but two problems remained:

  1. Every request waits the full second before it fails. Payments has been down for 5 minutes, and the sign-up service still sends a call for every request, waits 1 second, and gets a timeout. Users wait 1 second every time before they see an error, and the payment service keeps receiving requests, with no chance to catch its breath
  2. A slow payment service drags down unrelated features. Normally payments responds in 50 ms. With 200 sign-up requests a second, about 200 × 0.05 = 10 requests are waiting on payments at any moment (Little’s Law). When payments slows down to the 1-second timeout, the number waiting at once becomes 200. They hold threads, connections to downstream services, and memory, and features that do not need payments at all, such as browsing talks and logging in, slow down too
The sign-up service when payments fails or slows down1 / 4
The sign-up service when payments fails or slows downUsersRegistrationPaymentsRegistrationPaymentsUsersstill callsDown for 5 minutesError only after 1 sUsersRegistrationPayments200 sign-ups/s50 msAbout 10 waiting at onceRegistrationPayments1 s to time out200 waiting at onceUsersRegistrationbrowse, log inHeld by payment callsSlow too
  1. Every request waits the full secondPayments has been down for 5 minutes, and the sign-up service still sends a call for every request, waits 1 second, and gets a timeout. Users wait 1 second every time before they see an error, and payments keeps receiving requests, with no chance to catch its breath.
  2. Normally: only 10 waiting at onceNormally payments responds in 50 ms. With 200 sign-up requests a second, about 200 × 0.05 = 10 requests are waiting on payments at once.
  3. Slowed to 1 s: 200 waitingPayments slows down until it times out at 1 second, and the number of requests waiting at once becomes 200. They hold threads, connections to downstream services, and memory.
  4. Unrelated features slow down tooFeatures that do not need payments at all, such as browsing talks and logging in, slow down too, because the resources are taken.

The first problem is solved by a circuit breaker: when a downstream is known to be failing, stop calling it and fail right away. The second is solved by a bulkhead: each downstream can use up only a limited amount of resources, so when one downstream has trouble, it does not flood the whole ship.

The simplest approach and its limits

  • A manual switch: when payments fails, an engineer changes a setting to turn off the payment feature. Reacting takes minutes, and someone has to be woken up in the middle of the night; after recovery, someone also has to remember to turn it back on
  • A bigger thread pool, or virtual threads: virtual threads stop “not enough threads” from being the bottleneck, but the bottleneck just moves down: 200 requests waiting at once still hold connections, memory, and the patience of upstream callers. Unbounded concurrency means betting all your resources on the slowest downstream

Core mechanism

The three states of a circuit breaker

stateDiagram-v2
    [*] --> Closed
    Closed --> Open: Failure rate or slow-call rate over the threshold
    Open --> HalfOpen: Wait for a while
    HalfOpen --> Closed: Most trial calls succeed
    HalfOpen --> Open: Trial calls still fail
  • Closed (the circuit is closed, current flows): calls go through normally, and the results over the recent period are counted
  • Open (the circuit is open, current is cut off): once the failure rate crosses the threshold, later calls are not sent; an exception is thrown right away. Failing takes a few microseconds instead of a 1-second wait for the timeout
  • Half-open: after waiting for a while, let a small number of calls through as a test. If they succeed, go back to closed; if they fail, open again

The breaker protects both sides: the caller stops wasting resources waiting for calls that are bound to fail, and the downstream, spared a flood of requests, gets a chance to recover.

What to count, and over how long

The sliding window decides how long “recent” is:

  • By count: the last 100 calls
  • By time: all calls in the last 10 seconds. This suits services whose traffic varies a lot, because “100 calls” is half a second at peak and could be half an hour off-peak

Minimum number of calls: when the window holds too few calls, make no judgment. At midnight there are only 3 calls and 2 of them fail. The failure rate is 67%, but that does not mean the downstream is broken.

Slow calls count as failures too: the downstream returns no error, but every request takes 900 ms. For the caller this is as bad as a failure, or even worse, because it holds resources for longer. The slow-call threshold has to be shorter than the read timeout, so you notice the problem before the calls time out.

Only downstream problems count as failures: connection errors, timeouts, and 5xx are problems with the downstream; 400, 404, and 422 are problems with the request itself and mean the downstream is working. Count 4xx as failures, and a single client sending wrong parameters can open the breaker and stop everyone from paying (see Security).

Fallback: what to do once the breaker is open

The breaker only takes care of “failing fast”. What to do after the failure depends on how important the feature is:

Feature Fallback when the downstream fails
Personalized recommendations Show the list of popular talks instead (cached in advance)
Remaining seats Show the cached number marked “about”, and treat the database as the source of truth at sign-up
Payment Create the sign-up as “pending payment”, hold the seat for 15 minutes, and ask the user to finish paying later
Confirmation email Put it in a queue and send it later (Message Queues post)
Authorization checks, fraud detection Do not fall back to allowing; reject outright (see Security)

The fallback has to be cheaper and more reliable than the original call, and it must not depend on the same failing component. If the recommendation service fails and you fall back to querying the database for real-time recommendations, you may spread the failure to the database.

Bulkhead: limit the resources each downstream can use up

A ship is divided into compartments by bulkheads; when one compartment floods, the others are unaffected. A bulkhead in software is the same idea: each downstream has its own resource limit.

Form How Good for
Concurrency limit (semaphore) Cap the number of concurrent calls to a downstream, and reject immediately beyond it Most cases, especially with virtual threads
Separate thread pool Each downstream has its own thread pool When calls need to be separated from request threads
Separate connection pool Report queries use a different database connection pool Slow queries cannot borrow every connection from online transactions
Separate deployment Deploy the back office, batch jobs, and the public API separately A surge in one kind of traffic does not affect another

Estimate the limit with Little’s Law: payments gets 200 calls a second at peak with a p99 latency of 80 ms, so about 200 × 0.08 = 16 calls are waiting at once; set the limit to 20. When payments slows down, at most 20 requests are waiting on it; the 21st request is rejected immediately and holds no resources. Browsing talks and logging in are not affected at all.

Reject when over the limit; do not queue. Making requests queue for a slot only turns “waiting for payments” into “waiting for a slot”, and the resources are held just the same.

Putting it together

flowchart LR
    Req[Sign-up request] --> BH{Bulkhead<br/>concurrent calls < 20?}
    BH -->|no| Rej[Reject at once<br/>503 or fallback]
    BH -->|yes| CB{Circuit breaker<br/>closed?}
    CB -->|open| Fb[Fallback]
    CB -->|closed| TO[Call payments<br/>1 s timeout]
    TO -->|failed, retryable, budget left| TO

Timeouts and retries (the previous post), circuit breakers, and bulkheads solve different problems and are usually used together. Put the retry outside the breaker, and do not retry the “breaker is open” exception; otherwise, once the breaker opens, the retry loop keeps spinning for nothing.

Comparing options

Mechanism Solves Does not solve
Timeout A single call never waits forever During an outage, every request still waits until the timeout
Retry Transient failures Sustained failures; used wrongly, it amplifies the load
Circuit breaker Fails fast during a sustained outage and lets the downstream recover Resources held while the downstream is merely slow and has not crossed the threshold yet
Bulkhead One downstream’s problem does not spread to other features The failure of that downstream itself
Fallback Still offers part of the feature during a failure Has to be designed in advance, and tested
Rate limiting (next post) Protects you from being overwhelmed by too many requests Downstream failures

In Java

This post uses Resilience4j’s framework-independent core API (resilience4j-circuitbreaker) and the @ConcurrencyLimit built into Spring Framework 7. Resilience4j also has a Spring Boot integration module that you can configure with properties files and annotations, but check which Spring Boot versions it supports.

1. Configuring the breaker

java
@Configuration
public class CircuitBreakerSetup {

    @Bean
    CircuitBreakerRegistry circuitBreakerRegistry() {
        CircuitBreakerConfig downstream = CircuitBreakerConfig.custom()
                .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.TIME_BASED)
                .slidingWindowSize(10)                                  // count the last 10 seconds
                .minimumNumberOfCalls(20)                               // no judgment when there are too few calls
                .failureRateThreshold(50)
                .slowCallDurationThreshold(Duration.ofMillis(800))      // shorter than the 1-second read timeout
                .slowCallRateThreshold(50)
                .waitDurationInOpenState(Duration.ofSeconds(10))
                .permittedNumberOfCallsInHalfOpenState(5)
                .recordException(CircuitBreakerSetup::isDownstreamFailure)
                .build();
        return CircuitBreakerRegistry.of(downstream);
    }

    @Bean
    MeterBinder circuitBreakerMetrics(CircuitBreakerRegistry registry) {
        return TaggedCircuitBreakerMetrics.ofCircuitBreakerRegistry(registry);   // export state and failure rate to Micrometer
    }

    /** Only problems with the downstream itself count as failures. Other exceptions do not: the downstream responded normally. */
    static boolean isDownstreamFailure(Throwable e) {
        if (e instanceof ResourceAccessException) {                             // connection failure, timeout
            return true;
        }
        return e instanceof RestClientResponseException response && response.getStatusCode().is5xxServerError();
    }
}

Resilience4j’s defaults are: count-based over the last 100 calls, at least 100 calls, a 50% failure rate, a 60-second wait after opening, and a slow-call threshold of 60 seconds. A default slow-call threshold of 60 seconds does almost nothing; tune it to the downstream’s latency.

2. A non-critical feature: fall back

java
@Component
public class RecommendationClient {

    private static final Logger log = LoggerFactory.getLogger(RecommendationClient.class);

    private final RestClient restClient;
    private final CircuitBreaker circuitBreaker;
    private final PopularLectureCache popularLectures;

    public RecommendationClient(RestClient.Builder builder, CircuitBreakerRegistry registry,
                                PopularLectureCache popularLectures) {
        this.restClient = builder.baseUrl("https://recommendation.internal.example.com").build();
        this.circuitBreaker = registry.circuitBreaker("recommendation");
        this.popularLectures = popularLectures;
        this.circuitBreaker.getEventPublisher().onStateTransition(event ->
                log.warn("circuit breaker {}: {}", event.getCircuitBreakerName(), event.getStateTransition()));
    }

    public List<LectureCard> forMember(long memberId) {
        try {
            return circuitBreaker.executeSupplier(() -> restClient.get()
                    .uri("/v1/members/{id}/recommendations", memberId)
                    .retrieve()
                    .body(new ParameterizedTypeReference<List<LectureCard>>() {}));
        } catch (CallNotPermittedException | RestClientException e) {
            // Fall back to the popular list everyone shares: it does not depend on the recommendation service and never mixes in someone else's personalized results
            return popularLectures.top(10);
        }
    }
}

3. A critical feature: bulkhead plus breaker, fail fast

java
@Component
public class PaymentGateway {

    private final RestClient restClient;
    private final CircuitBreaker circuitBreaker;

    public PaymentGateway(RestClient.Builder builder, CircuitBreakerRegistry registry) {
        this.restClient = builder.baseUrl("https://payments.internal.example.com").build();
        this.circuitBreaker = registry.circuitBreaker("payment");
    }

    // At most 20 concurrent calls; beyond that, throw InvocationRejectedException at once (requires @EnableResilientMethods)
    @ConcurrencyLimit(limit = 20, policy = ConcurrencyLimit.ThrottlePolicy.REJECT)
    public ChargeResult charge(ChargeRequest request, String idempotencyKey) {
        return circuitBreaker.executeSupplier(() -> restClient.post()
                .uri("/v1/charges")
                .header("Idempotency-Key", idempotencyKey)
                .body(request)
                .retrieve()
                .body(ChargeResult.class));
    }
}
  • @ConcurrencyLimit’s default behavior is to wait for a slot, and REJECT is supported only from Spring Framework 7.0.3 on. A bulkhead should fail fast, so specify it explicitly
  • @ConcurrencyLimit wraps the outside, with the breaker inside: when the breaker is open, the call fails within a few microseconds and gives its slot back

When the sign-up service gets either of these two exceptions, it follows the fallback table above and creates the sign-up as “pending payment”:

java
@Service
public class CheckoutService {

    private final PaymentGateway payments;
    private final RegistrationService registrations;

    public CheckoutService(PaymentGateway payments, RegistrationService registrations) {
        this.payments = payments;
        this.registrations = registrations;
    }

    public CheckoutResult checkout(long registrationId, ChargeRequest charge, String idempotencyKey) {
        try {
            ChargeResult result = payments.charge(charge, idempotencyKey);
            registrations.markPaid(registrationId, result.chargeId());
            return CheckoutResult.paid(registrationId);
        } catch (CallNotPermittedException | InvocationRejectedException unavailable) {
            // The charge was definitely not sent: hold the seat and ask the user to pay later
            registrations.holdForPayment(registrationId, Duration.ofMinutes(15));
            return CheckoutResult.pendingPayment(registrationId);
        }
    }
}

Only when you are sure the request was not sent (rejected by the breaker or by the bulkhead) can you safely treat it as “not charged”. On a read timeout, the charge may already have gone through: query or resend with the same Idempotency Key instead of treating it as a failure.

The code above was written from the official documentation for Resilience4j 2.4 and Spring Framework 7; it has not been compiled or run.

Pitfalls and gotchas

  • Minimum number of calls set too low: at low traffic, a few occasional failures open the breaker, which then flips back and forth between open and half-open
  • One breaker for the whole service: only the refund API of the payment service is broken, yet charges are blocked too. Split breakers by endpoint or by feature
  • Counting 4xx as failures: client errors open the breaker
  • The fallback has never been tested: fallback code runs only during a failure, and nobody runs it day to day, so you find out on the day of the outage that it is broken too. You can force the breaker open regularly as a drill
  • The fallback calls another expensive dependency: the failure spreads from one service to another
  • The bulkhead makes requests queue: @ConcurrencyLimit waits by default, which gives you no isolation
  • Sizing the limit from average latency: size it from peak traffic and p99 latency, or normal peaks get rejected
  • Putting breaker state into the liveness probe: when the downstream fails, every instance is judged unhealthy and restarted. The problem is not solved, and your own service goes down too (health checks in the Load Balancing post)
  • Each server decides on its own: every server has its own breaker, so 20 servers each send their own half-open trial calls. This is usually acceptable, but know that the downstream will get 20 × 5 trial calls at once
  • No alert when the breaker opens: thanks to the fallback, users barely notice, but a feature has in fact stopped working. Record state changes and alert on them

Security

  • Attackers can open your breaker: if some inputs make the downstream return 500 (for example, special characters that trigger a downstream bug, or oversized query conditions), an attacker only has to send those requests over and over to push the failure rate past the threshold, and the breaker opens for every user. Countermeasures: count only failures related to downstream health; validate requests on your own side first, and do not send obviously invalid input downstream; for critical breakers, keep separate counts per tenant or per user
  • Security-related dependencies must not fall back to allowing: when the authorization service, fraud detection, or the rate-limiting service fails, “skip the check when the breaker is open” means an attacker only has to knock those services over first to get past your defenses. The fallback for these dependencies is always to reject (fail closed), or to switch to manual review
  • Cached fallback data must respect permissions too: when a fallback returns cached data, the cache key must include the user or the permission scope. Cache personalized responses under a shared key, and a fallback may return A’s data to B
  • Error messages must not leak internal structure: a response like “the circuit breaker for the recommendation service recommendation.internal is open” tells an attacker the names and state of your internal services. Return only a generic 503 and a retry time to the outside world
  • Expensive endpoints need their own bulkhead: if expensive endpoints such as report exports and full-text search share resources with the regular API, an attacker can take down the whole service just by calling them in bulk. Give them a separate, smaller concurrency limit
  • Keep back-office and public traffic apart: when the public API is flooded with requests, operators still need to be able to log in to the back office to handle the incident. Give the back office its own deployment or resource pool

When to use it, and when not to

  • Use a circuit breaker: when you call external services or other teams’ services, the downstream may be down for a long time, and there is a reasonable fallback or failing fast beats waiting
  • Use a bulkhead: when one service depends on several downstreams, or has both cheap and expensive endpoints, especially with virtual threads, where the thread count is no longer a natural limit
  • Do not use them: for calls to code in the same process; with only one dependency and no fallback, a breaker adds little (it can still fail fast, but weigh it against the added complexity); for resources such as databases that already have a connection pool limit, tune the pool and the timeouts first

Further reading: how an agent falls back and stops when the model service fails, in the Agent series Part 5-1 Exception Handling and Recovery.

References

Comments