Chapter 4. Reliability and error handling
Learning objectives
- Distinguish between errors to retry, errors to fix, and errors requiring human judgment by inspecting status codes, error codes in the response body, and headers.
- Explain the structure of rate limits and the multiple causes of 429 errors, and regulate traffic accordingly.
- Design a retry policy with jitter and budgets at a single layer, and establish layered timeouts and deadlines.
- Safely repeat mutating operations using idempotency keys, and recover from unknown outcome states.
- Recover interrupted responses and partial failures, and prevent failures from cascading to other features.
Introduction
At two in the morning, a manuscript proofreading job stalled. The person in charge arrived at work in the morning and ran the job again from the beginning; around lunchtime, editors reported that two duplicate proof copies had been uploaded for the same chapter. Looking at the logs, 529 and 429 errors were mixed overnight, and the retry logic had been infinitely repeating every failure at one-second intervals. The response to the failure caused greater damage than the failure itself.
In systems that use external APIs, failure is routine rather than an exception. What matters is distinguishing between types of failure, applying designated responses for each type, and never doing the same work twice. This chapter starts with error classification and progresses through rate limits, retries and backoff, timeouts, idempotency, interrupted responses and partial failures, and failure isolation.
Key concepts
Success, failure, and unknown outcome
The outcome of a request is not one of two possibilities, but one of three: a success response was received, a failure response was received, or no response was received at all. The third case is called an unknown outcome. The server might have already completed the work before the connection was dropped, or it might not have even started.
For a model call itself, even if the outcome is unknown, simply resending it is sufficient. It costs slightly more, but does not alter the outside world. The problem lies with operations that have side effects. If a refund, reservation creation, or email dispatch has an unknown outcome, treating it as a "failure" and executing it again risks executing it twice. Mutating operations with an unknown outcome should be handled in the following order:
- Query the actual state using the same business key.
- If it has already been applied, use that result as a success.
- If confirmed that it has not been applied, execute it again using the same idempotency key.
- If the state cannot be queried, do not re-execute automatically; place it in a pending state and alert a human.
Error classification table
Names differ across providers, but the meanings of status codes are similar.
| Status | Anthropic | OpenAI | Gemini (Interactions API) | Action |
|---|---|---|---|---|
| 400 | invalid_request_error (including reaching manually configured spend limits) |
Bad request | invalid_request, failed_precondition |
Fix request or configuration |
| 401 | authentication_error |
Authentication error | — | Check or replace key |
| 402 | billing_error |
— | payment_required |
Process billing information. Do not retry |
| 403 | permission_error |
Unsupported region, etc. | permission_denied |
Check permissions and access settings |
| 409 | conflict_error |
Conflict | — | Resolve conflict, then retry |
| 413 | request_too_large (Messages API 32MB) |
— | — | Reduce request size |
| 429 | rate_limit_error |
Multiple causes (next section) | rate_limit_exceeded, too_many_requests, quota_exceeded |
Varies by cause |
| 500 | api_error |
Server error | api_error |
Retry after backoff |
| 503 | — | server_is_overloaded |
service_unavailable |
Retry after backoff |
| 504 | timeout_error |
— | deadline_exceeded |
Consider streaming or batching; check client deadline |
| 529 | overloaded_error |
— | — | Retry after backoff |
Gemini documentation explicitly states not to retry client errors such as 400, 402, and 403, and OpenAI documentation also explains that a bad request will yield the same result until it is corrected.
Decision table for filtering retryable errors
Status codes alone are not enough. Read the error code in the body as well as the headers, and answer three questions.
| Question | Yes | No |
|---|---|---|
| Can the same request succeed over time? | Rate limits, overload, transient server errors | Format errors, authentication errors, spend limits, billing issues |
| Is it safe to repeat? | Model calls, queries, mutating operations with an idempotency key | Mutating operations without an idempotency key |
| Is there time left to wait? | Ample time remains before the deadline | The user has already left or the deadline has passed |
Automatically retry only when all three questions are answered "Yes." If the first question is "No," fix the request or alert a human; if the second is "No," proceed with the unknown outcome procedure; if the third is "No," finalize the failure and hand off to a fallback path.
Structure of rate limits
A rate limit is a cap on requests and tokens permitted over a given period of time. Measurement units differ by provider.
| Provider | Unit | Scope |
|---|---|---|
| Anthropic | Requests per minute (RPM), input tokens per minute (ITPM), and output tokens per minute (OTPM) by model tier | Organization. Lower limits can be set per workspace |
| OpenAI | RPM, RPD, TPM, TPD, images per minute (IPM), etc. | Organization and project. Some model families share limits |
| Gemini | RPM, input tokens per minute (TPM), requests per day (RPD) | Project, not API key. RPD resets at midnight Pacific Time |
Anthropic uses the token bucket algorithm. Because water is continuously refilled into a bucket at a constant rate and drawn out with each request, it does not reset all at once at a fixed time. As a result, a limit of 60 requests per minute may be enforced as 1 request per second, and even if the total minute volume is within the limit, a burst within a short instant can trigger a 429. Documentation recommends ramping up traffic gradually, as sudden spikes in usage can run into acceleration limits.
Remaining limits can be determined from response headers. Anthropic provides limit, remaining, and reset time headers for each item, such as anthropic-ratelimit-requests-remaining and anthropic-ratelimit-input-tokens-remaining, while OpenAI provides headers such as x-ratelimit-remaining-requests and x-ratelimit-remaining-tokens. Keep in mind differences in calculation methods as well. OpenAI calculates token limits using the larger of max_tokens and estimated tokens, and counts cached inputs toward TPM. Anthropic's OTPM counts only actual generation, and on most models, cache reads are not counted toward ITPM.
How to interpret 429 errors
Even for the same 429 error, the required response can be completely opposite depending on the cause.
| Cause | How to identify | Action |
|---|---|---|
| Rate limit exceeded | Usually includes a retry-after header (may be absent) |
Wait at least that long before retrying |
| Sudden surge | Anthropic acceleration limit, OpenAI slow_down |
Retry, but reduce the rate of traffic ramp-up |
| Anthropic tier spend limit | No retry-after, error.details.error_code is enforced_spend_limit_reached |
Stop retrying. SDK automatic retries will also fail. Notify the person in charge |
| OpenAI credit, spend, or usage limit | Error code indicates depleted credits or exceeded limit | Retrying is futile. Add credits or adjust limits |
| Gemini daily quota | quota_exceeded |
Wait until reset or request a quota increase |
Also remember that when reaching a spend limit configured directly on an organization or workspace in Anthropic, a 400 invalid_request_error is returned rather than a 429 (with the exception of Claude Code workspace limits, which return a 429 with retry-after). The Gemini codes in the table are based on the Interactions API; the generateContent API uses different formats such as RESOURCE_EXHAUSTED. You must branch on the cause, not merely the status code.
Exponential backoff and jitter
For an error that should be retried, you must determine how long to wait. Exponential backoff doubles the wait time with each attempt. Jitter adds random variation to this, preventing a massive number of clients experiencing the same failure from swarming back at the exact same moment. It is like a line collapsing in front of an elevator: if everyone rushes back at exactly 10 seconds later, they will tangle up again.
function backoffMs(attempt: number, retryAfterSec?: number): number | null {
const base = 500, cap = 30_000;
if (retryAfterSec !== undefined) {
const wait = retryAfterSec * 1000 + Math.random() * 1000; // Minimum wait + small random delay
return wait > cap ? null : wait; // If longer than cap, null: do not retry and finalize failure
}
const ceiling = Math.min(cap, base * 2 ** attempt);
return Math.random() * ceiling; // Full jitter: choose between 0 and ceiling
}
OpenAI documentation recommends treating the Retry-After value as a minimum wait and adding a small random delay, while advising that caps be placed on both the number of attempts and total retry time. It adds a warning that failed requests are also counted against minute limits, meaning that continuously resending the same request only makes matters worse.
Retry in one place, within a budget
Retries are hidden across multiple layers. The official Anthropic SDK retries connection errors, 429s, and 5xx errors by default twice with exponential backoff, respects retry-after, and allows customization via max_retries. The Gemini Python SDK retries transient errors up to 4 times, and the official OpenAI SDK retries connection errors and 408, 409, 429, and 5xx errors by default twice. If an application wrapper, job queue, and API gateway each add their own retries on top of this, the number of attempts multiplies.
The AWS Builders' Library describes retries as "selfish." This is because they consume additional server capacity to increase the success probability of one's own request. Therefore, it recommends retrying at only a single point in the stack, and only when the dependent service appears healthy. Practical approaches are as follows:
- Designate a single layer responsible for retries. If delegating to the SDK, disable retries in the wrapper; if retrying in the wrapper, set SDK retries to 0. Configuration names vary by SDK and language (e.g., Python
max_retries, TypeScriptmaxRetries). - Establish a retry budget. This includes the number of attempts, total wait time, and the ratio of retries relative to total requests (e.g., 10%). Maintaining a client-side token bucket that slowly refills tokens on successful responses and spends tokens when retrying prevents retries from surging during an outage.
- Record the original request ID and attempt number in the logs. You must know how many times an individual request was actually delivered in order to stay within budget.
Designing timeouts in layers
Handling all waiting with a single timeout either cuts connections too early or holds them for too long. Divide them into three layers:
| Layer | Meaning | Criteria for setting |
|---|---|---|
| Connection timeout | Until TCP/TLS connection is established | Short; a few seconds |
| Idle timeout | Until the next event arrives in the stream | High percentile (such as p99) of event intervals observed in normal responses, plus a margin |
| Overall deadline | Absolute time by which a response must be returned to the user | Latency objective of the response contract |
AWS introduces an approach of selecting a high percentile (e.g., p99.9) from the downstream service's latency distribution, accepting false-positive timeouts at a small rate. Deadlines are propagated downward. When executing tools, pass along the remaining time so that tasks expected to finish after the deadline are not started at all.
Long generation requests should be sent via streaming or batching. Anthropic documentation recommends this for requests that might exceed 10 minutes, because some networks terminate connections that remain idle for extended periods. The SDK checks whether non-streaming requests might exceed 10 minutes and configures TCP keep-alive, and the default timeout for the OpenAI SDK is also 10 minutes. According to OpenAI documentation, synchronous responses are canceled by dropping the connection, but tasks running on the server, such as in background mode, must be explicitly canceled to stop. If only an intermediate layer drops the connection while the application server's upstream request remains alive, generation and billing will continue.
Idempotency: Pressed twice, executed once
Even if the elevator call button is pressed multiple times, only one elevator arrives. The property where sending the same request multiple times yields the same result as sending it once is called idempotency. The HTTP standard (RFC 9110) defines PUT, DELETE, and safe methods as idempotent methods, stating that for a client to automatically retry a non-idempotent request, it must know that the request is actually idempotent or have a means to verify that the original request was not applied. AWS similarly concludes that an API with side effects is not safe to retry unless it provides idempotency.
Here is how idempotency is built in applications:
- Assign one key to each operation, and use that same key for all retries of that operation. Examples include a key constructed from a tool call ID, or a business key such as
refund:{order_number}:{refund_attempt}. - The receiver applies a unique constraint to the key and stores its status (in progress, completed, failed), a fingerprint (hash) of the request payload, and the result. To ensure that only one request is processed even if duplicate keys arrive concurrently, preempting the key must be done atomically (e.g., insertion using a unique constraint).
- When the same key arrives again, return the stored result. If the key is identical but the payload differs, reject it as a conflict.
- Set the retention period of the key to be longer than the window in which retries can occur.
Tool call IDs provided by the model are unique to each call, making them excellent ingredients for constructing keys. When resending the same tool call due to a network error, the same key accompanies it so the receiver recognizes the duplication. Creating a new key with every retry breaks this mechanism. Furthermore, in workflows where the model request itself is resent and the model may propose the same task again as a new call, include business identifiers such as an order number in the key so the receiver recognizes it as the same task. The same applies to inbound traffic. Documentation advises that OpenAI webhooks can rarely deliver the same event twice, so duplicates should be filtered out using the webhook-id header.
Recovering interrupted responses
Streaming can fail even after receiving a 200 response. Handle errors on an event-by-event basis, and determine recovery strategies in advance for when connections drop.
- Anthropic: You can store the received portion and request to resume reception. Models of Claude 4.5 and earlier insert the received portion as the beginning of a new assistant message, whereas models from Claude 4.6 onward send a user message instructing to "continue from where it was cut off" along with the received portion. Because tool use blocks and thinking blocks cannot be partially recovered, resume only up to the last text block and request the rest anew. Since continuing can introduce duplicates or misalignments, it is safer to request outputs from scratch when format is critical, such as with structured outputs.
- OpenAI: Long-running tasks can be run on the server with
background: trueand polled for status. When used in conjunction with streaming, you can store thesequence_numberarriving with each event as a cursor, and after a disconnection, resume receiving from that point usingstarting_after. In Zero Data Retention (ZDR) projects, it operates withstore=false, and response data is temporarily stored for approximately 10 minutes to allow polling.
Presenting incomplete results and confirming business completion are separate matters. Keep previews generated from interrupted responses in a "generating" state, and persist only results that are complete and have passed validation.
Recovering from partial failures
In tasks composed of multiple units, partial failure is common. The guiding principle is "preserve what succeeded, and redo only what failed, according to its cause."
- Parallel tool calls: If some calls fail, return failure results and let the model determine the next action. Send results containing the reason even for calls that were not executed (Chapter 2).
- Batch: Categorize results into success, error, canceled, and expired. Resubmit expired, canceled, and server errors, and do not resubmit request formatting errors until they are fixed. Do not regenerate items that have already succeeded.
- Multi-stage pipeline: Store per-item states (pending, in progress, completed, failed, quarantined) and record checkpoints at the end of each stage. Upon restart, skip completed items.
- Irreversible operations: For operations that cannot be canceled, such as email dispatch, establish separate compensation procedures (correction email, manual handling).
Inputs that repeatedly produce the same error should be moved to a dead letter queue so they do not block other tasks, allowing a human to investigate the cause.
Preventing failures from cascading
If an external API is slow or failing for an extended period, threads and connections waiting on those calls accumulate, slowing down even unrelated features. Mechanisms are needed to contain the damage within compartments, like the bulkheads of a ship.
| Mechanism | Operation | What to configure |
|---|---|---|
| Admission control | Immediately reject new requests when waiting requests exceed a certain threshold | Maximum queue size, user guidance upon rejection |
| Resource isolation (bulkhead) | Separate concurrency limits and connection pools by feature | Concurrency limit per feature |
| Circuit breaker | Stop calling altogether for a period when failure rate exceeds a threshold, then test a fraction of requests to verify recovery | Failure rate threshold, trip duration, number of probe requests |
| Fallback path | Pre-evaluated alternative model/provider, degraded functionality, static guidance | Quality criteria, conditions for switching and recovery |
A circuit breaker has three states. Like an electrical circuit, current flows when it is closed. In the normal (closed) state, calls are allowed through; in the tripped (open) state, requests are immediately routed to a fallback path; and in the test (half-open) state, if a portion of requests succeed, it closes again. Choosing a fallback model after an outage has already occurred is too late. Verify quality with the same evaluation set in advance, and record transitions in logs and metrics.
OpenAI's slow_down and server_is_overloaded
In its 2026-09-02 changelog, OpenAI distinguishes between two situations. When traffic increases too rapidly, a 429 with code slow_down is returned; when the model experiences temporary overload, a 503 with code server_is_overloaded is returned. While both are errors that can resolve over time, the underlying cause lies on different sides, requiring intervention in different places.
| Response | Where the cause lies | What to adjust |
|---|---|---|
429 + slow_down |
Rate of traffic increase on our side | Cap transmission rate and ramp up incrementally |
503 + server_is_overloaded |
Temporary overload on provider's side | Backoff and jitter, circuit breaker, fallback path |
Handling slow_down solely with backoff causes traffic to snap back to its original rate all at once when the wait finishes, triggering the same error again. Reduce the dequeue rate while waiting, and even after errors cease, ramp up slowly over several minutes. server_is_overloaded cannot be solved simply by reducing our own rate slightly. Wait within the retry budget, but if failure rates remain high, open the circuit breaker and divert to a fallback path. Keep metrics and alerts separated by error code as well. Counting both under a single metric removes the basis for choosing the appropriate remedy.
Shopping mall 'All Good Market' released product description generation tasks all at once at five times the usual volume to coincide with the start of a 10:00 AM sale. When slow_down errors accumulated in the logs, rather than increasing retry attempts, the team modified the scheduler to ramp up the dequeue rate over 10 minutes. When server_is_overloaded errors were mixed in at the same time, they separately evaluated whether to divert only that portion to a fallback model.
Rejection errors surging on version-upgrade days
A sudden surge in request rejections immediately after upgrading a model or API version will not resolve by waiting. The new version no longer accepts configuration options that were accepted until yesterday, so the problem resolves only when the request is modified. Recent examples from Anthropic include the following:
| What changed | Rejected request | Remediation |
|---|---|---|
| Claude Opus 5.5 (2026-09-22) | thinking.type: "disabled" |
Set thinking.type: "adaptive" and specify thinking depth with output_config.effort |
| API version 2026-10-21 | Request containing temperature (400) |
Remove the parameter |
| Prompt caching | Request with four block-level breakpoints plus top-level cache_control (automatic caching) (400) |
Breakpoints are limited to four per request. Reduce explicit breakpoints by one to leave room for automatic caching |
Follow the error classification table for handling. Remove these from retry lists and preserve the raw error message verbatim. Opus 5.5 even includes the alternative configuration to use in its rejection message. Before upgrading versions, run test calls against the new version using the exact production request format.
Do not trust successful responses unconditionally either. When the model refuses a structured output request carrying type: "json_schema" in output_config.format, the stop_reason is returned as "refusal". Parsing immediately can easily lead to mistaking it for a format error and entering a retry loop, so check stop_reason first. When resending conversations for retries or resuming generation, never summarize or rewrite earlier parts of thinking blocks. In models from Claude 5.1 onward, thinking blocks remain valid only when the preceding content is preserved identically in subsequent requests.
To save costs, the team responsible for an internal summarization bot had previously called the model with thinking disabled for short questions. When they changed the model to Claude Opus 5.5, all of the short questions failed. The place to fix was not the retry configuration, but the request on that path. They changed thinking.type to "adaptive" and lowered effort.
Queues and defaults of local inference servers
Even when hosting models locally, the failure types remain the same. The only difference is that we configure the limits ourselves instead of the provider. In Ollama, the default concurrency per model is 1 request (OLLAMA_NUM_PARALLEL), and requests exceeding the number queued when the server is busy (OLLAMA_MAX_QUEUE) are rejected. This effectively embeds the admission control discussed earlier directly into the server. Classify this rejection as an overload and apply backoff and jitter. Retrying immediately only fills the queue again.
Include load times in your timeout design. By default under keep_alive, a model remains in memory for 5 minutes; if set to 0, it is unloaded immediately after responding. Calling an unloaded model prepends model loading time before the first response, so allow ample time when waiting for the first event. The default number of concurrently loaded models (OLLAMA_MAX_LOADED_MODELS) is 3 times the number of GPUs, or 3 for CPU inference, and models are loaded only when they fit into memory.
In llama.cpp, llama-server changed its default port from 8080 to 9931 in an update on 2026-10-09 following an announcement on 2026-08-03. Docker images continue to use 8080 inside the container. If health checks fail with connection refused after an upgrade, it is a configuration issue rather than a transient failure, so specify --port instead of retrying. --api-key has no default value and opens without authentication if not explicitly provided. Multiple keys can be supplied as a comma-separated list, allowing key rotation by keeping both new and old keys simultaneously.
An internal search team handled both nightly indexing and morning queries on a single Ollama server. On days when indexing finished late and filled the queue, queries during the morning commute hours were rejected. By setting a separate ceiling on the number of concurrent requests for indexing jobs, capacity was preserved for queries.
Going deeper
Anatomy of a retry storm
Retries multiply across layers. If an API gateway retries 1 time, an application wrapper retries 3 times, and an SDK retries 2 times by default, then when failures persist, a single user request is delivered to the API up to (1+1)×(1+3)×(1+2) = 24 times. During an outage, traffic tens of times the normal volume surges, and because failed requests also consume limits, recovery is delayed further. Even with backoff, the multiplicative structure remains intact.
The sequence for preventing storms is as follows. First, reduce retry layers to one. Second, set a retry budget as a ratio. If retries exceed a certain proportion relative to normal requests, stop retrying and fail fast. Third, use a circuit breaker to take a fallback path instead of retrying when a dependent service is unhealthy. Fourth, do not release backlogged jobs all at once after an outage ends. Ramp up throughput in stages to avoid triggering acceleration limits again.
Validating recovery policies by injecting failures
Defects in retries and duplicate prevention cannot be found with normal responses alone. Build a failure injection layer that inserts mock responses in front of model calls and tool calls, and reproduce the following situations.
| Fault to inject | What to check |
|---|---|
429 with retry-after, transient 429 without headers, 429 with a spend limit error code |
Retry the first two with backoff; immediately halt and alert on the spend limit code |
| Consecutive 529 and 500 errors | Recover within budget or take a fallback path |
| Stream interrupted midway | Are incomplete results not saved? |
| Loss of response immediately after a mutation succeeds | Query using indeterminate outcome procedures and verify no duplicate execution occurs |
| Partial batch failure, same webhook delivered twice | Do not recreate successful items, and process the same event only once |
There are three inspection criteria: was the same job executed twice, is the actual delivery count for a single request within budget, and does the final status display match reality? Placing this test in the deployment pipeline allows catching regressions whenever retry logic is modified.
At work
Clear Spring Water Purifiers: Reports cut off at 60 seconds
The field technician app of water purifier rental company 'Clear Spring Water Purifiers' generated a water quality history report for each customer before inspections. After the reports grew longer, about 15% of requests failed, and technicians frequently tapped the retry button, generating the same report two or three times. Costs were 40% higher than the number of generated reports.
When senior backend engineer Bong investigated, the app server was calling the model non-streaming, and the in-house API gateway's request timeout was 60 seconds. Long reports took 70 to 90 seconds to generate and were cut off at the gateway, but the app server's model request remained alive, generating to completion and incurring charges. The gateway, app wrapper, and SDK were also each retrying independently.
Senior Engineer Bong's modifications were as follows:
- Switched the report route to streaming and turned off buffering for this route at the gateway. Changed timeouts to a "30-second idle between events" and an "overall 4-minute deadline".
- Retried only in one place at the SDK, and turned off retries in the wrapper and gateway.
- Severed the upstream stream if a technician closed the screen.
- Pre-generated reports the night before for customers scheduled for visits the next day. Generated in real time only for visits urgently added on the same day.
The option to increase the gateway timeout to 15 minutes was not adopted because it held connections for too long and carried the risk that idle connections would be severed by intermediate networks. The option to send the same request twice concurrently and use whichever response arrived first was rejected because it doubled costs. After the modifications, the failure rate dropped below 1%, and duplicate generation disappeared.
Pine Scent Publishing: A proofreading pipeline that does not rerun from scratch
Publishing house 'Pine Scent Publishing' divided book manuscripts by chapter, generated proofreading suggestions, and stored them in a manuscript management system. On a night when processing 12 manuscripts and 380 chapters, consecutive 529 errors halted the job, and the person in charge restarted the job from scratch in the morning. Proofread copies for chapters that were already saved were saved once more, incurring two days' worth of costs. One chapter contained many high-resolution scanned images, so its requests failed every time with 413 for exceeding the size limit, continuously blocking the retry queue.
Lead Platform Engineer Jin redesigned the pipeline:
- Saved the status (pending, in progress, completed, failed, quarantined) for each chapter. When restarted, completed chapters were skipped.
- Used
(manuscript ID, chapter number, proofreading round)as an idempotency key for storage. If the same key arrived again, the existing result was returned. - Divided errors according to Chapter 4's decision table. Retried 529, 500, and rate-limit 429 errors within budget, and immediately routed 413 and 400 errors to a quarantine queue without retries. The person in charge split and resubmitted quarantined chapters.
- Ran failure injection tests prior to release. Forcibly terminated the process mid-job and restarted it to verify that no duplicate saves occurred.
Migrating the entire workflow to the Batch API was also considered. Although it reduced costs, editors reviewed chapters in sequential order starting in the morning, whereas batch processing could take up to 24 hours and items not processed within the deadline could expire; therefore, it was decided to use it only for non-urgent re-proofreading rounds. Afterward, even on days with incidents, restarts processed only the remaining chapters, and not a single duplicate save occurred.
Common mistakes
- All 429s resolve if you wait. A 429 due to a spend limit or daily quota will continue to fail until the limit resets or is adjusted. Distinguish them by the error code in the response body.
- Retries are better the faster and more numerous they are. Failed requests also consume limits. You need backoff, jitter, count and time caps, and a retry budget.
- 400 errors can also be resolved by resending a few times. Request format issues will produce the same result until fixed.
- If a timeout occurred, it was not executed on the server. The outcome is indeterminate. For mutations, query the status before executing again.
- Increasing the timeout resolves duplicate execution. It only reduces the frequency. The fundamental solution is an idempotency key.
- Create a new idempotency key on each retry. If the key changes, the receiving side cannot know it is the same operation. Use the same key for retries of the same operation.
- Adding application retries to SDK retries is safer. The counts multiply, worsening the outage. Perform retries at only one layer.
Summary at a glance
| Topic | What to remember |
|---|---|
| Outcome status | Success, failure, indeterminate outcome. For mutations with an indeterminate outcome, query first |
| Retry decision | Can it succeed later, is it safe to repeat, is time remaining |
| 429 | Wait and retry for rate/spike limits; halt and alert for spend/quota limits. Anthropic custom configured limits return 400 |
| Rate limits | Because it uses a token bucket, even brief bursts hit limits. Ramp up gradually |
| Backoff | Exponential increase + jitter + cap. Retry-After is the minimum wait |
| Retry layers | In one place only. Check SDK defaults (2 times for Anthropic) |
| Timeouts | Connection, idle, overall deadline. Use streaming, batch, or background for long requests |
| Idempotency | Same key across all retries (tool call ID, business identifier) + unique constraint + result storage. Deduplicate incoming events as well |
| Partial failure | Preserve successes, handle failures by cause. Quarantine repeated failures |
| Fault isolation | Admission control, bulkheads, circuit breakers, pre-evaluated fallback paths |
Check the official docs
- Anthropic — API errors: Read about error types, SDK automatic retries, request IDs, and recommendations for long requests.
- Anthropic — Rate limits: Check token buckets, ramp-up limits, spend limit 429s, and response headers.
- OpenAI — Error codes: Check whether to retry for each specific cause of a 429.
- OpenAI — Rate limits: Read about
Retry-After, jitter, and limit consumption by failed requests. - IETF — RFC 9110 §9.2.2: Read about idempotent methods and automatic retry rules.
- AWS Builders' Library — Timeouts, retries, and backoff with jitter: Read about timeout configuration, retry amplification, and jitter.
- OpenAI — Changelog: Check the distinction between
429slow_downand503server_is_overloadedin the 2026-09-02 entry. - Anthropic — Prompt caching: Check the difference between automatic and explicit caching, the 4-breakpoint limit, and conditions that trigger a 400.
- Anthropic — What's new in Claude Opus 5.5: Check the rejection of disabling thinking and the
thinkingandeffortsettings to use instead. - Ollama — FAQ: Read about the default values and behaviors of
keep_alive,OLLAMA_NUM_PARALLEL,OLLAMA_MAX_QUEUE, andOLLAMA_MAX_LOADED_MODELS.
Self-check
4-1. Explain why a change request for which no response was received must be treated as “unknown outcome” rather than “failure,” and list the steps to take in an unknown outcome state in order.
4-2. Name two pieces of information that must be checked in addition to the HTTP status code when deciding whether to retry automatically, and give one example for each where it alters the decision.
4-3. Explain how token bucket rate limiting differs from the fixed-time reset method, and explain why rejections occur even when the total volume per minute is within the limit.
4-4. Define connection timeout, idle timeout, and overall deadline respectively, and explain why an idle timeout is better than a single request timeout for long generation requests.
4-5. Describe the information that the receiver of an idempotency key (payment or reservation server) must store, and how to handle a request that arrives with the same key but different contents.
4-6. A single LLM API is shared by three features: real-time consultation, document summarization, and overnight analysis. Design a table specifying the retry budget, concurrency limit, timeout, and failure behavior for each feature.
Hands-on tasks
Exercise
Fault injection retry wrapper (60 minutes)
- Create a layer that inserts mock responses in front of model calls. Randomly mix 429 with
retry-after, transient 429 without headers, 429 with a spending limit error code, 529, 500, and 400. - Implement the decision table and backoff function from this chapter, and disable automatic SDK retries. Set budgets for the number of attempts, total wait time, and retry ratio.
- Send 100 requests and aggregate the retry counts by error type, final outcomes, and the actual number of deliveries per request.
Done when: 400 and 429 with a spending limit error code are never retried, the rest either recover within budget or fall back to an alternate path, and the maximum number of deliveries per request does not exceed the designed value.
Exercise
Pipeline with checkpoints and idempotent storage (60 minutes)
- Create a job that processes 30 documents one by one with a model and stores them. Record the status of each document (pending, in progress, completed, failed, quarantined) in a file or database.
- For storage, use
(document ID, processing run)as the idempotency key so that if the same key arrives again, the existing result is returned. - Make two documents always produce non-retryable errors so they are sent to a quarantine queue, forcefully terminate the process while processing the 15th document, and then rerun it.
Done when: After rerunning, completed documents are not reprocessed, there are no duplicate results in storage, and the two quarantined documents are listed along with their reasons.