𝗖𝗶𝗿𝗰𝘂𝗶𝘁 𝗕𝗿𝗲𝗮𝗸𝗲𝗿 𝘀𝗽𝗹𝗶𝗴𝗮𝘁𝗼 𝘁𝗿𝗮𝘃𝗲𝗿𝘀𝗼 𝘂𝗻 𝗴𝘂𝗮𝘀𝘁𝗼
Qualche giorno fa mi sono imbattuto in un problema inaspettato.
La frustrazione è stata forte. Volevo risolverlo. La curiosità mi ha spinto a continuare.
Mi sono rimesso a studiare il problema. Ho trovato la soluzione. Si chiama circuit breaker.
Nel software, un circuit breaker impedisce che un singolo guasto faccia crashare l'intero sistema. Funziona come l'interruttore di casa tua.
Un circuit breaker ha tre stati:
- CLOSED: Tutto funziona. Tutte le richieste passano. Il sistema tiene traccia dei guasti. Se i guasti raggiungono un limite, il circuito si apre.
- OPEN: Il sistema interrompe immediatamente tutte le richieste. Questo dà al servizio in errore il tempo di riprendersi.
- HALF_OPEN: Il sistema permette alcune richieste di test. Se hanno successo, il circuito si chiude. Se falliscono, il circuito si riapre.
Ecco una semplice implementazione in codice:
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
}
}
}
Questo meccanismo ha risolto il mio recente problema. Impedisce che un'ondata di errori faccia crashare la tua applicazione.
Condividi le tue opinioni nei commenti. Sto ancora imparando.
Fonte: https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg