The handler had an idempotency check. It had a test for the idempotency check. The test passed. And a customer was still charged twice. Idempotency keys are not enough on their own, and this is the audit where we learned to stop trusting the word "idempotent" in a code review.
We can't name the client, and we won't invent numbers for the incident. What we can describe is the shape of the bug, because we have since seen variations of it in other codebases. If you run a payments webhook, you probably have a cousin of it.
The handler that looked correct
The webhook endpoint received payment events from a provider. The provider delivers at-least-once, so duplicates are expected, and the original developers handled that the standard way. The handler, simplified, did this:
- Parse the event and read its unique event ID.
- Query a
processed_eventstable:SELECT 1 WHERE event_id = ?. - If a row exists, return 200 and stop.
- Otherwise, run the business logic: mark the order paid, grant entitlements, enqueue a receipt email, and call an internal fulfilment service.
- Insert the event ID into
processed_events. - Return 200.
A reviewer skimming this sees a dedupe table and moves on. The flaw is the gap between steps 2 and 5. That is a classic check-then-act race, and the window is as wide as the business logic is slow.
The race: concurrent retries, not sequential ones
Sequential retries are fine. If the provider retries after the first attempt has fully committed, step 2 finds the row and exits. The failure needs two deliveries of the same event in flight at once.
That happens more than people expect. The fulfilment call in step 4 was slow under load. The provider's delivery timeout was shorter than the handler's worst-case latency, so the provider treated slow responses as failures and retried while the first request was still running. Two workers behind the load balancer then did this:
- Worker A reads
processed_events: no row. - Worker B reads
processed_events: no row. - Both run the business logic, including the side effects.
- Both insert the event ID. One succeeds. The other either hits an error that was swallowed by a broad
catch, or, because the column had no unique constraint, simply succeeds too.
The table had a plain index on event_id, not a unique one. Nothing in the database enforced the invariant the application claimed to hold. The idempotency check was advisory, and under concurrency advisory checks give no guarantee.
Why the tests never caught it
The test suite sent the same event twice, one after the other, and asserted the second call was a no-op. That is the only ordering in which this code is correct. The tests were written against the mental model of "a retry comes later", while production delivered "a retry arrives in parallel".
Mocking made it worse. The fulfilment service was stubbed to return instantly, so the race window shrank to microseconds. Even a concurrent test would likely have passed against that stub. The bug only appears when the slow dependency is slow.
The fix: let the database arbitrate, then use an outbox
The fix has two parts, and neither involves cleverer application logic.
1. A unique constraint, claimed first
We added a unique constraint on event_id and inverted the order. Instead of check, work, record, the handler now claims the event first by inserting the row inside a transaction. If the insert violates the constraint, another worker owns this event, and the handler returns 200 immediately. Only the winner proceeds.
The database serializes the two inserts for us. In Postgres, INSERT ... ON CONFLICT DO NOTHING and a check of the affected row count gives you a clean "did I win?" signal with no explicit locking. This is also the most useful kind of database design habit: encode the invariant in the schema, not in a code path someone can refactor away.
2. A transactional outbox for the side effects
Claiming first creates a new problem. If the winner claims the event and then crashes before finishing the work, the provider's retry sees the claim and skips it. The payment is recorded as handled but never fulfilled.
The answer is to keep the claim and the state change in a single transaction, and to turn the external side effects into rows rather than calls. Within one transaction the handler:
- inserts the processed-event row (the claim),
- marks the order paid,
- writes outbox rows for the receipt email and the fulfilment call.
If the transaction commits, all of it exists. If it rolls back, none of it does, and the retry gets a clean attempt. A separate worker drains the outbox and performs the real calls, with its own retries. The webhook response is now fast and no longer hostage to the slowest downstream service, which also removes the timeout that triggered the concurrent retries in the first place.
The outbox worker is at-least-once, so the consumers still need their own idempotency. We pass the outbox row ID downstream as the idempotency key, and it is stable across retries. The point is that each layer now defends itself with a mechanism that holds under concurrency.
What we'd tell any team running this pattern
The lesson from this code audit is not "add idempotency keys". They were already there. It is that a dedupe check is only as strong as the layer that enforces it. A few things we now check every time:
- Is the dedupe key protected by a unique constraint, or just an index?
- Is the claim made before the side effects, in the same transaction as the state change?
- Are external calls made inline in the handler, or deferred through an outbox?
- Is there a test that fires the same event from two threads against a deliberately slow dependency?
That last one is cheap. Run N concurrent deliveries of one event against a stub with an artificial delay, and assert exactly one set of side effects. It fails loudly on the original code and would have found this bug before a customer did.
This is the kind of problem orithLabs gets pulled into: an existing backend that mostly works, with a failure mode that only shows up under real traffic. If you'd like a second pair of eyes on a webhook handler or any other payment path, we're happy to read the code and tell you plainly what we find.