𝗘𝗹 𝗖𝗶𝗿𝗰𝘂𝗶𝘁 𝗕𝗿𝗲𝗮𝗸𝗲𝗿 𝗲𝘅𝗽𝗹𝗶𝗰𝗮𝗱𝗼 𝗮 𝘁𝗿𝗮𝘃é𝘀 𝗱𝗲 𝘂𝗻 𝗳𝗮𝗹𝗹𝗼
Hace unos días me enfrenté a un problema inesperado.
La frustración me golpeó con fuerza. Quería solucionarlo. La curiosidad me obligó a seguir adelante.
Volví a sentarme con el problema. Encontré la solución. Se llama circuit breaker.
En el software, un circuit breaker evita que un único fallo colapse todo tu sistema. Funciona como el interruptor de tu casa.
Un circuit breaker tiene tres estados:
- CLOSED: Todo funciona. Todas las peticiones pasan. El sistema rastrea los fallos. Si los fallos alcanzan un límite, el circuito se abre.
- OPEN: El sistema detiene todas las peticiones inmediatamente. Esto le da tiempo al servicio que está fallando para recuperarse.
- HALF_OPEN: El sistema permite algunas peticiones de prueba. Si tienen éxito, el circuito se cierra. Si fallan, el circuito se abre de nuevo.
Aquí tienes una implementación sencilla en código:
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
}
}
}
Este mecanismo solucionó mi problema reciente. Evita que una avalancha de errores acabe con tu aplicación.
Por favor, comparte tus opiniones en los comentarios. Todavía estoy aprendiendo.
Fuente: https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg