Message Delivery Semantics

At-most-once, at-least-once and effectively-once delivery, and how to build reliable consumers.

What is it?

When one service sends a message to another through a queue or broker, something can fail at every step: the network, the broker, or the consumer halfway through its work. Delivery semantics describe what you're guaranteed when that happens:

- At-most-once: each message is delivered zero or one times. Failures can lose messages, but never duplicate them. - At-least-once: each message is delivered one or more times. Nothing is lost, but duplicates happen. - Exactly-once: each message affects the system exactly one time. True exactly-once delivery over an unreliable network isn't possible in general, so what systems really offer is effectively-once processing: at-least-once delivery plus consumers that make duplicates harmless.

Most production systems choose at-least-once and design idempotent consumers.

Explain like I'm 10

At-most-once is dropping a postcard in the mailbox: it'll probably arrive, and if it doesn't, nobody resends it. At-least-once is a courier who keeps redelivering until you sign, even if you already signed and the receipt got lost. Effectively-once is you checking the parcel's tracking number and refusing a second copy of something you already received.

Examples

An idempotent consumer with deduplication

async function handlePaymentMessage(message) {
  await db.transaction(async (tx) => {
    // The unique constraint on message_id makes a duplicate insert fail.
    const inserted = await tx.insertIgnoreDuplicate("processed_messages", {
      message_id: message.id,
    });
    if (!inserted) return; // already processed: skip side effects

    await tx.update("accounts", { id: message.accountId }, {
      balance: tx.raw("balance + ?", [message.amount]),
    });
  });

  // Acknowledge only after the work is committed.
  await message.ack();
}

The dedup record and the business change commit in one transaction, so either both happen or neither does. If the consumer crashes before ack, the broker redelivers, and the duplicate is skipped.

How it works

Acknowledgements decide the semantics. A consumer receives a message, does work, and acks it so the broker stops tracking it.

- Ack before processing: a crash mid-work loses the message. At-most-once. - Ack after processing: a crash after the work but before the ack causes redelivery. At-least-once.

Brokers implement this differently. SQS hides a received message for a visibility timeout; if it isn't deleted in time, it reappears. Kafka consumers commit offsets; committing after processing gives at-least-once. Producers face the same choice: retrying a send whose ack was lost can publish a duplicate (Kafka's idempotent producer removes those per partition).

Effectively-once comes from making processing idempotent:

- Natural idempotency: "set status = shipped" is safe to repeat; "add $10" isn't. - A dedup table keyed by message id, written in the same transaction as the side effect. - Kafka transactions can atomically write outputs and commit input offsets, giving exactly-once for read-process-write pipelines that stay inside Kafka. External side effects (emails, API calls) still need idempotency.

Ordering: most systems guarantee order only within a partition (Kafka) or message group (SQS FIFO). Retries and parallel consumers can reorder messages, so consumers that care should check versions or sequence numbers.

Dead-letter queues (DLQs): after a set number of failed attempts, a message moves to a separate queue so one "poison" message doesn't block or endlessly retry. Someone must monitor and replay or discard the DLQ.

At-least-once (ack after work)
Broker --msg #7--> Consumer: process OK --ack--X (crash before ack)
Broker --msg #7--> Consumer: dedup table says "seen #7" -> skip -> ack

Retry and dead-letter flow
Queue --> Consumer --fail--> retry 1 --fail--> retry 2 --fail--> retry 3
                                                                   |
                                                             Dead-letter queue
                                                             (alert, inspect, replay)

Why does it exist?

Networks and processes fail, and a sender can't tell "the message was lost" from "the message arrived but the reply was lost". So any system must choose between possibly losing messages and possibly duplicating them. Delivery semantics make that choice explicit so consumers can be designed for it.

When to use it

- At-least-once + idempotent consumers: the default for anything that matters: orders, payments, emails, inventory. - At-most-once: high-volume data where loss is acceptable and duplicates would be misleading or wasteful, such as some metrics or telemetry. - Broker-level exactly-once (Kafka transactions): stream processing jobs that read from and write to Kafka. - DLQs: any consumer that can hit messages it can't process.

When not to use it

Don't pay for broker transactions when an idempotent consumer would do; they add latency and complexity and still don't cover external side effects. Don't promise global ordering across a high-throughput topic; it forces a single partition and caps throughput. Order per key (per user, per order) is usually what's actually needed.

Common mistakes

  • Believing the broker's 'exactly-once' label covers side effects like sending email or charging a card.

  • Acknowledging a message before the work is committed, silently turning at-least-once into at-most-once.

  • Writing the dedup record and the side effect in separate transactions, so a crash between them breaks idempotency.

  • Setting a visibility timeout shorter than processing time, so messages are redelivered while still being worked on.

  • Adding a DLQ but never alerting on or draining it, so failed messages pile up unnoticed.

Practice exercises

  1. Easy:

    For each, pick at-most-once or at-least-once: page-view analytics, password-reset emails, shipping-label creation. Explain the cost of each failure mode.

  2. Medium:

    Make a consumer that sends a welcome email idempotent, given the email provider has no idempotency key support.

  3. Hard:

    Design an order pipeline where events for the same order must be applied in order, while different orders are processed in parallel across 20 consumers.

Interview questions

Define at-most-once, at-least-once and exactly-once.

At-most-once: delivered zero or one times, possible loss. At-least-once: delivered one or more times, possible duplicates. Exactly-once: the effect happens once. In practice that means at-least-once delivery plus idempotent or transactional processing.

Why is true exactly-once delivery impossible in general?

A sender can't distinguish a lost message from a lost acknowledgement. To avoid loss it must retry, which risks duplicates; to avoid duplicates it must not retry, which risks loss. Only the receiver can collapse duplicates by remembering what it has processed.

How does ack timing determine semantics?

Acking before processing gives at-most-once, because a crash after the ack loses the work. Acking after processing gives at-least-once, because a crash before the ack causes redelivery of work already done.

What makes a consumer idempotent?

Processing the same message twice has the same effect as once. Either the operation is naturally idempotent (setting a value, upserting by key) or the consumer records processed message ids and skips repeats, atomically with the side effect.

What is a dead-letter queue for?

Holding messages that failed processing a set number of times, so a poison message stops blocking the queue or retrying forever. It needs monitoring, and a way to inspect, fix and replay messages.

What ordering guarantees does Kafka give?

Order within a partition only. Messages with the same key go to the same partition, so per-key order holds as long as each partition is processed by one consumer at a time. There's no order across partitions.

How does an SQS visibility timeout relate to duplicates?

A received message is hidden for the visibility timeout. If the consumer doesn't delete it in time, because it crashed or was too slow, the message becomes visible and is delivered again. Set the timeout above worst-case processing time, or extend it while working.

What does Kafka's exactly-once support actually cover?

Idempotent producers prevent duplicate writes from retries, and transactions atomically commit output records and consumer offsets. That gives exactly-once for read-process-write within Kafka. Effects outside Kafka (a database write, an HTTP call) still need idempotency or an outbox pattern.

How long should you keep dedup records?

At least as long as duplicates can arrive: the broker's maximum redelivery window plus producer retry windows, often hours to days. Keep them with a TTL or partition them by time so the table doesn't grow forever.

Retries are reordering your per-order events. How do you fix it?

Partition by order id so one consumer handles an order sequentially, and don't skip ahead past a failing message for that key (park the key or block its partition). Also include a version or sequence number and have the consumer ignore events older than the stored version.