
Updated: November 26, 2026.
When an AI API call fails, the first step is to read the response body and headers. A 429 can mean a request or token rate limit, a quota problem, or a spend cap. Those cases need different fixes. Blind retries make rate-limit traffic worse and cannot fix billing access.
Start with a request record
For every failed call, record the provider, model, HTTP status, provider error code, response headers, input and output token usage, elapsed time, and retry count. Remove prompts and customer data from logs unless you have a clear retention policy.
This record lets you distinguish:
- traffic limits from exhausted quota,
- input that exceeds a model’s context from a malformed request,
- provider latency from a client timeout,
- one expensive call from a retry loop.
Do not treat all failures as retryable. Authentication errors and invalid request parameters need a code or configuration fix, not another request.
429: respect the provider’s retry signal
If a response includes Retry-After, wait at least that long. Anthropic documents this header and notes that a spend-cap 429 may not include it. OpenAI recommends random exponential backoff for rate limits, and Google’s Gemini documentation describes 429 RESOURCE_EXHAUSTED and reducing expensive request rates.
Use bounded retries with jitter:
for attempt in 1..max_attempts:
response = send(request)
if response succeeded:
return response
if error is not a temporary rate or availability error:
fail immediately
wait = retry_after(response) or exponential_backoff(attempt)
sleep(wait + small_random_jitter)
fail with the last provider error
Keep concurrency under a limit per provider and model. If several workers receive a 429 at once, do not let each worker retry immediately. A shared queue or token bucket prevents the retry wave from becoming a larger one.
When the error says your quota or spend cap is exhausted, check billing and the project limit. Increasing backoff will not restore exhausted quota.
Set a maximum retry count and a total time budget. After the final attempt, return the provider’s error with a request identifier if available. This gives support a useful trace and stops a background job from running indefinitely.
Context length exceeded
The context limit applies to the complete request, not just the user’s visible question. System instructions, conversation history, tool definitions, retrieved passages and generated output all affect the request budget.
Start by logging token counts before sending. Then remove stale conversation turns, summarize decisions that still matter, and retrieve only the passages needed for the current question. For a large collection, use retrieval rather than attaching every document to every call.
Do not silently cut the end of a prompt. That can remove the user’s actual question or a safety constraint. If you must truncate, do it deliberately and tell the model which content was omitted.
Unexpected bills
Set an output-token budget for each task. A classification call should not be allowed to generate a report. Log usage per call, alert on unusually expensive requests, and add an application-level monthly ceiling where your product needs one.
Repeated context may qualify for prompt caching, depending on provider rules. Keep the reusable prefix stable and measure cached-token usage. The AI API price table shows the difference between standard and cached input for selected models.
Route simple tasks to a lower-cost model only after checking its outputs against a validator. Track cost per successful task, including retries and human corrections. The nominal token price alone does not show whether a model is economical for your workflow.
Timeouts and interrupted streams
For interactive responses, streaming can show progress before the full answer is ready. It does not remove the need to handle a broken connection. Persist the job state, set a deadline, and decide whether a partial response can be shown or must be discarded.
For background work, use a queue and a job identifier. Make retries idempotent where possible, so a worker restart does not charge for producing the same report twice. When the provider returns a temporary availability error, use bounded retry with backoff. When the input is invalid, return the error instead.
Keep connection timeout and overall task deadline separate. A connection timeout can catch a request that never reaches the provider; a task deadline limits how long your application waits for a complete response. Choose both based on the user-facing task and provider behavior, then log which limit ended the request.
Cache not reducing token use?
Check whether the provider reports a cache hit, whether the stable prefix is long enough, and whether its order changes between requests. A timestamp or user-specific value placed before reusable instructions can make an otherwise similar prompt different.
Anthropic’s prompt caching guide documents its caching behavior and lifetime. Other providers use their own rules. Do not assume one provider’s cache design applies to the rest.
FAQ
How should I handle an AI API 429?
Read the error code and Retry-After header, reduce concurrency, then retry temporary rate-limit errors with bounded exponential backoff and jitter. Check billing separately for quota or spend-cap errors.
Should every API error be retried?
No. Retry only temporary rate or availability errors. Authentication, invalid input and exhausted spend caps require a configuration, request or billing change.
How do I reduce context-window errors?
Measure the full request, remove irrelevant history, summarize older turns and retrieve only the passages needed for the current task. Preserve the user’s actual question and constraints.
Why is output costing more than expected?
The model may generate more tokens than the visible answer suggests, retry repeatedly, or include tool and reasoning output. Log provider usage and set a task-specific output limit.