Retry Only What Might Succeed

In Follow Every Page of Results, the planner sent six requests to find Mexico’s code, and every run of four.mjs sends eight more. So far, each one got an answer. Real servers have bad moments, though. An overloaded server answers 503, a server that limits your requests answers 429 when you’ve sent too many, and sometimes the connection drops before any answer arrives.

In this lesson, you’ll write a fetchWithRetry() function that tries again only when another try might succeed, waits before it does, and gives up after a few tries with an error that says why. You’ll also have the planner reuse what it fetched, so it asks for each country once. Start by deciding which failures deserve a second try.

Choose What to Retry

A retry helps only when the same request could get a different answer later. The status class you met in Sort Status Codes by Class tells you when that is. A 4xx code usually means you need to change the request, and a 5xx code means the server has the problem. Sending Mateo’s XX again gets the same 404 every time, because the typo is in the request.

Three failures can clear up on their own, so they’re the ones worth retrying:

  • 429 Too Many Requests: An exception among the 4xx codes. Your request was fine, but you sent too many. The server may add a Retry-After header that says how long to wait.
  • 503 Service Unavailable: The server can’t answer right now, often because it’s overloaded or down for maintenance.
  • No answer: fetch() rejects with a TypeError, as it did in Check the Status Before the Data when the host didn’t exist. After a dropped connection, the request may succeed on the next try.

Every other response goes back to the caller as it is. A 500 error could clear up too, but it often means a bug on the server that a second try only repeats.

You can’t make Nager.Date answer 503 on demand, and practicing on a real API sends it requests it doesn’t need. So you’ll test against a stand-in. Like the trip board’s module, it replaces fetch(), but this one answers every URL. Save it unchanged as stand_in.mjs in your planner folder:

Language: JavaScript Filename: stand_in.mjs
// A stand-in server for trying retries. Each fetch() call
// takes the next answer from the list given to answerWith():
// a status code, or "no answer" for a dropped connection.
// When the list is empty, it answers 200 with one holiday.
const holidays = [{ date: "2026-05-01", name: "Labour Day" }];
let answers = [];
let requests = 0;

export function answerWith(list) {
  answers = [...list];
  requests = 0;
}

globalThis.fetch = async (url) => {
  requests += 1;
  const answer = answers.shift() ?? 200;
  const { pathname } = new URL(url);
  console.log(`request ${requests}: ${pathname} -> ${answer}`);
  if (answer === "no answer") {
    throw new TypeError("fetch failed");
  }
  const headers = { "Content-Type": "application/json" };
  if (answer === 429) {
    headers["Retry-After"] = "1";
  }
  const body = answer === 200 ? holidays : { status: answer };
  const text = JSON.stringify(body);
  return new Response(text, { status: answer, headers });
};

Each fetch() call takes the next answer from the list you pass to answerWith() and logs it with a request number, so you can count what your code sends. A 429 comes with Retry-After: 1.

The first version of fetchWithRetry() checks each response and stops at a cap, a maximum number of tries. Waiting comes in the next section. Save it as retry.mjs:

Language: JavaScript Filename: retry.mjs
const retryable = [429, 503];

export async function fetchWithRetry(url, tries = 3) {
  let problem = "";
  for (let attempt = 1; attempt <= tries; attempt += 1) {
    const response = await fetch(url);
    if (!retryable.includes(response.status)) {
      return response;
    }
    problem = `answered ${response.status}`;
    await response.body?.cancel();
  }
  throw new Error(
    `Gave up on GET ${url} after ${tries} tries: ${problem}`,
  );
}

When the status isn’t in retryable, the function returns the response at once, whether it’s a 200 or a 404, so the caller’s ok check works as before. For a 429 or a 503, the function records the problem and tries again. When the tries run out, the error names the request, the number of tries, and the last problem.

The cancel() line is cleanup you can copy as it is. An unread body holds on to its connection, so cancel() throws the body away and frees the connection for the next try. The ?. skips the call when there’s no body. Bodies as streams are a topic for later.

Try it with three answers in a row: a 429, then a 503, then a 200. Save this script as try_retry.mjs:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.