Video in progress

What is the circuit breaker pattern, and what does it protect against?

When errors pile up, a circuit breaker temporarily stops calls to the problem service and immediately returns an error or a fallback. It saves the caller from waiting for nothing, and the problem service from extra load.

📖 Answer

The name comes from the electrical breaker: on a short circuit, the breaker cuts the current and keeps the house from catching fire.

Without a breaker: recommendation-service is down. Every request waits for a 3-second timeout, then fails. The user's page slows down, threads get tied up, and the failed service stays under a stream of requests even while it's trying to recover.

With a breaker: if more than 50% of the last 20 calls fail, the breaker "opens". For the next 30 seconds no calls are sent at all; a CallNotPermittedException or a fallback comes back immediately.

@CircuitBreaker(name = "recommendations", fallbackMethod = "emptyList")
public List<ProductDto> recommend(long userId) {
    return recommendationClient.forUser(userId);
}

private List<ProductDto> emptyList(long userId, Throwable ex) {
    return List.of(); // the page works fine without recommendations too
}

In Spring Boot 3 you usually use Resilience4j; the old Netflix Hystrix is no longer supported.