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.jsgives 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_000and 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
/askhandler 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: asetTimeoutthat aborts anAbortController, a signal you abort yourself. The deadline and each attempt become timers, each with asignaland astop(), so the loop now readsdeadline.signal.The loop passes a function,
firstText, tosend(), 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
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:
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.