Skip to main content

APIs · Intermediate · 26 min

Call third-party APIs reliably with timeouts, retries and a circuit breaker

By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13.1

You will build a reusable Node.js 26 API client that gives every request a deadline, retries only what is safe with backoff and jitter, honours Retry-After, stops calling a dead service with a circuit breaker and logs each attempt without leaking the API key.

On this page

Your app depends on someone else's API: a payment provider, an SMS gateway, a courier's tracking service. Most days it answers in 200 ms. Some days it takes 40 seconds, returns 503 for a minute, or tells you to slow down with a 429. Code that calls it with a bare fetch handles none of that. Requests pile up waiting, a short blip becomes a user-facing error, and when the service is down your app keeps sending it traffic it cannot answer.

In this tutorial you write a small client wrapper around Node's built-in fetch that handles those cases deliberately:

  • every attempt has a deadline, set with AbortSignal.timeout
  • only failures that are safe and worth repeating are retried: idempotent methods (or a POST with an idempotency key), on a timeout, a dropped connection, 429, 502, 503 or 504
  • the wait between retries grows exponentially with random jitter, and a Retry-After header from the server wins over the guess
  • a circuit breaker stops calls to a service that keeps failing, then lets one trial request through after a cool-down
  • each attempt is logged as one JSON line with a request id, and the API key never reaches the log

You practise against a deliberately flaky parcel-tracking API that you run on your own machine, so nothing depends on a real provider and nothing costs money. Everything uses Node's standard library: there is nothing to install from npm.

Step 1 · Create the project and a flaky practice API

Make a throwaway folder and an .env file with a made-up API key. umask 077 makes the file private from the moment it exists, and the key is generated by Node so it never appears on your command line or in shell history:

Bash
mkdir -p ~/api-client-demo
cd ~/api-client-demo
(umask 077; node -e "console.log('PARCELS_API_KEY=pk_test_' + crypto.randomBytes(16).toString('hex'))" > .env)
ls -l .env

With a real provider, you paste the key from its dashboard into .env instead, and add .env to .gitignore before your first commit: see keep secrets out of Git.

Now write flaky.mjs, the practice API. It checks the key on every request, prints one line per request with the X-Request-Id it received, and can misbehave on request:

  • ?fails=2&status=503&id=x makes the first two requests with that id fail with 503 (a 429 also carries Retry-After: 1)
  • /slow?ms=3000 answers after three seconds
  • /down answers 503 until you call POST /recover
  • /parcels/PX-0000 does not exist and answers 404
Bash
cat > flaky.mjs <<'JS'
import http from 'node:http';

const PORT = 4000;
const API_KEY = process.env.PARCELS_API_KEY;
if (!API_KEY) {
  console.error('PARCELS_API_KEY is not set. Start with: node --env-file=.env flaky.mjs');
  process.exit(1);
}

const seen = new Map(); // how often each planned-failure id has been requested
const hits = new Map(); // requests per path, for /stats
let outage = true; // whether /down is failing

function send(res, status, body, headers = {}) {
  const text = JSON.stringify(body);
  res.writeHead(status, { 'content-type': 'application/json', ...headers });
  res.end(text);
}

const server = http.createServer(async (req, res) => {
  for await (const chunk of req); // read and discard the request body
  const url = new URL(req.url, 'http://127.0.0.1');
  hits.set(url.pathname, (hits.get(url.pathname) ?? 0) + 1);
  console.log(`${req.method} ${url.pathname}${url.search} request-id=${req.headers['x-request-id'] ?? '-'}`);

  // Control routes for the exercises. No key needed.
  if (url.pathname === '/health') return send(res, 200, { ok: true });
  if (url.pathname === '/stats') return send(res, 200, Object.fromEntries(hits));
  if (url.pathname === '/outage' && req.method === 'POST') {
    outage = true;
    hits.delete('/down');
    return send(res, 200, { outage });
  }
  if (url.pathname === '/recover' && req.method === 'POST') {
    outage = false;
    return send(res, 200, { outage });
  }

  if (req.headers.authorization !== `Bearer ${API_KEY}`) {
    return send(res, 401, { error: 'missing or wrong API key' });
  }

  // ?fails=N&status=S&id=X: the first N requests for id X get status S.
  const fails = Number(url.searchParams.get('fails') ?? 0);
  if (fails > 0) {
    const id = `${req.method} ${url.pathname} ${url.searchParams.get('id')}`;
    const count = (seen.get(id) ?? 0) + 1;
    seen.set(id, count);
    if (count <= fails) {
      const status = Number(url.searchParams.get('status') ?? 503);
      const headers = status === 429 ? { 'retry-after': '1' } : {};
      return send(res, status, { error: `planned failure ${count} of ${fails}` }, headers);
    }
  }

  if (req.method === 'GET' && url.pathname.startsWith('/parcels/')) {
    const parcel = url.pathname.split('/')[2];
    if (parcel === 'PX-0000') return send(res, 404, { error: 'no such parcel' });
    return send(res, 200, { parcel, status: 'in_transit' });
  }
  if (req.method === 'GET' && url.pathname === '/slow') {
    const ms = Number(url.searchParams.get('ms') ?? 3000);
    const timer = setTimeout(() => send(res, 200, { waitedMs: ms }), ms);
    res.on('close', () => clearTimeout(timer)); // the caller gave up
    return;
  }
  if (req.method === 'POST' && url.pathname === '/shipments') {
    return send(res, 201, { shipment: `shp_${hits.get('/shipments')}`, idempotencyKey: req.headers['idempotency-key'] ?? null });
  }
  if (req.method === 'GET' && url.pathname === '/down') {
    return outage ? send(res, 503, { error: 'service unavailable' }) : send(res, 200, { ok: true });
  }
  send(res, 404, { error: 'not found' });
});

server.listen(PORT, '127.0.0.1', () => console.log(`practice parcels API on http://127.0.0.1:${PORT}`));
JS

Start it in your second terminal, from the same folder, and leave it running. --env-file loads .env into process.env, so no extra package is needed:

Bash
node --env-file=.env flaky.mjs

It prints practice parcels API on http://127.0.0.1:4000. This server is a toy for practice: the control routes have no authentication and it keeps everything in memory.

Check it worked

In your first terminal:

Bash
curl -s http://127.0.0.1:4000/health
echo
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:4000/parcels/PX-1001

The first command prints {"ok":true}. The second prints 401, because curl sent no key. The server terminal shows both requests, with request-id=- since curl sent no id.

Step 2 · Put a deadline on every request

Node's fetch has no overall deadline of its own. Under the hood it uses undici, which by default waits up to 300 seconds for response headers and another 300 seconds between chunks of the body. A provider that accepts the connection and then stalls can hold one of your requests, and whatever is waiting on it, for minutes.

AbortSignal.timeout(ms) gives you a signal that aborts after that many milliseconds. Pass it to fetch and the request is cancelled when the time runs out, and fetch rejects with an error named TimeoutError. Read the body inside the same try: the signal covers the body as well, so a server that sends headers quickly and then trickles the body is caught too.

Bash
cat > try-timeout.mjs <<'JS'
const headers = { authorization: `Bearer ${process.env.PARCELS_API_KEY}` };

for (const ms of [200, 3000]) {
  const started = performance.now();
  try {
    const response = await fetch(`http://127.0.0.1:4000/slow?ms=${ms}`, {
      headers,
      signal: AbortSignal.timeout(1000),
    });
    const body = await response.json();
    console.log(`server took ${ms} ms: ${response.status}`, body);
  } catch (err) {
    const took = Math.round(performance.now() - started);
    console.log(`server took ${ms} ms: ${err.name} after about ${took} ms`);
  }
}
JS
node --env-file=.env try-timeout.mjs

Choose the deadline from what the provider normally does, not from what you hope. If its documentation or your own measurements say most answers come back in under a second, two to five seconds is a sensible deadline for one attempt. Users on mobile data, which in much of Africa means slower and more variable networks, feel a long hang more than a fast, clear error.

Check it worked

The output is two lines, something like:

Text
server took 200 ms: 200 { waitedMs: 200 }
server took 3000 ms: TimeoutError after about 1003 ms

The second request gave up after about one second, not three.

Step 3 · Decide what is safe to retry

A retry is only safe if doing the operation twice has the same effect as doing it once. HTTP calls that property idempotent. GET, HEAD, OPTIONS, PUT and DELETE are idempotent by definition. POST is not: if a "create shipment" request timed out, you cannot tell whether the provider created the shipment before the connection dropped. Retrying it blindly can create two. The exception is a provider that accepts an Idempotency-Key header, where you send one random key and reuse it on every retry, so the provider can recognise the repeat. Make POST requests safe to retry with idempotency keys shows the server side of that.

A retry is only useful if the failure is likely to be temporary:

  • 429 Too Many Requests, 502 Bad Gateway, 503 Service Unavailable and 504 Gateway Timeout usually clear up.
  • 400, 401, 403, 404 and 422 mean the request itself is wrong. Sending it again gets the same answer.
  • 500 is left out here. It often means a bug in the provider that repeats on every try. Some providers document that a 500 is worth retrying; follow their documentation where it says so.
  • Timeouts and dropped or refused connections are worth another try.

Between attempts, wait longer each time (exponential backoff), and pick a random point below that ceiling (full jitter). Without the randomness, every client that failed at the same moment retries at the same moment, and a struggling service gets hit by synchronised waves. If the server sends Retry-After, as a number of seconds or an HTTP date, use that instead.

Put those rules in their own module:

Bash
cat > retry-policy.mjs <<'JS'
// Methods that RFC 9110 defines as idempotent: sending one twice has the
// same effect as sending it once.
const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);

// Statuses that usually mean "try again later", not "your request is wrong".
const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);

// Low-level network failures worth another try. fetch rejects with a
// TypeError and puts the system error in err.cause.
const RETRYABLE_NETWORK_CODES = new Set([
  'ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT', 'EAI_AGAIN',
  'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT',
]);

export function canRetryMethod(method, idempotencyKey) {
  return IDEMPOTENT_METHODS.has(method.toUpperCase()) || Boolean(idempotencyKey);
}

export function isRetryableStatus(status) {
  return RETRYABLE_STATUSES.has(status);
}

export function isRetryableError(err) {
  if (err?.name === 'TimeoutError') return true;
  return RETRYABLE_NETWORK_CODES.has(err?.cause?.code);
}

// Exponential backoff with "full jitter": the ceiling doubles after each
// failed attempt, and the actual wait is a random point below it.
export function backoffDelay(failedAttempts, { baseMs = 200, maxMs = 5000, random = Math.random } = {}) {
  const ceiling = Math.min(maxMs, baseMs * 2 ** (failedAttempts - 1));
  return Math.round(random() * ceiling);
}

// Retry-After is either a number of seconds or an HTTP date.
export function retryAfterMs(header, now = Date.now()) {
  if (!header) return null;
  const value = header.trim();
  if (/^\d+$/.test(value)) return Number(value) * 1000;
  const when = Date.parse(value);
  return Number.isNaN(when) ? null : Math.max(0, when - now);
}
JS

Then check each rule with a short script. Passing random: () => 1 shows the ceiling of each wait, and a fixed now makes the date case exact:

Bash
cat > policy-check.mjs <<'JS'
import { backoffDelay, canRetryMethod, isRetryableStatus, retryAfterMs } from './retry-policy.mjs';

console.log('GET retryable:', canRetryMethod('GET'));
console.log('POST retryable:', canRetryMethod('POST'));
console.log('POST with idempotency key retryable:', canRetryMethod('POST', 'b1946ac9'));
console.log('statuses retried:', [400, 401, 404, 429, 500, 502, 503, 504].filter(isRetryableStatus).join(' '));

const ceilings = [1, 2, 3, 4, 5, 6].map((n) => backoffDelay(n, { random: () => 1 }));
console.log('backoff ceilings (ms):', ceilings.join(' '));
const sample = [1, 2, 3, 4, 5, 6].map((n) => backoffDelay(n));
console.log('one random run (ms):', sample.join(' '));

const now = Date.UTC(2026, 10, 19, 12, 0, 0);
console.log('Retry-After "2":', retryAfterMs('2', now), 'ms');
console.log('Retry-After as a date:', retryAfterMs(new Date(now + 3000).toUTCString(), now), 'ms');
JS
node policy-check.mjs

Each retry costs time, and on a phone it costs the user's data, often prepaid. Keep the number of attempts small (three is a common choice) and cap the wait.

Check it worked

The output matches this, except the random run, which changes every time and stays under each ceiling:

Text
GET retryable: true
POST retryable: false
POST with idempotency key retryable: true
statuses retried: 429 502 503 504
backoff ceilings (ms): 200 400 800 1600 3200 5000
one random run (ms): 131 287 412 1388 960 4217
Retry-After "2": 2000 ms
Retry-After as a date: 3000 ms

Step 4 · Add a circuit breaker

Retries help with blips. When a provider is properly down, they make things worse: every request your app receives turns into three doomed calls, each waiting for its timeout. A circuit breaker counts consecutive failures and, past a threshold, refuses calls at once without sending them. The breaker has three states:

  • closed: requests go out normally and failures are counted. A success resets the count.
  • open: requests fail immediately, for a cool-down period.
  • half-open: after the cool-down, one trial request goes out. Success closes the circuit, failure opens it again for another cool-down.
Bash
cat > breaker.mjs <<'JS'
export class CircuitOpenError extends Error {
  constructor(name, retryInMs) {
    super(`circuit for ${name} is open; next try allowed in ${retryInMs} ms`);
    this.name = 'CircuitOpenError';
    this.retryInMs = retryInMs;
  }
}

// closed: requests go out, consecutive failures are counted.
// open: requests are refused at once until the cool-down has passed.
// half-open: one trial request goes out; its result closes or reopens the circuit.
export class CircuitBreaker {
  constructor({ name = 'api', failureThreshold = 5, cooldownMs = 30_000, now = () => Date.now() } = {}) {
    this.name = name;
    this.failureThreshold = failureThreshold;
    this.cooldownMs = cooldownMs;
    this.now = now;
    this.state = 'closed';
    this.failures = 0;
    this.openedAt = 0;
    this.trialInFlight = false;
  }

  // Call before each attempt. Throws CircuitOpenError if it must not go out.
  before() {
    if (this.state === 'open') {
      const waited = this.now() - this.openedAt;
      if (waited < this.cooldownMs) throw new CircuitOpenError(this.name, this.cooldownMs - waited);
      this.state = 'half-open';
    }
    if (this.state === 'half-open') {
      if (this.trialInFlight) throw new CircuitOpenError(this.name, 0);
      this.trialInFlight = true;
    }
  }

  success() {
    this.state = 'closed';
    this.failures = 0;
    this.trialInFlight = false;
  }

  failure() {
    this.trialInFlight = false;
    this.failures += 1;
    if (this.state === 'half-open' || this.failures >= this.failureThreshold) {
      this.state = 'open';
      this.openedAt = this.now();
    }
  }

  // The attempt ended without telling us anything about the service
  // (for example, the caller cancelled it).
  release() {
    this.trialInFlight = false;
  }
}
JS

The breaker takes a now function, so you can exercise it with a fake clock and no waiting:

Bash
cat > breaker-check.mjs <<'JS'
import { CircuitBreaker } from './breaker.mjs';

let clock = 0;
const breaker = new CircuitBreaker({ name: 'parcels', failureThreshold: 3, cooldownMs: 10_000, now: () => clock });

for (let i = 0; i < 3; i++) {
  breaker.before();
  breaker.failure();
}
console.log('after 3 failures:', breaker.state);

try {
  breaker.before();
} catch (err) {
  console.log('next call:', err.message);
}

clock = 10_000;
breaker.before();
console.log('after the cool-down:', breaker.state);

try {
  breaker.before();
} catch (err) {
  console.log('a second caller during the trial:', err.name);
}

breaker.success();
console.log('after a good trial:', breaker.state);
JS
node breaker-check.mjs

This breaker keeps its state in memory, per process. If you run several copies of your app, each one has its own breaker and trips on its own, which is usually what you want.

Check it worked

The output is:

Text
after 3 failures: open
next call: circuit for parcels is open; next try allowed in 10000 ms
after the cool-down: half-open
a second caller during the trial: CircuitOpenError
after a good trial: closed

Step 5 · Build the reusable client

client.mjs puts the pieces together. createApiClient takes the provider's base URL, the API key and your limits, and returns a request(method, path, options) function. For each call it:

  1. creates one request id with crypto.randomUUID() and sends it as X-Request-Id on every attempt, so you can match your log to the provider's, and quote it to their support team
  2. asks the breaker before each attempt, and gives up at once if the circuit is open
  3. gives each attempt its own AbortSignal.timeout, combined with the caller's own signal (if any) through AbortSignal.any, so a caller can still cancel
  4. tells the breaker how the attempt went: a timeout, a refused connection or a 5xx is a failure, any other answer means the service is alive
  5. retries only when the policy says the failure is temporary and the method is safe, waits for Retry-After or the backoff delay, and gives up if the server asks for a longer wait than maxDelayMs
  6. throws an ApiError with the status, request id and number of attempts when it gives up

The key goes into the Authorization header and nowhere else. Log entries are built from a fixed list of safe fields, never from the headers, and safeUrl replaces the value of any query parameter whose name looks like a key, token, secret, signature or password, for providers that put keys in the URL. The client refuses to start without a key rather than sending requests with Bearer undefined.

Bash
cat > client.mjs <<'JS'
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { CircuitBreaker } from './breaker.mjs';
import { backoffDelay, canRetryMethod, isRetryableError, isRetryableStatus, retryAfterMs } from './retry-policy.mjs';

export class ApiError extends Error {
  constructor(message, { status = null, requestId, attempts, body = null, cause } = {}) {
    super(message, { cause });
    this.name = 'ApiError';
    this.status = status;
    this.requestId = requestId;
    this.attempts = attempts;
    this.body = body;
  }
}

// Query parameters whose values never belong in a log.
const SECRET_PARAM = /key|token|secret|signature|password/i;

function safeUrl(url) {
  const copy = new URL(url);
  for (const name of [...copy.searchParams.keys()]) {
    if (SECRET_PARAM.test(name)) copy.searchParams.set(name, 'REDACTED');
  }
  return copy.pathname + copy.search;
}

function describe(err) {
  if (err.name === 'TimeoutError') return 'timed out';
  return err.cause?.code ?? err.message;
}

export function createApiClient({
  baseUrl,
  apiKey,
  name = new URL(baseUrl).host,
  timeoutMs = 5000,
  maxAttempts = 3,
  baseDelayMs = 200,
  maxDelayMs = 5000,
  breaker = new CircuitBreaker({ name }),
  log = (entry) => console.error(JSON.stringify(entry)),
} = {}) {
  if (!apiKey) throw new Error(`No API key for ${name}. Set it in the environment.`);

  return async function request(method, path, { body, headers = {}, idempotencyKey, signal } = {}) {
    method = method.toUpperCase();
    const url = new URL(path, baseUrl);
    const requestId = randomUUID();
    const retryAllowed = canRetryMethod(method, idempotencyKey);

    const sendHeaders = { accept: 'application/json', ...headers, authorization: `Bearer ${apiKey}`, 'x-request-id': requestId };
    if (idempotencyKey) sendHeaders['idempotency-key'] = idempotencyKey;
    let payload;
    if (body !== undefined) {
      sendHeaders['content-type'] = 'application/json';
      payload = JSON.stringify(body);
    }

    for (let attempt = 1; ; attempt++) {
      // Only safe fields go into a log entry: never the headers.
      const entry = { requestId, attempt, method, url: safeUrl(url) };

      try {
        breaker.before();
      } catch (err) {
        log({ ...entry, outcome: 'circuit open, not sent' });
        throw new ApiError(err.message, { requestId, attempts: attempt - 1, cause: err });
      }

      const started = performance.now();
      let response;
      let text;
      let failure;
      try {
        const timeout = AbortSignal.timeout(timeoutMs);
        response = await fetch(url, {
          method,
          headers: sendHeaders,
          body: payload,
          signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
        });
        text = await response.text(); // the deadline covers the body too
      } catch (err) {
        failure = err;
      }
      entry.ms = Math.round(performance.now() - started);

      // Tell the breaker what this attempt says about the service.
      if (failure) {
        if (isRetryableError(failure)) breaker.failure();
        else breaker.release();
      } else if (response.status >= 500) {
        breaker.failure();
      } else {
        breaker.success();
      }

      if (!failure && response.ok) {
        log({ ...entry, status: response.status });
        return { status: response.status, data: text ? JSON.parse(text) : null, requestId, attempts: attempt };
      }

      const status = response?.status ?? null;
      let reason = failure ? describe(failure) : `status ${status}`;
      const transient = failure ? isRetryableError(failure) : isRetryableStatus(status);
      let delay = backoffDelay(attempt, { baseMs: baseDelayMs, maxMs: maxDelayMs });
      const asked = retryAfterMs(response?.headers.get('retry-after'));
      if (asked !== null) delay = asked; // the server knows better than our guess
      if (delay > maxDelayMs) reason += `, server asked for a ${delay} ms wait`;

      const retry = transient && retryAllowed && attempt < maxAttempts && delay <= maxDelayMs;
      if (!retry) {
        log({ ...entry, outcome: reason, retry: false });
        throw new ApiError(`${method} ${safeUrl(url)} failed after ${attempt} attempt(s): ${reason}`, {
          status, requestId, attempts: attempt, body: text ?? null, cause: failure,
        });
      }

      log({ ...entry, outcome: reason, retryInMs: delay });
      await sleep(delay, undefined, { signal }); // stops waiting if the caller cancels
    }
  };
}
JS

The worst-case time for one call is roughly maxAttempts × timeoutMs plus the waits between attempts. With the defaults (three attempts, five seconds, waits capped at five seconds) that is up to about 25 seconds. If your own endpoint must answer faster than that, lower the limits for the client it uses.

Check it worked

The client refuses to start without a key:

Bash
node -e "import('./client.mjs').then(({ createApiClient }) => { try { createApiClient({ baseUrl: 'http://127.0.0.1:4000' }); } catch (err) { console.log(err.message); } })"

The output is No API key for 127.0.0.1:4000. Set it in the environment.

Step 6 · Run the client against the flaky API

demo.mjs makes seven calls, each meant to hit one case. The planned failures use a fresh id on every run, so you can run it again and get the same results. The second client points at port 4999, where nothing listens:

Bash
cat > demo.mjs <<'JS'
import { randomUUID } from 'node:crypto';
import { createApiClient } from './client.mjs';

const parcels = createApiClient({
  baseUrl: process.env.PARCELS_API_URL ?? 'http://127.0.0.1:4000',
  apiKey: process.env.PARCELS_API_KEY,
  timeoutMs: 1000,
  maxAttempts: 3,
});
// Nothing listens on port 4999, so every connection is refused.
const nowhere = createApiClient({ baseUrl: 'http://127.0.0.1:4999', apiKey: 'unused', maxAttempts: 3 });

// A fresh id per run, so the planned failures happen again each time.
const run = Date.now().toString(36);

async function show(label, call) {
  try {
    const result = await call();
    console.log(`${label}: ${result.status} after ${result.attempts} attempt(s)`);
  } catch (err) {
    console.log(`${label}: failed after ${err.attempts} attempt(s), ${err.status ?? 'no status'}`);
  }
}

await show('flaky GET', () => parcels('GET', `/parcels/PX-1001?fails=2&status=503&id=${run}-a`));
await show('rate-limited GET', () => parcels('GET', `/parcels/PX-1002?fails=1&status=429&id=${run}-b`));
await show('slow GET', () => parcels('GET', '/slow?ms=3000'));
await show('unknown parcel', () => parcels('GET', '/parcels/PX-0000'));
await show('POST, no key', () => parcels('POST', `/shipments?fails=1&id=${run}-c`, { body: { parcel: 'PX-1001' } }));
await show('POST, idempotency key', () =>
  parcels('POST', `/shipments?fails=1&id=${run}-d`, { body: { parcel: 'PX-1001' }, idempotencyKey: randomUUID() }),
);
await show('nothing listening', () => nowhere('GET', '/parcels/PX-1001'));
JS
node --env-file=.env demo.mjs 2> attempts.log

The results go to standard output and the attempt log goes to standard error, which the command saves in attempts.log. Look at the log:

Bash
cat attempts.log

Each line is one attempt, for example:

Text
{"requestId":"0d6c1a52-...","attempt":1,"method":"GET","url":"/parcels/PX-1002?fails=1&status=429&id=mi4x2k-b","ms":4,"outcome":"status 429","retryInMs":1000}
{"requestId":"0d6c1a52-...","attempt":2,"method":"GET","url":"/parcels/PX-1002?fails=1&status=429&id=mi4x2k-b","ms":2,"status":200}

Both attempts of one call share a request id. The retryInMs of 1000 is the server's Retry-After: 1, not a backoff guess. Find that id in the server terminal: it appears on both requests the server received.

Finally, confirm the key never reached the log:

Bash
if grep -q "pk_test_" attempts.log; then echo "API key found in the log"; false; else echo "no API key in the log"; fi

Check it worked

The standard output is:

Text
flaky GET: 200 after 3 attempt(s)
rate-limited GET: 200 after 2 attempt(s)
slow GET: failed after 3 attempt(s), no status
unknown parcel: failed after 1 attempt(s), 404
POST, no key: failed after 1 attempt(s), 503
POST, idempotency key: 201 after 2 attempt(s)
nothing listening: failed after 3 attempt(s), no status
  • The flaky and rate-limited calls recovered on their own.
  • The slow call timed out on all three attempts, after about a second each.
  • The 404 and the POST without a key failed on the first attempt: one is not temporary, the other is not safe to repeat.
  • The same POST with an idempotency key was retried and succeeded.
  • The refused connection was retried, then reported, without crashing the script.

The key check prints no API key in the log.

Step 7 · Watch the circuit breaker trip and recover

breaker-demo.mjs points a client with a small breaker (four failures, two-second cool-down, two attempts per call) at /down, which fails until you recover it. It then asks the server how many requests actually arrived, recovers the service, waits out the cool-down and calls again:

Bash
cat > breaker-demo.mjs <<'JS'
import { CircuitBreaker } from './breaker.mjs';
import { createApiClient } from './client.mjs';

const baseUrl = process.env.PARCELS_API_URL ?? 'http://127.0.0.1:4000';
const breaker = new CircuitBreaker({ name: 'parcels', failureThreshold: 4, cooldownMs: 2000 });
const parcels = createApiClient({
  baseUrl,
  apiKey: process.env.PARCELS_API_KEY,
  maxAttempts: 2,
  breaker,
  log: () => {}, // quiet for this demo
});

async function call(n) {
  try {
    const result = await parcels('GET', '/down');
    console.log(`call ${n}: ${result.status}, circuit ${breaker.state}`);
  } catch (err) {
    if (err.cause?.name === 'CircuitOpenError') console.log(`call ${n}: refused at once, circuit ${breaker.state}`);
    else console.log(`call ${n}: ${err.message}, circuit ${breaker.state}`);
  }
}

await fetch(`${baseUrl}/outage`, { method: 'POST' }); // start a fresh outage
for (let n = 1; n <= 5; n++) await call(n);

const stats = await (await fetch(`${baseUrl}/stats`)).json();
console.log(`requests that reached /down: ${stats['/down']}`);

await fetch(`${baseUrl}/recover`, { method: 'POST' });
console.log('service is back; waiting out the 2 second cool-down');
await new Promise((resolve) => setTimeout(resolve, 2100));
await call(6);
await call(7);
JS
node --env-file=.env breaker-demo.mjs

In a real app, keep one client (and so one breaker) per provider for the life of the process. Creating a new client for every request gives every request a fresh, closed breaker, and it never trips.

Check it worked

The output is:

Text
call 1: GET /down failed after 2 attempt(s): status 503, circuit closed
call 2: GET /down failed after 2 attempt(s): status 503, circuit open
call 3: refused at once, circuit open
call 4: refused at once, circuit open
call 5: refused at once, circuit open
requests that reached /down: 4
service is back; waiting out the 2 second cool-down
call 6: 200, circuit closed
call 7: 200, circuit closed

Five calls produced only four requests to the failing service: two calls of two attempts, then nothing until the cool-down passed. Without the breaker, the same five calls would have sent ten. Call 6 was the half-open trial, and its success closed the circuit.

Step 8 · Use it in your app, then clean up

To use the client with a real provider, copy client.mjs, retry-policy.mjs and breaker.mjs into your project, put the provider's base URL and key in environment variables, and create one client per provider when your app starts:

JavaScript
import { createApiClient } from './client.mjs';

export const parcels = createApiClient({
  baseUrl: process.env.PARCELS_API_URL,
  apiKey: process.env.PARCELS_API_KEY,
  timeoutMs: 3000,
});

// elsewhere: const { data } = await parcels('GET', `/parcels/${id}`);

Read the provider's documentation for three things before you go live: which statuses it says to retry, whether it sends Retry-After, and whether it accepts an idempotency key on POST. Adjust retry-policy.mjs to match.

When you are done with the practice project, stop the server with Ctrl+C in the second terminal. Then remove the folder, which also deletes the .env file with the made-up key:

Bash
cd ~
rm -rf ~/api-client-demo

Check it worked

ls ~/api-client-demo reports that there is no such file or directory, and curl -s http://127.0.0.1:4000/health prints nothing because the server has stopped.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.