Core Module
12 min forge
Circuit Breaker Pattern
Master the safety switch of distributed systems. Learn how to prevent cascading failures by stopping calls to a failing service.
π Circuit Breaker Pattern
The Circuit Breaker pattern is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.
π‘ The Logic (ELI5)
Think of an Electrical Panel in your House:
- You have a hair dryer that is faulty and causing a "Short Circuit."
- Without a Circuit Breaker, the wires in your walls would catch fire and burn the whole house down (Cascading Failure).
- Instead, the Circuit Breaker "trips" and cuts the power to that one room immediately.
- You wait a while, fix the dryer, and then flip the switch back on.
π The Deep Dive
The Three States
- Closed: Everything is normal. Requests flow through.
- Open: The service is failing. The circuit breaker "trips" and returns an error immediately without even trying to call the failing service.
- Half-Open: After a "timeout," the circuit breaker lets one request through to see if the service is fixed. If it works, it closes the circuit. If it fails, it stays open.
Why use it?
- Prevents Cascading Failures: If the "Payment Service" is slow, the "Order Service" shouldn't hang and eventually crash too.
- Service Recovery: Gives the failing service room to breathe and recover without being hammered by thousands of retry attempts.
π― Interview Pulse
Use Case
Always mention the Circuit Breaker when designing Microservices. Since services talk over a network, a network failure or a slow service is inevitable.
Fallback Logic
What happens when the circuit is "Open"? Answer: You provide a Fallback.
- If the "Recommendation Service" is down, return a hardcoded list of "Popular Items" instead of an error message.
- "We are sorry, payments are temporarily unavailable. We've saved your cart!"
Popular Libraries
- Hystrix (Netflix), Resilience4j. β‘