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
Related
larzretryRetry a flaky call with exponential backoff, or wrap it in a circuit breaker→Retry with Exponential Backoff in LarzscriptRetry a flaky call a few times, waiting longer between each attempt, instead of failing on the first hiccup or hammering a struggling service.→Memoize a Function in LarzscriptCache a function's results so calling it twice with the same input only does the real work once.→Implement a State Machine in LarzscriptDeclare states and transitions, fire events, and let the machine reject anything that isn't a legal move - a document workflow (draft -> review -> published) in a few lines.→