Claude API Error Retry: Exponential Backoff Guide
When a call to the Claude API fails with a 429, 500, 503, or a connection timeout, the correct response is almost never to retry immediately. Retrying instantly tends to hit the same overloaded endpoint again, and if you have multiple requests failing at once, they all retry together and make the problem worse. The fix is exponential backoff: wait a little after the first failure, wait longer after the second, longer still after the third, and give up after a fixed number of attempts.
This article covers exactly how to implement that pattern for Claude API calls — which errors are worth retrying, how long to wait between attempts, how to add jitter so retries don't collide, and how to avoid retrying requests that will never succeed no matter how many times you try them.
Which Claude API errors should trigger a retry
Not every error is retryable. Retrying a malformed request just wastes time and quota. Split errors into three buckets:
Retry these:
429(rate limited)500(internal server error)503(overloaded / service unavailable)529(Anthropic-specific overloaded signal)- Network-level failures: connection reset, DNS failure, timeout
Don't retry these:
400(bad request — fix the payload, don't resend it)401(invalid API key)403(permission denied)404(model or endpoint doesn't exist)
A simple rule: if the status code is in the 4xx range and isn't 429, it's a client-side problem that retries won't fix. If it's 429, 5xx, or a transport error, backoff and retry.
The exponential backoff formula
The basic shape is:
delay = base_delay * (multiplier ^ attempt_number)
A common starting point is a 1-second base delay with a multiplier of 2, capped at some maximum (say 60 seconds), and a maximum of 5 attempts:
| Attempt | Delay (no jitter) | |---|---| | 1 | 1s | | 2 | 2s | | 3 | 4s | | 4 | 8s | | 5 | 16s |
If the fifth attempt also fails, stop and surface the error to the caller or your logging system. Retrying forever just hides outages from you.
Add jitter or your retries will collide
If ten requests fail at the same moment and all retry after exactly 2 seconds, they hit the API at the same moment again. Jitter randomizes the delay so retries spread out over time instead of synchronizing. The most reliable approach is "full jitter": pick a random delay between 0 and the calculated exponential value.
function getBackoffDelay(attempt, baseDelay = 1000, maxDelay = 60000) {
const exponential = Math.min(baseDelay * 2 ** attempt, maxDelay);
return Math.random() * exponential;
}
A working retry wrapper
Here's a minimal implementation you can drop into a Node.js project calling an Anthropic-compatible chat completions endpoint:
const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 529]);
async function callWithBackoff(requestFn, maxAttempts = 5) {
let attempt = 0;
while (attempt < maxAttempts) {
try {
const response = await requestFn();
if (response.ok) return response;
if (!RETRYABLE_STATUS.has(response.status)) {
throw new Error(`Non-retryable error: ${response.status}`);
}
} catch (err) {
if (attempt === maxAttempts - 1) throw err;
}
const delay = getBackoffDelay(attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
attempt++;
}
throw new Error("Max retry attempts exceeded");
}
Call it like this:
await callWithBackoff(() =>
fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
messages: [{ role: "user", content: "Summarize this ticket." }],
}),
})
);
Respect the Retry-After header when present
Some 429 and 503 responses include a Retry-After header telling you exactly how long to wait before trying again. When it's present, use it instead of your calculated backoff value — the server knows its own load better than your client does:
const retryAfter = response.headers.get("retry-after");
const delay = retryAfter ? Number(retryAfter) * 1000 : getBackoffDelay(attempt);
Watch out for non-idempotent retries
Backoff logic gets risky when a request has side effects. If you're calling a tool that writes to a database or sends an email, and the Claude API times out after the tool call already executed but before your code received the response, retrying could trigger the action twice. For requests tied to tool use (see tool use docs), consider tracking a request ID or idempotency key so repeated attempts don't duplicate side effects downstream.
Where this fits if you're already behind a gateway
If you're calling the Anthropic API directly, you own all of this retry logic yourself — and you need to re-implement it in every service that talks to Claude. SubToAPI sits between your app and Claude as a single HTTPS API layer: application keys (sub_live_...), streaming, and usage metadata are handled centrally, so you write your retry wrapper once against one stable set of status codes instead of once per integration. Check the quickstart or the messages endpoint docs to see the request shape, and pricing if you're evaluating it for a team.
Whether you call Claude directly or through a layer like SubToAPI, the backoff logic above applies the same way — the status codes and headers are what you're reacting to, not the specific client.
questions
Should I retry streaming requests the same way as non-streaming ones? Mostly yes, but only if the stream fails before any tokens are received. If a stream starts and then drops mid-response, retrying from scratch duplicates partial output — buffer what you've received and decide whether to resume or discard before retrying. See the streaming docs for how partial responses are structured.
What's a reasonable maximum number of retry attempts? 3 to 5 attempts is standard for user-facing requests. Background jobs can go higher (8–10) since there's no one waiting on a response, but always cap the total elapsed time so a single failing request doesn't block a queue for minutes.
Does exponential backoff guarantee my request eventually succeeds? No. It reduces the chance of failure during transient overload or rate limiting, but if the underlying cause is a sustained outage or a fundamentally invalid request, no amount of backoff will fix it. Always log final failures after max attempts instead of retrying indefinitely.