Imagine you're building an application that depends on an external API.
Occasionally, the API returns a server error. Perhaps the network connection is unstable, the service is temporarily unavailable, or the database is taking longer than usual to respond.
The obvious solution is to retry the request.
async function fetchData(url) {
try {
return await fetch(url);
} catch (error) {
return await fetch(url);
}
}
If the first request fails, we try again.
Problem solved?
Not quite.
Now imagine that thousands of users are running the same application, all communicating with the same backend service.
The backend becomes overloaded. Requests start failing. Every client immediately retries its failed requests.
The service, which was already struggling to handle its existing workload, suddenly receives even more requests.
What started as a temporary slowdown can become a prolonged outage.
This is sometimes referred to as a retry storm, and it's one of the reasons why designing reliable applications involves more than simply wrapping API calls in retry loops.
Let's explore what can go wrong and how to implement retries that actually improve reliability.
1. A retry can multiply the workload of an already struggling server
Consider an API that normally handles 1,000 requests per second.
One day, the database starts responding slowly, causing 30% of those requests to fail.
If every failed request is retried once, we've introduced another 300 requests. If all those retries fail and are attempted again, that's another 300 requests.
| Attempt | Requests per second |
|---|---|
| Original requests | 1,000 |
| First retry | 300 |
| Second retry | 300 |
| Total | 1,600 |
Under these illustrative assumptions, we've increased the workload by 60% at precisely the moment the server is struggling.
The situation becomes more interesting when an application consists of several interconnected services.
Imagine this architecture:
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 760 250"
width="760" height="250"
role="img"
aria-label="Retry amplification across five service layers"
font-family="Arial, sans-serif">
<title>Retry amplification across five service layers</title>
<desc>Worst-case illustration of five independent retry layers multiplying three total attempts per layer into 243 attempts at the deepest dependency.</desc>
<rect width="760" height="250" rx="12" fill="#ffffff"/>
<text x="24" y="33" font-size="19" font-weight="600" fill="#0f172a">How retries multiply across services</text>
<!-- Service nodes -->
<rect x="20" y="65" width="128" height="55" rx="6" fill="#fffbeb" stroke="#d97706"/>
<rect x="168" y="65" width="128" height="55" rx="6" fill="#fffbeb" stroke="#d97706"/>
<rect x="316" y="65" width="128" height="55" rx="6" fill="#fffbeb" stroke="#d97706"/>
<rect x="464" y="65" width="128" height="55" rx="6" fill="#fffbeb" stroke="#d97706"/>
<rect x="612" y="65" width="128" height="55" rx="6" fill="#fef2f2" stroke="#dc2626"/>
<!-- Service labels -->
<text x="84" y="98" text-anchor="middle" font-size="13" fill="#0f172a">Client</text>
<text x="232" y="98" text-anchor="middle" font-size="13" fill="#0f172a">API Gateway</text>
<text x="380" y="98" text-anchor="middle" font-size="13" fill="#0f172a">Order Service</text>
<text x="528" y="98" text-anchor="middle" font-size="13" fill="#0f172a">Payment Service</text>
<text x="676" y="98" text-anchor="middle" font-size="13" fill="#0f172a">Database</text>
<!-- Connectors -->
<line x1="148" y1="92" x2="168" y2="92" stroke="#64748b" stroke-width="1.5"/>
<polygon points="168,92 160,87 160,97" fill="#64748b"/>
<line x1="296" y1="92" x2="316" y2="92" stroke="#64748b" stroke-width="1.5"/>
<polygon points="316,92 308,87 308,97" fill="#64748b"/>
<line x1="444" y1="92" x2="464" y2="92" stroke="#64748b" stroke-width="1.5"/>
<polygon points="464,92 456,87 456,97" fill="#64748b"/>
<line x1="592" y1="92" x2="612" y2="92" stroke="#64748b" stroke-width="1.5"/>
<polygon points="612,92 604,87 604,97" fill="#64748b"/>
<!-- Attempt counts -->
<text x="84" y="150" text-anchor="middle" font-size="23" font-weight="600" fill="#92400e">3</text>
<text x="232" y="150" text-anchor="middle" font-size="23" font-weight="600" fill="#92400e">9</text>
<text x="380" y="150" text-anchor="middle" font-size="23" font-weight="600" fill="#92400e">27</text>
<text x="528" y="150" text-anchor="middle" font-size="23" font-weight="600" fill="#92400e">81</text>
<text x="676" y="150" text-anchor="middle" font-size="23" font-weight="600" fill="#b91c1c">243</text>
<text x="84" y="170" text-anchor="middle" font-size="12" fill="#475569">attempts</text>
<text x="232" y="170" text-anchor="middle" font-size="12" fill="#475569">attempts</text>
<text x="380" y="170" text-anchor="middle" font-size="12" fill="#475569">attempts</text>
<text x="528" y="170" text-anchor="middle" font-size="12" fill="#475569">attempts</text>
<text x="676" y="170" text-anchor="middle" font-size="12" fill="#475569">attempts</text>
<line x1="24" y1="190" x2="736" y2="190" stroke="#e2e8f0"/>
<text x="380" y="214" text-anchor="middle" font-size="14" fill="#b91c1c">Five independent retry layers: 3 × 3 × 3 × 3 × 3 = 243</text>
<text x="380" y="234" text-anchor="middle" font-size="12" fill="#475569">Worst-case illustration, assuming three total attempts at every layer.</text>
</svg>If five layers independently allow three total attempts, including the original attempt, a single logical operation could generate as many as 243 attempts at the deepest dependency.
This isn't just a hypothetical architectural concern. Amazon discusses this exact form of retry amplification in its Builders' Library and recommends carefully controlling where retries occur within a service stack.
AWS Builder Center
Now consider how easily this can happen in an ordinary application:
-
The frontend retries an API request.
-
The backend HTTP client has its own retry policy.
-
The background job queue retries failed jobs.
-
The third-party SDK automatically retries requests.
Each mechanism might be reasonable on its own.
Together, they can generate considerably more traffic than anyone intended.
Before adding retries to an application, check whether the libraries and infrastructure you're already using implement their own retry behaviour.
2. Not every failed request deserves another attempt
Here's a common JavaScript retry implementation.
async function fetchWithRetry(url, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
if (i === attempts - 1) {
throw error;
}
}
}
}
It looks reasonable. If a request fails, we try again, up to three total attempts.
However, consider what happens when the server returns 401 Unauthorized.
Unless something changes between attempts, such as refreshing an expired access token, sending the same request again is unlikely to help.
The same applies to malformed requests, invalid parameters, and many other client errors.
We need to distinguish between failures that might resolve themselves and failures that require some form of intervention.
Which HTTP status codes should we retry?
| Status | Meaning | Suggested behaviour |
|---|---|---|
| 400 | Bad Request | Correct the request |
| 401 | Unauthorized | Authenticate or refresh credentials |
| 403 | Forbidden | Resolve the permissions issue |
| 404 | Not Found | Usually do not retry |
| 408 | Request Timeout | Consider retrying if safe |
| 409 | Conflict | Depends on the API and conflict |
| 422 | Unprocessable Content | Correct the submitted data |
| 429 | Too Many Requests | Wait before retrying |
| 500 | Internal Server Error | Depends on the operation |
| 502 | Bad Gateway | Consider retrying |
| 503 | Service Unavailable | Consider retrying with backoff |
| 504 | Gateway Timeout | Consider retrying if safe |
These are suggested policies, not universal rules. The API's documentation and the semantics of the operation should determine the final decision.
HTTP's specification explicitly distinguishes between operations that can safely be repeated and those that require additional knowledge before an automatic retry.
RFC Editor
A detail about JavaScript's fetch()
Unlike some HTTP client libraries, fetch() doesn't automatically throw an error when the server returns an HTTP error status.
try {
const response = await fetch("/api/products");
console.log(response.status);
// A 500 response can reach this line.
} catch (error) {
console.error(error);
}
An HTTP 500 response is still an HTTP response. The promise generally rejects for failures such as network errors or cancellation, rather than unsuccessful HTTP status codes.
A retry mechanism built around fetch() therefore needs to inspect the response explicitly.
const retryableStatuses = new Set([
408,
429,
500,
502,
503,
504
]);
function shouldRetry(status) {
return retryableStatuses.has(status);
}
This simple distinction prevents us from blindly retrying every unsuccessful request.
The status list is an example policy for read-only requests. It isn't sufficient on its own to determine whether an operation with side effects can safely be repeated.
3. Retrying immediately is rarely a good idea
Suppose an external API returns a 503 Service Unavailable response.
Our application immediately retries.
The API is still unavailable, so we retry again.
Depending on how quickly the server rejects requests, all three attempts could happen within a fraction of a second.
We've exhausted our retry allowance without giving the service a meaningful opportunity to recover.
A better approach is to introduce a delay.
const sleep = ms =>
new Promise(resolve => setTimeout(resolve, ms));
We could wait one second between attempts.
await sleep(1000);
That's better than retrying immediately, but a fixed delay introduces another problem.
If thousands of clients experience a failure at approximately the same time, they could all retry one second later.
We've simply moved the spike in traffic.
Introducing exponential backoff
Instead of waiting the same amount of time between attempts, we progressively increase the delay after each failure.
function getRetryDelay(attempt) {
const baseDelay = 1000;
const maxDelay = 30000;
return Math.min(
baseDelay * 2 ** (attempt - 1),
maxDelay
);
}
The resulting delays look like this:
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 760 340"
width="760" height="340"
role="img"
aria-label="Exponential backoff retry delays"
font-family="Arial, sans-serif">
<title>Exponential backoff retry delays</title>
<desc>Retry delays increase from one to two, four, eight and sixteen seconds, then reach the thirty-second cap. This illustration does not include jitter.</desc>
<rect width="760" height="340" rx="12" fill="#ffffff"/>
<text x="24" y="34" font-size="20" font-weight="600" fill="#0f172a">Exponential backoff</text>
<text x="24" y="58" font-size="13" fill="#475569">Base delay: 1 second · Maximum delay: 30 seconds</text>
<!-- Retry 1 -->
<text x="24" y="98" font-size="14" fill="#334155">Retry 1</text>
<rect x="120" y="81" width="540" height="24" rx="4" fill="#f1f5f9"/>
<rect x="120" y="81" width="18" height="24" rx="4" fill="#d97706"/>
<text x="730" y="98" text-anchor="end" font-size="14" fill="#0f172a">1s</text>
<!-- Retry 2 -->
<text x="24" y="137" font-size="14" fill="#334155">Retry 2</text>
<rect x="120" y="120" width="540" height="24" rx="4" fill="#f1f5f9"/>
<rect x="120" y="120" width="36" height="24" rx="4" fill="#d97706"/>
<text x="730" y="137" text-anchor="end" font-size="14" fill="#0f172a">2s</text>
<!-- Retry 3 -->
<text x="24" y="176" font-size="14" fill="#334155">Retry 3</text>
<rect x="120" y="159" width="540" height="24" rx="4" fill="#f1f5f9"/>
<rect x="120" y="159" width="72" height="24" rx="4" fill="#d97706"/>
<text x="730" y="176" text-anchor="end" font-size="14" fill="#0f172a">4s</text>
<!-- Retry 4 -->
<text x="24" y="215" font-size="14" fill="#334155">Retry 4</text>
<rect x="120" y="198" width="540" height="24" rx="4" fill="#f1f5f9"/>
<rect x="120" y="198" width="144" height="24" rx="4" fill="#d97706"/>
<text x="730" y="215" text-anchor="end" font-size="14" fill="#0f172a">8s</text>
<!-- Retry 5 -->
<text x="24" y="254" font-size="14" fill="#334155">Retry 5</text>
<rect x="120" y="237" width="540" height="24" rx="4" fill="#f1f5f9"/>
<rect x="120" y="237" width="288" height="24" rx="4" fill="#d97706"/>
<text x="730" y="254" text-anchor="end" font-size="14" fill="#0f172a">16s</text>
<!-- Retry 6 -->
<text x="24" y="293" font-size="14" fill="#334155">Retry 6</text>
<rect x="120" y="276" width="540" height="24" rx="4" fill="#f1f5f9"/>
<rect x="120" y="276" width="540" height="24" rx="4" fill="#d97706"/>
<text x="730" y="293" text-anchor="end" font-size="14" fill="#0f172a">30s</text>
<text x="24" y="325" font-size="12" fill="#475569">Illustrative delay sequence before adding randomness.</text>
</svg>The first retry happens after one second. The next after two seconds, followed by four seconds, eight seconds, and so on.
Eventually, the delay reaches our configured maximum.
This is known as capped exponential backoff.
It gives the downstream service more time to recover while preventing the retry delay from growing indefinitely.
However, there's still something missing.
4. Add randomness to prevent synchronised retries
Imagine 10,000 clients using the same exponential backoff algorithm.
They all experience a failure at roughly the same time.
They wait one second.
They all retry.
They fail again.
They wait two seconds.
They all retry again.
Even though we're using exponential backoff, the requests are still arriving in clusters.
We need to introduce a little randomness into the retry schedule. This technique is known as jitter.
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 760 390"
width="760" height="390"
role="img"
aria-label="Comparison of retry schedules with and without jitter"
font-family="Arial, sans-serif">
<title>Retry schedules with and without jitter</title>
<desc>Five client timelines illustrate clustered retries without jitter and retries spread over time with jitter.</desc>
<rect width="760" height="390" rx="12" fill="#ffffff"/>
<!-- Without jitter -->
<text x="24" y="35" font-size="19" font-weight="600" fill="#0f172a">Exponential backoff without jitter</text>
<text x="24" y="69" font-size="12" fill="#475569">Client 1</text>
<text x="24" y="93" font-size="12" fill="#475569">Client 2</text>
<text x="24" y="117" font-size="12" fill="#475569">Client 3</text>
<text x="24" y="141" font-size="12" fill="#475569">Client 4</text>
<text x="24" y="165" font-size="12" fill="#475569">Client 5</text>
<line x1="110" y1="65" x2="730" y2="65" stroke="#e2e8f0"/>
<line x1="110" y1="89" x2="730" y2="89" stroke="#e2e8f0"/>
<line x1="110" y1="113" x2="730" y2="113" stroke="#e2e8f0"/>
<line x1="110" y1="137" x2="730" y2="137" stroke="#e2e8f0"/>
<line x1="110" y1="161" x2="730" y2="161" stroke="#e2e8f0"/>
<circle cx="130" cy="65" r="5" fill="#dc2626"/>
<circle cx="220" cy="65" r="5" fill="#dc2626"/>
<circle cx="400" cy="65" r="5" fill="#dc2626"/>
<circle cx="700" cy="65" r="5" fill="#dc2626"/>
<circle cx="130" cy="89" r="5" fill="#dc2626"/>
<circle cx="220" cy="89" r="5" fill="#dc2626"/>
<circle cx="400" cy="89" r="5" fill="#dc2626"/>
<circle cx="700" cy="89" r="5" fill="#dc2626"/>
<circle cx="130" cy="113" r="5" fill="#dc2626"/>
<circle cx="220" cy="113" r="5" fill="#dc2626"/>
<circle cx="400" cy="113" r="5" fill="#dc2626"/>
<circle cx="700" cy="113" r="5" fill="#dc2626"/>
<circle cx="130" cy="137" r="5" fill="#dc2626"/>
<circle cx="220" cy="137" r="5" fill="#dc2626"/>
<circle cx="400" cy="137" r="5" fill="#dc2626"/>
<circle cx="700" cy="137" r="5" fill="#dc2626"/>
<circle cx="130" cy="161" r="5" fill="#dc2626"/>
<circle cx="220" cy="161" r="5" fill="#dc2626"/>
<circle cx="400" cy="161" r="5" fill="#dc2626"/>
<circle cx="700" cy="161" r="5" fill="#dc2626"/>
<text x="730" y="185" text-anchor="end" font-size="13" fill="#b91c1c">Retries arrive in clusters</text>
<line x1="24" y1="200" x2="736" y2="200" stroke="#e2e8f0"/>
<!-- With jitter -->
<text x="24" y="230" font-size="19" font-weight="600" fill="#0f172a">Exponential backoff with jitter</text>
<text x="24" y="259" font-size="12" fill="#475569">Client 1</text>
<text x="24" y="283" font-size="12" fill="#475569">Client 2</text>
<text x="24" y="307" font-size="12" fill="#475569">Client 3</text>
<text x="24" y="331" font-size="12" fill="#475569">Client 4</text>
<text x="24" y="355" font-size="12" fill="#475569">Client 5</text>
<line x1="110" y1="255" x2="730" y2="255" stroke="#e2e8f0"/>
<line x1="110" y1="279" x2="730" y2="279" stroke="#e2e8f0"/>
<line x1="110" y1="303" x2="730" y2="303" stroke="#e2e8f0"/>
<line x1="110" y1="327" x2="730" y2="327" stroke="#e2e8f0"/>
<line x1="110" y1="351" x2="730" y2="351" stroke="#e2e8f0"/>
<circle cx="130" cy="255" r="5" fill="#d97706"/>
<circle cx="156" cy="255" r="5" fill="#d97706"/>
<circle cx="310" cy="255" r="5" fill="#d97706"/>
<circle cx="580" cy="255" r="5" fill="#d97706"/>
<circle cx="130" cy="279" r="5" fill="#d97706"/>
<circle cx="205" cy="279" r="5" fill="#d97706"/>
<circle cx="340" cy="279" r="5" fill="#d97706"/>
<circle cx="690" cy="279" r="5" fill="#d97706"/>
<circle cx="130" cy="303" r="5" fill="#d97706"/>
<circle cx="175" cy="303" r="5" fill="#d97706"/>
<circle cx="250" cy="303" r="5" fill="#d97706"/>
<circle cx="480" cy="303" r="5" fill="#d97706"/>
<circle cx="130" cy="327" r="5" fill="#d97706"/>
<circle cx="213" cy="327" r="5" fill="#d97706"/>
<circle cx="380" cy="327" r="5" fill="#d97706"/>
<circle cx="650" cy="327" r="5" fill="#d97706"/>
<circle cx="130" cy="351" r="5" fill="#d97706"/>
<circle cx="190" cy="351" r="5" fill="#d97706"/>
<circle cx="290" cy="351" r="5" fill="#d97706"/>
<circle cx="530" cy="351" r="5" fill="#d97706"/>
<text x="730" y="378" text-anchor="end" font-size="13" fill="#92400e">Retries are distributed over time</text>
</svg>One commonly used implementation is called full jitter.
function getRetryDelay(attempt) {
const baseDelay = 1000;
const maxDelay = 30000;
const exponentialDelay = Math.min(
baseDelay * 2 ** (attempt - 1),
maxDelay
);
return Math.floor(
Math.random() * exponentialDelay
);
}
Rather than always waiting for the calculated exponential delay, we choose a random duration between zero and that delay.
| Retry | Without jitter | With full jitter |
|---|---|---|
| 1 | 1,000ms | 0–999ms |
| 2 | 2,000ms | 0–1,999ms |
| 3 | 4,000ms | 0–3,999ms |
| 4 | 8,000ms | 0–7,999ms |
| 5 | 16,000ms | 0–15,999ms |
Different clients are now likely to retry at different times.
Amazon's engineering research demonstrates how adding jitter to exponential backoff can reduce contention and unnecessary work compared with synchronised retry schedules.
It's a surprisingly small change to the implementation, but an important one when applications operate at scale.
Full jitter can occasionally produce a delay close to zero. If an API requires a minimum waiting period, that requirement should take precedence over our randomised delay.
5. Sometimes the server already tells you when to retry
Have you ever received a response like this?
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/json
{
"error": "Rate limit exceeded"
}
The server is telling us that we have exceeded its rate limit and should wait before trying again.
Unfortunately, many custom retry implementations ignore this information.
They calculate their own delay and continue retrying, potentially making the situation worse.
The Retry-After header can contain either a duration in seconds or an HTTP date. It can appear in responses such as 429 Too Many Requests and 503 Service Unavailable.
We can handle both formats in JavaScript.
function parseRetryAfter(value) {
if (!value) {
return null;
}
const header = value.trim();
// Retry-After: 30
if (/^\d+$/.test(header)) {
return Number(header) * 1000;
}
// Retry-After: Wed, 02 Dec 2026 10:00:00 GMT
const date = Date.parse(header);
if (!Number.isNaN(date)) {
return Math.max(0, date - Date.now());
}
return null;
}
Then incorporate the result into our retry policy.
const retryAfter = parseRetryAfter(
response.headers.get("Retry-After")
);
const delay = Math.max(
retryAfter ?? 0,
getRetryDelay(attempt)
);
await sleep(delay);
We now respect the server's requested waiting period while retaining our own exponential backoff policy.
There's one more consideration.
If the server asks us to wait ten minutes, but our application has an overall timeout of thirty seconds, we shouldn't simply shorten the server's requested delay and retry anyway.
Instead, we should stop retrying and allow the caller to decide whether to wait, defer the operation, or inform the user.
For cross-origin browser requests, the server may also need to explicitly expose the Retry-After response header through its CORS configuration.
6. A failed response doesn't mean the operation failed
This is where retries become particularly dangerous.
Imagine a customer making a payment through your application.
await fetch("/api/payments", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
orderId: "ORDER-123",
amount: 100
})
});
The server receives the request, processes the payment successfully, and records the transaction.
However, before the response reaches the client, the network connection drops.
From the client's perspective, the request failed.
From the server's perspective, the payment succeeded.
If we automatically retry the request, we might charge the customer twice.
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 760 340"
width="760" height="340"
role="img"
aria-label="A successful payment appears to fail due to a lost response"
font-family="Arial, sans-serif">
<title>A successful payment appears to fail due to a lost response</title>
<desc>The payment API processes a payment, but its response is lost. The client retries the payment, risking a duplicate charge.</desc>
<rect width="760" height="340" rx="12" fill="#ffffff"/>
<text x="24" y="35" font-size="20" font-weight="600" fill="#0f172a">When a successful operation appears to fail</text>
<!-- Participants -->
<rect x="80" y="58" width="160" height="42" rx="6" fill="#fffbeb" stroke="#d97706"/>
<rect x="520" y="58" width="160" height="42" rx="6" fill="#fffbeb" stroke="#d97706"/>
<text x="160" y="84" text-anchor="middle" font-size="15" fill="#0f172a">Client</text>
<text x="600" y="84" text-anchor="middle" font-size="15" fill="#0f172a">Payment API</text>
<!-- Lifelines -->
<line x1="160" y1="100" x2="160" y2="310" stroke="#94a3b8" stroke-dasharray="5 5"/>
<line x1="600" y1="100" x2="600" y2="310" stroke="#94a3b8" stroke-dasharray="5 5"/>
<!-- Initial request -->
<line x1="160" y1="134" x2="600" y2="134" stroke="#64748b" stroke-width="2"/>
<polygon points="600,134 590,129 590,139" fill="#64748b"/>
<text x="380" y="123" text-anchor="middle" font-size="14" fill="#334155">POST /payments — $100</text>
<!-- Successful payment -->
<rect x="510" y="148" width="180" height="31" rx="5" fill="#f0fdf4" stroke="#16a34a"/>
<text x="600" y="168" text-anchor="middle" font-size="13" fill="#166534">Payment successful</text>
<!-- Lost response -->
<line x1="600" y1="200" x2="380" y2="200" stroke="#dc2626" stroke-width="2" stroke-dasharray="6 4"/>
<line x1="373" y1="193" x2="387" y2="207" stroke="#dc2626" stroke-width="3"/>
<line x1="387" y1="193" x2="373" y2="207" stroke="#dc2626" stroke-width="3"/>
<text x="490" y="190" text-anchor="middle" font-size="12" fill="#b91c1c">Response lost</text>
<!-- Retried request -->
<line x1="160" y1="245" x2="600" y2="245" stroke="#d97706" stroke-width="2"/>
<polygon points="600,245 590,240 590,250" fill="#d97706"/>
<text x="380" y="234" text-anchor="middle" font-size="14" fill="#92400e">Client retries the same payment</text>
<!-- Potential duplicate -->
<rect x="490" y="267" width="220" height="34" rx="5" fill="#fef2f2" stroke="#dc2626"/>
<text x="600" y="289" text-anchor="middle" font-size="14" fill="#b91c1c">Possible duplicate charge</text>
<text x="380" y="327" text-anchor="middle" font-size="12" fill="#475569">A communication failure is not proof that the operation failed.</text>
</svg>Similar problems can occur when creating orders, sending emails, submitting financial transactions, updating inventory, or processing background jobs.
The underlying problem is that a network failure doesn't tell us whether the server completed the requested operation.
Understanding idempotency
An operation is considered idempotent when repeating it has the same intended effect as performing it once.
For example:
PUT /api/users/123/preferences
{
"theme": "dark"
}
Setting the same preference multiple times should leave the user's preference in the same final state.
Compare that with:
POST /api/wallet/deposit
{
"amount": 100
}
Executing this operation twice could increase the wallet balance by $200 instead of $100.
HTTP defines several methods, including GET, PUT, and DELETE, as idempotent in terms of their intended effects. POSTand PATCH are not guaranteed to be idempotent.
However, we can design an otherwise non-idempotent operation to support safe retries.
Using idempotency keys
An idempotency key uniquely identifies a logical operation.
const idempotencyKey = crypto.randomUUID();
We then include the key in our request.
async function createPayment(payment, idempotencyKey) {
return fetch("/api/payments", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey
},
body: JSON.stringify(payment)
});
}
If the request needs to be retried, we send the same key again.
const payment = {
orderId: "ORDER-123",
amount: 100
};
const key = crypto.randomUUID();
// Initial attempt
await createPayment(payment, key);
// If another attempt is necessary,
// reuse the same key.
The server needs to recognise the key and prevent the same logical payment from being processed twice.
This is not something the client can enforce simply by adding a header. The API must explicitly implement and support idempotency.
Stripe, for example, provides documented support for idempotency keys when creating or updating resources. Its API also defines how repeated requests, conflicting parameters, saved responses and key expiration are handled.
A few important implementation details:
-
Generate one key per logical operation, not per retry.
-
Reuse the same key and request parameters across attempts.
-
Persist the key when the operation must survive application restarts.
-
Enforce uniqueness and concurrency safety on the server.
-
Understand the API's idempotency key retention period.
For financial transactions and other critical operations, reconciliation may still be necessary when the final outcome is uncertain.
Before retrying an operation, ask whether it is safe to perform it twice.
7. Three retries can turn a five-second request into a long wait
Let's say our API client has a timeout of five seconds per attempt and allows three retries.
That's four total attempts.
If every attempt reaches its timeout, we could spend twenty seconds waiting for responses, even before accounting for the delays between attempts.
| Operation | Duration |
|---|---|
| Initial attempt | 5 seconds |
| Backoff | 1 second |
| First retry | 5 seconds |
| Backoff | 2 seconds |
| Second retry | 5 seconds |
| Backoff | 4 seconds |
| Third retry | 5 seconds |
| Total | 27 seconds |
These are illustrative durations assuming every attempt times out and no jitter is applied.
From the application's perspective, we might consider this a perfectly reasonable retry policy.
From the user's perspective, they've clicked a button and waited nearly half a minute without receiving a result.
This is why we need two different kinds of limits.
Per-attempt timeout: How long an individual request is allowed to run.
Overall retry budget: How much time the complete operation is allowed to consume, including retries and waiting periods.
For example, we might configure:
const retryConfig = {
maxAttempts: 3,
attemptTimeout: 5000,
totalTimeout: 12000,
baseDelay: 500,
maxDelay: 5000
};
Even if we haven't reached the maximum number of attempts, we stop when the overall time budget is exhausted.
A background synchronisation job might tolerate several minutes of retrying.
A user-facing search request might need to fail after a few seconds.
The right timeout depends on the operation and the expectations of the caller, rather than a single default applied across the entire application.
8. Building a better retry utility in JavaScript
We've now identified several problems with traditional retry implementations.
Let's put the solutions together into a reusable JavaScript utility that supports:
-
A limited number of attempts.
-
Selective retrying of HTTP status codes.
-
Exponential backoff with full jitter.
-
Support for
Retry-After. -
Individual request timeouts.
-
An overall time budget.
-
Cancellation by the caller.
To keep the implementation safe and understandable, we'll initially restrict it to GET requests. Write operations should have a separate, explicitly defined idempotency policy.
Step 1: Create an abortable delay function
An ordinary setTimeout() doesn't understand whether the caller has cancelled an operation.
If the user navigates away from a page while we're waiting to retry, we should be able to cancel the waiting period as well.
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
signal?.throwIfAborted();
const timer = setTimeout(() => {
cleanup();
resolve();
}, ms);
function onAbort() {
clearTimeout(timer);
cleanup();
reject(signal.reason);
}
function cleanup() {
signal?.removeEventListener("abort", onAbort);
}
signal?.addEventListener("abort", onAbort, {
once: true
});
});
}
This allows us to interrupt both the active request and the delay between requests.
Step 2: Define our retry policy
const RETRYABLE_STATUSES = new Set([
408,
429,
500,
502,
503,
504
]);
function getBackoffDelay(
attempt,
baseDelay,
maxDelay
) {
const exponentialDelay = Math.min(
baseDelay * 2 ** (attempt - 1),
maxDelay
);
return Math.floor(
Math.random() * exponentialDelay
);
}
function parseRetryAfter(value) {
if (!value) return null;
const header = value.trim();
if (/^\d+$/.test(header)) {
return Number(header) * 1000;
}
const date = Date.parse(header);
return Number.isNaN(date)
? null
: Math.max(0, date - Date.now());
}
We'll also define a custom error to retain the HTTP status code when a request fails.
class HttpError extends Error {
constructor(status, retryAfter = null) {
super(`HTTP request failed: ${status}`);
this.name = "HttpError";
this.status = status;
this.retryAfter = retryAfter;
}
}
Step 3: Implement fetchWithRetry()
async function fetchWithRetry(
url,
{
maxAttempts = 3,
baseDelay = 500,
maxDelay = 5000,
attemptTimeout = 5000,
totalTimeout = 12000,
signal
} = {}
) {
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
throw new RangeError("Invalid maxAttempts");
}
for (const value of [
baseDelay,
maxDelay,
attemptTimeout,
totalTimeout
]) {
if (
!Number.isInteger(value) ||
value < 1 ||
value > 2147483647
) {
throw new RangeError("Invalid timing option");
}
}
const budgetSignal = AbortSignal.timeout(totalTimeout);
const operationSignal = signal
? AbortSignal.any([signal, budgetSignal])
: budgetSignal;
const startedAt = performance.now();
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
operationSignal.throwIfAborted();
const remaining = totalTimeout -
(performance.now() - startedAt);
if (remaining <= 0) {
throw new Error("Retry time budget exhausted");
}
const timeoutSignal = AbortSignal.timeout(
Math.max(1, Math.floor(
Math.min(attemptTimeout, remaining)
))
);
const requestSignal = AbortSignal.any([
operationSignal,
timeoutSignal
]);
let response;
let retryAfter = null;
try {
response = await fetch(url, {
method: "GET",
signal: requestSignal
});
} catch (error) {
operationSignal.throwIfAborted();
// Fetch commonly reports network failures
// as TypeError and timeouts via the signal.
if (
!timeoutSignal.aborted &&
!(error instanceof TypeError)
) {
throw error;
}
lastError = error;
}
if (response) {
if (response.ok) {
// Don't blindly retry malformed JSON.
const data = await response.json();
operationSignal.throwIfAborted();
return data;
}
retryAfter = parseRetryAfter(
response.headers.get("Retry-After")
);
lastError = new HttpError(
response.status,
retryAfter
);
// Release the unsuccessful response body.
await response.body?.cancel().catch(() => {});
if (!RETRYABLE_STATUSES.has(response.status)) {
throw lastError;
}
}
operationSignal.throwIfAborted();
if (attempt === maxAttempts) {
throw lastError;
}
const backoff = getBackoffDelay(
attempt,
baseDelay,
maxDelay
);
const delay = Math.max(
backoff,
retryAfter ?? 0
);
const timeLeft = totalTimeout -
(performance.now() - startedAt);
// Don't retry earlier than the server requested
// simply because our time budget is too short.
if (delay >= timeLeft) {
throw lastError;
}
console.warn(
`Attempt ${attempt} failed. ` +
`Retrying in ${delay}ms.`
);
await sleep(delay, operationSignal);
}
throw lastError;
}
This implementation is longer than a simple retry loop, but each additional piece addresses a specific failure scenario.
It uses AbortSignal.timeout() and AbortSignal.any() to combine request deadlines and caller cancellation. Both methods are defined by the DOM Standard.
One limitation worth mentioning is that fetch() can report both network failures and certain permanent request errors as TypeError. Browsers don't always expose enough information to distinguish them. A production HTTP client may need more precise error classification.
This example also deliberately avoids automatically retrying failures while decoding a successful response body. That keeps malformed JSON and body-processing errors from being silently treated as ordinary transient failures.
Step 4: Use it in an application
try {
const products = await fetchWithRetry(
"/api/products",
{
maxAttempts: 3,
attemptTimeout: 4000,
totalTimeout: 10000
}
);
console.log(products);
} catch (error) {
console.error(
"Unable to retrieve products:",
error
);
}
If the user navigates away or the application no longer needs the result, we can cancel the entire operation.
const controller = new AbortController();
fetchWithRetry("/api/products", {
signal: controller.signal
})
.then(products => {
console.log(products);
})
.catch(error => {
if (!controller.signal.aborted) {
console.error(error);
}
});
// Cancel the request and any pending retries.
controller.abort();
This is particularly useful in React applications, search interfaces, dashboards, and other environments where requests may become irrelevant before they complete.
The utility is intended as a learning example for modern JavaScript runtimes. In production, an established HTTP client or service SDK with configurable retry policies may be preferable to maintaining a custom implementation.
9. Sometimes the best retry is no retry at all
So far, we've discussed how to retry more responsibly.
But what happens when a service has been unavailable for ten minutes?
Even with exponential backoff and jitter, thousands of clients could continue sending requests to an unhealthy service.
At some point, it might make more sense to temporarily stop sending requests altogether.
This is the idea behind the circuit breaker pattern.
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 760 300"
width="760" height="300"
role="img"
aria-label="Three states of the circuit breaker pattern"
font-family="Arial, sans-serif">
<title>Three states of the circuit breaker pattern</title>
<desc>The circuit opens when failures reach a threshold, then becomes half-open after a cooldown. Successful test requests close the circuit; failed tests reopen it.</desc>
<rect width="760" height="300" rx="12" fill="#ffffff"/>
<text x="24" y="34" font-size="20" font-weight="600" fill="#0f172a">The circuit breaker pattern</text>
<!-- Closed state -->
<rect x="24" y="114" width="200" height="96" rx="8" fill="#f0fdf4" stroke="#16a34a"/>
<text x="124" y="139" text-anchor="middle" font-size="17" font-weight="600" fill="#166534">Closed</text>
<text x="124" y="166" text-anchor="middle" font-size="13" fill="#0f172a">Requests proceed</text>
<text x="124" y="185" text-anchor="middle" font-size="12" fill="#475569">Failures are monitored</text>
<!-- Open state -->
<rect x="280" y="114" width="200" height="96" rx="8" fill="#fef2f2" stroke="#dc2626"/>
<text x="380" y="139" text-anchor="middle" font-size="17" font-weight="600" fill="#b91c1c">Open</text>
<text x="380" y="166" text-anchor="middle" font-size="13" fill="#0f172a">Requests blocked</text>
<text x="380" y="185" text-anchor="middle" font-size="12" fill="#475569">Service gets time to recover</text>
<!-- Half-open state -->
<rect x="536" y="114" width="200" height="96" rx="8" fill="#fffbeb" stroke="#d97706"/>
<text x="636" y="139" text-anchor="middle" font-size="17" font-weight="600" fill="#92400e">Half-open</text>
<text x="636" y="166" text-anchor="middle" font-size="13" fill="#0f172a">Limited test requests</text>
<text x="636" y="185" text-anchor="middle" font-size="12" fill="#475569">Check service recovery</text>
<!-- Closed to open -->
<line x1="224" y1="162" x2="280" y2="162" stroke="#64748b" stroke-width="1.5"/>
<polygon points="280,162 272,157 272,167" fill="#64748b"/>
<text x="252" y="99" text-anchor="middle" font-size="12" fill="#475569">Failure threshold</text>
<!-- Open to half-open -->
<line x1="480" y1="162" x2="536" y2="162" stroke="#64748b" stroke-width="1.5"/>
<polygon points="536,162 528,157 528,167" fill="#64748b"/>
<text x="508" y="99" text-anchor="middle" font-size="12" fill="#475569">Cooldown ends</text>
<!-- Successful recovery -->
<path d="M636 210 V250 H124 V210" fill="none" stroke="#16a34a" stroke-width="1.5"/>
<polygon points="124,210 119,218 129,218" fill="#16a34a"/>
<text x="380" y="272" text-anchor="middle" font-size="12" fill="#166534">Successful test requests — resume normal traffic</text>
<!-- Failed recovery -->
<path d="M636 114 V64 H380 V114" fill="none" stroke="#dc2626" stroke-width="1.5"/>
<polygon points="380,114 375,106 385,106" fill="#dc2626"/>
<text x="508" y="55" text-anchor="middle" font-size="12" fill="#b91c1c">Test fails — reopen circuit</text>
</svg>A circuit breaker generally operates in three states.
| State | Behaviour |
|---|---|
| Closed | Requests are allowed normally, and failures are monitored. |
| Open | Requests fail immediately without contacting the unhealthy service. |
| Half-open | A limited number of requests are allowed to test whether the service has recovered. |
| When the service becomes healthy again, normal traffic resumes. |
This approach can prevent an unavailable downstream service from consuming application resources continuously.
While circuit breakers can be useful, they also introduce state-management complexity and recovery behaviour that needs to be tested. Retry budgets, concurrency limits and rate limiting may be sufficient for simpler applications.
You don't need a circuit breaker in every API client.
But when building services that depend heavily on other services, it's worth understanding the pattern.
Bonus: Make retries observable
Imagine your monitoring system reports that 99.9% of your API operations are successful.
That sounds excellent.
But what if half of those operations require two or three attempts before succeeding?
Your application might be hiding a serious infrastructure problem.
Without monitoring individual attempts, retries can disguise deteriorating service health.
Useful metrics include:
| Metric | What it tells us |
|---|---|
| First-attempt success rate | Whether the dependency is healthy without retries |
| Retry rate | How often additional attempts are necessary |
| Retry exhaustion rate | How often all permitted attempts fail |
| Attempts per operation | How much additional traffic retries generate |
| Total operation latency | What the user actually experiences |
| HTTP 429 rate | Whether we're exceeding service limits |
| Timeout rate | Whether the service is responding too slowly |
It is also useful to distinguish a logical operation from its individual attempts in logs and distributed traces.
For example:
{
"operationId": "request-8f92",
"attempt": 2,
"maxAttempts": 3,
"status": 503,
"nextRetryInMs": 842,
"elapsedMs": 420
}
This makes it much easier to understand what is happening when a service starts failing.
A successful retry is still evidence that something failed initially.
We shouldn't lose that information simply because the final operation succeeded.
A practical retry checklist
Before implementing retries in your next application, consider the following questions.
| Question | Recommended approach |
|---|---|
| Is the failure temporary? | Retry selectively |
| Is the operation safe to repeat? | Check idempotency |
| How many times should we try? | Limit total attempts |
| How long should we wait between attempts? | Exponential backoff |
| Could clients retry simultaneously? | Add jitter |
| Did the server provide a waiting period? | Respect Retry-After |
| How long can the user reasonably wait? | Set an overall time budget |
| Can the caller cancel the operation? | Support abort signals |
| Are other application layers retrying? | Coordinate retry policies |
| Is the dependency experiencing a sustained outage? | Consider load shedding or a circuit breaker |
| Can we see retry behaviour in monitoring? | Record attempts and outcomes |
These questions are more important than choosing a particular retry library.
Final thoughts
Retries are one of those engineering techniques that look deceptively simple.
A request failed. Try again.
But once we consider network uncertainty, rate limits, distributed services, duplicate transactions and thousands of concurrent users, the problem becomes considerably more interesting.
A retry is not free.
It consumes time, network bandwidth, server resources and potentially database capacity. In some cases, it may repeat an operation that has already succeeded.
The goal of implementing retries shouldn't be to make every request succeed at any cost.
It should be to recover from temporary failures without making the underlying problem worse.
The next time you're about to add a retry loop to your application, consider what happens if every other client is doing exactly the same thing.
That small change in perspective might lead you to design a much more reliable system.
THE CONVERSATION
Comments
Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.
Loading comments…