Lesson 5 of 9 · 29m
Idempotency Keys and Exactly-Once Effects
Use provider idempotency correctly, deduplicate webhook processing, and make fulfillment safe under retries, double clicks, and worker crashes.
Networks retry. Users double-click. Workers crash after charging a card but before writing the database row. Exactly-once delivery is a fantasy; exactly-once effect is an engineering discipline. Payment systems survive because operations are idempotent: repeating the same logical operation does not repeat the side effect.
Separate transport idempotency from business idempotency
Stripe idempotency keys protect a specific API request from accidental repetition:
curl https://api.stripe.com/v1/payment_intents -u "$STRIPE_SECRET_KEY:" -H "Idempotency-Key: order-ord_123-attempt-1" -d amount=2900 -d currency=usdIf the request times out and you retry with the same key, Stripe returns the original result rather than creating a second PaymentIntent. That is transport idempotency. It does not know whether you already emailed a receipt, unlocked premium access, or shipped a product. Business effects need their own deduplication.
Deduplicate webhook events by provider event ID
A durable event table usually includes:
CREATE TABLE payment_events (
id BIGSERIAL PRIMARY KEY,
provider TEXT NOT NULL,
provider_event_id TEXT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ,
UNIQUE(provider, provider_event_id)
);Insert the event before processing it. A unique constraint violation means the event was already accepted. Processing can then be retried independently, with processed_at or a richer state machine marking completion.
Make fulfillment idempotent too
Do not write this:
def fulfill(order):
order.paid = True
user.credits += order.creditsWrite an operation that can run twice safely:
def fulfill(order):
with transaction():
locked = Order.objects.select_for_update().get(id=order.id)
if locked.fulfillment_status == "fulfilled":
return
ledger.add_credit_once(
account=locked.account,
amount=locked.credits,
reference=f"order:{locked.id}:credit",
)
locked.fulfillment_status = "fulfilled"
locked.save()The ledger reference uniqueness is the important part. It turns a retry into a no-op. Database constraints are stronger than application-level good intentions.
Use idempotency keys at workflow boundaries
Stable key design matters:
same logical retry order-{id}-attempt-{n}
new payment after expiry order-{id}-attempt-{n+1}
refund retry refund-{refund_id}-attempt-{n}
webhook consumer provider-event-{event_id}Do not use random UUIDs generated blindly on every retry; that defeats the point. Do not reuse keys across changed amounts, currencies, or orders.
Beware side effects outside the transaction
If you update the database and then send email, a crash can leave email unsent. If you send email first and then crash before commit, a retry sends email twice. Use an outbox table or idempotent job state:
database commit writes outbox row
worker sends receipt once per outbox row
worker marks outbox row deliveredExternal side effects need coordination. There is no magic distributed transaction with your email provider.
Field notes
- Idempotency keys expire at providers; your own deduplication must be durable for the business lifetime of the operation.
- Do not treat HTTP 500 as proof the provider operation failed. It may have succeeded after the response was lost.
- Unique constraints beat
SELECTthenINSERTchecks because concurrency defeats check-then-act logic. - Make admin retry buttons idempotent; operators click them repeatedly during incidents.
- Test kill-9 worker crashes, not just normal exceptions.
Was this lesson helpful?