Senior
What is a Circuit Breaker?
sobes.tech AI
Answer from AI
Circuit Breaker is a design pattern used to increase the resilience of distributed systems. It prevents continuous attempts to access a non-functioning service, helping to avoid cascading failures and excessive load.
Working principle:
- When a certain number of errors is exceeded, the Circuit Breaker "opens" and blocks further calls to the problematic service.
- After some time, it attempts to "close" the circuit and check if the service has recovered.
- If the service responds successfully, the Circuit Breaker returns to its normal state.
In Node.js, this is often implemented using libraries such as opossum.
Example of usage with the opossum library:
const CircuitBreaker = require('opossum');
function asyncServiceCall() {
return new Promise((resolve, reject) => {
// emulate call to an external service
if (Math.random() > 0.7) resolve('Success');
else reject('Failure');
});
}
const breaker = new CircuitBreaker(asyncServiceCall, {
timeout: 3000, // response timeout
errorThresholdPercentage: 50, // error threshold for triggering
resetTimeout: 5000 // time before attempting to recover
});
breaker.fire()
.then(console.log)
.catch(console.error);