Distributed SystemsVol. 5 · Part V
0 / 0

Shelves / Distributed Systems

DS·68

Delivery Semantics

At-most-once, at-least-once and "exactly-once" delivery defined precisely: where each comes from (ack and commit ordering), why true exactly-once delivery is impossible over an unreliable network, and how systems achieve effectively-once processing with deduplication, idempotent handlers, transactional offset storage and end-to-end keys. Covers the boundary of Kafka EOS, outbox and inbox, side effects, and code in Java, Go, Python, Rust and Elixir.

24 topics · ~17 min read · 28-question quiz
Updated Suggest a correction

Start here: why "exactly once" is a design, not a setting

The crash that charges twice

A payment worker takes a message, charges the customer (a row in charges), then acknowledges. Now the worker dies right after charging message pay-3 and before acknowledging it:

Python
with db.transaction():
    db.execute("INSERT INTO charges VALUES (%s, %s)", (p["id"], p["amount"]))
if p["id"] == "pay-3" and not crashed:
    crashed = True; continue          # the worker "dies" after charging, before acking
await m.ack_sync()
Text
naive handler: 5 payments, 6 deliveries, 6 charges, ₹1800 charged; duplicates: [('pay-3', 2)]

The broker never got the ack, so after the ack wait it delivered pay-3 again, and the customer paid ₹300 twice. Nothing was broken: this is at-least-once delivery working as designed. Swap the order (ack first, then charge) and a crash loses the payment instead: at-most-once. There's no third ordering of "do the work" and "tell the broker" that survives a crash between them, which is why exactly-once delivery over an unreliable network is impossible.

What is possible: effectively-once processing

You can't stop a message arriving twice, but you can make the second arrival do nothing. Record the message ID in the same database transaction as the effect, with a unique constraint:

Python
with db.transaction():
    fresh = db.execute("INSERT INTO processed VALUES (%s) ON CONFLICT DO NOTHING RETURNING 1", (p["id"],)).fetchone()
    if fresh: db.execute("INSERT INTO charges VALUES (%s, %s)", (p["id"], p["amount"]))
Text
idempotent handler (dedup table in the same transaction): 5 payments, 6 deliveries, 5 charges, ₹1500 charged; duplicates: none

Six deliveries, five charges. Delivery stayed at-least-once; the processing became exactly-once because the effect and the "seen it" marker commit or roll back together. This is the idea behind every "exactly-once" feature you'll meet: Kafka transactions commit output records and consumer offsets atomically; Flink checkpoints state and offsets together; this table does it with PostgreSQL.

The producer side

Producers retry too, after a timeout whose outcome they don't know. Brokers can drop the duplicate if the producer labels each message:

Python
await js.publish("ord.placed", b'{"order":42}', headers={"Nats-Msg-Id": "order-42"})
await js.publish("ord.placed", b'{"order":42}', headers={"Nats-Msg-Id": "order-42"})   # the producer retried
Text
producer sent order-42 twice with the same message ID: first ack seq=1 duplicate=None, second ack seq=1 duplicate=True; stream holds 1

JetStream remembers IDs for a duplicate window (two minutes by default); Kafka's idempotent producer uses producer IDs and sequence numbers (chapter 67's lab); SQS FIFO queues use a deduplication ID for five minutes. All of them protect only against retries within the window or session. A business ID chosen by the producer (the order number, a payment's idempotency key) is what lets consumers deduplicate forever.

Guarantee Ordering of work and acknowledgement On a crash Typical use
At-most-once Acknowledge, then work Message lost Metrics, telemetry, best-effort notifications
At-least-once Work, then acknowledge Message repeated The default for almost everything
Effectively-once At-least-once + idempotent effect (atomic dedup) Repeat absorbed Payments, inventory, anything with money

How deep to go in delivery semantics

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Define at-most-once, at-least-once and effectively-once and where each comes from
L2 Write consumers that acknowledge after work and deduplicate with a unique key
L3 Explain producer idempotence, transactions, outbox and inbox, and the limits of EOS
L4 Diagnose duplicate and lost effects: dual writes, check-then-act races, window expiry
L5 Design end-to-end idempotency keys and delivery guarantees per flow in a system
L6 Audit and evolve delivery guarantees across an organisation's platforms and partners

The three guarantees

Definitions

A delivery guarantee describes how many times a message's effect can happen, given failures:

Guarantee Effect happens Typical mechanism Failure behaviour
At-most-once 0 or 1 times Send without retry; ack/commit before processing Messages can be lost
At-least-once 1 or more times Retry until acked; ack/commit after processing Messages can be duplicated
Exactly-once Exactly 1 time At-least-once plus deduplication / atomic commit Neither lost nor duplicated, within a defined boundary

The difference is simply the order of two steps: "do the work" and "record that it's done". Whichever comes first is what survives a crash in between.

at-most-once commit ✕ process → message lost at-least-once process ✕ commit → redelivered: dup effectively-once process + commit in ONE transactionor idempotent process (dedup by id) → both or neither ✕ = crash between the two steps
Ordering of 'process' and 'commit' decides the guarantee. Commit first and a crash in between loses the message (at-most-once); process first and a crash in between reprocesses it (at-least-once); doing both atomically, or making processing idempotent, gives effectively-once.

At-most-once

Fire-and-forget: UDP metrics, acks=0 producers, auto-ack consumers, NATS core pub/sub. Use it when losing some data is acceptable and duplicates are worse or pointless: metrics samples, telemetry, cache invalidation hints (a missed one expires anyway), real-time positions where the next update supersedes the last.

At-least-once

The default for anything that matters. The producer retries until acknowledged; the consumer acknowledges only after processing. Duplicates arise from:

  • Producer retries after a lost ack (mitigated by broker-side producer idempotence).
  • Consumer crash after processing but before ack or commit.
  • Rebalances: partition moves before the old owner committed.
  • Visibility timeout expiry (SQS), redelivery after nack, replay.
  • Upstream duplicates: user double-click, client retry, an upstream at-least-once hop.

At-least-once is only correct if consumers tolerate duplicates, which is the whole subject of chapter 74.

Exactly-once: what's possible

Why exactly-once delivery is impossible

Over an unreliable network, the sender can't know whether a message arrived without an acknowledgement, and it can't know the acknowledgement arrived without another, and so on (the two generals problem, chapter 65). So a sender must either risk not resending (possible loss) or resend (possible duplicate). No protocol delivers a message exactly once over a lossy channel with crashes.

What is achievable is exactly-once processing or effect: the message may be delivered several times, but its effect is applied once. This is often called effectively-once:

Exactly-once = at-least-once delivery + idempotent (or deduplicated, or transactional) processing.

The three ways to get effectively-once

  1. Idempotent operations: applying the message twice has the same result. "Set order 42 status to SHIPPED" is naturally idempotent; "add 10 to balance" isn't, but "apply ledger entry e-981 (unique)" is, if the uniqueness is enforced.
  2. Deduplication: record each processed message ID and skip IDs seen before. The record must be stored atomically with the effect (the same database transaction), or a crash between them reopens the gap.
  3. Atomic commit of effect and progress: store the consumer's offset (or processed-message marker) in the same transaction as the output. Kafka transactions do this for Kafka outputs; for a database sink, store the offsets in the database next to the data and seek to them on startup.
Java
// Java + Spring: idempotent consumer, dedup record and effect in ONE transaction (the "inbox" pattern)
@KafkaListener(topics = "payments")
@Transactional                                             // DB transaction
public void onPayment(PaymentCaptured evt) {
    int inserted = jdbc.update("""
        INSERT INTO processed_messages(consumer, message_id) VALUES ('ledger', ?)
        ON CONFLICT DO NOTHING""", evt.eventId());
    if (inserted == 0) return;                             // duplicate: already applied
    ledger.credit(evt.accountId(), evt.amountCents(), evt.eventId());
}   // commit: dedup marker and ledger entry together; offset committed after (at-least-once + dedup = once)

The boundary problem

The roadmap's rule for this chapter:

Exactly-once inside a messaging system does not automatically make an entire business workflow exactly-once.

Kafka's EOS guarantees that a read-process-write cycle within Kafka is atomic. But a typical workflow crosses boundaries:

Kafka EOS boundary (transactions) orders processor invoices consume + produce + offsets: atomic order API outbox + clientidempotency key payment API Postgres email each crossing needs its own mechanism: payment API → idempotency key · Postgres → upsert / dedup table in same tx email → dedup record checked before send (accept rare dup) · producer → outbox
Exactly-once has a boundary. Inside Kafka, transactions make consume, transform, produce and offset commit atomic. Crossing out of Kafka (calling a payment API, writing to a database, sending email) is outside that transaction; each crossing needs its own idempotency mechanism.
  • Into Kafka from a database: "update DB then publish" is a dual write. If the publish fails, the event is lost; if publishing first, the DB update may fail. The fix is the transactional outbox (write the event to an outbox table in the same DB transaction; a relay or CDC publishes it, at-least-once) (chapter 73).
  • Out of Kafka to a database: idempotent upserts, or dedup table in the same transaction as the effect, or offsets stored in the database.
  • Out of Kafka to an external API: pass a stable idempotency key (derived from the event ID) so the provider dedupes retries (Stripe and most payment APIs support this, chapter 74).
  • Non-idempotent side effects (sending an email or SMS): record "sent" before or after sending; either way a crash window remains. Choose which failure you prefer (rare duplicate email or rare missed email), and minimise the window.

Effectively-once by system

System What it offers Boundary
Kafka Idempotent producer + transactions + read_committed (EOS v2); Kafka Streams exactly_once_v2 Kafka topics and offsets
Kafka Connect Exactly-once source connectors (KIP-618); sink exactly-once depends on the connector (e.g. offsets stored in the sink) Connector + target
Apache Flink Exactly-once state via checkpoints (Chandy-Lamport-style barriers); end-to-end exactly-once with two-phase-commit sinks (Kafka transactional sink) or idempotent sinks Flink state + transactional sinks
AWS SQS FIFO Deduplication ID within a 5-minute window, plus ordered message groups Send dedup only; consumers still see redelivery after visibility timeout
Google Pub/Sub Exactly-once delivery option for pull subscriptions: an acked message isn't redelivered, within the region, ack ID validity rules apply Pub/Sub ack; your side effects still need idempotency
Azure Service Bus Duplicate detection window on MessageId; transactions across entities in a namespace Service Bus
NATS JetStream Publish dedup with Nats-Msg-Id within a window; double-ack (AckSync) for consumers JetStream

The pattern is consistent: each product guarantees exactly-once within its own walls; end to end, it's your job.

Designing for duplicates

Message identity

Effectively-once needs a stable identity per logical message, assigned once at the origin and preserved through retries and hops:

  • An event ID (UUID v7 or ULID, which sort by time) set when the event is created, not when it's sent.
  • Or a natural business key (orderId + eventType + version).
  • Not broker-assigned IDs or offsets, which differ on re-publication, and not content hashes alone (two genuinely separate identical payments would collide).

Propagate correlation IDs (the whole workflow) and causation IDs (the message that caused this one) too, for tracing and for deriving downstream idempotency keys deterministically: paymentKey = hash(orderId, "charge", attempt-agnostic).

Deduplication storage

Approach Notes
Dedup table in the same DB as the effect UNIQUE(consumer, message_id); insert in the same transaction. The gold standard. Prune old rows after the maximum redelivery window
Unique constraint on the effect itself E.g. ledger_entries.source_event_id UNIQUE: the effect is the dedup record
Version / sequence checks Apply an update only if event.version > row.version; also handles reordering
Redis SET NX with TTL Fast, but not atomic with the DB effect: crash between leaves a gap. Use it to filter most duplicates, backed by DB constraints
Bloom filter Probabilistic pre-check; false positives would drop real messages, so only as a hint

Windows

Every dedup mechanism has a window: SQS FIFO 5 minutes, NATS JetStream's configurable duplicate window, your table's retention. Duplicates arriving after the window (a replay from last month, a very delayed retry) get through. For replay-heavy systems, make the effect itself idempotent (upserts, unique constraints) rather than relying on time-bounded dedup.

// Go: idempotent consumer with Postgres, dedup + effect in one transaction
func (h *Handler) Handle(ctx context.Context, m Message) error {
    return pgx.BeginFunc(ctx, h.db, func(tx pgx.Tx) error {
        tag, err := tx.Exec(ctx,
            `INSERT INTO processed_messages(consumer, message_id) VALUES ('ledger', $1)
             ON CONFLICT DO NOTHING`, m.ID)
        if err != nil { return err }
        if tag.RowsAffected() == 0 { return nil }          // duplicate
        _, err = tx.Exec(ctx,
            `INSERT INTO ledger(account_id, amount_cents, source_event) VALUES ($1, $2, $3)`,
            m.AccountID, m.Amount, m.ID)
        return err
    })   // only after commit does the caller ack / commit the offset
}

Choosing a guarantee

  • Default to at-least-once delivery with idempotent consumers. It's simple, robust, and works across every broker.
  • Use at-most-once only where loss is genuinely fine.
  • Use transactional EOS (Kafka Streams, Flink) when building stream-processing pipelines that stay inside the platform, where it's cheap to enable and removes a whole class of bugs.
  • Never claim end-to-end exactly-once without naming the mechanism at every boundary. Write it down per integration: "orders → billing: at-least-once + dedup table keyed by event ID".

Lab: duplicates and losses, counted

NATS JetStream 2.11 and PostgreSQL 16 on one machine, driven from Python (nats-py, psycopg 3). Every number is a count of real rows and stored messages.

Experiment 1: the broker's duplicate window

1,000 events, each published twice (as a producer does when an ack times out):

Text
without a message ID: 2000 stored
with a message ID:    1000 stored

Labelling each publish with Nats-Msg-Id made the broker discard the retries. Kafka's idempotent producer does the same per producer session; SQS FIFO with MessageDeduplicationId per five minutes; Azure Service Bus with duplicate detection per configured window. None of them help once the window passes or a different process re-sends the event, so consumers still deduplicate.

Experiment 2: check-then-act is a race

500 payment messages, each delivered to two workers at the same moment (a redelivery after an ack timeout while the first worker was still busy). Each worker "calls the gateway" for 0.5 ms:

Text
check, then insert:                         997 charges, 497 duplicates
unique constraint in the same transaction:  500 charges, 0 duplicates

SELECT … WHERE msg_id = ? followed by an insert let both workers see "not processed" and both charge: 497 of 500 payments doubled. With INSERT … ON CONFLICT DO NOTHING RETURNING 1 first, the second worker's insert waited on the first one's uncommitted key, then found the conflict and skipped. Deduplication needs the database's uniqueness guarantee (or a lock), not a read.

Experiment 3: dual writes versus the outbox

1,000 orders. Each must be saved in PostgreSQL and announced as an OrderPlaced event. The process crashes 2% of the time between the two steps:

Text
commit, then publish: 1000 orders,  977 events; orders with no event 23, events with no order 0
publish, then commit:  973 orders, 1000 events; orders with no event 0,  events with no order 27
outbox + relay:       1000 orders, 1000 events; orders with no event 0,  events with no order 0, relay crashed 17 times

Writing to two systems without a shared transaction is the dual-write problem: whichever goes first, a crash leaves them disagreeing. 23 kitchens never heard about paid orders, or 27 kitchens cooked orders that didn't exist. The transactional outbox writes the order and an outbox row in one transaction; a relay publishes unsent rows and marks them. The relay crashed 17 times after publishing and before marking, so it republished those rows; it used the outbox row ID as the message ID, so the broker's dedup window absorbed the repeats. In production the relay is often Debezium reading the outbox table from the WAL (chapter 63), and consumers deduplicate on the event ID.

Experiment 4: what idempotence costs

5,000 messages, one transaction each, with and without the dedup insert:

Text
without a dedup insert: 0.473 ms per message
with a dedup insert:    0.541 ms per message

About 14% more per message, or 0.07 ms, for a guarantee that turns duplicate payments into non-events. Keep the processed table bounded: delete rows older than the longest possible redelivery delay (plus a margin), or partition it by day and drop old partitions.

Try it yourself

  1. In experiment 2, wrap check-then-act in SERIALIZABLE isolation and count retries and duplicates.
  2. Make the relay in experiment 3 publish without a message ID and count duplicate events; then deduplicate them in the consumer.
  3. Shorten JetStream's duplicate_window to 1 second, publish, wait 2 seconds, publish again with the same ID. What's stored?
  4. Replace the processed table with an idempotency key on the business table (UNIQUE (payment_id) on charges). What do you lose?

Revision sheet: delivery semantics

Key ideas

  • The three guarantees come from the order of "do the work" and "acknowledge/commit": ack first is at-most-once, work first is at-least-once.
  • Exactly-once delivery is impossible over unreliable networks (two generals; the FLP-style uncertainty of a timeout). Exactly-once processing is achievable: at-least-once delivery plus idempotent, atomic effects.
  • Producer side: idempotent producers (Kafka PID + sequence), dedup windows (JetStream, SQS FIFO, Service Bus), business IDs.
  • Consumer side: dedup tables in the same transaction, unique constraints, natural idempotence (SET status = 'PAID'), conditional updates with versions, idempotency keys for external APIs.
  • Kafka EOS: transactional producer + sendOffsetsToTransaction + read_committed; it covers Kafka-to-Kafka only.
  • Outbox and inbox: outbox avoids dual writes on the producer; inbox (dedup table) on the consumer; CDC relays.
  • Side effects outside a transaction (email, SMS, third-party calls) need provider idempotency keys, intent records and reconciliation.

Numbers to remember

  • Lab: dedup window 2,000→1,000 stored; check-then-act doubled 497 of 500 payments, a unique constraint 0; dual writes lost 23 events or invented 27, the outbox 0; a dedup insert added 0.07 ms (14%) per message.

Pitfalls

  • Believing a broker's "exactly-once" flag covers your database or emails.
  • Deduplicating with SELECT-then-INSERT.
  • Dedup marker and effect in separate transactions.
  • Unbounded dedup tables; windows shorter than redelivery delays.
  • Dual writes to a database and a broker.
  • New message IDs generated on each retry.

Glossary

  • Effectively-once: each message's effect happens once despite repeated delivery.
  • Idempotent: applying an operation twice has the same effect as once.
  • Idempotency key: client-supplied ID a server uses to deduplicate requests.
  • Dual write: updating two systems without a shared transaction.
  • Transactional outbox: events stored in the same transaction as state, published later.
  • Inbox: consumer-side table of processed message IDs.