𝗖𝗶𝗿𝗰𝘂𝗶𝘁 𝗕𝗿𝗲𝗮𝗸𝗲𝗿 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 𝗧𝗵𝗿𝗼𝘂𝗴𝗵 𝗙𝗮𝗶𝗹𝘂𝗿𝗲
काही दिवसांपूर्वी मला एका अनपेक्षित समस्येचा सामना करावा लागला.
मी खूप निराश झालो होतो. मला ती समस्या सोडवायची होती. कुतूहलामुळे मी प्रयत्न करणे सोडले नाही.
मी पुन्हा त्या समस्येवर काम करायला बसलो. मला त्याचे समाधान सापडले. त्याला 'सर्किट ब्रेकर' (circuit breaker) म्हणतात.
सॉफ्टवेअरमध्ये, सर्किट ब्रेकर एका सिंगल फेल्युअरमुळे (failure) तुमचे संपूर्ण सिस्टम क्रॅश होण्यापासून वाचवतो. हे तुमच्या घरातील सर्किट ब्रेकरप्रमाणेच काम करते.
सर्किट ब्रेकरच्या तीन अवस्था (states) असतात:
- CLOSED: सर्व काही व्यवस्थित चालते. सर्व विनंत्या (requests) पूर्ण होतात. सिस्टम अपयशांचा (failures) मागोवा घेते. जर अपयशांची संख्या एका मर्यादेपर्यंत पोहोचली, तर सर्किट 'ओपन' होते.
- OPEN: सिस्टम सर्व विनंत्या त्वरित थांबवते. यामुळे ज्या सेवेमध्ये त्रुटी येत आहे, तिला सावरण्यासाठी वेळ मिळतो.
- HALF_OPEN: सिस्टम काही चाचणी विनंत्या (test requests) करण्याची परवानगी देते. जर त्या यशस्वी झाल्या, तर सर्किट 'क्लोज' होते. जर त्या अयशस्वी झाल्या, तर सर्किट पुन्हा 'ओपन' होते.
येथे कोडमधील एक साधे अंमलबजावणी (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