Reliability and Cost Engineering › Idempotency: Making Retries and Replays Safe
Language AI HandbookAll chapters An operation is idempotent if repeated identical requests have the same intended effect as one request. HTTP specifies that GET is idempotent. A charge endpoint can apply the same payment again unless it deduplicates the logical operation. Hidden mutations matter too, such as an email send or a write to conversation memory.
A repeated generation may produce different text and incur a second charge. Persist and replay the accepted result when your application requires the same answer.
An idempotency key identifies a logical operation. Use the same key for each retry, scope it to the caller, and check that a reused key carries the same operation parameters. While a valid record is retained, the service can replay the stored result.
The one-process demonstration below serializes duplicate calls using a per-key lock. Its guarantee is limited to callbacks that complete and whose result is recorded in the live process.
PythonIn [12]Expand
import threading
class IdempotentExecutor:
"""Deduplicates side effects by idempotency key.
Concurrent duplicate keys block on a per-key lock so the
first recorded result is reused."""
def __init__(self):
self._results = {} # key -> result
self._locks = {} # key -> Lock
self._guard = threading.Lock()
self.executions = 0 # count of successfully recorded callbacks
def _lock_for(self, key):
with self._guard:
if key not in self._locks:
self._locks[key] = threading.Lock()
return self._locks[key]
def run(self, key, side_effect):
lock = self._lock_for(key)
with lock:
if key in self._results:
return self._results[key], "cached"
result = side_effect() # the thing we must not repeat
self._results[key] = result
with self._guard:
self.executions += 1
return result, "executed"The per-key lock keeps two calls from observing a missing result for the same key at once. The short guard protects the lock registry. Different keys can execute their callbacks concurrently.
PythonIn [13]Expand
executor = IdempotentExecutor()
side_effect_calls = {"n": 0}
counter_lock = threading.Lock()
def charge_once():
with counter_lock:
side_effect_calls["n"] += 1
return {"charged": True, "amount_cents": 4200}
# 16 concurrent attempts, all with the SAME logical key.
key = "ord-77123-charge"
threads = [
threading.Thread(target=lambda: executor.run(key, charge_once))
for _ in range(16)
]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"threads: 16, same key")
print(f"side effects actually executed: {side_effect_calls['n']}")
print(f"executor.executions: {executor.executions}")
print(f"stored result: {executor._results[key]}")ConsoleOut [13]Expand
threads: 16, same key
side effects actually executed: 1
executor.executions: 1
stored result: {'charged': True, 'amount_cents': 4200}The sixteen submitted threads share one key and produce one recorded execution. The other calls replay that result.
A process crash can erase the in-memory record after the outside operation commits. A callback can also fail after committing its effect. Use a durable idempotency record and make local mutations atomic with that record. For an external charge, reuse the key at the provider if its API supports it and reconcile uncertain outcomes. A local lock cannot make the provider commit and local record write atomic. The Amazon Builders' Library walks through this failure boundary.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!