Idempotency
Safe to retry.
A customer clicks pay. The network is slow, so the app retries. Did we just charge them twice? An idempotent operation gives the same result, no matter how many times you repeat it.

- Pay, then a retry
- Charged twice?
- Same result every time
Which verbs are safe
Some operations are naturally idempotent. Get only reads. Put sets something to a value, so doing it twice changes nothing. Delete removes something, and removing it again is harmless. But post creates something new each time, so a retried post can create a duplicate order.
Idempotent
- GET: just readsPUT: set to a valueDELETE: gone is gone
Not idempotent
- POST: creates newRetry = duplicateNeeds protection
Idempotency keys
The fix is an idempotency key. The client makes a unique key for each payment, and sends it with every retry. The server remembers keys it has already handled. Run it. The same payment arrives three times, but the customer is charged only once.
processed = {}
charges = []
def pay(key, amount):
if key in processed:
return processed[key]
charges.append(amount)
result = f"charged {amount} (#{len(charges)})"
processed[key] = result
return result
for attempt in range(3):
print(f"attempt {attempt + 1}:", pay("order-7-pay", 30))
print("total charges:", len(charges))attempt 1: charged 30 (#1) attempt 2: charged 30 (#1) attempt 3: charged 30 (#1) total charges: 1
Summary
Idempotent operations are safe to retry. For creates and payments, use an idempotency key. Next, two other API styles you'll meet. GraphQL and g RPC.
Key takeaways- Retries happen
- GET, PUT, DELETE are safe
- POST needs a key