Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSystem Design for Python JuniorsModule 1 · System Design FundamentalsDesigning for failurepredict15 / 105
+100 XP
Task
📝 **Task:** Predict the 7-line trace of state strings emitted by the circuit breaker as it cycles through 2 successes, 3 failures, 1 short-circuit, and 1 recovery probe. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

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

    def call(self, fn):
        # OPEN — short-circuit, never call the real fn.
        if self.state == "OPEN":
            return "fallback"
        try:
            result = fn()
        except Exception:
            self.failures += 1
            if self.failures >= self.threshold:
                self.state = "OPEN"
            return "fallback"
        # Success path — only reset failure count from HALF_OPEN.
        if self.state == "HALF_OPEN":
            self.state = "CLOSED"
            self.failures = 0
        return result

    def half_open(self):
        # An external timer in a real CB would do this. We trigger
        # it manually so the prediction stays deterministic.
        self.state = "HALF_OPEN"


def ok():    return "ok"
def boom():  raise RuntimeError("dep down")

cb = CircuitBreaker(threshold=3)

cb.call(ok);   print(cb.state)        # CLOSED, success — state unchanged
cb.call(ok);   print(cb.state)        # CLOSED
cb.call(boom); print(cb.state)        # 1 fail → CLOSED still (under threshold)
cb.call(boom); print(cb.state)        # 2 fails → CLOSED
cb.call(boom); print(cb.state)        # 3 fails → OPEN (just tripped)
cb.call(ok);   print(cb.state)        # OPEN — short-circuited, real fn skipped
cb.half_open()
cb.call(ok);   print(cb.state)        # HALF_OPEN probe success → CLOSED

# What does this print? Type your prediction.

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…