Topic 5 of 5 · 5 min read
Idempotent writes and safe retries
Goal: Make a payment or webhook write idempotent so a retried request has no extra effect.
An operation is idempotent when running it twice has the same effect as running it once, and you build that by recording a unique key for each request and letting the database refuse the second one. Networks fail between "sent" and "answered", so every client will retry sooner or later.
Check yourself · 1 of 3
What does it mean for a payment endpoint to be idempotent?
Why it matters
A client sends "charge 40" and the connection drops. Did the charge happen? The client cannot know, so it retries. Without protection the customer is charged twice. Webhooks make this worse: providers such as Stripe deliver the same event more than once by design, so your handler must accept duplicates.
The building blocks
- Idempotency key. The client generates a unique value (a UUID) per logical operation and sends it in a header. The server stores it with the result in a table with a
UNIQUEconstraint. - Upsert.
INSERT ... ON CONFLICT (key) DO NOTHINGis atomic. If it inserts a row, you are first; if it inserts zero rows, this is a repeat. - Return the stored result. On a repeat, return the first response, not an error. Stripe's API works this way.
- Natural keys. For webhooks, use the provider's event id as the key.
- Transactional outbox. To update a row and send a message reliably, write both the change and an
outboxrow in one transaction. A separate worker reads the outbox and publishes, marking rows done. Delivery is at least once, so consumers still dedupe.
Before and after
# Before: a retry charges again
def handle(req):
charge_card(req.amount)
db.insert_payment(req.order_id, req.amount)
# After: the key row is claimed first, in a transaction
def handle(req):
with db.transaction() as tx:
claimed = tx.execute(
"INSERT INTO idempotency (key, status) VALUES (%s, 'started') "
"ON CONFLICT (key) DO NOTHING", [req.key]).rowcount
if claimed == 0:
return tx.stored_response(req.key)
tx.insert_payment(req.order_id, req.amount, provider_key=req.key)
Pass the same key to the payment provider so its side is safe too. The charge call itself is outside the claim's transaction when it is slow; store the state (started, done) so a crash in the middle can be resumed.
Rules for retries
- Retry only idempotent operations, or ones protected by a key.
- Use exponential backoff with jitter, and a maximum attempt count.
- Keys expire after a window (Stripe keeps them at least 24 hours), so state the window.
- A key reused with different parameters is a client bug; reject it.
What goes wrong
- A key checked with SELECT then inserted later: that is a race again.
- Marking the webhook as processed before the work succeeds, so a crash loses it.
- Doing the side effect (an email) inside the transaction, where a rollback cannot undo it.
Examples
A duplicate webhook
A provider sends invoice.paid twice, 40 seconds apart. The handler inserts the event id into processed_events with a unique constraint before crediting the account. The second delivery inserts zero rows, so the handler returns 200 and does nothing.
Outbox for a welcome email
Signup inserts the user and an outbox row {type: 'welcome_email', user_id: 91} in one transaction. A worker polls the outbox, sends the email and marks the row sent. If the server crashes after the commit, the email is still sent. If the signup rolls back, no email row exists.
Key points
- Idempotent means a repeated request has no extra effect; clients retry, so every write that matters needs this.
- Store a unique idempotency key and let a UNIQUE constraint decide who is first.
- INSERT ... ON CONFLICT DO NOTHING is an atomic claim; the row count tells you whether you won.
- On a repeat, return the stored first result instead of an error.
- A transactional outbox commits the change and the message together, then a worker delivers it at least once.
Common mistakes
- Checking for the key with a SELECT and inserting later, which reopens the race.
- Returning an error on a repeated request instead of the first result.
- Marking an event as processed before the work is done.
- Sending an email or calling an API inside the transaction and assuming rollback undoes it.
Check yourself · 2 of 3
A handler does SELECT to see if the idempotency key exists, then INSERTs it. Two retries arrive together and both charge. What is the fix?
Check yourself · 3 of 3
A webhook handler marks the event as processed, then credits the account, and the server crashes between the two steps. What is the result?
Practice items, not counted towards your mastery.
Start here
- Transaction Isolation (PostgreSQL documentation) (opens in a new tab)DocsFree
What read committed, repeatable read and serializable allow, and why serialization failures must be retried.
- PostgreSQL: Explicit locking (opens in a new tab)DocsFree
Row and table lock modes, FOR UPDATE, and the section on deadlocks and lock ordering.
- Jepsen: Consistency models (opens in a new tab)ArticleFree
A map of isolation and consistency models and which anomalies each one allows.
More for this topic
- Idempotent requests (Stripe API reference) (opens in a new tab)DocsFree
How a real payments API uses an idempotency key so a retried request returns the first result.
- Transactional outbox (microservices.io) (opens in a new tab)ArticleFree
The pattern for publishing a message and updating the database without losing either.
- PostgreSQL: INSERT (ON CONFLICT) (opens in a new tab)DocsFree
The exact semantics of ON CONFLICT DO NOTHING and DO UPDATE for atomic upserts.