Loading video player…

Fit Retries Into a Time Budget

In this lesson, you gave the assistant’s model calls a time budget. The wardens want every hiker to see an answer’s first words, or a message, within eight seconds, even in the August rush, when the provider times out on one request in twenty.

Key Points

  • A timeout covers one attempt, not the request. The retry loop in model/retry.js gives each attempt its own timeout, retries a failed attempt twice, and pauses between attempts, starting at one second and doubling.
  • Setting the timeout to the budget doesn’t keep the wait inside it. With timeoutMs: 8_000 and a stand-in provider that never answers, the stand-in got three requests and the hiker waited 27.0 seconds: 3 × 8 s of attempts plus 1 s and 2 s of pauses.
  • Work backward from the budget. One retry, three seconds per attempt and a one-second pause come to seven seconds at worst, one second inside the eight. Three seconds must still sit above one healthy attempt’s p95: its time to the first text for a stream, the whole call otherwise.

    Your latency report from the last course puts the first words’ p95 at 3,215 ms, but it counts from the request’s start with rate-limit retries included, so it’s an upper bound on one attempt’s figure.

    If an attempt needs longer than three seconds, drop the retry and give one attempt longer.

  • Make the deadline something your code owns. Settings change, so the /ask handler starts one timeout signal per question and passes it to retrieval and every model call. In the loop, AbortSignal.any() combines it with each attempt’s signal into one that aborts when either does.

    The loop stops retrying once the deadline has passed, and sleep() takes the deadline too. With the eight-second timeout and two retries back, the deadline still stopped the wait at 8.0 seconds.

    With the fitted settings, the wait was 7.0 seconds. Both are approximate, because timers run on the event loop.

  • For a stream, the attempt’s timer stops at the first text. A three-second timer on a whole streamed answer cut the stand-in’s stream off on both attempts. When the timer stops at the first chunk that holds text, that chunk came at 0.8 seconds and the answer was done at 4.4, on the stand-in’s toy schedule.

  • A timer you can stop. AbortSignal.timeout() can’t be stopped. timer() makes one that can: a setTimeout that aborts an AbortController, a signal you abort yourself. The deadline and each attempt become timers, each with a signal and a stop(), so the loop now reads deadline.signal.

    The loop passes a function, firstText, to send(), and a streamed call runs it on its first text. Other calls never run it. It stops both timers, because the wardens’ eight seconds were only for the first words.

    Keepalives, events without words, don’t count, so a stalled stream still timed out at 7.0 seconds. A long answer ran to 10.4 seconds, so a thirty-second cap, answerMs, covers the whole answer. Once words are on the page, the loop never retries, because a second answer would repeat them.

  • The number: on the stand-in, the worst-case wait went from 27.0 seconds to 7.0.

The Final Code

Language: JavaScript Filename: model/retry.js
import { setTimeout as sleep } from "node:timers/promises";

export const RETRY = { timeoutMs: 3_000, retries: 1, backoffMs: 1_000, answerMs: 30_000 };
export const DEADLINE_MS = 8_000;

const retryable = (err) =>
  err.name === "TimeoutError" || err.status === 429 || err.status >= 500;

// A timeout you can stop, which AbortSignal.timeout() can't do. It aborts
// with a TimeoutError, as AbortSignal.timeout() does, so retryable() still
// retries it.
export function timer(ms) {
  const controller = new AbortController();
  const id = setTimeout(
    () => controller.abort(new DOMException("timed out", "TimeoutError")),
    ms,
  );
  return { signal: controller.signal, stop: () => clearTimeout(id) };
}

// deadline: the request's timer(DEADLINE_MS), from the /ask handler.
// send(signal, firstText) passes signal to fetch and reads the answer to its
// end. A streamed call runs firstText() on its first chunk that holds text.
export async function withRetries(send, deadline, retry = RETRY) {
  for (let attempt = 0; ; attempt++) {
    const limit = timer(retry.timeoutMs);
    const signal = AbortSignal.any([
      deadline.signal,
      limit.signal,
      AbortSignal.timeout(retry.answerMs),
    ]);
    let started = false;
    const firstText = () => {
      started = true; // words are on the page: never retry now
      limit.stop();
      deadline.stop(); // the eight seconds are met
    };
    try {
      return await send(signal, firstText);
    } catch (err) {
      const last = attempt === retry.retries;
      const stop = started || deadline.signal.aborted;
      if (stop || last || !retryable(err)) throw err;
      // undefined: the value sleep() resolves to, unused here.
      await sleep(retry.backoffMs * 2 ** attempt, undefined, { signal: deadline.signal });
    } finally {
      limit.stop();
    }
  }
}

In the /ask handler, start the deadline when the question arrives and pass it to retrieval and every model call:

Language: JavaScript Filename: server.js
const deadline = timer(DEADLINE_MS);

If the deadline fires, or an answer breaks off or hits its cap, the hiker still needs a message. That’s the next lesson, Fall Back When the Model Fails.

00:00 In the August rush, the provider times out on one request in twenty. The wardens want every hiker to see an answer’s first words, or a message, within eight seconds.

00:11 Every model call goes through your retry loop: a timeout per attempt, two retries, and pauses that start at one second and double.

00:21 Eight seconds sounds like a timeout, so you set it to eight thousand milliseconds. To test it, a stand-in provider never answers. How long does the hiker wait before the error?

00:35 Your turn: pause the video and predict it. Twenty-seven seconds, and the stand-in got three requests.

00:45 On a timeline, the first attempt waits its full eight seconds and times out. The loop pauses one second and sends again: eight more seconds. It pauses two seconds, and the last attempt takes another eight.

01:02 The timeout limits each attempt, not the request. The hiker waits for every attempt and every pause.

01:10 Work backward from eight seconds: one retry, three seconds per attempt, and a one-second pause. At worst, three, plus one, plus three makes seven seconds, one to spare.

01:24 Check three seconds against one healthy attempt’s p95 to first words. Your latency report’s 3.2 seconds includes retries, so it’s an upper bound. If three seconds is too tight, drop the retry.

01:39 Settings change, so the route owns a deadline: a timeout signal per question, passed to retrieval and every model call. AbortSignal.any() combines it with each attempt’s signal into one that aborts when either does.

01:55 The loop stops retrying once the deadline has passed, and sleep takes the deadline too. With the eight-second timeout and two retries back, the deadline still stops the wait at eight seconds.

02:08 With the fitted settings, it’s seven.

02:12 A streamed answer runs for seconds, so a three-second timer cuts it off, on both attempts. For a stream, the attempt’s timer stops at the first text, here at 0.8 seconds.

02:25 The answer is done at 4.4, on a toy schedule.

02:31 AbortSignal.timeout() can’t be stopped. timer() makes one that can: a setTimeout that aborts an AbortController, a signal you abort yourself.

02:41 The deadline and each attempt become timers, with a signal and a stop(). The loop passes a function to send(). On the first text, it stops both timers.

02:52 The wardens’ eight seconds were only for the first words. Keepalives, events without words, don’t count. A stalled stream still times out at seven seconds.

03:04 A long answer runs to 10.4 seconds, so a thirty-second cap covers it.

03:10 Once words are on the page, the loop never retries. A second answer would repeat them.

03:17 A timeout covers one attempt. Add up the attempts and the pauses, fit them inside the request’s deadline, and let the deadline cancel whatever’s left.

03:27 The stand-in’s worst case fell from twenty-seven seconds to seven. If the deadline fires, or an answer breaks off or hits its cap, the hiker still needs a message.

03:37 That’s the next lesson, Fall Back When the Model Fails.

Become a Member to join the conversation.