Learn

VISUAL GUIDE · APIS & QUEUES

When a job runs twice

Step 8 of 10: Record the key in the same transaction

STEP 8 / 10ORIGINAL SKETCH
enqueuelease jobdebit order 42redeliverdebit order 42Checkout APIJob queuelease 30 sWorker AWorker BLedger DBwallets + done keyskey exists: no-op
A checkout API enqueues a charge job; worker A leases it and writes to the ledger database but its acknowledgement is lost; the queue redelivers to worker B, which writes again unless an idempotency key stops it; an external card provider can also receive the key.
8 / 10
  1. Enqueue
  2. Lease
  3. Side effect
  4. Ack lost
  5. Timeout
  6. Redelivery
  7. At-least-once
  8. Dedupe key
  9. Conditional write
  10. External effects

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.