Lesson 63.2 · 2 of 4 · 5 min read · Reviewed 24 Nov 2026
Retries and idempotency
By the end, you can
- Retry failed calls safely.
- Make side-effecting actions idempotent.
Which errors to retry
| Error | Retry? |
|---|---|
| 429 rate limited | Yes, after the retry-after time |
| 500, 529 overloaded, timeouts | Yes, with backoff |
| 400 invalid request | No, fix the request |
| 401/403 auth | No, fix credentials |
Use exponential backoffExponential backoff: Waiting longer after each failed retry, for example 1, 2, 4 then 8 seconds. with jitterJitter: Randomness added to retry delays so clients do not all retry at the same instant.: wait 1s, 2s, 4s… plus a random amount, up to a cap. That stops many clients retrying in lockstep. The Playground’s failure lab shows a retry storm and its fix.
The danger: repeated side effects
A timeout doesn’t tell you whether the action happened. Retrying “issue refund” might refund twice.
Idempotency
Send a unique idempotency keyIdempotency key: A unique id sent with a write request so the server can ignore duplicate retries of the same request. with each action, for example derived from the ticket and step. The receiving service stores the key and returns the original result if it sees it again. Design your own tools this way too:
issue_refund(order_id, amount, idempotency_key="T-8812-refund-1")
Agent-level retries
If the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. itself retries a tool after an error, the same rule applies. Tools with side effects must be safe to call twice.
Key points
- Retry transient failures (429, 500, 529, timeouts) with exponential backoff and jitter; don't retry invalid requests.
- Retrying an action with side effects can repeat it: two refunds instead of one.
- Use idempotency keys so a repeated request has the same effect as one.
Make a refund tool safe to retry
Retry a timed-out refund with backoff and jitter without refunding the customer twice.
You will have: An issue_refund() function with backoff, jitter and an idempotency key, and output proving one refund for three calls.
Steps
- Run the starter: three calls, three refunds, because each timeout hid a success.
- Write backoff() as exponential growth with a cap plus seeded random jitter.
- Send an idempotency key built from the ticket and step on every attempt.
- Re-run and compare the number of calls with the number of refunds.
Done when
- The output shows 'calls made: 3' and 'refunds issued: 1'.
- The waits grow with each attempt and are not identical round numbers.
Open in the Playground No API key needed.
Starter code (Python)
import random
rnd = random.Random(7)
# A simulated refund service. The first two calls time out AFTER the refund was applied.
LEDGER = [] # refunds actually issued
SEEN = {} # idempotency key -> result, kept by the service
calls = {"n": 0}
class Timeout(Exception):
pass
def refund_service(order_id, amount, idempotency_key=None):
calls["n"] += 1
if idempotency_key and idempotency_key in SEEN:
result = SEEN[idempotency_key] # seen before: return the original result
else:
LEDGER.append((order_id, amount))
result = {"refund_id": f"r-{len(LEDGER)}", "amount": amount}
if idempotency_key:
SEEN[idempotency_key] = result
if calls["n"] <= 2:
raise Timeout("no reply within 10 s")
return result
def backoff(attempt, base=1.0, cap=8.0):
# TODO: exponential backoff with jitter: min(cap, base * 2**attempt) plus up to 50% random extra
return 0.0
def issue_refund(order_id, amount, max_tries=4):
# TODO: send an idempotency key derived from the ticket and step, e.g. f"T-8812-refund-1"
for attempt in range(max_tries):
try:
return refund_service(order_id, amount)
except Timeout:
print(f"timeout, waiting {backoff(attempt):.2f}s (simulated)")
raise RuntimeError("gave up")
print(issue_refund("A-1001", 40))
print("refunds issued:", len(LEDGER))
Show a solution
import random
rnd = random.Random(7)
# A simulated refund service. The first two calls time out AFTER the refund was applied.
LEDGER = [] # refunds actually issued
SEEN = {} # idempotency key -> result, kept by the service
calls = {"n": 0}
class Timeout(Exception):
pass
def refund_service(order_id, amount, idempotency_key=None):
calls["n"] += 1
if idempotency_key and idempotency_key in SEEN:
result = SEEN[idempotency_key] # seen before: return the original result
else:
LEDGER.append((order_id, amount))
result = {"refund_id": f"r-{len(LEDGER)}", "amount": amount}
if idempotency_key:
SEEN[idempotency_key] = result
if calls["n"] <= 2:
raise Timeout("no reply within 10 s")
return result
def backoff(attempt, base=1.0, cap=8.0):
wait = min(cap, base * 2 ** attempt)
return wait + rnd.uniform(0, wait * 0.5)
def issue_refund(order_id, amount, ticket="T-8812", step=1, max_tries=4):
key = f"{ticket}-refund-{step}"
for attempt in range(max_tries):
try:
return refund_service(order_id, amount, idempotency_key=key)
except Timeout:
print(f"timeout, waiting {backoff(attempt):.2f}s (simulated)")
raise RuntimeError("gave up")
print(issue_refund("A-1001", 40))
print("calls made:", calls["n"])
print("refunds issued:", len(LEDGER))
Do it Fix a retry storm in the failure lab in the Playground. No API key needed.