Claude API Timeout Handling and Retries, Done Right
Claude API calls fail for reasons that have nothing to do with your prompt: a connection drops mid-stream, the model takes longer than your client's timeout to finish a long completion, or Anthropic's servers return a transient overloaded_error during a traffic spike. None of these are bugs in your code — they're normal operating conditions for any production LLM integration, and the fix is the same one you'd use for any flaky network dependency: set sane timeouts, retry the right errors with backoff, and design your calling code so a retry never causes duplicate side effects.
This article covers the concrete settings and retry logic you need: which timeout to set and where, which HTTP status codes are safe to retry, how exponential backoff with jitter should look in code, and why streaming requests need different timeout handling than standard request/response calls.
Why Claude API calls time out
Three distinct failure modes get lumped together as "timeouts," and they need different handling:
- Connection timeout — the TCP/TLS handshake never completes. Usually a network issue on your side or a DNS problem. Safe to retry immediately.
- Request timeout — the connection opens but no response arrives within your client's configured window. For non-streaming calls with long
max_tokens, generation time alone can exceed a short timeout. Raise the timeout before you add retry logic. - Server-side overload — Anthropic returns
429(rate limited) or529/overloaded_errorduring high load. These are explicitly designed to be retried after a delay.
Misreading which category you're in is the most common mistake. If every request to a specific long-form prompt times out, you have a request-timeout problem — retrying won't help until you raise the timeout or reduce max_tokens. If failures are intermittent and spread across prompts, you have a transient server issue, and retries with backoff are the correct fix.
Set timeouts before you add retries
A retry loop around a timeout that's too short just multiplies failed requests. Pick timeouts based on actual generation time, not a generic default:
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 120_000); // 120s
try {
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: { /* ... */ },
body: JSON.stringify(payload),
signal: controller.signal,
});
} finally {
clearTimeout(timeout);
}
For large max_tokens values (4,000+), 60 seconds is often too short for a non-streaming call. Either raise the timeout to match expected generation time, or switch to streaming so you get incremental output and can apply a shorter idle timeout instead of a total one — see below.
Which errors are safe to retry
Not every failure should trigger a retry. Retrying a 400 just repeats the same invalid request.
Retry with backoff:
429— rate limited500,502,503— server-side errors529/overloaded_error— temporary capacity issue- Connection resets and request timeouts
Don't retry:
400— malformed request (fix the payload)401/403— authentication or permission issue413— payload too large422— invalid parameters (e.g., bad model name)
Exponential backoff with jitter
A fixed delay between retries causes synchronized retry storms when many clients fail at once. Exponential backoff with jitter spreads retries out:
async function callWithRetry(fn, maxAttempts = 5) {
let attempt = 0;
while (true) {
try {
return await fn();
} catch (err) {
attempt++;
const retryable = [429, 500, 502, 503, 529].includes(err.status);
if (!retryable || attempt >= maxAttempts) throw err;
const base = Math.min(1000 * 2 ** attempt, 30_000);
const jitter = Math.random() * base * 0.5;
await new Promise((r) => setTimeout(r, base + jitter));
}
}
}
Cap the maximum delay (30 seconds here) so a single request doesn't hang indefinitely, and cap attempts (5 here) so a persistent outage fails fast instead of looping forever. If the API returns a Retry-After header, honor it instead of your own backoff calculation — it reflects the server's actual recovery estimate.
Streaming needs a different timeout model
A single "total request timeout" doesn't work well for streamed responses, because a slow-but-progressing stream looks identical to a stalled one until you measure time between chunks rather than time to completion.
Use an idle timeout that resets on every received chunk:
let lastChunk = Date.now();
const idleCheck = setInterval(() => {
if (Date.now() - lastChunk > 30_000) {
controller.abort(); // no data for 30s — treat as stalled
}
}, 5_000);
for await (const chunk of stream) {
lastChunk = Date.now();
process(chunk);
}
clearInterval(idleCheck);
This lets long, legitimately slow completions finish without timing out, while still catching genuinely dead connections quickly. Details on handling streamed chunks, including SSE event types and reconnection, are in the streaming docs.
Retries and side effects: avoid duplicate work
If a timeout occurs after the model has already started generating (common with long completions), a naive retry sends the same prompt again and pays for tokens twice. Two mitigations help:
- Lower
max_tokensand request timeout together so a stuck request fails fast, before much generation cost has accrued. - Log request IDs and token usage on every attempt so you can detect duplicate completions in billing or usage review, even without built-in idempotency keys.
If you're routing Claude calls through SubToAPI, every request against https://api.subtoapi.app/v1/messages returns usage metadata in the response, so you can tell which attempt in a retry sequence actually completed and reconcile token spend across your team. That doesn't replace client-side retry logic — you still set your own timeouts and backoff — but it gives you one place to see what actually ran, which matters when multiple services share the same plan. Setup takes a few minutes via the quickstart and the request/response shape is documented in the Messages API reference.
A minimal production-ready pattern
async function sendMessage(payload) {
return callWithRetry(async () => {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(90_000),
});
if (!res.ok) {
const err = new Error(`Request failed: ${res.status}`);
err.status = res.status;
throw err;
}
return res.json();
});
}
This combines a sane request timeout, status-code-aware retries, and exponential backoff in under 20 lines — the core of what most production integrations need.
questions
How long should my Claude API timeout be? Base it on expected generation time, not a fixed default. For short responses (under 500 tokens), 30–60 seconds is usually enough. For long completions or large max_tokens values, use 90–120 seconds or switch to streaming with an idle timeout instead.
Should I retry every failed Claude API request? No. Retry 429, 500, 502, 503, and 529/overload errors with exponential backoff. Don't retry 400, 401, 403, or 422 — those indicate a request problem that a retry won't fix.
How do I avoid duplicate charges when retrying after a timeout? Keep request timeouts tight relative to expected generation time so failures happen before much output is generated, and log request IDs and token usage per attempt so you can spot and reconcile any duplicate completions during billing review.