javascript / expert
Snippet
The Circuit Breaker Pattern for Service Resilience
The Circuit Breaker pattern prevents an application from repeatedly trying to execute an operation that is likely to fail, allowing the system to recover while providing a fallback or error immediate response.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class CircuitBreaker {private state = 'CLOSED';private failures = 0;private threshold = 3;async execute(requestFn) {if (this.state === 'OPEN') throw new Error('Circuit is open');try {const result = await requestFn();this.failures = 0;return result;} catch (err) {this.failures++;if (this.failures >= this.threshold) this.state = 'OPEN';throw err;}}}
nextjs
Breakdown
1
if (this.state === 'OPEN') throw ...
Immediately rejects requests if the failure threshold has been reached, protecting the downstream service.
2
this.failures = 0;
Resets the failure counter on a successful operation, restoring the 'CLOSED' state logic.
3
if (this.failures >= this.threshold) this.state = 'OPEN';
Trips the breaker after consecutive failures, initiating a cooldown period for the system.