Learn

VISUAL GUIDE · APIS & QUEUES

When a job runs twice

Recap

THE WHOLE PICTUREORIGINAL SKETCH
enqueuelease jobredelivercharge + keyCheckout APIJob queuelease 30 sWorker AWorker BLedger DBwallets + done keysCard providersame key: same result
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.
Recap
  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

RECAP

What to remember

  • A lease (visibility timeout) hides a job instead of deleting it, so a crashed worker's job comes back.
  • A lost acknowledgement after the side effect turns into a second run of that side effect.
  • At-least-once delivery is the normal case; the side effect is the operation that must be safe to retry.
  • Write a dedupe record in the same transaction as the effect, or use a conditional write, so the retry changes nothing.
  • Use a key tied to the business action, set by the producer, and pass it to any external service that performs the effect.

NOW CLOSE THE GUIDE AND REDRAW IT

Without looking, draw the queue, two workers and the database. Mark where the acknowledgement is lost, then draw where duplicate work is prevented. Next to it, write which operation must be safe to retry and why the queue cannot do it for you.

Check your drawing against this list afterwards, not before:

  • The lease or visibility timeout on the queue, with the job hidden rather than deleted.
  • The lost acknowledgement after the side effect, and the redelivery to a second worker.
  • An idempotency key tied to the business action, not to the delivery attempt.
  • The dedupe record and the effect inside one transaction (or a conditional write).
  • The retry acknowledged as a no-op instead of failing forever.
  • A note on external effects: pass the key to the provider.

APPLY IT

Sketch a message broker with per-message acknowledgement

GO DEEPER WITH OUR GUIDES

OFF-SITE SOURCES · NOT WRITTEN BY US

Sources and further reading