Back
+20 XP
Concept

Circuit Breaker Pattern for Resilient Microservices

When remote microservices fail, naive retries trigger thread starvation and cascading failures. A Circuit Breaker trips from `CLOSED` to `OPEN` after repeated errors, failing fast without hammering downed dependencies ⚡.

python
class CircuitBreaker:
    def __init__(self, threshold=2):
        self.state = "CLOSED"
        self.failures = 0
        self.threshold = threshold

    def call(self, func):
        if self.state == "OPEN":
            return "FAST_FAIL"
        try:
            res = func()
            self.failures = 0
            return res
        except Exception:
            self.failures += 1
            if self.failures >= self.threshold:
                self.state = "OPEN"
            return "ERROR"

cb = CircuitBreaker(threshold=2)
failing = lambda: 1 / 0
cb.call(failing)
cb.call(failing)
print(f"State: {cb.state}, Response: {cb.call(failing)} 🛑")

# 86. Circuit Breaker Pattern for Resilient Microservices When remote microservices fail, naive retries trigger thread starvation and cascading failures. A Circuit Breaker trips from `CLOSED` to `OPEN` after repeated errors, failing fast without hammering downed dependencies ⚡. ```python class CircuitBreaker: def __init__(self, threshold=2): self.state = "CLOSED" self.failures = 0 self.threshold = threshold def call(self, func): if self.state == "OPEN": return "FAST_FAIL" try: res = func() self.failures = 0 return res except Exception: self.failures += 1 if self.failures >= self.threshold: self.state = "OPEN" return "ERROR" cb = CircuitBreaker(threshold=2) failing = lambda: 1 / 0 cb.call(failing) cb.call(failing) print(f"State: {cb.state}, Response: {cb.call(failing)} 🛑") ``` After a cooldown interval, the breaker enters `HALF_OPEN` to test a single canary request. If the canary succeeds, the breaker resets to `CLOSED`; if it fails, it returns to `OPEN` 🛡️! --- ### Question What state transition does a Circuit Breaker execute when consecutive errors surpass the threshold? 🧠 - [ ] a. From `CLOSED` to `OPEN`, immediately intercepting calls and failing fast ⚡ - [ ] b. From `OPEN` to `TERMINATED`, exiting the application process - [ ] c. From `HALF_OPEN` to `INFINITE_RETRY`, looping indefinitely - [ ] d. From `CLOSED` to `THREAD_SPIN`, spawning background threads --- ### Challenge Implement `CircuitBreaker(threshold=2)`. Call a failing function twice to trip the breaker. Call a 3rd time and print `(cb.state, cb.call(failing))`. 🎯 <details> <summary>Solution</summary> ```python class CircuitBreaker: def __init__(self, threshold=2): self.state = 'CLOSED' self.failures = 0 self.threshold = threshold def call(self, f): if self.state == 'OPEN': return 'FAST_FAIL' try: res = f() self.failures = 0 return res except Exception: self.failures += 1 if self.failures >= self.threshold: self.state = 'OPEN' return 'ERROR' cb = CircuitBreaker(threshold=2) failing = lambda: 1 / 0 cb.call(failing) cb.call(failing) print((cb.state, cb.call(failing))) ``` </details>

Checkpoint

What state transition does a Circuit Breaker execute when consecutive errors surpass the threshold? 🧠

Practice

Implement `CircuitBreaker(threshold=2)`. Call a failing function twice to trip the breaker. Call a 3rd time and print `(cb.state, cb.call(failing))`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks