DEV Community

Cover image for The replay that posted twice: idempotency keys are a contract, not a convenience
InApp
InApp

Posted on Originally published at imapp.blogspot.com

The replay that posted twice: idempotency keys are a contract, not a convenience

I built a handler that listened to a webhook, parsed the payload, and created a record. During testing I retried a delivery manually and got a duplicate. Fine, I thought — I'll just dedupe on the event ID. Then a real retry happened 40 minutes later with a slightly different timestamp and my dedup silently missed it. The record was created twice and downstream billing picked up both.

The mistake was treating idempotency as a client-side courtesy. What actually matters is the key: a stable identifier the sender puts in an Idempotency-Key header, and the receiver stores against the resulting side effect. If the key is present and already seen, return the original response, do not re-execute. If it's missing, you have to either generate one from deterministic inputs or refuse the request. Implicit dedup on 'looks similar' is how you get phantom duplicates.

A few things I now enforce: keys are client-generated and scoped per operation, not per connection; the store is keyed by (scope, key) with a TTL long enough to cover any reasonable retry window; and the stored response is replayed verbatim, including status code, so a flaky retry gets the same answer. If the original call is still in flight, hold the retry on a short lock instead of running it twice.

While debugging this I used the Webhook Catch API at https://x402.freeq.one/tools/webhook_catch.html to replay real payloads cheaply — saves spinning up a full endpoint every time.

If you ship anything that mutates state on receipt of an event, assume at-least-once delivery and make the key the contract.

Top comments (0)