AI Hints
Home›System Design Tutorial›Safe Retries and API Styles
System Design · Lesson 19 of 120

Idempotency

Safe to retry.

⏱ 2 min read▶ Video at 21:29🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Idempotency
From the video: Idempotency
  • 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.

idem.pypython
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))
Output
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
Next up: GraphQL and gRPC — other API styles