STEP 8 OF 10 · DEDUPE KEY
Record the key in the same transaction
Give the job an idempotency key that means "this business action": charge:order-42. Have the producer set the key instead of minting a new one per attempt, so a retried enqueue also carries the same key.
The worker now does two things in one database transaction: insert charge:order-42 into a done_keys table with a unique constraint, and debit the wallet. Either both commit or neither does.
When worker B retries, the insert fails on the unique key, the transaction rolls back, and worker B simply acknowledges the job. The wallet is debited once.
This also covers a worker A that was only slow, not dead, so both run at once: the database makes the second insert wait for the first transaction, then rejects it.
Why it matters. Putting the record and the effect in one transaction closes the gap. There is no moment where the money moved but the key was not saved.