નિષ્ફળતા દ્વારા સર્કિટ બ્રેકરની સમજૂતી

થોડા દિવસો પહેલા મને એક અણધારી સમસ્યાનો સામનો કરવો પડ્યો હતો.

હું ખૂબ જ નિરાશ થયો હતો. હું તેને ઠીક કરવા માંગતો હતો. જિજ્ઞાસાએ મને આગળ વધવા માટે મજબૂર કર્યો.

હું ફરીથી તે સમસ્યા પર બેઠો. મને તેનો ઉકેલ મળ્યો. તેને સર્કિટ બ્રેકર (circuit breaker) કહેવામાં આવે છે.

સોફ્ટવેરમાં, સર્કિટ બ્રેકર એક જ નિષ્ફળતાને તમારી સમગ્ર સિસ્ટમને ક્રેશ થતી અટકાવે છે. તે તમારા ઘરના બ્રેકરની જેમ કામ કરે છે.

સર્કિટ બ્રેકરની ત્રણ અવસ્થાઓ (states) હોય છે:

  • CLOSED: બધું બરાબર કામ કરે છે. બધી વિનંતીઓ (requests) પસાર થાય છે. સિસ્ટમ નિષ્ફળતાઓને ટ્રેક કરે છે. જો નિષ્ફળતાઓની સંખ્યા મર્યાદા સુધી પહોંચે, તો સર્કિટ ખુલી (open) જાય છે.
  • OPEN: સિસ્ટમ તરત જ બધી વિનંતીઓ અટકાવી દે છે. આનાથી નિષ્ફળ જતી સર્વિસને રિકવર થવા માટે સમય મળે છે.
  • HALF_OPEN: સિસ્ટમ થોડી ટેસ્ટ વિનંતીઓની મંજૂરી આપે છે. જો તેઓ સફળ થાય, તો સર્કિટ બંધ (close) થઈ જાય છે. જો તેઓ નિષ્ફળ જાય, તો સર્કિટ ફરીથી ખુલી (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