Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 30 min

Project: a weather API client

By the end of this chapter, you'll be able to

  • Design a class that encapsulates access to an API
  • Cache responses with an expiry time
  • Retry after a temporary error with a growing delay
  • Make the code testable by injecting the clock and the log

Step 1: the rules

SituationExpected behaviour
Response cached less than a minute agono network call
Temporary error (5xx status, timeout)new attempt after 50 ms, then 100 ms, then give up at the 3rd failure
Permanent error (4xx status, such as 404)give up immediately: retrying wouldn't change anything
One city failsthe others are still displayed

Doubling the wait at each attempt is called exponential backoff: a struggling service isn't flooded by thousands of clients all retrying at the same moment.

The answer is kept for a minute: the next displays will cost nothing.

Step 6 of 6
Text description of the animation
  1. The display asks for Lima's weather.
  2. No recent answer: the service has to be called.
  3. The service is temporarily down (503): wait 50 ms and try again.
  4. Still down: wait 100 ms, double the previous delay.
  5. The service is back: the answer arrives.
  6. The answer is kept for a minute: the next displays will cost nothing.

Step 2: the client and its tests

The simulated server reproduces three difficulties: Lima is down for the first two calls, Atlantis doesn't exist, Oslo answers too slowly.

// --- Simulated server: Lima is down for the first two calls, Atlantis doesn't exist, Oslo is slow ---
const data = { dakar: 29, oslo: -2, lima: 18, hanoi: 31 };
const calls = {};
const fetch = (url, options = {}) => new Promise((resolve, reject) => {
  const city = new URL(url).pathname.split("/").pop();
  calls[city] = (calls[city] ?? 0) + 1;
  const status = !(city in data) ? 404 : city === "lima" && calls[city] <= 2 ? 503 : 200;
  const timer = setTimeout(() => resolve({ ok: status === 200, status, json: async () => ({ city, temperature: data[city] }) }), city === "oslo" ? 300 : 40);
  options.signal?.addEventListener("abort", () => { clearTimeout(timer); reject(options.signal.reason); });
});
// --- End of simulated server ---

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

class HttpError extends Error {
  constructor(status, city) {
    super(`HTTP ${status} for ${city}`);
    this.name = "HttpError";
    this.status = status;
  }
}

class WeatherClient {
  #cache = new Map();
  #options;

  constructor({ ttlMs = 60_000, attempts = 3, timeoutMs = 1000, pauseMs = 50, clock = () => Date.now(), log = () => {} } = {}) {
    this.#options = { ttlMs, attempts, timeoutMs, pauseMs, clock, log };
  }

  async #load(city) {
    const { timeoutMs } = this.#options;
    let response;
    try {
      response = await fetch(`https://api.example.org/weather/${city}`, { signal: AbortSignal.timeout(timeoutMs) });
    } catch (e) {
      throw new Error(e.name === "TimeoutError" ? `timed out after ${timeoutMs} ms for ${city}` : `network unavailable for ${city}`);
    }
    if (!response.ok) throw new HttpError(response.status, city);
    return response.json();
  }

  async weather(city) {
    const { ttlMs, attempts, pauseMs, clock, log } = this.#options;
    const cached = this.#cache.get(city);
    if (cached && clock() - cached.date < ttlMs) {
      log(`${city}: cache`);
      return cached.data;
    }
    for (let attempt = 1; ; attempt++) {
      try {
        const data = await this.#load(city);
        this.#cache.set(city, { date: clock(), data });
        log(`${city}: network (attempt ${attempt})`);
        return data;
      } catch (e) {
        const permanent = e instanceof HttpError && e.status < 500;
        if (permanent || attempt === attempts) throw e;
        log(`${city}: ${e.message}, retrying in ${pauseMs * 2 ** (attempt - 1)} ms`);
        await wait(pauseMs * 2 ** (attempt - 1));
      }
    }
  }

  async several(cities) {
    const results = await Promise.allSettled(cities.map((c) => this.weather(c)));
    return results.map((r, i) => (r.status === "fulfilled" ? `${r.value.city}: ${r.value.temperature} °C` : `${cities[i]}: unavailable (${r.reason.message})`));
  }
}

// --- Tests, with a simulated clock to control the cache ---
function check(condition, message) {
  if (!condition) throw new Error(`test failed: ${message}`);
}
let now = 0;
const lines = [];
const client = new WeatherClient({ ttlMs: 1000, clock: () => now, log: (l) => lines.push(l) });
check((await client.weather("dakar")).temperature === 29, "first read");
await client.weather("dakar");
check(lines.at(-1) === "dakar: cache", "second read from the cache");
now = 1500;
await client.weather("dakar");
check(lines.at(-1).startsWith("dakar: network"), "cache expired after 1 s");
console.log("Tests: OK");

// --- The dashboard ---
const cities = ["hanoi", "lima", "atlantis", "oslo"];
const journal = new Map(cities.map((c) => [c, []]));
const dashboard = new WeatherClient({ timeoutMs: 200, log: (l) => journal.get(l.split(":")[0]).push(l) });
const display = await dashboard.several(cities);
console.log(display.join("\n"));
console.log("Log:");
for (const cityLines of journal.values()) for (const l of cityLines) console.log("  ·", l);
Tests: OK
hanoi: 31 °C
lima: 18 °C
atlantis: unavailable (HTTP 404 for atlantis)
oslo: unavailable (timed out after 200 ms for oslo)
Log:
  · hanoi: network (attempt 1)
  · lima: HTTP 503 for lima, retrying in 50 ms
  · lima: HTTP 503 for lima, retrying in 100 ms
  · lima: network (attempt 3)
  · oslo: timed out after 200 ms for oslo, retrying in 50 ms
  · oslo: timed out after 200 ms for oslo, retrying in 100 ms

Choices worth noticing:

  • All API access is inside the class. The rest of the application calls weather(city) or several(cities) and never sees fetch, the cache or the retries.
  • A dedicated error class, HttpError, carries the status: e instanceof HttpError && e.status < 500 cleanly identifies a permanent error.
  • A private method #load isolates the network call; its technical errors (timeout) are translated into clear messages, identical in every browser.
  • The clock and the log are injected into the constructor. In production, you keep the defaults (Date.now, nothing); in the tests, a simulated clock lets you check the cache's expiry without waiting a real minute.
  • Promise.allSettled guarantees that a failing city doesn't prevent the others from being displayed.
  • The log is grouped by city before display: the requests run in parallel, and the real order of the messages would vary from one run to the next.

Your turn

Mini-lab: measuring the cache's effectJavaScript

Output

Click “Run” to execute your code.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Solved exercise: duplicate requests

When the page loads, three components ask for Dakar's weather at the same moment. The cache is no help: the first answer hasn't arrived yet when the other two requests go out. Write a function dedupe(fn) that returns a version of fn: while a request for a key is in flight, later requests for the same key receive the same promise.

Hint 1
A Map associates each key with the in-flight promise. If the key is there, return that promise; otherwise call fn and store it.
Hint 2
When the promise settles (success or failure), remove the key with .finally(…): otherwise a temporary error would stay in memory forever.
Show the solution and common mistakes
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let networkCalls = 0;
async function loadWeather(city) {
  networkCalls += 1;
  await wait(100);
  if (city === "atlantis") throw new Error(`HTTP 404 for ${city}`);
  return { city, temperature: 29 };
}

function dedupe(fn) {
  const inFlight = new Map();
  return (key) => {
    if (!inFlight.has(key)) {
      const promise = fn(key).finally(() => inFlight.delete(key));
      inFlight.set(key, promise);
    }
    return inFlight.get(key);
  };
}

const weather = dedupe(loadWeather);
const [a, b, c] = await Promise.all([weather("dakar"), weather("dakar"), weather("dakar")]);
console.log(a.temperature, a === b && b === c, "network calls:", networkCalls);

await weather("dakar");
console.log("after it finished, new call:", networkCalls);

const attempts = await Promise.allSettled([weather("atlantis"), weather("atlantis")]);
console.log(attempts.map((r) => r.status).join(", "), "network calls:", networkCalls);
29 true network calls: 1
after it finished, new call: 2
rejected, rejected network calls: 3

The three components get the same object (a === b), for a single network call. Once the answer has arrived, the key is released: the next request goes back to the network (or, in the full client, to the cache).

Common mistakes:

  • Storing the result instead of the promise: during the 100 ms wait there is no result yet, and all three requests go out.
  • Forgetting to remove the key on failure: the page would stay stuck on a past error, even once the service is back.

Summary

  1. 1An API access class hides fetch, the cache and the retries behind two simple methods.
  2. 2A cache with an expiry time avoids useless and costly calls.
  3. 3Only temporary errors are retried, with a delay that doubles at each attempt.
  4. 4Injecting the clock and the log makes the code testable without waiting.
  5. 5Sharing the in-flight promise avoids sending the same request several times.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.