Design for Failure: Retries, Queues and Idempotency
Networks fail halfway, so every action that costs money or sends a message needs a bounded retry policy, an idempotency key and a queue that tolerates duplicate delivery.
5 min read / Updated / Last checked
- Format
- Guide · Advanced
- Who it is for
- Builders and technical founders
- You leave with
- Add idempotency keys, bounded retries with jitter and duplicate-safe queue consumers, and test that no action runs twice.
The problem
On September 12, 2025, Cloudflare's dashboard and parts of its API went down for over an hour. A bug in the dashboard put an object into a React useEffect dependency list. The object was recreated on every render, so the effect ran again and again, calling the internal Tenant Service API far more often than intended. The extra load arrived during a Tenant Service update, overwhelmed it, and because that service takes part in authorizing API requests, they failed with 5xx errors from 17:57 to 19:12 UTC. Among Cloudflare's fixes: random delays to spread out retries, and marking requests as retries so loops like this are easier to spot [1].
That incident is the load side of failure: clients calling again until the server falls over. The other side is quieter and costs more. A request times out after the server already charged the card, the client retries, and the customer is charged twice. A worker crashes after sending an email but before recording it, the job runs again, and the customer gets two. A webhook arrives twice and an order ships twice.
Code written for the happy path, by a person or an AI tool, usually has no answer to either side. It never retries, or it retries everything in a tight loop.
How it works
Three mechanisms work together. Each one is simple. They only work when all three are in place.
Bounded retries. Retry only errors that can succeed on a second try: timeouts, dropped connections, HTTP 429 and 503. Never retry a 400 or a validation error. Cap the attempts, wait longer after each one (exponential backoff) and add a random amount to each wait (jitter) so thousands of clients do not retry in the same instant. Retry at one layer of the stack only. AWS's Builders' Library shows why: five layers that each retry three times multiply load on a struggling database by 243 [2]. The same article states the condition for any of this: calls with side effects are not safe to retry unless the API is idempotent [2].
Idempotency keys. An idempotent operation has the same effect whether it runs once or five times. For "create an order," the client generates a unique key per logical action and sends it with every attempt. The server stores the first result under that key and returns it for any repeat. Stripe documents the behavior precisely: it saves the status code and body of the first request with a key, including 500 errors, keys can be up to 255 characters, keys may be pruned once they are at least 24 hours old, and a repeat with different parameters is rejected as misuse [3]. An IETF draft standardizes the Idempotency-Key header: 409 Conflict while the original request is still running, 422 when a key is reused with a different payload, 400 when a required key is missing [4].
Queues that expect duplicates. Move slow or retryable work out of the request into a queue. Many queues, SQS standard queues among them, deliver at least once, not exactly once. In Amazon SQS, a received message becomes invisible for a visibility timeout (30 seconds by default, at most 12 hours) and reappears if the consumer does not delete it in time. Even within that window, SQS does not guarantee a message arrives only once [5]. Messages that keep failing go to a dead-letter queue for a person to inspect [5]. Webhooks behave the same way: Stripe retries delivery for up to three days in live mode, does not guarantee order and asks receivers to log processed event IDs and skip repeats [6].
Failure paths and the control that stops each one
Fig. 01- Client times out and resends the orderIdempotency key replays the stored response
- Every layer retries a failing serviceRetry at one layer, capped, with jitter
- Queue delivers the same message twiceConsumer records message ID with the effect
- Webhook arrives twice, out of orderDedupe on event ID, fetch current state
- Message fails on every attemptDead-letter queue and an alert
By the numbers
- of severe dashboard impact in Cloudflare's September 2025 retry incident [1]
- 75 minutes
- load from three retries at each of five layers [2]
- 243x
- minimum age before Stripe may prune a stored idempotency key [3]
- 24 hours
- of webhook delivery retries in Stripe live mode [6]
- 3 days
- default SQS visibility timeout before a message reappears [5]
- 30 seconds
| Interface | What it guarantees | What the receiver must do |
|---|---|---|
Stripe API with Idempotency-Key | First response replayed for repeats of the same key [3] | One key per logical action, same parameters on every retry |
| Stripe webhooks | Retries for up to 3 days, no ordering guarantee [6] | Log processed event IDs, return 2xx fast, process from a queue |
| Amazon SQS standard queue | At-least-once delivery, visibility timeout up to 12 hours [5] | Make the consumer idempotent, configure a dead-letter queue |
IETF Idempotency-Key draft | 409 while running, 422 on payload mismatch [4] | Store key and payload fingerprint together |
The 243x figure is the reason to choose one retry layer deliberately [2]. Cloudflare's incident started with a client that called too often [1]. On the other side, every row in the table says the same thing: providers deliver at least once and leave deduplication to the receiver. A system that assumes exactly-once delivery has a duplicate-action bug that has not fired yet.
Implementation
The server side first. This order endpoint claims the key, performs the charge once, and stores the response in the same transaction as the order. SQLite keeps the example self-contained. The same pattern works with a unique key column in Postgres.
"""Idempotent order creation: the first response per key is stored and replayed."""
import hashlib
import json
import sqlite3
SCHEMA = """
CREATE TABLE IF NOT EXISTS idempotency_keys (
key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, status TEXT NOT NULL, response TEXT);
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY, customer TEXT NOT NULL, amount_cents INTEGER NOT NULL);
"""
class Conflict(Exception): """409: the first request with this key is still running."""
class Mismatch(Exception): """422: the key was reused with a different payload."""
def create_order(db: sqlite3.Connection, key: str, payload: dict, charge) -> dict:
fp = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
try:
with db: # claim the key; the primary key makes this atomic
db.execute("INSERT INTO idempotency_keys VALUES (?, ?, 'processing', NULL)", (key, fp))
except sqlite3.IntegrityError:
row = db.execute("SELECT fingerprint, status, response FROM idempotency_keys"
" WHERE key = ?", (key,)).fetchone()
if row[0] != fp:
raise Mismatch(key)
if row[1] != "done":
raise Conflict(key)
return json.loads(row[2]) # replay, no second side effect
try:
charge_id = charge(payload["amount_cents"], idempotency_key=key) # pass the key on
except Exception:
with db: # release the key so the client can retry safely
db.execute("DELETE FROM idempotency_keys WHERE key = ?", (key,))
raise
with db: # order row and stored response commit together
cur = db.execute("INSERT INTO orders (customer, amount_cents) VALUES (?, ?)",
(payload["customer"], payload["amount_cents"]))
response = {"order_id": cur.lastrowid, "charge_id": charge_id}
db.execute("UPDATE idempotency_keys SET status = 'done', response = ? WHERE key = ?",
(json.dumps(response), key))
return responseThree details carry the design. The same key is passed to the payment provider, so a retry that reaches the provider again gets the first charge back instead of a new one [3]. A failed charge releases the key, so the client's next attempt is processed rather than stuck behind a 409. And a process that dies between the charge and the final commit leaves the key in processing. Give that state a lease in production: once a key has been processing longer than the slowest charge (60 seconds, as an illustrative value), the next retry takes it over, and the provider-side key still prevents a second charge.
The client side generates one key per user action (a UUID when the user presses Pay, reused on every retry) and retries with a cap and jitter.
"""Client-side retries: few attempts, exponential backoff, random jitter."""
import random
import time
class Retryable(Exception):
"""Timeouts, connection resets, HTTP 429 and 503. Never 400 or 422."""
def call_with_retries(fn, *, attempts=4, base=0.2, cap=5.0, sleep=time.sleep):
for attempt in range(attempts):
try:
return fn()
except Retryable:
if attempt == attempts - 1:
raise # give up and surface the error, do not loop forever
# Wait a random time between 0 and an exponentially growing ceiling.
sleep(random.uniform(0, min(cap, base * 2 ** attempt)))Queue consumers and webhook handlers follow the same rule with a different key. Insert the message ID or Stripe event ID into a processed_events table with a primary key, in the same transaction as the effect. If the insert fails on the key, the event was already handled: acknowledge it and stop [6]. For an email or any other effect outside the database, record the ID before sending and pass it to the provider as its idempotency key where the provider supports one.
Test it
These tests use pytest and a fake payment provider that counts real charges. The central assertion is the business rule itself: one charge, whatever the client does.
import sqlite3
import pytest
from orders import SCHEMA, Mismatch, create_order
ORDER = {"customer": "cus_123", "amount_cents": 4900}
class FakePSP:
"""Stands in for the payment provider and counts real charges."""
def __init__(self, fail_first=False):
self.charges, self.fail_first = [], fail_first
def __call__(self, amount, idempotency_key):
if self.fail_first:
self.fail_first = False
raise TimeoutError("provider timed out")
self.charges.append((amount, idempotency_key))
return f"ch_{len(self.charges)}"
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.executescript(SCHEMA)
return conn
def test_same_key_twice_charges_once(db):
psp = FakePSP()
first = create_order(db, "key-1", ORDER, psp)
assert create_order(db, "key-1", ORDER, psp) == first # client retried
assert len(psp.charges) == 1
assert db.execute("SELECT count(*) FROM orders").fetchone()[0] == 1
def test_key_reused_with_other_payload_is_rejected(db):
create_order(db, "key-2", ORDER, FakePSP())
with pytest.raises(Mismatch):
create_order(db, "key-2", {**ORDER, "amount_cents": 9900}, FakePSP())
def test_failed_charge_releases_key_for_retry(db):
psp = FakePSP(fail_first=True)
with pytest.raises(TimeoutError):
create_order(db, "key-3", ORDER, psp)
create_order(db, "key-3", ORDER, psp)
assert len(psp.charges) == 1Expected: three passing tests. Then run three checks against a staging environment:
- Duplicate webhook. Resend a delivered event with
stripe events resend <event_id> --webhook-endpoint=<endpoint_id>[6]. Expected: the handler logs a skipped duplicate, no second fulfillment. - Crash mid-job. Kill a worker after it receives a message and before it deletes it. Expected: the message reappears after the visibility timeout [5], and its effect happens once in total.
- Retry storm. Make a dependency return 503 for a minute. Expected: client attempts stop at the cap, waits are spread out, and the dependency recovers without a second outage.
Decision
Add idempotency before the first real payment, not after the first double charge. On an existing codebase, the work is one table, one middleware and one test per endpoint that moves money or sends messages.
- Every endpoint that charges, refunds, books, sends or deletes accepts an idempotency key and stores its first response.
- Retries live in one layer, retry only transient errors, stop at a cap and use jitter [2].
- Every queue consumer and webhook handler deduplicates on the message or event ID, and every queue has a dead-letter queue with an alert.
- The duplicate-request test runs in CI. For the founder-level view of which events must never repeat, see System Design for Non-Technical Founders.
Sources
- [1]A deep dive into Cloudflare's September 12, 2025 dashboard and API outage (opens in a new tab)Tom Lianza, Cloudflare, September 2025
- [2]Timeouts, retries, and backoff with jitter (opens in a new tab)Amazon Builders' Library, December 2019
- [3]Idempotent requests (opens in a new tab)Stripe API Reference, November 2026
- [4]The Idempotency-Key HTTP Header Field, draft-ietf-httpapi-idempotency-key-header-08 (opens in a new tab)IETF HTTPAPI Working Group, October 2026
- [5]Amazon SQS visibility timeout (opens in a new tab)Amazon Web Services, November 2026
- [6]Receive Stripe events in your webhook endpoint (opens in a new tab)Stripe Docs, November 2026
Technical guidance, not legal or security certification.
Related resources
Need a technical review of an AI-built MVP?
Discuss your build