Implementing Resilience Patterns in TypeScript with Cockatiel: Circuit Breaker, Retry, and Bulkhead

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

It is 4:30 PM on a Friday when a third-party payment API starts timing out. Within three minutes, your entire Node.js backend stops responding—even /health and login routes that never touch payments. That domino effect is a cascading failure.

The outage upstream is rarely what kills your service. Instead, your own app keeps waiting on dead sockets and retrying blindly until its connection pools and event loop run dry. You can stop this by building resilience patterns directly into your TypeScript service layer with Cockatiel.

Quick Start (5 Min): Protecting a Fragile API Call

Cockatiel is a zero-dependency TypeScript resilience library modeled after .NET’s Polly. It ships with strong types and composable policies out of the box. You can wrap a flaky HTTP call in under five minutes.

1. Install Cockatiel

Add the package to your project:

npm install cockatiel

2. Wrap Your First Fetch Call

Instead of calling fetch bare, attach a retry policy with exponential backoff. Temporary 503 errors will recover automatically without hammering the upstream server:

import { ExponentialBackoff, handleAll, retry } from 'cockatiel';

const retryPolicy = retry(handleAll, {
  maxAttempts: 3,
  backoff: new ExponentialBackoff({ initialDelay: 100 }),
});

export async function fetchInventory(sku: string): Promise<unknown> {
  return retryPolicy.execute(async () => {
    const response = await fetch(`https://api.example.com/inventory/${sku}`);
    if (!response.ok) {
      throw new Error(`Upstream error: ${response.status}`);
    }
    return response.json();
  });
}

That takes 14 lines of code. A single dropped packet or a 200ms container restart no longer bubbles up as a 500 error to your users.

How Retry, Circuit Breaker, and Bulkhead Work Together

Retries alone will not save you during a real outage. Worse, retrying a dead service multiplies the load right when it is trying to recover. Distributed backends need three complementary patterns, each guarding against a different failure mode.

Smart Retries with Exponential Backoff

When a downstream API drops 2% of requests under load, naive code retries in a tight loop. Fixed-delay retries create a “thundering herd” where 500 clients hit the server at the exact same millisecond.

ExponentialBackoff solves this by spacing out attempts—for example, 100ms, 200ms, then 400ms. Cockatiel also adds random decorrelated jitter by default, spreading those retries across time so the upstream service can breathe.

Circuit Breaker to Fail Fast

Suppose your payment gateway goes completely offline. Without a circuit breaker, every incoming request hangs for 10 to 30 seconds waiting on a TCP timeout before failing. Your server has no feedback loop, so it keeps sending doomed traffic.

A Circuit Breaker tracks consecutive failures or error rates. Once failures cross a threshold, the circuit opens and rejects new calls in under a millisecond with a BrokenCircuitError. After a cooldown window (halfOpenAfter), it lets one probe request through to check if the dependency is healthy again.

import { ConsecutiveBreaker, circuitBreaker, handleAll } from 'cockatiel';

const breakerPolicy = circuitBreaker(handleAll, {
  halfOpenAfter: 10_000, // Wait 10 seconds before testing recovery
  breaker: new ConsecutiveBreaker(5), // Open after 5 consecutive failures
});

Bulkhead Isolation for Resource Protection

A slow reporting query can easily tie up all 100 sockets in your HTTP agent or database pool. Once that happens, unrelated endpoints like /health and /login stall right behind it because they share the same unbounded concurrency.

Named after watertight compartments in a ship’s hull, a Bulkhead caps how many executions run at once and how many wait in line. Excess requests fail immediately with a BulkheadRejectedError. Your reporting endpoint might shed load, but the rest of your API stays fast.

import { bulkhead } from 'cockatiel';

// Allow 10 concurrent calls and queue up to 20 more
const bulkheadPolicy = bulkhead(10, 20);

Composing Policies and Handling Timeouts in Production

Production code rarely uses these policies one by one. Cockatiel’s wrap() combines them into a single pipeline, executing from left (outermost) to right (innermost).

A battle-tested order is Bulkhead → Retry → Circuit Breaker → Timeout. Here is what each layer handles:

  1. Bulkhead sits at the front door to cap total concurrent callers entering the pipeline.
  2. Retry wraps the breaker so transient blips get retried, while an open circuit stops wasted attempts.
  3. Circuit Breaker watches the inner execution and trips when timeouts or 5xx responses pile up.
  4. Timeout sits closest to the socket so a hung request aborts cleanly instead of waiting 30 seconds.
import {
  BrokenCircuitError,
  BulkheadRejectedError,
  ConsecutiveBreaker,
  ExponentialBackoff,
  TimeoutStrategy,
  bulkhead,
  circuitBreaker,
  handleWhen,
  retry,
  timeout,
  wrap,
} from 'cockatiel';

class HttpStatusError extends Error {
  constructor(public readonly status: number, message: string) {
    super(message);
  }
}

// Retry 5xx, 429, and network/timeout errors, but never an open circuit
const isTransient = handleWhen((err) => {
  if (err instanceof BrokenCircuitError) {
    return false;
  }
  if (err instanceof HttpStatusError) {
    return err.status >= 500 || err.status === 429;
  }
  return true;
});

const bulkheadPolicy = bulkhead(10, 20);
const retryPolicy = retry(isTransient, {
  maxAttempts: 3,
  backoff: new ExponentialBackoff({ initialDelay: 200, maxDelay: 5_000 }),
});
const breakerPolicy = circuitBreaker(isTransient, {
  halfOpenAfter: 15_000,
  breaker: new ConsecutiveBreaker(5),
});
const timeoutPolicy = timeout(3_000, TimeoutStrategy.Aggressive);

// Log state transitions for alerting
breakerPolicy.onBreak(() => console.warn('[Resilience] Circuit opened'));
breakerPolicy.onReset(() => console.info('[Resilience] Circuit closed again'));

const resilientPolicy = wrap(
  bulkheadPolicy,
  retryPolicy,
  breakerPolicy,
  timeoutPolicy
);

export async function chargeCustomer(orderId: string): Promise<unknown> {
  try {
    return await resilientPolicy.execute(async ({ signal }) => {
      const res = await fetch(`https://payments.example.com/charge/${orderId}`, {
        method: 'POST',
        signal,
      });
      if (!res.ok) {
        throw new HttpStatusError(res.status, `Payment API returned ${res.status}`);
      }
      return res.json();
    });
  } catch (err) {
    if (err instanceof BrokenCircuitError) {
      throw new Error('Payment service is temporarily unavailable. Please try again shortly.');
    }
    if (err instanceof BulkheadRejectedError) {
      throw new Error('Too many concurrent payment requests. Please retry in a moment.');
    }
    throw err;
  }
}

Pay close attention to the { signal } parameter in execute. When the 3-second limit expires, TimeoutStrategy.Aggressive aborts that AbortSignal. Passing it to fetch cancels the underlying HTTP request immediately instead of leaving it open in the background.

Five Habits for Production TypeScript Backends

  • Pair write retries with idempotency keys: Retrying a timed-out POST /charge call can double-charge a customer if the first request actually succeeded. Send a unique idempotency key on every non-idempotent write.
  • Filter errors with handleWhen: Skip handleAll in production. A 400 Bad Request or 401 Unauthorized will fail identically on every attempt and can trip your circuit breaker by mistake.
  • Isolate policies per dependency: Create separate breakers and bulkheads for Stripe, Redis, and your inventory API. One broken vendor should never trip the circuit for healthy services.
  • Hook events into your metrics: Attach onBreak, onHalfOpen, and onFailure listeners to increment Prometheus counters or emit structured logs. Silent circuit trips are painful to debug at 2 AM.
  • Chaos-test locally before shipping: Point your client at a mock server that sleeps for 5 seconds or returns 503s. Verify that timeouts abort, circuits open after 5 failures, and fallback errors read cleanly.
Share: