Your fallback chain keeps answering hikers when a model fails. During an outage, though, every hiker still waits three seconds for each role first, and the chain learns nothing from the hiker before them.
In this lesson, you’ll add a circuit breaker that skips a failing role for a while and notices when it recovers. Start with how it decides the role is down.
Count Failures, Then Stop Asking
A circuit breaker counts one role’s recent failures and, after a few, stops calling it. Like the breaker in a hut’s electrical panel, it’s closed while calls flow and open once it trips. Unlike that one, it resets itself. After a cool-off, it lets one trial call through. A success closes it, and a failure opens it again.
Create model/breaker.js. Three failures within thirty seconds trip it, and each state change becomes a breaker span through Observing AI Features’ span() helper:
model/breaker.js
import { span } from "../trace.js";
export const BREAKER = { limit: 3, windowMs: 30_000, coolOffMs: 30_000 };
export function createBreaker(role, settings = BREAKER) {
let state = "closed";
let failures = [];
let openedAt = 0;
function move(traceId, next) {
state = next;
return span(traceId, "breaker", (s) => {
s.role = role;
s.state = next;
});
}
The state lives in a closure, so all requests in one server process share one breaker per role. A restart resets it. With several processes, each breaker trips on its own. You can accept that or use shared storage. .allow() returns "closed" or "trial" to allow a call, or null to skip the role: