API / Microservices Design Patterns Interview Questions
How does the Circuit Breaker pattern work and what are its three states?
The Circuit Breaker pattern prevents cascading failures by detecting when a downstream service is unavailable and fast-failing subsequent calls instead of letting them queue up and exhaust threads. It is named after the electrical circuit breaker that trips when current exceeds a safe threshold.
The pattern has three states:
- Closed (normal) — calls pass through to the downstream service. The breaker counts failures. When the failure rate (or failure count) exceeds a configured threshold within a time window, the breaker trips to Open.
- Open — all calls are immediately rejected with an error (or the Fallback is invoked) without contacting the downstream service. A timer starts. This gives the failing service time to recover without being bombarded with traffic.
- Half-Open — after the timer expires, the breaker allows a limited number of probe requests through. If they succeed, the breaker transitions back to Closed. If they fail, it returns to Open.
// Resilience4j Circuit Breaker (Java)
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
.failureRateThreshold(50) // open if >50% fail
.waitDurationInOpenState(Duration.ofSeconds(30))
.permittedNumberOfCallsInHalfOpenState(5)
.slidingWindowSize(10)
.build();
CircuitBreaker cb = CircuitBreakerRegistry.of(config)
.circuitBreaker("inventoryService");
Supplier<Stock> decorated = CircuitBreaker
.decorateSupplier(cb, () -> inventoryClient.getStock(sku));
Try<Stock> result = Try.ofSupplier(decorated)
.recover(CallNotPermittedException.class, e -> defaultStock());
The circuit breaker is most effective when combined with a Fallback (Q31) — when the circuit is Open, the fallback returns a cached or degraded response so the caller can still serve the request in a degraded mode rather than propagating a hard error to the user.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
