At-Least-Once, At-Most-Once, Exactly-Once: What Delivery Guarantees Actually Mean

Every message-queue tutorial promises “reliable delivery.” Then the first bill arrives: duplicate charges fired twice, notification emails sent in triplicate, a counter incremented two extra times because a consumer crashed mid-batch. The problem is almost never the queue. It’s a mismatch between the delivery guarantee the infrastructure provides and the guarantee the application assumed it had.

There are exactly three delivery semantics in distributed messaging, and once you can name where the failure happens, choosing the right one stops being guesswork. This post walks through each guarantee from both sides of the wire — producer and consumer — shows why exactly-once delivery is not something you can buy off the shelf, and ends with the pattern that most production systems actually run: at-least-once delivery with an idempotent consumer.

The three guarantees, defined by failure point

A delivery guarantee describes what happens when something breaks between a producer and a consumer:

  • At-most-once — the message may be lost, but it is never delivered twice. Fire, forget, and hope.
  • At-least-once — the message is never lost, but it may be delivered more than once. Retries everywhere.
  • Exactly-once — neither lost nor duplicated. The option everyone asks for first.

The counterintuitive part is that these are not three settings on a broker. They emerge from where the ack happens relative to the work. A producer that retries after an ambiguous timeout drifts from at-most-once toward at-least-once. A consumer that commits its offset before processing drifts the other way. The broker just stores bytes; the semantics live in the edges.

The producer side: the ack that never arrived

Consider the simplest failure in messaging. A producer writes a record, the broker commits it to disk and replicates it, and then the network partition swallows the ack. The producer sees a timeout. Its only safe move is to retry — and now the log holds two identical records. That single scenario is why naive retries turn at-most-once into at-least-once on the write path.

Kafka solves this with the idempotent producer. Each producer gets an assigned producer ID (PID), and every batch carries a sequence number per partition. The broker tracks the last sequence per (PID, partition) and silently discards duplicates, so a retry caused by a lost ack doesn’t create a second record. Since Kafka 3.0, enable.idempotence is on by default, along with the acks=all setting it requires. This closes the producer-side duplication hole for retries within a single producer session — but it does nothing for the consumer side, which is where the real damage happens.

The consumer side: the commit race

A consumer reads a batch, processes each record, then commits the new offset. Two orderings are possible, and neither is free:

Commit first, process second. If the consumer crashes after committing but before processing, the replacement consumer resumes past those records. They are never processed. This is at-most-once: cheap, and silently lossy.

Process first, commit second. If the consumer crashes after processing three records but before the commit lands, the partition is re-read from the old offset. Those three records run again. This is at-least-once: durable, and duplicating.

Since “we lost the customer’s order” is a worse failure mode than “we charged the customer twice and can refund,” nearly every serious system picks at-least-once and then deals with the duplicates. The question is how.

What exactly-once actually buys you

Kafka’s transactions exist to close the consumer-side race — but only for a specific shape of application. A transactional producer can write output records and commit the corresponding input offsets atomically, in one transaction. Downstream consumers that run with isolation.level=read_committed never see output from aborted transactions. A crash mid-transaction leaves both the output and the offset commit rolled back, so the read-process-write cycle replays cleanly. This is exactly-once semantics as Kafka defines it: exactly-once processing for a Kafka-to-Kafka pipeline, such as a streams application.

The catch is the boundary. The moment your side effect leaves Kafka — a row in Postgres, an HTTP call to a payment provider, an email — the transaction no longer covers it. Nobody can commit a database row and a Kafka offset atomically across two independent systems; between any two systems connected by a network, there is always a crash window after one succeeds and before the other knows. This is the two-generals problem wearing a modern jacket. Vendors who market “exactly-once delivery” end-to-end are selling exactly-once processing inside their own boundary plus a deduplication problem for you.

Transactions also cost throughput and latency — more round trips, more coordination, marked records that read_uncommitted consumers must skip or handle. It’s a good trade inside Kafka-internal pipelines and rarely worth it anywhere else.

The pattern that works: at-least-once plus an idempotent consumer

The pragmatic architecture accepts duplicates as a fact of life and makes processing idempotent instead. Each message carries a unique ID (most producers set a message key or a UUID header). The consumer tracks processed IDs in the same transaction as its business write, so a replayed message hits a conflict and is skipped:

CREATE TABLE processed_messages (
    message_id TEXT PRIMARY KEY,
    processed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// Consume runs the at-least-once loop with an idempotent handler.
// Library: github.com/segmentio/kafka-go
func Consume(ctx context.Context, r *kafka.Reader, db *sql.DB) error {
	for {
		m, err := r.FetchMessage(ctx) // no auto-commit
		if err != nil {
			return err
		}

		err = process(ctx, db, m)
		if err != nil {
			// transient failure: don't commit, the redelivery handles it
			continue
		}

		if err := r.CommitMessages(ctx, m); err != nil {
			return err
		}
	}
}

// process applies the side effect and the dedupe marker in ONE transaction.
// A replayed message finds message_id already present and becomes a no-op.
func process(ctx context.Context, db *sql.DB, m kafka.Message) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	msgID := string(m.Key) // producer-supplied unique ID
	var exists bool
	err = tx.QueryRowContext(ctx,
		`SELECT true FROM processed_messages WHERE message_id = $1`,
		msgID).Scan(&exists)
	if err != nil && !errors.Is(err, sql.ErrNoRows) {
		return err
	}
	if exists {
		return nil // duplicate from a redelivery: already applied
	}

	// 1. the business write
	if _, err := tx.ExecContext(ctx,
		`UPDATE accounts SET balance = balance + $1 WHERE id = $2`,
		amountFrom(m), accountFrom(m)); err != nil {
		return err
	}

	// 2. the dedupe marker, same transaction
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO processed_messages (message_id) VALUES ($1)`,
		msgID); err != nil {
		return err
	}

	return tx.Commit()
}

The critical property is that the dedupe check and the side effect share one transaction. If they don’t — say the marker is written to Redis and the balance to Postgres — you have rebuilt the commit race one layer down, with a crash window between marker and effect. Atomicity between marker and effect is the whole trick.

Pitfalls worth knowing before you ship this

  • Dedupe table growth. processed_messages grows forever without cleanup. Add a TTL sweep (delete rows older than your maximum redelivery window) or partition by day and drop old partitions. The window only needs to exceed the longest redelivery delay you can produce.
  • Weak dedupe keys. If the producer doesn’t guarantee a stable ID per logical message, the consumer can’t invent one. A key derived from message content breaks when legitimate retries carry different timestamps. Push the ID requirement upstream.
  • Batch semantics. Committing offsets every message is slow; committing every thousand amplifies reprocessing after a crash. With the dedupe table in place, large batches are safe — replays are cheap no-ops — so tune the commit interval for throughput, not correctness.
  • Non-transactional side effects. An HTTP call can’t join your database transaction. If the call succeeds and the commit fails, the redelivery replays the call. Either make the downstream idempotent too (idempotency keys on the API — most payment APIs support this) or record the call’s outcome inside the same transaction before triggering it.

Choosing by failure tolerance, not by fashion

The decision tree is short. If losing a message is acceptable but processing twice is not — metrics sampling, cache invalidation pings — run at-most-once and enjoy the simplicity. If losing a message is unacceptable, run at-least-once with an idempotent consumer, which covers the overwhelming majority of production workloads. Reach for transactional exactly-once only when your pipeline lives entirely inside Kafka, and treat any promise of exactly-once delivery across system boundaries as a deduplication problem that someone — you — still has to solve.

Leave a Reply

Your email address will not be published. Required fields are marked *