Sub topic 9
When Is a Retry Safe? Idempotency and Side Effects
This chapter assumes you can already classify errors as retryable or permanent and have written a basic retry loop. Here you decide whether repeating a request is harmless.
Why a retry can be unsafe
A retry sends the same request again. That is safe only if the second request cannot cause a different effect than the first. An operation is idempotent if running it many times leaves the system in the same state as running it once.
A plain LLM completion call is mostly safe to repeat. It reads a prompt and returns text. The worst outcome is paying for tokens twice. The risk grows when your code does more than ask for text:
- The model calls a tool that sends an email, charges a card, or writes a database row.
- Your code saves the result of the call before the failure is known.
- The request starts a long-running job on the provider's side.
The core difficulty is that a timeout does not tell you whether the server did the work. The request may have failed before it arrived, or it may have finished and the response was lost on the way back.
Separate the model call from the side effect
Retrying the model call is usually fine. Retrying the action that follows needs care. Keep the two apart in your code, so the retry loop wraps only the call that is safe to repeat.
def generate_reply(call_model, prompt):
"""Safe to retry: no side effects, only a paid generation."""
return call_model(prompt)
def send_reply(send_email, address, text, sent_ids, message_id):
"""Not safe to retry blindly: guard it with a stable ID."""
if message_id in sent_ids:
return "already sent"
send_email(address, text)
sent_ids.add(message_id)
return "sent"
sent = set()
log = []
fake_send = lambda to, body: log.append((to, body))
print(send_reply(fake_send, "[email protected]", "Hi", sent, "msg-1"))
print(send_reply(fake_send, "[email protected]", "Hi", sent, "msg-1"))
print(len(log))The second call returns already sent, and the log holds one entry. The ID is created once, before the first attempt, and reused on every retry. In production, keep these IDs in a database, not in memory, so they survive a restart.
Idempotency keys
Many APIs let you attach an idempotency key, a unique string you generate per logical operation. The server stores the result under that key. If the same key arrives again, it returns the stored result instead of repeating the work. Create the key once, outside the retry loop. A new key per attempt defeats the purpose.
Support varies by provider, so check the documentation of the API you use. Do not assume that a completion endpoint deduplicates requests.
Partial results
If a response fails halfway, as in a stream, you may hold part of the output. Decide whether to discard it and start over, or keep it. Discarding is simplest and avoids duplicated text. Streaming failures get their own chapter.
A decision checklist
| Question | If yes |
|---|---|
| Does the call only read or generate text? | Retry freely, within limits. |
| Does it trigger a payment, message, or write? | Use a stable ID or idempotency key before retrying. |
| Can you not tell whether the first attempt succeeded? | Check the state first, or use a key. |
| Is the effect impossible to deduplicate? | Surface the error and let a person decide. |
Exercise
A request that charges a customer times out. Your retry loop sends it again with a new random key each time. Why is this wrong, and what is the fix?
Show answer
A new key per attempt makes each retry look like a separate operation, so the customer can be charged more than once. Generate one key per logical charge before the loop starts and send the same key on every attempt.
Exercise
Why can a timeout not tell you whether the server did the work?
Show answer
The request may have been lost before reaching the server, or the server may have finished and the response was lost on the way back. Both look like silence to the client.