Domdhi logoDOMDHI.OS
BACK_TO_COURSE

Pulling Data In

Failures and Retries: Break It on Purpose

Everything Fails Eventually

The question isn't whether a request fails. It's whether you find out. This is the other half of the code from the last lesson:

const MAX_WAIT = 60; // seconds
const wait = (ms) => new Promise((done) => setTimeout(done, ms));

async function getPage(url, maxTries = 5) {
  for (let attempt = 1; attempt <= maxTries; attempt++) {
    let res = null;
    try {
      res = await fetch(url, {
        headers: { Authorization: `Bearer ${process.env.API_KEY}` },
        signal: AbortSignal.timeout(30_000), // 30 second limit
      });
      if (res.ok) return await res.json();
    } catch (err) {
      console.error(`Attempt ${attempt}: ${err.message}`);
    }

    // Our mistake (400, 401, 403...): stop now.
    if (res && res.status >= 400 && res.status < 500 && res.status !== 429) {
      throw new Error(`HTTP ${res.status}, not retrying`);
    }

    // Their problem or the network: wait, then try again.
    const asked = Number(res?.headers.get("retry-after"));
    if (asked > MAX_WAIT) {
      throw new Error(`Told to wait ${asked}s, stopping`);
    }
    const backoff = 1000 * 2 ** (attempt - 1); // 1s, 2s, 4s, 8s
    if (attempt < maxTries) await wait(asked > 0 ? asked * 1000 : backoff);
  }
  throw new Error(`Gave up after ${maxTries} tries`);
}

Five tries means four waits. With no Retry-After, that's 1 + 2 + 4 + 8 = 15 seconds of waiting before it gives up and says so. If the API asks for more than 60 seconds, it stops and tells you instead of hanging for an hour or asking again too early. It only reads Retry-After as a number of seconds; some APIs send a date instead, so ask which one yours uses.

The thing to look for is what's not there: nothing that swallows an error and returns an empty list. An empty list and a failed request look identical on a chart. One means no calls. The other means you have no idea.

Reads Are Safe to Repeat. Writes Might Not Be.

Asking for a list twice is harmless. Sending "create invoice" twice can bill somebody twice. And a timeout doesn't mean it failed. It can mean it worked and you didn't hear back. Before code retries a write, the API needs a way to recognize a repeat, usually called an idempotency key. No such thing? Look up whether the first one worked before you send another.

Your Check

Have AI run these and show you the output:

Break it What should happen
Wrong key Stops right away, says 401
Fake 429 with Retry-After: 2 Waits at least 2 seconds, then continues
Fake 429 with Retry-After: 3600 Stops right away, says how long it was told to wait
Fake 500 every time Five tries, then a loud failure
Kill it halfway and rerun Finishes, no duplicates, no gaps
Run it twice Second run changes no totals
WARNING

"I handled errors" can mean "I hid them." Ask AI: "Show me every place this code catches an error and what it does next." Anything that says "log and continue" needs a reason.

QUIZ

An API request fails and the code returns an empty list. Why is that dangerous?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS