A retried LLM request after a timeout or 5xx must not double-charge, double-send or repeat a tool action the model already triggered, and idempotency keys are what make that possible.
Idempotency keys and backoff on re-issued requests
Wrap each call in exponential backoff with jitter. On a 429 status, which means too many requests, honor the Retry-After header before trying again. Attach an idempotency key, a unique identifier for the request, so that downstream effects such as database updates or external API calls can be tracked and not repeated.
Results can also be cached by a hash of the request. If a generation is retried with identical input, the cached answer comes back immediately and costs nothing extra.
- Attach an idempotency key to requests.
- Use exponential backoff with jitter.
- Cache results by request hash.
- Use upsert for side-effecting tools.
- Avoid naive retries on irreversible actions.
Why the deduplication key comes from the input
The discipline resembles idempotent HTTP PUT requests and at-least-once message queues: repeating an operation must not create unintended copies. One difference matters. The message here is nondeterministic, so a retried generation can return different text each time.
Because the output varies, the key must be built from the input. A key built from the output would produce several entries for one input, which defeats its purpose.
Making tool calls safe to repeat
When the model re-emits the same tool call after a partial failure, the tool should create the record once or update the existing one. Use upsert on a natural key in place of a plain insert.
A naive retry loop is the tempting shortcut, and it can re-run send_email or charge_card. The result is multiple charges or spam. The assumption that a retry on error is safe is the root problem. Idempotency keys track the request and its effects, so only one action happens.
Retry policy by task type
| Task type | Retry approach | Reason |
|---|---|---|
| Pure text generation | Retry freely, cache by input hash | No side effects, and the cache cuts cost. |
| Agents that call APIs or modify databases | Idempotency keys on every call | Repeats would duplicate the action. |
| Irreversible actions | Gate behind a confirmation step, no auto-retry | A repeat cannot be undone. |
Example scenario: 15% of calls are retried after 5xx errors
The likely cause is a system that does not track the state of requests, so a retry runs the same action again. A request that is not idempotent can trigger a second effect from the same input.
- Check request logs to see whether the first request was recorded before the error.
- Verify that the retry reuses the identifier of the original request.
- Inspect application logic to confirm duplicate processing is blocked on retries.