CodeBlanks Logo Icon CodeBlanks

Circuit breaker

Learn the circuit breaker pattern.

Circuit breaker

A circuit breaker temporarily stops a call that fails repeatedly. It has three states: closed (normal), open (calls rejected) and half-open (trial).

Example: class CircuitBreaker(val threshold: Int). When failures reach threshold, the circuit goes open; calls are rejected. This pattern prevents a failing dependency from dragging the whole system down. After a period, half-open tries again.

Threshold and the open state

When failures reach threshold, the circuit goes open. In the open state, calls are rejected immediately; no real work is done. This reduces load when the external service is failing.

Example: threshold = 2. After two failed calls, the circuit goes open. The third call does no work; it returns "open". This pattern prevents error accumulation and gives the system recovery time.

Practice Write the CircuitBreaker class

Define class CircuitBreaker(val threshold: Int) with var failures = 0 and var open = false. Write fun execute(action: () -> String): String: if open, return "open"; otherwise call action and return its result on success, or on exception increment failures, set open = true when reaching threshold and return "error". In main create CircuitBreaker(2) and print three execute { throw RuntimeException() } results.

Starter code

Main.kt
// CircuitBreaker class: threshold, failures, open
// execute: open returns open, action success returns result, exception returns error
// in main print three failing call results

Sample solution

Main.kt
class CircuitBreaker(val threshold: Int) {
    var failures = 0
    var open = false
    fun execute(action: () -> String): String {
        if (open) return "open"
        return try {
            action()
        } catch (e: Exception) {
            failures++
            if (failures >= threshold) open = true
            "error"
        }
    }
}

fun main() {
    val cb = CircuitBreaker(2)
    println(cb.execute { throw RuntimeException() })
    println(cb.execute { throw RuntimeException() })
    println(cb.execute { "ok" })
}

Expected output

error
error
open

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the CircuitBreaker definition

Question
____ CircuitBreaker(val threshold: Int)
Answer
class CircuitBreaker(val threshold: Int)

Explanation: class CircuitBreaker declares a class.

2 Match the circuit-breaker parts

Term Meaning
threshold Failure threshold
closed Normal state
open Call rejection
half-open Trial

3 What happens when a circuit breaker is in the open state?

  • All calls succeed
  • Calls are rejected Correct answer
  • System restarts
  • Threshold resets

Explanation: In the open state, calls are rejected immediately.

All lessons in Advanced