Stop a Call That Takes Too Long

Your retry loop turns a rate limit into a short wait, but a call that never answers can still hold up the batch. Each adapter gives fetch() a signal with a 60-second timeout, a placeholder that nobody chose with drafts in mind.

In this lesson, you’ll decide where the time limit belongs in the retry loop and how long it should be, so a stuck call costs the batch one email. First, consider when the clock starts.

Give Each Attempt Its Own Clock

An overall deadline uses one signal created when ask() starts and keeps the clock running through the loop’s waits. A per-attempt timeout creates a fresh signal for each request, so every attempt gets the full limit.

For this batch, use a per-attempt timeout so a Retry-After wait doesn’t eat into the time the next attempt has to draft. One email can then take longer than the limit in total. For a page that someone is waiting on, you’d use one overall deadline instead. Add the limit to model/settings.js, above export const settings:

Language: JavaScript Filename: model/settings.js
const timeoutMs = Math.round(
  Number(read("MODEL_TIMEOUT_SECONDS", "30")) * 1000
);
if (!(timeoutMs >= 1 && timeoutMs <= 2_147_483_647)) {
  throw new Error(
    "MODEL_TIMEOUT_SECONDS must be 0.001 to 2147483 seconds"
  );
}

The calculation rounds the timeout to whole milliseconds because AbortSignal.timeout() throws a RangeError for a fractional millisecond. The check keeps the value within the range supported by Node.js timers. Add timeoutMs, to the settings object and MODEL_TIMEOUT_SECONDS= to .env.example. Then, in sendWithRetries() in model/index.js, create the signal at the top of each attempt:

Language: JavaScript Filename: model/index.js
    const signal = AbortSignal.timeout(settings.timeoutMs);
    try {
      return await adapter.send({ ...request, signal });
    } catch (error) {
      signal.throwIfAborted();

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.