App patterns · real, tested code

Implement a Circuit Breaker in Larzscript

Stop hammering a failing dependency: after enough real failures, fail fast for a cooldown period instead of trying again.

retry.breaker(threshold, cooldown_seconds) tracks failures; retry.guard() runs a call through it, throwing immediately once the breaker is open instead of making a real (doomed) call.

larzscript pkg install retry

Code

import "retry" as retry

let attempts = 0
fn flaky() {
  attempts = attempts + 1
  throw {"type": "LarzRuntimeError", "message": "service down"}
}

let cb = retry.breaker(3, 30)
let i = 0
while i < 5 {
  try {
    retry.guard(cb, flaky)
  } catch e {
    print("call", i, "failed:", e["message"])
  }
  i = i + 1
}
print("total real attempts made:", attempts)
Output
call 0 failed: service down (line 6) (line 76)
call 1 failed: service down (line 6) (line 76)
call 2 failed: service down (line 6) (line 76)
call 3 failed: circuit breaker is open (line 60)
call 4 failed: circuit breaker is open (line 60)
total real attempts made: 3