← Back to Backend, page 2

backend-0021 · Medium mid

What does at-least-once delivery mean in a message queue, why do duplicates happen, and how do you make a consumer idempotent?

With at-least-once delivery the broker keeps a message until the consumer acknowledges it. If the consumer crashes or is slow after doing the work but before the ack, the message becomes visible again and is delivered a second time. So duplicates are normal, and the consumer must be idempotent: record each message's unique business id with the effect in the same transaction, or use naturally idempotent operations such as upserts. Exactly-once processing is built from at-least-once delivery plus idempotency.

Full answer

Delivery guarantees

  • At-most-once: acknowledge first, process later. A crash loses the message. No duplicates.
  • At-least-once: process first, acknowledge after. A crash causes a redelivery, so duplicates are possible. This is the default for SQS, RabbitMQ with manual acks, Kafka with committed offsets after processing.
  • Exactly-once: only within a closed system (for example Kafka transactions between topics). Across a database and an external API it is built by at-least-once plus idempotent handling.

Why duplicates happen

  • Crash between the effect and the ack. Visibility timeout shorter than the processing time. Network loss of the ack. Producer retries after a timeout (the first send had succeeded).

Making a consumer idempotent

  1. Put a unique id in every message (an event id or an idempotency key made by the producer, not the broker's delivery id).
  2. Store processed ids in a table with a unique constraint and insert it in the same database transaction as the business change. If the insert conflicts, skip the work and acknowledge.
  3. Or design operations to be idempotent: set a status to a value, upsert by key, "set balance to X" instead of "add 100".
  4. Keep processed ids as long as duplicates can arrive (retention of the broker plus a margin).

Also set the visibility timeout above the p99 processing time, extend it for long jobs, and make ack the last step.

javascript
// A queue with a visibility timeout, like SQS. Time is a number that we move by hand.
class Queue {
  constructor(visibilityTimeout) { this.timeout = visibilityTimeout; this.messages = []; }
  send(body) { this.messages.push({ body, visibleAt: 0, receiveCount: 0 }); }
  receive(now) {
    const m = this.messages.find((x) => x.visibleAt <= now);
    if (!m) return null;
    m.visibleAt = now + this.timeout; m.receiveCount++;
    return m;
  }
  ack(m) { this.messages = this.messages.filter((x) => x !== m); }
}

function run(label, handler) {
  const queue = new Queue(30);
  queue.send({ id: 'pay-1001', account: 'A', amount: 100 });
  const state = { balance: 0, seen: new Set() };

  let m = queue.receive(0);
  handler(state, m.body);                                   // the effect is applied...
  /* ...and the consumer crashes here, before queue.ack(m) */
  console.log(label, '| at t=5 visible again?', queue.receive(5) !== null);

  m = queue.receive(31);                                    // after the visibility timeout the message returns
  console.log(label, '| at t=31 redelivered, receiveCount =', m.receiveCount);
  handler(state, m.body);
  queue.ack(m);
  console.log(label, '| final balance =', state.balance, '| messages left =', queue.messages.length);
}

run('naive consumer     ', (state, msg) => { state.balance += msg.amount; });
run('idempotent consumer', (state, msg) => { if (state.seen.has(msg.id)) return; state.seen.add(msg.id); state.balance += msg.amount; });

The queue and the clock are simulated, so the redelivery happens at a known moment. In a real system the 'seen' set is a database table with a unique constraint, updated in the same transaction as the balance. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): naive consumer | at t=5 visible again? false naive consumer | at t=31 redelivered, receiveCount = 2 naive consumer | final balance = 200 | messages left = 0 idempotent consumer | at t=5 visible again? false idempotent consumer | at t=31 redelivered, receiveCount = 2 idempotent consumer | final balance = 100 | messages left = 0

Key points

  • Process first, acknowledge last gives at-least-once delivery.
  • Crashes, timeouts and producer retries create duplicates.
  • Idempotent consumers record the message id in the same transaction as the effect.
  • Prefer operations that are naturally idempotent.
  • Exactly-once effects come from at-least-once plus idempotency.

Common mistakes

  • Acknowledging before the work is done and calling it reliable.
  • Using the broker's delivery id instead of a business id for deduplication.
  • Deduplicating in memory only (lost on restart).
  • A visibility timeout shorter than the job.
  • Keeping dedup records for too short a time.

Follow-ups

  • How does Kafka's offset commit relate to at-least-once?
  • How do SQS FIFO queues deduplicate?
  • Why is 'exactly once' often a marketing term?

Tips

  • Define the three guarantees.
  • Say 'ack last, dedupe by id'.
  • Explain the crash window.