தோல்வி மூலம் சர்க்யூட் பிரேக்கர் (Circuit Breaker) விளக்கம்

சில நாட்களுக்கு முன்பு நான் எதிர்பாராத ஒரு சிக்கலை எதிர்கொண்டேன்.

ஏமாற்றம் என்னை மிகவும் பாதித்தது. அதைச் சரிசெய்ய நான் விரும்பினேன். ஆர்வம் என்னை தொடர்ந்து முன்னேறத் தூண்டியது.

நான் மீண்டும் அந்தப் பிரச்சனையை ஆராய்ந்து பார்த்தேன். அதற்கான தீர்வை நான் கண்டறிந்தேன். அதுதான் சர்க்யூட் பிரேக்கர் (circuit breaker) என்று அழைக்கப்படுகிறது.

மென்பொருளில் (software), ஒரு சிறிய தோல்வி உங்கள் முழு அமைப்பையும் (system) முடக்குவதைத் தடுக்க சர்க்யூட் பிரேக்கர் உதவுகிறது. இது உங்கள் வீட்டில் உள்ள மின்சார பிரேக்கரைப் போலவே செயல்படுகிறது.

சர்க்யூட் பிரேக்கருக்கு மூன்று நிலைகள் உள்ளன:

  • CLOSED: அனைத்தும் இயங்கும். அனைத்து கோரிக்கைகளும் (requests) அனுமதிக்கப்படும். சிஸ்டம் தோல்விகளைக் கண்காணிக்கும். தோல்விகள் ஒரு குறிப்பிட்ட எல்லையைத் தாண்டினால், சர்க்யூட் திறக்கப்படும் (opens).
  • OPEN: சிஸ்டம் உடனடியாக அனைத்து கோரிக்கைகளையும் நிறுத்திவிடும். இது தோல்வியுற்ற சேவை (service) மீண்டு வர கால அவகாசம் அளிக்கிறது.
  • HALF_OPEN: சிஸ்டம் சில சோதனை கோரிக்கைகளை (test requests) அனுமதிக்கும். அவை வெற்றியடைந்தால், சர்க்யூட் மூடப்படும் (closes). அவை தோல்வியடைந்தால், சர்க்யூட் மீண்டும் திறக்கப்படும் (opens).

இதோ இதற்கான ஒரு எளிய குறியீடு (code):

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

இந்த வழிமுறை எனது சமீபத்திய சிக்கலைச் சரிசெய்தது. பிழைகளின் பெருக்கத்தால் உங்கள் அப்ளிகேஷன் (application) முடங்குவதைத் இது தடுக்கிறது.

உங்கள் கருத்துக்களைக் கருத்துப் பெட்டியில் (comments) பகிரவும். நான் இன்னும் கற்றுக்கொண்டிருக்கிறேன்.

ஆதாரம்: https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg