Thuta Learning
API Tutorial
ProjectsWeb DevelopmentIntermediate

Mini Project — Part 3: Error Handling and Polish

API TutorialLesson 3145 min

What you'll walk away with

  • Add a per-attempt timeout with AbortSignal.timeout and recognise the TimeoutError it causes
  • Retry transient failures with exponential backoff, honouring Retry-After, and decide which methods are safe to replay
  • Classify failures as http, network, timeout or parse so callers can react differently to each
  • Walk every page of a list with an async generator
  • Return a typed result and a friendly message instead of letting the CLI crash

Explain it simply

Explain it simply

Parts 1 and 2 work on a good day. Part 3 is about the other days: the server is slow, the Wi-Fi drops, the provider answers 429, or a proxy sends back an HTML error page. Nothing here adds a feature; it makes the existing features behave when things go wrong.

Think of a courier who phones ahead, waits a sensible time at the door, tries again tomorrow after a failed delivery, but never delivers the same parcel twice, and leaves a clear note when giving up. That courier is the client you are about to finish.

Problem → Why → Solution

The problem: a client with no opinion about failure

The Part 2 client has no opinion about failure. If the server never answers, fetch waits for a very long time and the command simply hangs. A 503 that would have cleared a second later ends the whole command. A proxy returns an HTML page with status 200 and res.json() fails with a SyntaxError about angle brackets, which says nothing about the real cause.

The opposite instinct is just as harmful. Wrapping every call in a loop that retries on any error sounds safe, but it can create the same user three times, and it hammers a struggling server exactly when it needs relief.

draft.js
// A tempting but dangerous retry loop
async function withRetry(fn) {
  for (let i = 0; i < 3; i++) {
    try {
      return await fn();
    } catch {
      // try again immediately, whatever went wrong
    }
  }
}

await withRetry(() => client.createUser(input)); // may create the same user three times

Why not retry everything?

A retry is a second chance only when repeating the request is harmless. Repeating a GET changes nothing, but repeating a POST that the server already processed creates a duplicate, and retrying instantly gives an overloaded server more load exactly when it needs less. So a good policy is selective (which failures, which methods), patient (backoff) and bounded (a maximum).

Core concept: fail fast, retry carefully, explain clearly

Three separate mechanisms keep a client healthy. A timeout bounds how long you wait: AbortSignal.timeout(ms) returns a signal that aborts after the delay, and passing it to fetch as signal makes the request reject with a TimeoutError. Create a fresh signal for every attempt, because one signal represents one deadline and cannot be reset. A retry policy decides which failures deserve another try and how long to pause. And an error taxonomy lets the code behind the CLI react differently to a refused request, a dead network and a slow server.

1. Classify the failure

attemptOnce() turns everything that can go wrong into one ApiError with a kind: network when no response came (the real reason is in err.cause.code, such as ECONNREFUSED), timeout, parse when a 2xx body is not JSON, and http otherwise.

2. Decide whether a retry is safe

A 429 is always retryable, because the server refused the work. Network errors, timeouts and 502, 503 or 504 are retried only for idempotent methods (GET, HEAD, PUT, DELETE). POST and PATCH are never replayed automatically.

3. Wait, then try again

If the server sent Retry-After, use that. Otherwise wait baseDelay x 2 to the power (attempt - 1), capped at a maximum and ideally randomised with jitter so that many clients do not retry in lockstep. After the last allowed retry, rethrow the error.

Two smaller ideas finish the job. A pagination iterator, written as an async generator (async *iterateUsers), requests page after page and yields users one at a time, so callers write for await (const user of client.iterateUsers()) and never count pages. And a result type, { ok: true, value } or { ok: false, error }, lets the CLI branch on result.ok in one place and print friendlyMessage(error), so a user reads 'That token looks wrong' instead of a stack trace.

FailureRetry?Reason
429 Too Many RequestsYes, after Retry-AfterThe server refused; nothing was processed
502/503/504, timeout, network drop (GET/PUT/DELETE)Yes, with backoffRepeating changes nothing
The same failures on POST/PATCHNoThe server may already have acted
400/401/404/409/422, malformed JSONNoRepeating gives the same answer
Mental model: one attempt, one verdict
  1. Start a fresh timeout for this attempt
  2. Turn the outcome into ApiError or data
  3. Retry only safe failures, with a pause
  4. Give up loudly after the limit

A retry is only a second chance when repeating the request is harmless; everything else is reported immediately and clearly.

General pattern

javascript
for (let attempt = 1; ; attempt++) {
  try {
    return await attemptOnce(); // fresh AbortSignal.timeout(ms) created inside
  } catch (err) {
    if (!isSafeToRetry(err) || attempt > maxRetries) throw err;
    await sleep(retryAfter ?? Math.min(cap, base * 2 ** (attempt - 1)));
  }
}

One retry loop: every attempt carries a fresh timeout, a failure is checked for safety and for the limit, and then the code sleeps for the server's hint or a doubling delay.

Part 3 code: timeouts, retries, error kinds, pagination, help

This is the complete Part 3 file. It is long because the mock API from Part 2 is included again, this time with a fault queue: push a fault and exactly one upcoming request is spoiled, which is what makes every retry rule testable. Read the client first, then the eight numbered demo scenarios at the bottom.

The demo replaces sleep with a function that only records the delay it was asked for, so nothing really waits and the output is the same on every run. In production leave sleep alone, keep jitter on, and keep the timeout generous enough for your slowest healthy request.

part3.mjs
// user-cli, part 3: timeouts, retries with backoff, error kinds, pagination, help.
// Save as part3.mjs and run: node part3.mjs   (Node 20.12 or newer)
// Lines marked NEW (or between ">>> NEW" and "<<< end") were added in this part.
import http from "node:http";

// ===== 1. Mock API: now with injectable faults =====
const TOKEN = "demo-token-123";
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
  { id: "u_3", name: "Chidi", email: "chidi@example.com" },
  { id: "u_4", name: "Dara", email: "dara@example.com" },
  { id: "u_5", name: "Eli", email: "eli@example.com" },
];
let nextId = 6;
const faults = []; // NEW: each queued fault spoils exactly one upcoming request
let served = 0; // NEW: how many requests reached the server

function send(res, status, body, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(body));
}
function fail(res, status, code, message, fields) {
  send(res, status, { error: { code, message, ...(fields && { fields }) } });
}
async function readJson(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  return raw ? JSON.parse(raw) : {};
}
function validate(input, partial) {
  const fields = {};
  if (!partial || "name" in input) {
    if (typeof input.name !== "string" || !input.name.trim()) fields.name = "required";
  }
  if (!partial || "email" in input) {
    if (typeof input.email !== "string" || !/^[^@\s]+@[^@\s]+$/.test(input.email)) {
      fields.email = "invalid";
    }
  }
  return fields;
}

// >>> NEW in part 3: misbehave on purpose when a fault is queued
function injectFault(fault, res) {
  if (fault === "garbled") { // a proxy error page sent with a JSON content type
    res.writeHead(200, { "Content-Type": "application/json" });
    return res.end("<html>Bad gateway page</html>");
  }
  if (fault === "slow") return; // never answers; the client gives up and closes
  const { status, code, message, retryAfter } = fault;
  const headers = retryAfter ? { "Retry-After": String(retryAfter) } : {};
  send(res, status, { error: { code, message } }, headers);
}
// <<< end of injectFault

const mock = http.createServer(async (req, res) => {
  served++; // NEW
  if (req.headers.authorization !== `Bearer ${TOKEN}`) {
    return fail(res, 401, "UNAUTHORIZED", "Missing or invalid token");
  }
  if (faults.length) return injectFault(faults.shift(), res); // NEW
  const url = new URL(req.url, "http://mock");
  const one = url.pathname.match(/^\/v1\/users\/([\w-]+)$/);
  const found = one && users.find((u) => u.id === one[1]);
  try {
    if (req.method === "GET" && url.pathname === "/v1/users") {
      const page = Number(url.searchParams.get("page") ?? 1);
      const limit = Number(url.searchParams.get("limit") ?? 10);
      const data = users.slice((page - 1) * limit, page * limit);
      return send(res, 200, { data, meta: { page, limit, total: users.length } });
    }
    if (req.method === "POST" && url.pathname === "/v1/users") {
      const input = await readJson(req);
      const fields = validate(input, false);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (users.some((u) => u.email === input.email)) {
        return fail(res, 409, "CONFLICT", "Email already in use");
      }
      const user = { id: `u_${nextId++}`, name: input.name.trim(), email: input.email };
      users.push(user);
      return send(res, 201, { data: user });
    }
    if (one && !found) return fail(res, 404, "NOT_FOUND", `User ${one[1]} not found`);
    if (req.method === "GET" && found) return send(res, 200, { data: found });
    if (req.method === "PATCH" && found) {
      const changes = await readJson(req);
      const fields = validate(changes, true);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (changes.name) found.name = changes.name.trim();
      if (changes.email) found.email = changes.email;
      return send(res, 200, { data: found });
    }
    if (req.method === "DELETE" && found) {
      users.splice(users.indexOf(found), 1);
      res.writeHead(204);
      return res.end();
    }
    fail(res, 404, "NOT_FOUND", "No such route");
  } catch (err) {
    if (err instanceof SyntaxError) {
      return fail(res, 400, "INVALID_JSON", "Body is not JSON");
    }
    fail(res, 500, "INTERNAL", "Unexpected server error");
  }
});

// ===== 2. The client library =====
class ApiError extends Error {
  constructor(status, code, message, extra = {}) {
    super(message, { cause: extra.cause }); // NEW: keep the low-level error
    this.name = "ApiError";
    this.status = status; // NEW: 0 means no HTTP response arrived at all
    this.code = code;
    this.fields = extra.fields;
    this.kind = extra.kind ?? "http"; // NEW: "http" | "network" | "timeout" | "parse"
    this.retryAfterMs = extra.retryAfterMs; // NEW
  }
}

function loadConfig(env = process.env) {
  const token = env.API_TOKEN;
  if (!token) throw new Error("API_TOKEN is not set (put it in .env, never in code)");
  return { baseUrl: env.API_BASE_URL ?? "https://api.example.com/v1", token };
}

// >>> NEW in part 3: retry policy helpers
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE"]);
const TRANSIENT = new Set([502, 503, 504]);

function parseRetryAfter(value, now = Date.now()) {
  if (!value) return undefined;
  if (/^\d+$/.test(value.trim())) return Number(value) * 1000; // seconds
  const when = Date.parse(value); // or an HTTP date
  return Number.isNaN(when) ? undefined : Math.max(0, when - now);
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function fetchFailure(err, timeoutMs) {
  if (err.name === "TimeoutError") {
    const message = `No answer within ${timeoutMs}ms`;
    return new ApiError(0, "TIMEOUT", message, { kind: "timeout", cause: err });
  }
  const code = err.cause?.code ?? "NETWORK_ERROR"; // e.g. ECONNREFUSED
  const message = "Could not reach the server";
  return new ApiError(0, code, message, { kind: "network", cause: err });
}

function backoffDelay(attempt, { baseDelayMs, maxDelayMs, jitter }) {
  const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
  return jitter ? Math.round(Math.random() * ceiling) : ceiling;
}

function shouldRetry(method, err) {
  if (err.status === 429) return true; // the server refused it, so replay is safe
  if (!IDEMPOTENT.has(method)) return false; // never replay a POST blindly
  return err.kind === "network" || err.kind === "timeout" || TRANSIENT.has(err.status);
}
// <<< end of retry policy helpers

function createClient(options) {
  const { baseUrl, token } = options;
  const { timeoutMs = 5000, retries = 3, baseDelayMs = 200, maxDelayMs = 5000 } = options;
  const { jitter = true, onRetry = () => {} } = options;
  const sleep = options.sleep ?? wait;

  // NEW: one attempt = one fresh timeout signal, and every failure becomes an ApiError
  async function attemptOnce(method, route, body) {
    const headers = {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
      "Accept-Version": "v1", // NEW: pin the API version (header style)
    };
    if (body !== undefined) headers["Content-Type"] = "application/json";
    let res, text;
    try {
      res = await fetch(`${baseUrl}${route}`, {
        method,
        headers,
        body: body === undefined ? undefined : JSON.stringify(body),
        signal: AbortSignal.timeout(timeoutMs),
      });
      text = res.status === 204 ? "" : await res.text();
    } catch (err) {
      throw fetchFailure(err, timeoutMs);
    }
    if (res.status === 204) return null;
    const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"));
    let payload;
    try {
      payload = JSON.parse(text);
    } catch {
      if (!res.ok) {
        const msg = `Server answered ${res.status} without a JSON body`;
        throw new ApiError(res.status, `HTTP_${res.status}`, msg, { retryAfterMs });
      }
      const message = "Response body is not valid JSON";
      throw new ApiError(res.status, "BAD_JSON", message, { kind: "parse" });
    }
    if (!res.ok) {
      const e = payload.error ?? {};
      const code = e.code ?? `HTTP_${res.status}`;
      throw new ApiError(res.status, code, e.message ?? res.statusText, {
        fields: e.fields,
        retryAfterMs,
      });
    }
    return payload;
  }

  // NEW: request() keeps its signature, but now it retries what is safe to retry
  async function request(method, route, body) {
    for (let attempt = 1; ; attempt++) {
      try {
        return await attemptOnce(method, route, body);
      } catch (err) {
        const retryable = err instanceof ApiError && shouldRetry(method, err);
        if (!retryable || attempt > retries) throw err;
        const policy = { baseDelayMs, maxDelayMs, jitter };
        const delay = err.retryAfterMs ?? backoffDelay(attempt, policy);
        if (delay > maxDelayMs) throw err; // the server wants longer than we will wait
        onRetry({ attempt, retries, delay, error: err });
        await sleep(delay);
      }
    }
  }

  const userPath = (id) => `/users/${encodeURIComponent(id)}`;
  const client = {
    listUsers({ page = 1, limit = 10 } = {}) {
      return request("GET", `/users?page=${page}&limit=${limit}`);
    },
    async getUser(id) {
      return (await request("GET", userPath(id))).data;
    },
    async createUser(input) {
      return (await request("POST", "/users", input)).data;
    },
    async updateUser(id, changes) {
      return (await request("PATCH", userPath(id), changes)).data;
    },
    async deleteUser(id) {
      await request("DELETE", userPath(id));
    },
    // >>> NEW in part 3: walk every page without the caller counting pages
    async *iterateUsers({ pageSize = 2 } = {}) {
      for (let page = 1; ; page++) {
        const { data, meta } = await client.listUsers({ page, limit: pageSize });
        yield* data;
        if (data.length === 0 || page * pageSize >= meta.total) return;
      }
    },
    // <<< end new
  };
  return client;
}

// >>> NEW in part 3: typed results and human-readable messages
/** @typedef {{ ok: true, value: any } | { ok: false, error: ApiError }} Result */
/** @returns {Promise<Result>} */
async function toResult(fn) {
  try {
    return { ok: true, value: await fn() };
  } catch (error) {
    if (error instanceof ApiError) return { ok: false, error };
    throw error; // a bug in our own code should stay loud
  }
}

function friendlyMessage(err) {
  if (err.kind === "timeout") return "The server took too long to answer.";
  if (err.kind === "network") return `Cannot reach the server (${err.code}).`;
  if (err.kind === "parse") return "The server replied with something that is not JSON.";
  switch (err.status) {
    case 401: return "That token looks wrong - please double-check it.";
    case 404: return "Nothing exists with that id.";
    case 409: return "That email is already taken.";
    case 422: return `Please fix: ${Object.keys(err.fields ?? {}).join(", ")}.`;
    case 429: return "Rate limited. Wait a little, then try again.";
    default: return `Request failed (${err.status} ${err.code}).`;
  }
}

const USAGE = [
  "usage: user-cli <command>",
  "  list                       show the first page of users",
  "  get <id>                   show one user",
  "  create <name> <email>      add a user",
  "  update <id> key=value...   change name and/or email",
  "  delete <id>                remove a user",
].join("\n");
// <<< end of results and messages

function parsePairs(pairs) {
  const changes = {};
  for (const pair of pairs) {
    const i = pair.indexOf("=");
    if (i < 1) throw new Error(`expected key=value, got "${pair}"`);
    changes[pair.slice(0, i)] = pair.slice(i + 1);
  }
  return changes;
}

const show = (u) => `${u.id}: ${u.name} <${u.email}>`;

// NEW: runCommand returns { ok, text } so main() can set the exit code once
async function runCommand(client, argv) {
  const [cmd, ...args] = argv;
  const commands = {
    list: async () => {
      const { data, meta } = await client.listUsers();
      return `${data.map((u) => u.name).join(", ")} (${meta.total} total)`;
    },
    get: async () => show(await client.getUser(args[0])),
    create: async () => {
      const user = await client.createUser({ name: args[0], email: args[1] });
      return `created ${show(user)}`;
    },
    update: async () => {
      const user = await client.updateUser(args[0], parsePairs(args.slice(1)));
      return `updated ${show(user)}`;
    },
    delete: async () => {
      await client.deleteUser(args[0]);
      return `deleted ${args[0]}`;
    },
  };
  if (!commands[cmd]) return { ok: false, text: USAGE };
  const result = await toResult(commands[cmd]);
  if (result.ok) return { ok: true, text: result.value };
  return { ok: false, text: friendlyMessage(result.error) };
}
// A real cli.js would end with:
//   const r = await runCommand(client, process.argv.slice(2));
//   console.log(r.text); process.exitCode = r.ok ? 0 : 1;

// ===== 3. Demo: every scenario below is deterministic =====
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
try {
  const { port } = mock.address();
  const baseUrl = `http://127.0.0.1:${port}/v1`;
  const waits = [];
  const fast = {
    baseUrl, token: TOKEN, timeoutMs: 300, baseDelayMs: 20, jitter: false,
    sleep: async (ms) => { waits.push(ms); }, // do not really sleep in a demo
    onRetry: ({ attempt, retries, delay, error }) =>
      console.log(`  retry ${attempt}/${retries} in ${delay}ms after ${error.code}`),
  };
  const client = createClient(fast);
  const unavailable = { status: 503, code: "UNAVAILABLE", message: "Try later" };

  console.log("1. two 503s, then success (GET is safe to replay)");
  faults.push(unavailable, unavailable);
  console.log("  ->", (await client.getUser("u_1")).name, `after ${served} requests`);

  console.log("2. 429 with Retry-After: 1 beats our own backoff");
  faults.push({ status: 429, code: "RATE_LIMITED", message: "Slow down", retryAfter: 1 });
  console.log("  ->", (await client.getUser("u_2")).name);

  console.log("3. a 503 on POST is not replayed");
  served = 0;
  faults.push(unavailable);
  const gus = { name: "Gus", email: "gus@example.com" };
  const created = await toResult(() => client.createUser(gus));
  console.log("  ->", created.error.status, `after ${served} request`);

  console.log("4. a slow server hits the per-attempt timeout, then recovers");
  faults.push("slow");
  console.log("  ->", (await client.getUser("u_3")).name);

  console.log("5. malformed JSON is a parse error, not retried");
  faults.push("garbled");
  const garbled = await toResult(() => client.getUser("u_1"));
  console.log("  ->", garbled.error.kind, "|", friendlyMessage(garbled.error));

  console.log("6. nothing is listening on the port");
  const closed = http.createServer();
  await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
  const deadUrl = `http://127.0.0.1:${closed.address().port}/v1`;
  await new Promise((resolve) => closed.close(resolve));
  const offline = createClient({ ...fast, baseUrl: deadUrl, retries: 1 });
  const down = await toResult(() => offline.listUsers());
  console.log("  ->", down.error.kind, down.error.code, "|", friendlyMessage(down.error));

  console.log("7. the iterator hides the paging");
  served = 0;
  const names = [];
  for await (const user of client.iterateUsers({ pageSize: 2 })) names.push(user.name);
  console.log("  ->", names.join(", "), `(${served} requests)`);

  console.log("8. the CLI turns every failure into a sentence");
  const wrong = createClient({ ...fast, token: "nope" });
  const attempts = [[client, ["get", "u_99"]], [wrong, ["list"]], [client, ["help"]]];
  for (const [who, argv] of attempts) {
    const out = await runCommand(who, argv);
    console.log("  ->", out.ok ? "ok" : "fail", "|", out.text.split("\n")[0]);
  }
  console.log("sleeps requested:", waits.join(", "));
} finally {
  mock.close();
}

Code breakdown

  1. Fresh deadline per attemptsignal: AbortSignal.timeout(timeoutMs),

    Every call to attemptOnce() creates a new signal, so a second attempt gets its own full deadline even after the first one timed out.

  2. Read the real network codeconst code = err.cause?.code ?? "NETWORK_ERROR"; // e.g. ECONNREFUSED

    A fetch network failure is a TypeError whose message is just fetch failed. The useful code sits in err.cause, so it is pulled out and used as the ApiError code.

  3. Method decides replay safetyif (!IDEMPOTENT.has(method)) return false; // never replay a POST blindly

    After the 429 rule, this line keeps POST and PATCH out of the retry path. A create that got a 503 therefore cannot become a duplicate user.

  4. Retry-After beats our guessconst delay = err.retryAfterMs ?? backoffDelay(attempt, policy);

    When the server says how long to wait, that is more accurate than the client's own guess. Without a hint the code falls back to exponential backoff.

  5. Yield users, not pagesyield* data;

    iterateUsers() hands out the users of each page one at a time. The caller just reads with for await and never tracks page numbers, limits or totals.

  6. A typed resultif (error instanceof ApiError) return { ok: false, error };

    Only an ApiError becomes an ok: false result. A bug in our own code keeps throwing, so real mistakes stay loud.

  7. Fault injection makes retries testablefaults.push(unavailable, unavailable);

    This tells the mock to answer the next two requests with 503. The retry logic can now be tested exactly, without waiting for a real server to misbehave.

You should see
1. two 503s, then success (GET is safe to replay)
  retry 1/3 in 20ms after UNAVAILABLE
  retry 2/3 in 40ms after UNAVAILABLE
  -> Alice after 3 requests
2. 429 with Retry-After: 1 beats our own backoff
  retry 1/3 in 1000ms after RATE_LIMITED
  -> Bob
3. a 503 on POST is not replayed
  -> 503 after 1 request
4. a slow server hits the per-attempt timeout, then recovers
  retry 1/3 in 20ms after TIMEOUT
  -> Chidi
5. malformed JSON is a parse error, not retried
  -> parse | The server replied with something that is not JSON.
6. nothing is listening on the port
  retry 1/1 in 20ms after ECONNREFUSED
  -> network ECONNREFUSED | Cannot reach the server (ECONNREFUSED).
7. the iterator hides the paging
  -> Alice, Bob, Chidi, Dara, Eli (3 requests)
8. the CLI turns every failure into a sentence
  -> fail | Nothing exists with that id.
  -> fail | That token looks wrong - please double-check it.
  -> fail | usage: user-cli <command>
sleeps requested: 20, 40, 1000, 20, 20

Backoff in numbers

With a base delay of 200 ms and a cap of 5 seconds, the pause doubles after every failure until the cap stops it. Full jitter then picks a random wait between zero and that ceiling, which spreads out clients that all failed at the same moment.

schedule.mjs
// The wait before the next try doubles each time, up to a cap
const baseDelayMs = 200;
const maxDelayMs = 5000;

for (let failed = 1; failed <= 6; failed++) {
  const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (failed - 1));
  console.log(`after failure ${failed}: wait ${ceiling} ms (jitter: 0-${ceiling} ms)`);
}

Retry-After deserves one more detail: it arrives either as a number of seconds or as an HTTP date. A small parser handles both, treats a date in the past as zero and returns undefined for anything it cannot read, so the code falls back to its own backoff.

retry-after.mjs
// Retry-After comes in two shapes: a number of seconds, or an HTTP date
function parseRetryAfter(value, now = Date.now()) {
  if (!value) return undefined;
  if (/^\d+$/.test(value.trim())) return Number(value) * 1000;
  const when = Date.parse(value);
  return Number.isNaN(when) ? undefined : Math.max(0, when - now);
}

const now = Date.parse("Wed, 21 Oct 2026 07:27:58 GMT"); // fixed clock for the demo
console.log("seconds form:", parseRetryAfter("3", now));
console.log("date form:   ", parseRetryAfter("Wed, 21 Oct 2026 07:28:00 GMT", now));
console.log("date in past:", parseRetryAfter("Wed, 21 Oct 2026 07:20:00 GMT", now));
console.log("nonsense:    ", parseRetryAfter("soon", now));
console.log("missing:     ", parseRetryAfter(null, now));

Our client refuses to wait when the server asks for longer than maxDelayMs and throws the 429 instead. A script that would sleep for an hour is worse than one that fails loudly and lets the caller decide.

Timeline of a retried request

The diagram traces scenario 1 and scenario 3 from the demo. Notice how the same 503 is waited out by a GET but thrown at once by a POST.

text
Retry timeline
--------------
GET /users/u_1   (timeoutMs 300, baseDelayMs 20, retries 3, jitter off)

  attempt 1  ----> 503 UNAVAILABLE
                   wait 20 ms
  attempt 2  ----> 503 UNAVAILABLE
                   wait 40 ms
  attempt 3  ----> 200 OK   user returned to the caller

POST /users   (the same 503 on the first attempt)

  attempt 1  ----> 503 UNAVAILABLE
                   thrown at once: the server may already have saved the user

Document it: a README that matches the code

A client nobody can run is unfinished. The README is the last step, and the cheapest way to keep it correct is to copy the command list from the same place the CLI prints its help.

README.md
# user-cli

A small command-line client for the Users API.

## Setup

1. Copy `.env.example` to `.env` and paste your own token.
2. Run `node --env-file=.env cli.mjs list` (Node 20.6 or newer).

## Commands

| Command | What it does |
| --- | --- |
| `list` | show the first page of users |
| `get <id>` | show one user |
| `create <name> <email>` | add a user |
| `update <id> key=value` | change the name and/or email |
| `delete <id>` | remove a user |

## When something fails

- `401`: the token is wrong or expired, check `.env`
- `429`: you are sending too fast, the client waits and retries by itself
- `timeout` or `network`: the server is slow or unreachable, try again later

In real projects

In real projects

Every production client has this layer, whether it is written by hand or comes in an SDK. Official libraries ship with default timeouts, retries for transient errors and typed errors precisely because most outages from the consumer's side are not 'the API is down' but 'the API was slow and we waited forever' or 'the API hiccuped and we retried too aggressively'.

Teams add monitoring on top of the same structure: they log the error kind and code (never the Authorization header), count retries per endpoint and alert when the retry rate climbs. Beyond this lesson lie circuit breakers, which stop calling a dependency that keeps failing, and bulkheads, which keep one slow API from using up every connection. Both build on exactly the classification you wrote here.

Common mistakes

Common mistakes

Retrying every method

Replaying a POST after a 503 can create the record twice, because the server may have saved it before failing. Retry GET, HEAD, PUT and DELETE automatically; for POST retry only a 429, or send an idempotency key if the provider supports it.

Retrying instantly, with no backoff or jitter

A loop with no pause turns one hiccup into a flood of requests. Double the wait each time, cap it, and add jitter so thousands of clients do not all come back at the same moment.

Sharing one AbortSignal across attempts

A signal created once, outside the loop, stays aborted after its first timeout, so every later attempt fails instantly.

Trusting Retry-After without a limit

A header that says 3600 would put the script to sleep for an hour. Compare it with a maximum and give up with the 429 when it is too long.

You can prove the third mistake in a few lines. Watch the first attempt wait out the whole deadline while the second fails instantly.

shared-signal.mjs
import http from "node:http";

const server = http.createServer(() => {}); // accepts the request and never answers
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${server.address().port}/`;

// Mistake: one signal created OUTSIDE the retry loop
const signal = AbortSignal.timeout(100);
for (const attempt of [1, 2]) {
  const started = Date.now();
  try {
    await fetch(url, { signal });
  } catch (err) {
    const instant = Date.now() - started < 50;
    console.log(`attempt ${attempt}: ${err.name}, failed instantly: ${instant}`);
  }
}
server.closeAllConnections();
server.close();

Mini challenge

Extract a reusable withBackoff helper

The retry loop in request() only works for fetch. Extract it into withBackoff(fn, options), a generic helper for any async function. It should call fn(attempt), stop on success, rethrow immediately when shouldRetry says no or the retries are used up, and otherwise wait min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1)), unless the error carries its own retryAfterMs.

  • On success return { value, attempts, delays } where delays lists every wait
  • A permanent error (shouldRetry returns false) is rethrown after exactly one attempt
  • When the retries run out, the last error is rethrown with attempts and delays attached to it
  • An error with retryAfterMs uses that value instead of the formula
  • Inject sleep so the test does not really wait
with-backoff.mjs
// Extract the retry loop into a helper that works for ANY async function.

async function withBackoff(fn, options = {}) {
  // options: retries, baseDelayMs, maxDelayMs, shouldRetry(err), sleep(ms)
  // TODO 1: call fn(attempt) inside a loop, starting at attempt 1
  // TODO 2: on success return { value, attempts, delays }
  // TODO 3: rethrow at once when shouldRetry(err) is false or the retries are used up
  // TODO 4: otherwise wait min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1)),
  //         or err.retryAfterMs when the error carries one, then loop again
}

// TODO 5: test four cases with a fake sleep (so nothing really waits):
//         flaky then ok / permanent error / always failing / retryAfterMs hint

Expected: Seven lines: a flaky call that succeeds on attempt 3 with delays 100 and 200, a permanent error after 1 attempt with no delays, an exhausted call after 4 attempts with delays 100, 200 and 400, and a throttled call that waits the server's 1500 ms.

Show hint

Use for (let attempt = 1; ; attempt++) with try/catch inside. Check attempt > retries and !shouldRetry(err) before computing the delay, and push every delay into an array so the caller can see the schedule.

Show solution
with-backoff.mjs
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Generic retry helper: works for any async function, not only fetch
async function withBackoff(fn, options = {}) {
  const { retries = 3, baseDelayMs = 100, maxDelayMs = 1000 } = options;
  const { shouldRetry = () => true, sleep = wait } = options;
  const delays = [];
  for (let attempt = 1; ; attempt++) {
    try {
      return { value: await fn(attempt), attempts: attempt, delays };
    } catch (err) {
      if (attempt > retries || !shouldRetry(err)) {
        err.attempts = attempt;
        err.delays = delays;
        throw err;
      }
      const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
      const delay = err.retryAfterMs ?? backoff; // the server's hint wins
      delays.push(delay);
      await sleep(delay);
    }
  }
}

// Test doubles: a transient error, and a sleep that does not really wait
const transient = (message, extra = {}) =>
  Object.assign(new Error(message), { transient: true, ...extra });
const isTransient = (err) => err.transient === true;
const noSleep = async () => {};
const opts = { shouldRetry: isTransient, sleep: noSleep };

// 1. fails twice, then works
const flaky = await withBackoff(async (attempt) => {
  if (attempt < 3) throw transient("503");
  return "ok";
}, opts);
console.log(`flaky: ${flaky.value} after ${flaky.attempts} attempts`);
console.log(`delays [${flaky.delays}]`);

// 2. a permanent error must not be retried
try {
  await withBackoff(async () => {
    throw new Error("bad request");
  }, opts);
} catch (err) {
  console.log(`fatal: "${err.message}" after ${err.attempts} attempt`);
  console.log(`delays [${err.delays}]`);
}

// 3. always failing: stop after the retry limit and rethrow the last error
try {
  await withBackoff(async () => {
    throw transient("still down");
  }, { ...opts, retries: 3 });
} catch (err) {
  console.log(`exhausted: "${err.message}" after ${err.attempts} attempts`);
  console.log(`delays [${err.delays}]`);
}

// 4. the delay can come from the server instead of the formula
const throttled = await withBackoff(async (attempt) => {
  if (attempt === 1) throw transient("429", { retryAfterMs: 1500 });
  return "ok";
}, opts);
console.log(`throttled: ${throttled.value}, delays [${throttled.delays}]`);

Quick quiz 1 / 3

With baseDelayMs = 200, maxDelayMs = 5000 and jitter off, how long does backoffDelay wait after the third failed attempt (attempt = 3)?

Quick quiz 2 / 3

The server answers 503 to each of these requests. Which one does the Part 3 client NOT retry automatically?

Quick quiz 3 / 3

A client creates const signal = AbortSignal.timeout(2000) once, outside its retry loop, and passes it to every attempt. What goes wrong?

What to remember

  • Give every attempt its own AbortSignal.timeout so a silent server cannot hang the command
  • Retry only what is safe: 429 always, network errors, timeouts and 502/503/504 only for GET, HEAD, PUT and DELETE, never a blind POST
  • Back off exponentially with jitter, honour Retry-After, cap the wait and stop after a fixed number of retries
  • Classify failures as http, network, timeout or parse and return a typed result so the CLI can print a friendly message
  • Fault injection and an injectable sleep make every retry rule testable without waiting

OWASP API Security Project — OWASP

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project — Part 3: Error Handling and Polish | Thuta Learning