LLM Engineering · Exercise 6 of 6 Previous
Advanced
Write a circuit breaker
Write CircuitBreaker(threshold, open_ms) with the attribute state (starts as "closed"), allow(now) and record(ok, now).
allow(now): if the state is "open" and now - opened_at >= open_ms, change it to "half-open". Return True unless the state is "open". record(ok, now): on success set the state to "closed" and reset the failure count. On failure add one to the count, and if the state is "half-open" or the count has reached threshold, set the state to "open" and remember now as opened_at.
What Check tests
- It starts closed and allows calls
- It opens after the threshold of failures and blocks calls
- One failure is not enough, and a success resets the count
- After the cool-down it is half-open and allows one trial
- A failed trial opens it again, a successful one closes it
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.