Skip to main content

Retry-After

A server that allows three requests per five seconds. Press Send 5 at once: three calls succeed, two get 429 Too Many Requests, wait for the time in the Retry-After header, and then succeed. The callers only see the final 200.

advancedretrieserrorsmockingsend
import { useEffect, useState, useSyncExternalStore } from "react";

import { getQuote } from "./api";
import { logStore, rateLimiter } from "./server";

type Call = { id: number; state: "sending" | "done" | "failed"; status?: number | null; ms?: number };

const ServerPanel = () => {
const [, rerender] = useState(0);
// Re-renders a few times a second, only to show the countdown of the simulated server.
useEffect(() => {
const interval = setInterval(() => rerender((value) => value + 1), 250);
return () => clearInterval(interval);
}, []);
const { used, resetsIn } = rateLimiter.status();

return (
<article>
<h6>Simulated server</h6>
<p>
Requests in this window: <strong>{used}</strong> / {rateLimiter.limit}
</p>
<progress value={used} max={rateLimiter.limit} />
<small className="muted">{resetsIn > 0 ? `Window resets in ${resetsIn} s` : "Window is open"}</small>
</article>
);
};

export const App = () => {
const [calls, setCalls] = useState<Call[]>([]);
const log = useSyncExternalStore(logStore.subscribe, logStore.get);

const send = async (count: number) => {
const startedAt = performance.now();
const ids = Array.from({ length: count }, (_, index) => Date.now() + index);
setCalls((prev) => [...ids.map((id): Call => ({ id, state: "sending" })), ...prev].slice(0, 10));

await Promise.all(
ids.map(async (id) => {
// Resolves only after the interceptor has waited and sent the request again.
const { status, success } = await getQuote.send();
const ms = Math.round(performance.now() - startedAt);
setCalls((prev) =>
prev.map((call) => (call.id === id ? { id, state: success ? "done" : "failed", status, ms } : call)),
);
}),
);
};

return (
<main className="container">
<hgroup>
<h1>Retry-After</h1>
<p>
The server allows 3 requests per 5 seconds. Send 5 at once: two get a 429 and wait as long as the server asks.
</p>
</hgroup>
<div className="toolbar">
<div role="group">
<button type="button" onClick={() => send(1)}>
Send 1 request
</button>
<button type="button" className="secondary" onClick={() => send(5)}>
Send 5 at once
</button>
</div>
</div>
<div className="grid-3">
<article>
<h6>Calls</h6>
{calls.length === 0 && <p className="muted">Nothing sent yet.</p>}
<ul className="list">
{calls.map((call) => (
<li key={call.id}>
{call.state === "sending" && <span aria-busy="true">sending</span>}
{call.state === "done" && <ins>{call.status} OK</ins>}
{call.state === "failed" && <span className="error">{call.status} failed</span>}
{call.ms !== undefined && <small className="muted">{(call.ms / 1000).toFixed(1)} s</small>}
</li>
))}
</ul>
</article>
<article>
<h6>Interceptor log</h6>
{log.length === 0 && <p className="muted">No 429 yet.</p>}
<ol className="list">
{log.map((entry) => (
<li key={entry.id}>
<small className="muted">{entry.time}</small> {entry.text}
</li>
))}
</ol>
</article>
<ServerPanel />
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/retry-after hyper-fetch-react-retry-after && cd hyper-fetch-react-retry-after && npm install && npm run dev
What it shows
  1. client.onError handles 429 for every request of the client, in one place.
  2. response.extra.headers gives the response headers, so the interceptor can read Retry-After.
  3. Returning request.send() from the interceptor makes the caller's send() resolve with the retried response.
  4. setUsed(true) marks the resend, so it is never deduplicated into the request that waits for it.

How it works​

  1. api.ts adds an error interceptor with client.onError(async (response, request) => ...). Any other status is returned unchanged.

  2. The fetch adapter stores the response headers, with lowercase names, in extra.headers. parseRetryAfter accepts both forms of the header: a number of seconds, or an HTTP date.

  3. The interceptor waits and returns a new attempt. While it waits, the original request is still in progress, so hooks such as useFetch keep loading: true:

    await sleep(seconds * 1000);
    return request.setUsed(true).send();
  4. A second 429 goes through the same interceptor again. A wait longer than MAX_WAIT_SECONDS, or a missing header, returns the 429 to the caller instead of blocking it.

  5. getQuote sets deduplicate: false, because each click in this demo is a separate call. GET requests are deduplicated by default.

  6. DummyJSON has no rate limit, so server.ts and getQuote.setMock() play one. The mock answers 429 with a retry-after header in extra, the same place where the fetch adapter puts real headers.

When to use it
  • Public APIs with rate limits, such as GitHub, Stripe or OpenAI, which send Retry-After with 429 or 503.
  • Bulk actions and imports that send many requests in a row.
  • Together with queued: true, to send fewer requests at once in the first place.

Summary

One client.onError interceptor reads Retry-After from extra.headers, waits, and resends the request with setUsed(true). Every request of the client respects the server's rate limit without any change at the call site.