Wrap your request in a retry helper that waits and tries again when the server answers 429 or a 5xx, and cap the number of attempts. This version honors a Retry-After header when the server sends one and falls back to exponential backoff with jitter when it does not.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function fetchWithRetry(url, options = {}, { maxRetries = 5, baseMs = 500, capMs = 30000 } = {}) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(url, options);
const retryable = res.status === 429 || res.status >= 500;
if (!retryable || attempt >= maxRetries) return res;
const retryAfter = res.headers.get('retry-after');
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const backoffMs = Math.min(capMs, baseMs * 2 ** attempt);
const waitMs = Number.isFinite(seconds) ? seconds * 1000 : Math.random() * backoffMs;
await res.arrayBuffer(); // release the connection before waiting
await sleep(waitMs);
}
}Why this works
Status 429 means the client has sent too many requests in a given amount of time. The spec says a 429 response may include a Retry-After header telling the client how long to wait, so the header is optional and your code needs a fallback. When it is missing, the wait ceiling doubles each attempt up to capMs, and Math.random() picks a delay somewhere below that ceiling so a batch of workers does not retry in lockstep.
The helper reads Retry-After as a number of seconds. If an API sends something else, Number() returns NaN and the code falls back to backoff. Check your API's docs for the format it uses.
Caveats
Retrying a POST that creates a document can create it twice if the first attempt succeeded on the server but the response was lost or came back as a 5xx. If the API supports idempotency keys, send one. If not, narrow the retryable check to 429 only and review the 5xx failures by hand.
Retries only treat the symptom. In a bulk job, also cap concurrency (for example, a pool of 5 workers) so you stay under the limit instead of hitting it repeatedly.
Back to All Questions