What is a circuit breaker?
markdown
# Understanding Circuit Breakers
## Overview
A Circuit Breaker is a design pattern used in microservices architecture to prevent cascading failures and improve system resilience. It acts as a proxy between services, managing the flow of requests based on the health of the service being called.
## Necessary Cookies
### Performance Cookies
**[Performance]** ### Advertising Cookies
**[Advertising]** ### Uncategorized Cookies
**[Uncategorized]** Other uncategorized cookies are those that are being analyzed and have not yet been classified into a category. No cookies to display.
### User Options
- **[Reject]**
- **[Save my settings]**
- **[Accept all]**
Powered by SeniorMicroservicesSystem design
## Example Usage
We have service `A`, which makes a request to service `B`. It, in turn, calls an external API and stores something in the database. The Circuit Breaker can act as a `proxy` between services `A` and `B`. This proxy will operate on the `fail-safe` principle and, in the event of a critical error for the service, will be able to cut off traffic to `B`. The conditions under which the breaker will trigger can vary. The most common scenario is a threshold of a certain type of errors (e.g., `500/502` codes) within a specific time frame (e.g., 60 seconds).
After that, it will check whether the problem has been resolved, and when the service is operational again, it will restore traffic to it. Technically, the Circuit Breaker has several states where it determines what to do with requests to the service.
## Circuit Breaker States
### Closed
This state means that everything is fine with the service, and requests are being routed correctly. In the event of critical errors, it starts counting them, and if their number exceeds the set threshold, the proxy transitions to the `Open` state. Additionally, a waiting timer is started, which, after expiration, transitions to the `Half-Open` state, where a health check of the service occurs.
### Open
In this state, the Circuit Breaker will not route requests to the service. Instead, it will return an `error` or `fallback`. Here, everything depends on the implementation, but the essence of this state is to prevent traffic from reaching the service.
### Half-Open
In this state, we allow a limited number of requests to the service. If all of them succeed, we transition the Circuit Breaker to the `Closed` state and restore traffic to the service. If at least one request fails, we switch the state back to `Open` and restart the timer.Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.