Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Circuit Breaker Implementation in TypeScript

14 min readintermediate
Website QA and SEO audits

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

A circuit breaker sits in front of a remote dependency and stops calling it once failures cross a threshold, failing fast instead of waiting for a timeout that is not going to succeed. It has three states: CLOSED, where calls pass through and failures are counted; OPEN, where calls are rejected immediately without touching the dependency; and HALF-OPEN, where a small number of trial calls are allowed through to discover whether recovery has happened. The reason it matters more than it first appears is that the failure it prevents is not the failed call, it is RESOURCE EXHAUSTION in the caller. Every request waiting on a five-second timeout occupies a thread, a connection and memory, so a slow dependency silently converts into a caller-side outage, and from there into a cascade through everything that depends on the caller. Failing in one millisecond instead of five seconds is what stops that chain.

Circuit Breaker in TypeScript: what you actually reach for

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.

TypeScript implementation

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. Return a discriminated union from the guarded call so callers must handle the open-circuit case explicitly rather than receiving a fallback value indistinguishable from a real one.
typescript
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 Free

The TypeScript-specific 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. 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.

Performance in TypeScript, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Circuit Breaker between languages.

Real-World Applications

Circuit Breaker is used extensively in production software: web servers, database engines, operating system schedulers, and distributed systems use this pattern to coordinate work across threads and processes. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Circuit Breaker helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Circuit Breaker appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Circuit Breaker over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Circuit Breaker to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.