వైఫల్యం ద్వారా సర్క్యూట్ బ్రేకర్ వివరణ

కొన్ని రోజుల క్రితం నేను ఊహించని ఒక సమస్యను ఎదుర్కొన్నాను.

నిరాశ నన్ను తీవ్రంగా తాకింది. నేను దానిని పరిష్కరించాలనుకున్నాను. కుతూహలం నన్ను ముందుకు సాగించమని ప్రేరేపించింది.

నేను మళ్ళీ ఆ సమస్యపై దృష్టి సారించాను. నాకు పరిష్కారం దొరికింది. దానిని సర్క్యూట్ బ్రేకర్ (circuit breaker) అని పిలుస్తారు.

సాఫ్ట్‌వేర్‌లో, సర్క్యూట్ బ్రేకర్ అనేది ఒకే ఒక వైఫల్యం వల్ల మీ మొత్తం సిస్టమ్ క్రాష్ కాకుండా నిరోధిస్తుంది. ఇది మీ ఇంట్లోని బ్రేకర్ లాగా పనిచేస్తుంది.

సర్క్యూట్ బ్రేకర్‌కు మూడు స్టేట్లు ఉంటాయి:

  • CLOSED: అంతా సజావుగా సాగుతుంది. అన్ని రిక్వెస్ట్‌లు వెళ్తాయి. సిస్టమ్ వైఫల్యాలను ట్రాక్ చేస్తుంది. వైఫల్యాలు ఒక పరిమితికి చేరుకుంటే, సర్క్యూట్ ఓపెన్ అవుతుంది.
  • OPEN: సిస్టమ్ వెంటనే అన్ని రిక్వెస్ట్‌లను నిలిపివేస్తుంది. ఇది వైఫల్యం చెందిన సర్వీస్‌కు కోలుకోవడానికి సమయాన్ని ఇస్తుంది.
  • HALF_OPEN: సిస్టమ్ కొన్ని టెస్ట్ రిక్వెస్ట్‌లను అనుమతిస్తుంది. అవి విజయవంతమైతే, సర్క్యూట్ క్లోజ్ అవుతుంది. అవి విఫలమైతే, సర్క్యూట్ మళ్ళీ ఓపెన్ అవుతుంది.

కోడ్‌లో దీనికి సంబంధించిన ఒక సాధారణ ఇంప్లిమెంటేషన్ ఇక్కడ ఉంది:

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
        }
    }
}

ఈ మెకానిజం నా ఇటీవలి సమస్యను పరిష్కరించింది. ఇది ఎర్రర్ల వరద వల్ల మీ అప్లికేషన్ దెబ్బతినకుండా ఆపుతుంది.

దయచేసి మీ అభిప్రాయాలను కామెంట్లలో పంచుకోండి. నేను ఇంకా నేర్చుకుంటున్నాను.

మూలం: https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg