AI Agents & LLMsMedium
How do you handle rate limits, retries and errors with LLM APIs?
Learning path, stage 5 of 5: Shipping to production · question 4 of 10Retry only what can succeed on retry: 429 rate limits, 5xx/overloaded errors, timeouts and network failures. Use exponential backoff with jitter, and respect the retry-after header. Don't retry 400-type errors: fix the request. Add timeouts, limits on how many calls run at once, and a fallback path so one slow provider doesn't take your app down.
Error classes
- 400 invalid request / 413 too large: a bug in your request. Don't retry.
- 401 / 403: auth or permission problems. Alert, don't retry.
- 429 rate limited: back off. Limits usually cover requests per minute and input and output tokens per minute.
- 500 / 529 overloaded: temporary. Retry with backoff, possibly fall back to another model or region.
- Refusal / safety stop: not an error code. Handle it in your app logic.
Resilience patterns
- Exponential backoff + full jitter, so clients don't all retry at the same moment.
- Concurrency limits / token buckets on your side, to stay under the limits.
- Idempotency: a retried request must not, for example, send an email twice.
- Circuit breaker and fallback model when the error rate spikes.
- Official SDKs already retry some errors, so know the defaults before adding your own retry loop on top.
Sources
Code example
tsx
1// Typed error handling + backoff with jitter on top of the SDK's own retries.2import Anthropic from "@anthropic-ai/sdk";34const client = new Anthropic({ maxRetries: 2, timeout: 60_000 }); // SDK-level retries + timeout (ms)56const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));78export async function callWithBackoff(params: Anthropic.MessageCreateParamsNonStreaming, attempts = 4) {9 for (let i = 0; ; i++) {10 try {11 return await client.messages.create(params);12 } catch (err) {13 const retryable =14 err instanceof Anthropic.RateLimitError ||15 err instanceof Anthropic.InternalServerError ||16 err instanceof Anthropic.APIConnectionError;17 if (!retryable || i >= attempts - 1) throw err; // BadRequest, Auth etc: fail fast1819 const header = err instanceof Anthropic.APIError ? err.headers?.get("retry-after") : null;20 const base = header ? Number(header) * 1000 : 1000 * 2 ** i;21 await sleep(Math.random() * base); // full jitter22 }23 }24}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @opentelemetry/api vitest, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.