DevPath
Mid lesson · 12 min

Make a payment handler safe to replay

Separate delivery count from business effect.

Name the operation

Queue messages and webhooks can be delivered more than once. Give each payment event a stable identifier from the source. A handler must recognize a replay even after a crash. A process-local set is insufficient because it disappears on restart and is not shared across workers.

Make the database enforce uniqueness

Store the event ID with a unique constraint. In a transaction, check or insert the event record and apply the ledger change. Concurrent duplicates may both pass an initial read, so the unique constraint is the final guard. Treat its duplicate error as a replay, not a second credit.

# In one transaction: insert event_id under a UNIQUE constraint,
# then append the matching ledger entry.
# On a duplicate key, return the recorded result.

Account for outside effects

If the handler also calls another service, a database transaction cannot roll that call back. Use an outbox or provider idempotency key. Test delivery twice, concurrent delivery, and a crash after the ledger write. Assert that the final balance changes once and the replay returns a stable result.

Check your understanding

Why is `if not seen(event_id): credit()` unsafe with two workers?

Show explanation

Both can observe 'not seen' before either writes. A database uniqueness constraint and transactional effect close the race.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Add exponential backoff with jitter

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.