𝗖𝗶𝗿𝗰𝘂𝗶𝘁 𝗕𝗿𝗲𝗮𝗸𝗲𝗿 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 𝗧𝗵𝗿𝗼𝘂𝗴𝗵 𝗙𝗮𝗶𝗹𝘂𝗿𝗲
I faced an unexpected problem a few days ago.
Frustration hit me hard. I wanted to fix it. Curiosity forced me to keep going.
I sat down with the problem again. I found the solution. It is called a circuit breaker.
In software, a circuit breaker prevents a single failure from crashing your entire system. It works like the breaker in your home.
A circuit breaker has three states:
- CLOSED: Everything works. All requests go through. The system tracks failures. If failures hit a limit, the circuit opens.
- OPEN: The system stops all requests immediately. This gives the failing service time to recover.
- HALF_OPEN: The system allows a few test requests. If they succeed, the circuit closes. If they fail, the circuit opens again.
Here is a simple implementation in code:
export class CircuitBreaker { constructor(failureThreshold, cooldownMs) { this.failureThreshold = failureThreshold this.cooldownMs = cooldownMs this.state = "CLOSED" this.failureCount = 0 this.lastFailureTime = null }
openCircuit() {
this.state = "OPEN"
this.lastFailureTime = Date.now()
}
closeCircuit() {
this.state = "CLOSED"
this.failureCount = 0
this.lastFailureTime = null
}
halfOpenCircuit() {
this.state = "HALF_OPEN"
}
async execute(fn) {
if (this.state === "OPEN") {
const cooldownExpired = Date.now() - this.lastFailureTime >= this.cooldownMs
if (!cooldownExpired) {
throw new Error("Circuit is open.")
}
this.halfOpenCircuit();
}
try {
const result = await fn()
if (this.state === "HALF_OPEN") {
this.closeCircuit()
}
return result;
} catch (error) {
if (this.state === "HALF_OPEN") {
this.openCircuit()
throw error;
}
this.failureCount++
if (this.failureCount >= this.failureThreshold) {
this.openCircuit()
}
throw error
}
}
}
This mechanism fixed my recent issue. It stops the flood of errors from killing your application.
Please share your thoughts in the comments. I am still learning.
Source: https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg