Sub topic 11
Idempotency and Safe Retries
This chapter assumes you know basic DNS and load balancing, how stateless services work, and the cross-region replication and messaging ideas from the earlier chapters. Here you will see why retries are unavoidable in an active-active system and how to make them safe.
Why retries happen
In a multi-region system, a client often cannot tell whether a request succeeded. A timeout, a failover, or a duplicate message delivery all leave the same doubt. The client retries, and the operation may run twice.
An operation is idempotent if running it many times has the same effect as running it once. Setting a value is idempotent. Adding 10 to a balance is not. Most message systems offer at-least-once delivery, so duplicates will happen and the consumer must cope.
Idempotency keys
The client generates a unique key for each logical operation and sends it with every attempt. The server records the key with the result. A repeat request with a known key returns the stored result and skips 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 twiceThe comment in the code matters most. A key store local to one region does not protect a retry that lands in another region.
Common errors
- Key store not shared across regions. After a failover, the retry reaches a region that has never seen the key and applies the operation again. Replicate the key store, or route all requests for a given key to one owner region.
- Replication lag on the key. Even a replicated store may not yet hold the key when the retry arrives. For money or other irreversible effects, check the key with a strongly consistent write, or accept a small risk and add reconciliation.
- Check and apply are not atomic. The code above has a race. Two concurrent retries can both pass the
incheck. In production, insert the key with a conditional write (for example, "insert if absent") before doing the work. - Keys generated per attempt. If the client creates a new key on each retry, the server sees different requests. Generate the key once per logical operation.
- Keys kept forever or too briefly. Keep keys longer than the longest realistic retry window, and expire them after that.
- Different payload, same key. Store a hash of the request and reject a reuse of the key with a different body.
Safe retry practice
Retry only idempotent operations, or operations that carry a key. Use exponential backoff with random jitter so many clients do not retry in lockstep against a recovering region. Set a retry limit and a total deadline.
On the consumer side of a queue, apply the same idea: record each message ID and skip IDs already handled. Alternatively, design the operation itself to be naturally idempotent, such as "set status to shipped" instead of "advance status".
Exercise
A client charges a card in region A. The reply is lost, so the client retries and the request reaches region B. Region B charges the card again. Give two likely causes and one fix for each.
Show answer
Cause 1: the idempotency key store is local to region A, so region B never saw the key. Fix: use a key store replicated across regions, or route by key to one owner region. Cause 2: the key was replicated but had not arrived at region B yet because of replication lag. Fix: write the key with a strongly consistent, conditional write before applying the charge, or add reconciliation to detect and refund duplicates.