Skip to main content

Custom retry

A quote loader with a retry policy of its own. Pick a scenario: network errors and 5xx answers are retried with a delay that doubles each time, a 404 stops at once, and a server that keeps failing is given up on after four retries.

advancedretrieserrorssendmocking
import { useState } from "react";

import { type Attempt, getQuote, type Quote, type Scenario, scenarios, startScenario, withBackoff } from "./api";

const describe = ({ status, willRetry, delay }: Attempt) => {
if (status === 200) return <ins>success</ins>;
if (willRetry) return `retry in ${delay} ms`;
if (status !== null && status >= 400 && status < 500) return <mark>not retried, a 4xx will not change</mark>;
return <mark>gave up, no retries left</mark>;
};

export const App = () => {
const [attempts, setAttempts] = useState<Attempt[]>([]);
const [loading, setLoading] = useState(false);
const [result, setResult] = useState<{ quote?: Quote; error?: string; ms: number }>();

const run = async (scenario: Scenario) => {
startScenario(scenario);
setAttempts([]);
setResult(undefined);
setLoading(true);
const startedAt = performance.now();

const { data, error } = await withBackoff(() => getQuote.send(), {
onAttempt: (attempt) => setAttempts((prev) => [...prev, attempt]),
});

setLoading(false);
setResult({ quote: data ?? undefined, error: error?.message, ms: Math.round(performance.now() - startedAt) });
};

return (
<main className="container">
<hgroup>
<h1>Custom retry</h1>
<p>Retry network errors and 5xx answers with a growing delay. A 4xx answer is final and is not retried.</p>
</hgroup>
<div className="scenarios">
{(Object.keys(scenarios) as Scenario[]).map((scenario) => (
<button key={scenario} type="button" className="outline" disabled={loading} onClick={() => run(scenario)}>
{scenario}
</button>
))}
</div>
<div className="grid-2">
<article>
<h6>Attempts</h6>
{attempts.length === 0 && !loading && <p className="muted">Pick a scenario.</p>}
<table>
<tbody>
{attempts.map((attempt) => (
<tr key={attempt.attempt}>
<td>#{attempt.attempt}</td>
<td>
<code>{attempt.status === 0 ? "network error" : attempt.status}</code>
</td>
<td>{describe(attempt)}</td>
</tr>
))}
</tbody>
</table>
{loading && <p aria-busy="true">Waiting...</p>}
</article>
<article>
<h6>Result</h6>
{!result && <p className="muted">{loading ? "Still trying." : "Nothing yet."}</p>}
{result?.quote && (
<blockquote>
{result.quote.quote}
<footer>
<cite>{result.quote.author}</cite>
</footer>
</blockquote>
)}
{result?.error && <p className="error">{result.error}</p>}
{result && <small className="muted">Finished after {result.ms} ms.</small>}
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/custom-retry hyper-fetch-react-custom-retry && cd hyper-fetch-react-custom-retry && npm install && npm run dev
What it shows
  1. A retry condition: status 0 (network error or timeout) and 5xx are retried, 4xx is final.
  2. Exponential backoff with jitter: 250 ms, 500 ms, 1 s, 2 s, each plus a random part.
  3. send() never throws: the loop reads success and status from the response.
  4. An attempt log with the status and decision of every attempt.

How it works​

  1. isRetryable(status) is the policy. The fetch adapter reports network errors and timeouts as status 0, so they are retried together with 5xx. A 4xx answer will be the same next time, so it is returned as it is.

  2. withBackoff(send, options) calls send(), decides, waits and calls it again. The delay doubles with every attempt, and the random part spreads out clients that failed at the same time:

    const delay = Math.round(baseDelay * 2 ** (attempt - 1) + Math.random() * 100);
  3. getQuote.send() resolves with { data, error, status, success } for every outcome, so the loop needs no try/catch, and withBackoff returns the last response with its full type.

  4. onAttempt reports each attempt to App.tsx, which shows the status and the decision in a table.

  5. DummyJSON does not fail on demand, so getQuote.setMock() answers with the statuses of the chosen scenario. The policy sees the same statuses a real API would send.

Built-in retries​

The request options cover the common case. retry and retryTime resend a failed request after a fixed delay, inside the dispatcher, and setRetryOnError decides which failures to retry:

const getQuoteWithRetry = getQuote
.setRetry(4)
.setRetryTime(500)
.setRetryOnError((response) => isRetryable(response.status));

retryTime is one number for every attempt, so a delay that grows needs a loop like withBackoff. The Retries example shows the built-in options.

When to use it
  • APIs behind load balancers or rate-limited gateways that fail for short moments.
  • Many clients that could hit a recovering server at the same time.
  • Any request where a 4xx answer means "fix the input", not "try again".

Summary

A status check decides which failures are worth another attempt, and a short loop around send() waits longer after each one. The built-in retry, retryTime and setRetryOnError cover retries with a fixed delay.