Learn

VISUAL GUIDE · APIS & QUEUES

When a job runs twice

Introduction

THE CASTORIGINAL SKETCH
enqueueCheckout APIJob queuelease 30 s
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.
Intro
  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

THE PROBLEM

Watch a queued charge run twice after a lost acknowledgement, then make the retry harmless with an idempotency key written in the same transaction as the effect.

Checkout puts a job on a queue: charge order 42 from the customer's wallet. A worker takes the job, debits the wallet, and crashes before it can tell the queue it finished. When the 30-second lease on the job runs out, another worker gets the same job and debits the wallet again. Follow the job through both deliveries, then change one thing so the second run does nothing.

By the end you can

  • Explain what a lease (visibility timeout) is and why the queue redelivers when it expires.
  • Show how a lost acknowledgement turns into a duplicate side effect.
  • Explain why at-least-once delivery is the normal case and the handler must be safe to retry.
  • Make a retry a no-op with a dedupe record in the same transaction, or with a conditional write.
  • Choose an idempotency key that stays the same across retries, and pass it on to external services.

Assumptions behind the numbers

  • Illustrative: the queue hides a leased job for 30 seconds (a visibility timeout); real queues let you choose this per queue or per message.
  • Illustrative: the charge is a debit of ₹499 from a wallet balance stored in the same database as the dedupe records.
  • The queue delivers each job at least once. It does not know whether the worker's side effect happened, only whether an acknowledgement arrived.