Idempotency
Idempotency means sending the same request more than once has the same effect as sending it once. The same request can arrive twice when a sender hears nothing back and sends it again.
One payment arrives twice, with no key
Nothing marks the second arrival as a repeat. The charge count is 2.
charges = []
def pay(amount):
charges.append(amount)
pay(20)
pay(20)
print("charges:", len(charges))The same payment with the same key
The receiver stores the key from the first arrival and ignores the repeat. The charge count is 1.
charges = []
stored = {}
def pay(key, amount):
if key in stored:
return stored[key]
charges.append(amount)
stored[key] = "paid"
return stored[key]
pay("pay-123", 20)
pay("pay-123", 20)
print("charges:", len(charges))
print("stored key:", list(stored)[0])Two different keys are two payments
A new key means a new request, so both payments go through. The charge count is 2.
charges = []
stored = {}
def pay(key, amount):
if key in stored:
return stored[key]
charges.append(amount)
stored[key] = "paid"
return stored[key]
pay("pay-123", 20)
pay("pay-124", 20)
print("charges:", len(charges))
print("stored keys:", len(stored))Example
plain_charges = []
plain_charges.append(20)
plain_charges.append(20)
keyed_charges = []
stored = {}
def pay(key, amount):
if key in stored:
return stored[key]
keyed_charges.append(amount)
stored[key] = "paid"
return stored[key]
pay("pay-123", 20)
pay("pay-123", 20)
print("without a key, charges:", len(plain_charges))
print("with the same key, charges:", len(keyed_charges))
print("stored key:", list(stored)[0])Key points
- Idempotency: Sending the same request again changes nothing beyond the first send.
- Duplicate arrival: The same request can arrive twice when a sender hears nothing back.
- Idempotency key: A unique value sent with a request, which the receiver stores and checks.
- Without a key: The receiver cannot tell a repeat from a new request, so it does the work again.
- With a key: The receiver sees the stored key and returns the first result instead of repeating the work.
In this example, the same payment arrives twice in both models. Without a key it charges 2 times, and with the same key stored it charges 1 time, so the counts are the whole difference.
Note
Idempotency matters most for requests that spend or change something, like a payment.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A payment request carrying key pay-123 arrives twice, and the receiver stores keys. How many times is the customer charged?