Sub topic 11
Idempotency and Safe Retries
This chapter assumes you know basic HTTP APIs, how DNS-based failover moves traffic between regions, and what asynchronous replication means. It covers how to make operations safe to repeat, which matters because active-active systems retry constantly.
Why retries are unavoidable
In a multi-region system, a client often cannot tell whether a request succeeded. A timeout can mean any of these:
- The request never arrived.
- The request was applied, but the response was lost.
- The request is still running and will finish later.
After a regional failover, the client retries against another region. If the first region already applied the operation, a naive retry charges a card twice, ships two orders, or sends two emails.
Messaging adds a second source of repeats. Most cross-region queues and event streams offer at-least-once delivery. A consumer will see some messages more than once. Exactly-once delivery across regions is not something you can assume, so the receiving code must tolerate duplicates.
What idempotent means
An operation is idempotent if running it several times has the same effect as running it once. Some operations are naturally idempotent:
PUT /users/7/emailwith a fixed value. Repeating it leaves the same state.DELETE /orders/42. After the first call the order is gone, and later calls change nothing.- Setting a field to an absolute value, such as
status = "shipped".
Others are not:
POST /paymentscreates a new payment on every call.balance = balance + 10adds 10 on every call.- Appending a row to a log.
The fix for non-idempotent operations is to attach an identity to each logical request, then record that identity when the work is done.
Idempotency keys
An idempotency key is a unique identifier that the client generates once per logical operation and reuses on every retry of that operation. The server stores the result under that key. When the same key arrives again, the server returns the stored result instead of repeating the work.
processed = {} # in production this must be a durable store visible to the handling region
def handle_once(request_id, apply):
"""Run apply() at most once per request_id and return the stored result on retries."""
if request_id in processed:
return processed[request_id]
result = apply()
processed[request_id] = result
return result
print(handle_once("req-42", lambda: "charged")) # charged
print(handle_once("req-42", lambda: "charged")) # charged, not applied twiceThis example works in one process. The comment in the code names the real requirement: the key store must be visible to whichever region handles the retry. If region A records the key and region B cannot see it, a retry that lands in B runs the operation again.
Rules for good keys
- The client generates the key, not the server. A server-generated ID does not exist yet when the first response is lost.
- Use a random value such as a UUID, or a stable business identifier such as an order ID plus an action name.
- Reuse the same key for every retry of one logical operation. Use a new key for a new operation.
- Bind the key to the request contents. If the same key arrives with a different payload, reject it with an error such as HTTP 422. Otherwise a bug in the client can silently return the wrong stored result.
- Expire keys after a retention window, for example 24 hours, longer than any realistic retry period.
Where the key store lives
The hardest design decision is where to keep processed keys. Each choice has a different failure mode.
| Key store design | Duplicate protection across regions | Cost and risk |
|---|---|---|
| Local to each region | None. A retry in another region repeats the work. | Fast and simple, but unsafe after failover. |
| Replicated asynchronously | Partial. A retry arriving before replication catches up repeats the work. | Fast writes, with a window of exposure equal to replication lag. |
| Synchronously replicated or single-owner | Strong. | Adds cross-region latency to every write, or ties the key to one region. |
| Stored in the same transaction as the business data | Strong, within whichever database owns that data. | Needs the data and the key in one datastore. |
The last row is usually the best option. If the key record and the business change commit in one transaction, either both exist or neither does. There is no state where the work happened but the key is missing.
Combine this with write ownership from the earlier chapter. If one region owns a given customer's data, route that customer's writes and their key checks to the owning region. Then the key store and the data cannot disagree.
Making the check atomic
A common bug is a check-then-act race. Two retries arrive at nearly the same time. Both check, both find no key, and both apply the operation.
The key insert must be an atomic operation that fails if the key exists. In a relational database, use a unique constraint.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE payments (id INTEGER PRIMARY KEY, amount INTEGER)")
db.execute("CREATE TABLE idempotency (key TEXT PRIMARY KEY, payment_id INTEGER)")
def charge(key, amount):
try:
with db: # one transaction: both inserts commit, or neither does
cur = db.execute("INSERT INTO payments (amount) VALUES (?)", (amount,))
db.execute(
"INSERT INTO idempotency (key, payment_id) VALUES (?, ?)",
(key, cur.lastrowid),
)
return cur.lastrowid
except sqlite3.IntegrityError:
# Key already exists: return the earlier result instead of charging again
row = db.execute(
"SELECT payment_id FROM idempotency WHERE key = ?", (key,)
).fetchone()
return row[0]
print(charge("req-42", 500)) # 1
print(charge("req-42", 500)) # 1, same payment returned
print(db.execute("SELECT COUNT(*) FROM payments").fetchone()[0]) # 1The primary key on idempotency.key rejects the second insert. The with db: block rolls back the duplicate payment row, so only one payment exists. In a NoSQL store, use a conditional write such as "put if not exists".
In-flight requests
A retry can arrive while the first attempt is still running. The server needs a third state besides "never seen" and "done".
- On the first arrival, insert the key with status
in_progress. - When the work finishes, update the record to
completedand store the response. - If a retry sees
in_progress, return a conflict response such as HTTP 409, or make it wait briefly. Do not start a second run. - Give
in_progressrecords a timeout. If the worker crashes, a record stuck in this state would block retries forever.
The timeout creates a trade-off. A short timeout may let a slow but alive worker run in parallel with its replacement. A long timeout delays recovery. Pick a value above the longest normal processing time.
Idempotent message consumers
The same idea applies to event consumers. Each message carries a unique ID, set by the producer. The consumer records the IDs it has handled and skips repeats.
Consumer pattern: check the message ID, apply the effect, record the ID, all in one transaction.Because Mermaid diagrams must follow a fixed format, the flow is shown below.
Two details matter here:
- Record the ID in the same transaction as the effect. If you record it first and crash before applying the effect, the message is lost. If you apply first and crash before recording, the message is applied twice.
- Make effects idempotent where you can. Setting
status = "shipped"survives a duplicate even if the ID check fails.
Retry behavior on the client
Idempotency makes retries safe. It does not make them free. Poorly tuned retries can overload a region that is already struggling, which is especially dangerous after a failover when surviving regions absorb the extra load.
- Use exponential backoff. Wait longer after each failure, for example 100 ms, 200 ms, 400 ms.
- Add jitter, a random offset on each wait. Without it, thousands of clients retry at the same moment.
- Cap the number of attempts and the total time.
- Retry only errors that can be transient, such as timeouts and 503 responses. Do not retry a 400 validation error.
Common errors
- Key store not shared across regions. Duplicates appear only during failover, so normal testing misses them.
- Server-generated keys. The client has nothing stable to reuse on retry.
- Check-then-insert without a unique constraint. Concurrent retries both pass the check.
- Recording the key outside the business transaction. A crash between the two steps leaves data and key disagreeing.
- External side effects. An email or a call to a payment provider is not covered by your database transaction. Pass your idempotency key to the downstream service when it supports one.
- Keys that expire too early. A retry after expiry is treated as new work.
- Ignoring payload mismatch. Reusing a key for a different request returns a wrong cached answer.
Limits of the pattern
An idempotency key prevents repeated effects for the same logical request. It does not resolve two different requests that conflict, such as two users editing the same record from different regions. That is the job of write ownership and conflict resolution, covered in earlier chapters. The two techniques work together: idempotency handles duplicates, and conflict resolution handles concurrent but distinct writes.
Exercise
A client sends POST /payments with key "k1" to region A. Region A charges the card, but the response times out. The client fails over and retries with key "k1" against region B. Asynchronous replication of the key store has a lag of 2 seconds, and the retry reaches region B after 300 ms. What happens, and name two designs that prevent the duplicate charge?
Show answer
Region B does not yet have key "k1", so it treats the request as new and charges the card a second time. Two fixes: (1) route all writes and key checks for that customer to the region that owns the data, so the retry goes to region A or a synchronous owner, and (2) store the key in the same transaction as the payment in a datastore that is synchronously replicated or single-owner, so region B sees the key before it can act. Passing the key to the payment provider as its own idempotency key also protects against the duplicate charge.
Exercise
Why must the consumer of a cross-region event record the message ID in the same transaction as the effect, and not before or after it?
Show answer
If the ID is recorded first and the consumer crashes before applying the effect, the redelivered message is skipped and the effect is lost. If the effect is applied first and the consumer crashes before recording the ID, the redelivered message is applied again. A single transaction makes both steps succeed or fail together.