Step-by-step version

VISUAL GUIDE · ONE-PAGE VERSION

When a job runs twice

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.
STEP 1 / 10ORIGINAL 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.

STEP 1 OF 10 · ENQUEUE

Checkout hands off the charge

The checkout API puts a job on the queue: { job: 7, action: "charge", order: 42, amount: 499 }. It answers the customer right away instead of waiting on the payment work.

The queue now owns the job. Its promise is simple: it will keep handing the job out until someone confirms it is done.

Why it matters. Queues let the front door stay fast and let slow work retry later. That retry promise is also where duplicates come from.

STEP 2 / 10ORIGINAL SKETCH
enqueuelease jobCheckout APIJob queuelease 30 sWorker Ahas 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.

STEP 2 OF 10 · LEASE

Worker A leases the job

Worker A pulls job 7. The queue does not delete it. It hides it for 30 seconds, the visibility timeout. Think of it as a lease: worker A has 30 seconds to finish and say so.

If worker A acknowledges in time, the queue deletes the job. If not, the job becomes visible again for someone else.

Why it matters. Hiding instead of deleting is what makes the queue survive worker crashes. A deleted job would vanish with the worker that held it.

STEP 3 / 10ORIGINAL SKETCH
enqueuelease jobdebit order 42Checkout APIJob queuelease 30 sWorker ALedger DBwallets + done keysbalance −499
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.

STEP 3 OF 10 · SIDE EFFECT

Worker A debits the wallet

Worker A subtracts ₹499 from the customer's wallet and commits. The money has moved. This is the side effect: a change in the world that someone will notice if it happens twice.

Why it matters. Name the side effect explicitly. It is the only part of the job that is dangerous to repeat.

STEP 4 / 10ORIGINAL SKETCH
enqueuelease jobackdebit order 42Checkout APIJob queuelease 30 sWorker Acrashed before ackLedger DBwallets + done keys
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.

STEP 4 OF 10 · ACK LOST

The acknowledgement never arrives

Worker A is about to send "done with job 7" to the queue. That acknowledgement never arrives: the process is killed during a deploy just before sending it, or the network drops the message.

The ledger says the charge happened. The queue has no idea.

Why it matters. There is always a gap between doing the work and reporting it. A crash in that gap is rare per job and certain over millions of jobs.

STEP 5 / 10ORIGINAL SKETCH
enqueuelease jobdebit order 42Checkout APIJob queuelease 30 sjob 7 visible againWorker ALedger DBwallets + done keys
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.

STEP 5 OF 10 · TIMEOUT

The lease runs out

Thirty seconds pass with no acknowledgement. The queue cannot tell "worker crashed before charging" from "worker charged and then crashed". Both look like silence.

Redelivering is the only safe choice for the queue. Dropping the job would lose charges whenever a worker died early.

Why it matters. The queue picks redelivery because losing work is usually worse than repeating it. That choice moves the duplicate problem to the handler.

STEP 6 / 10ORIGINAL SKETCH
enqueuelease jobdebit order 42redeliverdebit order 42Checkout APIJob queuelease 30 sWorker AWorker BLedger DBwallets + done keyscharged twice
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.

STEP 6 OF 10 · REDELIVERY

Worker B runs it again

Worker B leases job 7, sees an ordinary charge, and debits the wallet another ₹499. Worker B did nothing wrong. It followed the job exactly.

The customer has now paid twice for one order.

Why it matters. Duplicates do not need a bug. A correct queue and correct workers produce them whenever an acknowledgement is lost.

STEP 7 / 10ORIGINAL SKETCH
enqueuelease jobackdebit order 42redeliverdebit order 42Checkout APIJob queuelease 30 sWorker AWorker Bmust be safe to rerunLedger DBwallets + done keys
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.

STEP 7 OF 10 · AT-LEAST-ONCE

Expect every job more than once

You could acknowledge before doing the work. Then a crash loses the charge entirely: that is at-most-once delivery. Acknowledge after, and a crash repeats it: at-least-once.

No setting on the queue makes the debit and the acknowledgement happen as one step, because they live in different systems. So production systems pick at-least-once and make the handler safe to run again.

The operation that must be safe to retry is the side effect, the debit. Repeating the lease or the acknowledgement is already harmless.

Why it matters. Once you accept at-least-once as normal, the design question changes from "how do I stop retries" to "how do I make a retry harmless".

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.

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.

STEP 9 / 10ORIGINAL SKETCH
enqueuelease jobdebit order 42redeliverdebit order 42Checkout APIJob queuelease 30 sWorker AWorker BLedger DBwallets + done keys0 rows: already done
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.

STEP 9 OF 10 · CONDITIONAL WRITE

Or let the row say whether it is done

When the effect is a state change on one row, a conditional write works without a separate table: UPDATE orders SET status = 'charged' WHERE id = 42 AND status = 'pending', with the debit in the same transaction.

The first run changes one row. The retry changes zero rows, sees that, and skips the debit. Same outcome as the dedupe record: the retry is a no-op.

Why it matters. A state machine on the row is often the simplest idempotency key you already have. Pick whichever matches where the effect lives.

STEP 10 / 10ORIGINAL 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.

STEP 10 OF 10 · EXTERNAL EFFECTS

Pass the key along when the effect is elsewhere

If the money moves at a card provider instead of in your database, you cannot share a transaction with it. Send the same key with the request instead; providers that support idempotency keys return the first result for a repeated key rather than charging again. They only remember keys for a limited time (often a day or more), so retries must arrive within that window.

For effects with no such support, such as some email providers, record "sent" after the call and accept that a crash in between can still cause a rare duplicate. Say that trade-off out loud.

Why it matters. Idempotency has to reach the system that performs the effect. A key that stops at your own database cannot protect a charge made somewhere else.

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