What is the Circuit Breaker Pattern?
A Circuit Breaker monitors for failures and short-circuits calls to a downstream service if it detects that the service is failing repeatedly. This avoids:
- Repeated failures when a service is already known to be down.
- Overloading a failing service, which could make recovery slower or impossible.
- Wasting resources (like threads or connections) on calls that are likely to fail.
- Cascading failures that spread through a distributed system when one part goes down.
It works like an electrical circuit breaker:
State | Description |
---|---|
Closed | Everything is normal. Calls pass through. Failures are counted. |
Open | Too many failures. Calls are blocked and fail immediately. |
Half-Open | After a wait time, limited test calls are allowed to check if recovery happened. |
When to Use It
Use a Circuit Breaker when your microservice depends on other services or remote calls and you want to:
- Prevent failure propagation (e.g., DB down, another service is slow/unavailable)
- Implement graceful degradation (e.g., return fallback response)
- Improve system resilience and uptime
When NOT to Use Circuit Breakers
Avoid circuit breakers on:
- Internal logic that doesn’t call external systems
- Validation or authentication endpoints (you want them to fail fast)
- In-memory or cache-only services (e.g., Redis as primary session store — instead, use a fallback or replication strategy)
How to Use Circuit Breaker in Spring Boot Microservices
1. Requests pass through the circuit breaker.
2. If failure rate exceeds threshold (e.g., 50% of last 10 calls), breaker opens.
3. While open, requests are short-circuited to fallback immediately.
4. After a timeout (e.g., 10s), it enters half-open state and tries a few test requests.
5. If test calls succeed → closed, else → open again.
Best Practices
- Combine with retry, timeout, bulkhead, and rate limiter patterns
- Always define meaningful fallbacks
- Monitor breaker metrics via actuator endpoints
Common Use Cases in Fintech:
Use Case | Reason to Use Circuit Breaker |
---|---|
Payment Processing | Depends on third-party (e.g., Stripe, Visa API) |
Bank Transfers | Relies on partner banks, core banking APIs |
KYC/AML Checks | External services like Onfido, Jumio, or IDScan |
Credit Score Checks | External API call to bureaus like TransUnion |
Balance Verification | If it’s a downstream microservice (e.g., ledger DB) |
Fraud Detection Service | AI engine or external fraud scoring system |
Exchange Rate Service | Often external or delayed via cache |
Notification System | Push/SMS/email via external provider (Twilio, etc.) |
Account Statements | Depends on report services, might be slow |
Leave a Reply