Circuit Breaker Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circuit Breaker runs in O(1) time and O(1) space, in TypeScript as in every other language.
- ✓cockatiel is written in TypeScript and composes typed policies, circuitBreaker, retry, timeout and bulkhead, into a single wrap() pipeline, with a ConsecutiveBreaker or SamplingBreaker choosing the tripping rule.
- ✓Compose the policies with wrap() in a deliberate order, timeout innermost, then breaker, then retry, and give the result a named exported type so every call site shares it.
- ✓The TypeScript trap: A fallback typed identically to the success value is indistinguishable at the type level, so downstream code cannot tell a real payment confirmation from a degraded placeholder and will happily persist the placeholder as if it were real, this is a genuine data-integrity bug that the type system will catch only if you model the two outcomes as different variants.
- ✓Erased at runtime. Composition adds one function call per policy layer per invocation, negligible against I/O.
What Circuit Breaker actually is
Circuit Breaker in TypeScript: what you actually reach for
TypeScript implementation
import {
circuitBreaker, retry, timeout, wrap,
ConsecutiveBreaker, ExponentialBackoff, handleAll, TimeoutStrategy,
} from 'cockatiel';
export type ChargeResult =
| { readonly kind: 'charged'; readonly id: string }
| { readonly kind: 'degraded'; readonly reason: 'circuit-open' };
const breaker = circuitBreaker(handleAll, {
halfOpenAfter: 30_000,
breaker: new ConsecutiveBreaker(5),
});
// Order is SEMANTIC: timeout innermost, then breaker, then retry.
// Retry INSIDE the breaker would make each retry count toward tripping it.
const policy = wrap(
retry(handleAll, { maxAttempts: 3, backoff: new ExponentialBackoff() }),
breaker,
timeout(3_000, TimeoutStrategy.Aggressive),
);
export async function charge(amountCents: number): Promise<ChargeResult> {
try {
const id = await policy.execute(({ signal }) => chargeUpstream(amountCents, signal));
return { kind: 'charged', id };
} catch {
// A degraded result is a DIFFERENT TYPE, so no caller can persist it
// as if it were a real confirmation.
return { kind: 'degraded', reason: 'circuit-open' };
}
}
declare function chargeUpstream(amountCents: number, signal: AbortSignal): Promise<string>;Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Circuit Breaker?
cockatiel is written in TypeScript and composes typed policies, circuitBreaker, retry, timeout and bulkhead, into a single wrap() pipeline, with a ConsecutiveBreaker or SamplingBreaker choosing the tripping rule. opossum has DefinitelyTyped definitions and is generic over the wrapped function signature. The typed win here is making the DEGRADED path part of the return type rather than an implicit any from a fallback.
What is the most common TypeScript mistake when implementing Circuit Breaker?
A fallback typed identically to the success value is indistinguishable at the type level, so downstream code cannot tell a real payment confirmation from a degraded placeholder and will happily persist the placeholder as if it were real, this is a genuine data-integrity bug that the type system will catch only if you model the two outcomes as different variants. The ordering trap applies here too: wrapping retry inside the breaker means every retry increments the breaker, so a three-attempt retry trips a five-failure breaker after two logical calls.
How does Circuit Breaker actually perform in TypeScript?
Erased at runtime. Composition adds one function call per policy layer per invocation, negligible against I/O. The genuine benefit is that the whole resilience posture for a dependency is one typed, testable value that can be unit-tested with a fake clock rather than being spread across call sites. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.