Sub topic 9
When Is a Retry Safe? Idempotency and Side Effects
Earlier chapters covered which errors are worth retrying and how to space the retries. This chapter covers a different question: even when an error is retryable, is it safe to send the request again? The answer depends on what the request did before it failed.
This chapter assumes you can write Python functions and exceptions, you know HTTP methods and status codes, and you have called an LLM API with an SDK or an HTTP client.
Why a failed request is not always an unprocessed request
When a call fails, you know only what your client observed. You do not know what the server did. A read timeout shows the problem. The server may have received your request, generated the full answer, and charged your account. Only the response was lost on the way back.
There are three possible states after a failure:
- The request never reached the server.
- The server rejected it before doing any work.
- The server did the work, but you never saw the result.
Retrying is harmless in the first two states. In the third state, a retry repeats the work. For a plain text completion, that costs a little money and time. For an operation that sends an email or charges a card, it can cause real damage.
Idempotency in plain terms
An operation is idempotent if running it several times has the same effect on the system as running it once. Setting a value to 5 is idempotent. Adding 1 to a counter is not.
HTTP defines GET, PUT, and DELETE as idempotent. POST is not, and almost every LLM API call is a POST. That does not make LLM calls dangerous to retry. The call itself changes nothing in your systems, so the risk comes from what your code does with the result.
Two kinds of work in an LLM application
Separate the model call from the actions around it.
- The model call. It reads a prompt and returns text. A duplicate wastes tokens and counts against your rate limits, but it creates no lasting change in your own systems. It is safe to retry.
- Side effects. These are actions that change state somewhere: writing to a database, sending a message, calling a payment API, or running a tool the model requested. A duplicate changes the outcome.
A useful rule is to retry the model call freely and protect side effects separately. Keep them in different functions so a retry loop around the model call never contains an action.
What each failure tells you
The following table lists what you can infer from common failures.
| Failure | Did the server act? | Safe to retry without a key? |
|---|---|---|
| Connection refused, DNS failure, connect timeout | No, the request was never delivered | Yes |
| 429 Too Many Requests | No, it was rejected for rate limiting | Yes |
| 400, 401, 404 | No, it was rejected | Retrying cannot help |
| 500, 502, 503, 504 | Unknown | Safe for the model call. Uncertain for side effects |
| Read timeout | Possibly yes | Safe for the model call. Uncertain for side effects |
| Connection dropped mid-response | Possibly yes | Safe for the model call. Uncertain for side effects |
The status codes 500 to 504 and the read timeout are the ambiguous ones. A gateway returns 504 when it gave up waiting for a backend that may still be running.
Encoding the decision in code
This function captures the table. It decides only whether a retry is safe. The error classification from earlier chapters still decides whether a retry is useful.
import httpx
# These errors mean the request was never delivered to the server.
NEVER_SENT = (httpx.ConnectError, httpx.ConnectTimeout)
def safe_to_retry(error_or_status, has_side_effects: bool, has_idempotency_key: bool) -> bool:
"""Return True if sending the request again cannot cause a duplicate effect."""
if not has_side_effects or has_idempotency_key:
return True
if isinstance(error_or_status, NEVER_SENT):
return True
if error_or_status == 429:
return True
return False
print(safe_to_retry(503, has_side_effects=False, has_idempotency_key=False))
print(safe_to_retry(503, has_side_effects=True, has_idempotency_key=False))
print(safe_to_retry(503, has_side_effects=True, has_idempotency_key=True))
print(safe_to_retry(httpx.ConnectError("refused"), True, False))
print(safe_to_retry(httpx.ReadTimeout("slow"), True, False))The output is True, False, True, True, False.
Idempotency keys
An idempotency key is a unique string that the client attaches to a request. The server remembers the key. If the same key arrives again, the server returns the original result instead of repeating the work. Many payment and messaging APIs support this through a header, commonly Idempotency-Key.
Check your provider's documentation before relying on this for LLM calls. Support varies, and you should not assume a header is honored unless the docs say so. Where it is not supported, you can still apply the same pattern to the actions your application performs after the model responds.
Protecting side effects triggered by a model
Agents and tool-calling applications are where this matters most. The model asks you to run a function such as create_ticket, and your code runs it. If a failure occurs after the tool ran but before the conversation was saved, a retry of the whole step runs the tool again.
Two details affect how you build the key.
- The tool call ID the model returns is not a stable identity. If you retry the model call, you get a new response with new IDs.
- Derive the key from the business intent instead: the ID of the user's request, the tool name, and the canonical form of the arguments.
import hashlib
import json
def make_key(request_id: str, tool_name: str, args: dict) -> str:
"""Build a stable key from the intent of the action, not from model output IDs."""
canonical = json.dumps(args, sort_keys=True, separators=(",", ":"))
raw = f"{request_id}|{tool_name}|{canonical}"
return hashlib.sha256(raw.encode()).hexdigest()[:32]
class ActionStore:
"""Runs each action at most once per key. Replace the dict with a database table in production."""
def __init__(self):
self._done = {}
def run_once(self, key, action):
if key in self._done:
return self._done[key]
result = action()
self._done[key] = result
return result
tickets = []
def create_ticket(title: str) -> dict:
tickets.append(title)
return {"ticket_id": len(tickets)}
store = ActionStore()
key = make_key("req-42", "create_ticket", {"title": "Printer jam"})
first = store.run_once(key, lambda: create_ticket("Printer jam"))
second = store.run_once(key, lambda: create_ticket("Printer jam"))
print(first, second, len(tickets))The output is {'ticket_id': 1} {'ticket_id': 1} 1. The second call returns the saved result and creates no second ticket.
The sort_keys=True argument matters. Without it, two dictionaries with the same content but a different key order produce different hashes, and the guard fails silently.
Partial results and streaming
A stream that breaks halfway leaves you with partial output. Retrying restarts generation from the beginning, and the model may produce different text. Do not append the new response to the partial one. Either discard the partial text or keep it only for display until the new attempt completes. Do not run side effects on partial output. Wait for the complete, validated response first. A later chapter covers streaming failures in detail.
Output varies between attempts
LLM output is not deterministic, even for the same prompt. A retry can return a different answer than the lost one. This matters in two situations:
- If your workflow compares or merges results from separate attempts, they may disagree.
- If an earlier attempt succeeded server-side and its action ran, the retried response may choose a different action.
Handle this by tying the action to the request ID, as in the key above, and not to the text of any one response.
Common mistakes
- Wrapping the model call and the tool execution in one retry loop. Each retry then repeats the tool.
- Treating every timeout as proof that nothing happened.
- Building keys from random values such as a fresh UUID per attempt. A new key on each attempt defeats the purpose.
- Using the model's tool call ID as the key, which changes on every new response.
- Assuming an SDK adds idempotency protection. SDK retries repeat the request, and they do not make your own actions safe.
Exercise
Your support agent calls an LLM, which asks for a refund_customer tool. The tool call succeeds, but your service times out while saving the conversation, and the whole step is retried. The model returns a new response with a new tool call ID that asks for the same refund. Describe how you would prevent a double refund, and say which value you would not use for the idempotency key.
Show answer
Derive the key from stable business inputs: the original request ID, the tool name refund_customer, and the canonical arguments (customer and amount, serialized with sorted keys). Check the key in a database table with a unique constraint before running the refund, and pass the key to the payment API if it supports one. On the retry, the same key finds the saved result and returns it without refunding again. Do not use the tool call ID from the model, because the retried response has a new one and the guard would miss the duplicate.