Retries, timeouts and idempotence
When a response disappears
In the bookstore, checkout request order-41 reaches the server at 0 ms; the server commits at 80 ms; the response is lost. At 200 ms the client times out. Sending the same request again without coordination could create a second order. A timeout does not cancel remote work by itself. Retrying is appropriate for a transient failure only when the operation is safe to repeat or supports a verified idempotency contract. A permanent validation or authorization error should stop; an ambiguous outcome may need a status lookup or reconciliation. Follow documented provider and SDK semantics rather than classifying errors only by HTTP number.
Bound attempts, time and load
An attempt timeout limits waiting for an individual call; an overall deadline includes all attempts and delays. Budget connection, DNS, TLS and application processing according to the actual client implementation. Set timeout using observed latency, a tolerable false-timeout rate and the upstream deadline. Exponential backoff grows the wait; full jitter chooses a random delay between zero and a capped exponential bound. For base 100 ms, cap 250 ms, the first three bounds are 100, 200 and 250 ms. With three total attempts, only two waits can occur. The offline fixture uses half the bound as a deterministic stand-in, not random jitter. Three attempts consuming 200 ms each plus waits 50 and 100 ms use 750 ms. A 650 ms deadline cannot fit the third full attempt. Stop before starting an attempt that cannot fit. In production, pass remaining time downstream and use cancellation where supported, while remembering that cancellation may race with commit. Respect Retry-After within the deadline. Three attempts at each of three independent retry layers can cause 27 downstream calls; assign a retry owner or shared budget rather than multiplying retries. See AWS SDK retry behavior and Azure transient faults.
Use idempotency and event revisions
Idempotence means repeating an operation has the same intended effect as executing it once. It does not mean the underlying code executes only once. For checkout, scope an idempotency key to caller, operation and logical request; store a payload fingerprint and result durably. A matching retry returns the prior outcome; a reused key with a different payload is rejected. Store the key and business mutation atomically, or use a recoverable workflow when crossing transactional boundaries. Concurrent retries require uniqueness or conditional writes. Keep keys long enough for the expected retry and replay horizon; expiry changes the guarantee. External payments or messages need their own idempotency contract and reconciliation. Never include personal data or secrets in a key. See AWS idempotent APIs. Spanner's transaction guide warns about repeated external effects from transaction retries.
For read-model updates, each event in the next example is an authoritative complete stock snapshot for one item, numbered by one trusted producer. A newer snapshot can safely supersede an earlier one; a delta event such as subtract one cannot use this strategy because skipping a version may lose a mutation. For deltas, deduplicate event IDs and enforce sequence or recover missing events before applying. Equal revision with a different value is a conflict requiring investigation. Acknowledgement should follow durable processing, not precede it.
Circuit breakers and backpressure
A circuit breaker normally permits calls (closed), rejects or redirects them when a configured failure threshold is reached (open), and after a recovery interval permits limited probes (half-open). Close after successful probes, reopen on failure. Thresholds, time windows and probe limits depend on traffic and dependency behavior. A breaker protects a failing dependency; it does not repair it or authorize returning incorrect inventory. Backpressure signals that the consumer cannot accept more work: cap concurrent requests and queue length, throttle producers, or shed optional traffic. If arrival is 120 messages/s and processing is 100 messages/s, a fluid model accumulates 20 messages/s; with 600 messages of spare buffer, that fills in 30 seconds. When input falls to 80/s, a 600-message backlog drains in 30 seconds if capacity remains 100/s. Real queues have burstiness and varying processing times; monitor oldest message age, failure rate and queue depth. Do not allow unbounded queues or retry storms. See Azure circuit breaker and rate limiting.
Run the deterministic model locally
Save the following as distributed_demo.py and run python distributed_demo.py with Python 3. No network, packages, accounts or credentials are required. The inputs are trusted synthetic integers and strings, and attempt durations are fixed. The function returns attempt count, elapsed milliseconds and decision. The snapshot and fencing functions are pure state transitions; they deliberately omit persistence, authentication, synchronization, leases and real failure detection. The caller must enforce positive timing parameters and valid event shape in a real implementation. A fencing token equal to the last accepted token is allowed here because one lease owner may perform multiple writes; operation deduplication is separate.
def retry_plan(outcomes, deadline=1000, timeout=200, base=100, cap=250, max_attempts=3): # Each mock outcome consumes a full attempt timeout. # Deterministic half-window jitter is for this fixture only. elapsed, attempts = 0, 0 for outcome in outcomes[:max_attempts]: if elapsed + timeout > deadline: return attempts, elapsed, "DEADLINE" attempts += 1 elapsed += timeout if outcome == "ok": return attempts, elapsed, "OK" if outcome != "transient": return attempts, elapsed, "STOP" if attempts == max_attempts: return attempts, elapsed, "EXHAUSTED" wait = min(cap, base * 2 ** (attempts - 1)) // 2 if elapsed + wait + timeout > deadline: return attempts, elapsed, "DEADLINE" if attempts < len(outcomes): elapsed += wait return attempts, elapsed, "UNKNOWN"
def apply_snapshot(state, event): # state = (revision, stock); event is a complete snapshot. version, stock = event if version < 1 or stock < 0: return state, "INVALID" if version < state[0]: return state, "STALE" if version == state[0]: return state, "DUPLICATE" if stock == state[1] else "CONFLICT" return (version, stock), "APPLIED"
def fenced_write(last_token, token): return (last_token, "REJECT") if token < last_token else (token, "ACCEPT")
print(retry_plan(["transient", "transient", "ok"]))state = (1, 10)for event in [(3, 8), (3, 8), (2, 9), (3, 7)]: state, result = apply_snapshot(state, event) print(state, result)print(fenced_write(8, 7))Expected output:
(3, 750, 'OK')(3, 8) APPLIED(3, 8) DUPLICATE(3, 8) STALE(3, 8) CONFLICT(8, 'REJECT')The first line uses three attempts and two waits. Version 3 is applied before version 2 arrives, so version 2 is stale. Repeating version 3 with identical stock does not change it; differing stock at version 3 is a conflict. Token 7 cannot overwrite a write accepted under token 8.
Practice and diagnose
Change the deadline to 650 ms: after two attempts and a 50 ms wait, 450 ms has elapsed. The next 100 ms wait plus 200 ms attempt would exceed the deadline, so the result is (2, 450, 'DEADLINE'). Try a permanent outcome, duplicate and out-of-order snapshots, and a negative stock value. In a real incident, correlate operation IDs, attempt counters, deadline expiry, deduplication hits, version conflicts, replica lag, breaker state, and queue age. Record whether a response failed or the effect is known to have failed. Escalate unresolved financial or inventory integrity ambiguity instead of blindly replaying. This is a reasoning model, not an implementation of a database, consensus protocol, production retry client or lock manager.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Retries, timeouts and idempotence — knowledge check
Choose the best answer for each offline scenario.
After a checkout timeout, what is known?
With three total attempts per layer at three nested layers, what is the worst-case downstream count?
What should happen when an idempotency key is reused with a different payload?
For the snapshot model, current revision 3 and incoming revision 2 mean what?
What is the purpose of the half-open breaker state?