विफलता के माध्यम से सर्किट ब्रेकर की व्याख्या
कुछ दिन पहले मुझे एक अप्रत्याशित समस्या का सामना करना पड़ा।
मैं बहुत हताश महसूस कर रहा था। मैं इसे ठीक करना चाहता था। जिज्ञासा ने मुझे आगे बढ़ने के लिए मजबूर किया।
मैं फिर से उस समस्या को सुलझाने के लिए बैठ गया। मुझे समाधान मिल गया। इसे सर्किट ब्रेकर (circuit breaker) कहा जाता है।
सॉफ्टवेयर में, एक सर्किट ब्रेकर किसी एक विफलता को आपके पूरे सिस्टम को क्रैश करने से रोकता है। यह आपके घर के ब्रेकर की तरह काम करता है।
एक सर्किट ब्रेकर की तीन अवस्थाएं (states) होती हैं:
- CLOSED: सब कुछ ठीक काम करता है। सभी अनुरोध (requests) पूरे होते हैं। सिस्टम विफलताओं को ट्रैक करता है। यदि विफलताएं एक सीमा तक पहुँच जाती हैं, तो सर्किट खुल (open) जाता है।
- OPEN: सिस्टम तुरंत सभी अनुरोधों को रोक देता है। इससे विफल हो रही सेवा को ठीक होने का समय मिलता है।
- HALF_OPEN: सिस्टम कुछ परीक्षण अनुरोधों (test requests) की अनुमति देता है। यदि वे सफल होते हैं, तो सर्किट बंद (close) हो जाता है। यदि वे विफल होते हैं, तो सर्किट फिर से खुल (open) जाता है।
यहाँ कोड में एक सरल कार्यान्वयन (implementation) दिया गया है:
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
}
}
}
इस तंत्र (mechanism) ने मेरी हालिया समस्या को हल कर दिया। यह त्रुटियों (errors) की बाढ़ को आपके एप्लिकेशन को क्रैश करने से रोकता है।
कृपया कमेंट्स में अपने विचार साझा करें। मैं अभी भी सीख रहा हूँ।
स्रोत: https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg