# Exactly-Once Processing, For Real

Page title: Exactly-Once Semantics

> A deep dive into at-least-once vs. exactly-once semantics, idempotency, and the transactional outbox pattern for reliable data pipelines.

Canonical page: <https://sandgraal.github.io/letstalkcdc/exactly-once/>

> **Known errata for this page (2)**
>
> - **Corrected: exactly-once is a per-hop question** (updated 2026-10-09)
>
>   This page said exactly-once was not achievable and that source connectors such as Debezium are at-least-once into Kafka. That is too blunt. Since Debezium 3.3 the documentation describes an opt-in exactly-once mode for Kafka Connect source connectors (MariaDB, MongoDB, MySQL, Oracle, PostgreSQL, SQL Server), built on Kafka transactions. It needs distributed mode, Kafka Connect 3.3.0 or later, `exactly.once.source.support=enabled` on the workers and `exactly.once.support=required` on the connector. It is off by default, and Debezium's own page still says it provides at-least-once delivery, has no internal deduplication layer, and that it is unclear whether the implementation is fully correct. It lists KAFKA-17734, KAFKA-17754 and KAFKA-17582 as open; as of 2026-10-09 KAFKA-17754 (a delayed EndTxn causing aborted reads and lost writes) is marked resolved in Apache JIRA via KIP-890, and the other two remain open. Kafka transactions make writes and offsets atomic inside Kafka; they do not cover a database, a warehouse load or an HTTP call. The page now answers hop by hop. The sink still has to be idempotent, keyed on the primary key and ordered by source log position. The errata page's source-connector note was updated to match.
> - **Corrected: the event-ID table needs the same transaction** (updated 2026-10-12)
>
>   The deduplication-table recipe said to insert the event ID into a `processed_events` table and proceed. Done as two separate steps, a crash after the ID is recorded and before the sink write skips the replayed event as a duplicate, and the change is lost permanently. The ID insert and the sink write must happen in the same transaction. The page also now says, beside the pseudocode and the two event-ID `MERGE` examples, that they remove replays only: the sink still needs the upsert ordered by source log position. The Snowflake-style and BigQuery statements are labelled as not run. The page also described the event-ID statements as skipping an event they have already seen; they leave the table unchanged when the event comes again, by re-applying the same payload. The deduplication table needs a primary key or unique constraint on the event ID in the same transactional store as the sink; in PostgreSQL a unique violation aborts the transaction, so use `INSERT ... ON CONFLICT DO NOTHING` and check the row count.
>
> [See all corrections and caveats](https://sandgraal.github.io/letstalkcdc/errata/)

Cut through marketing myths. See which hops of a CDC pipeline can be exactly-once, which cannot, and how to build sinks that behave idempotently under failure.

See the Failure Mode Run the Interactive Demo

Whether a CDC pipeline is "exactly-once" depends on *which hop* you ask about. Exactly-once *delivery* across *independent* systems (DB → Kafka → warehouse/search) is not achievable end to end, but individual hops can be, under conditions. What we actually ship is **Exactly-Once *Processing* (EOP)**: combine **[At-Least-Once](https://sandgraal.github.io/letstalkcdc/glossary/#at-least-once) (ALO)** transport with **idempotent** sinks so replays don’t create duplicates. ALO stays the default stance on this site, and EOP is still required even when one hop is exactly-once.

## Exactly-once, hop by hop

| Hop | Can it be exactly-once? | How | Caveat |
| --- | --- | --- | --- |
| Source database → Kafka (a Kafka Connect source connector such as Debezium) | Only if you opt in | Kafka Connect exactly-once source support ([KIP-618](https://cwiki.apache.org/confluence/display/KAFKA/KIP-618%3A+Exactly-Once+Support+for+Source+Connectors), built on Kafka transactions, [KIP-98](https://cwiki.apache.org/confluence/display/KAFKA/KIP-98+-+Exactly+Once+Delivery+and+Transactional+Messaging)). Needs distributed mode and Kafka Connect 3.3.0 or later, `exactly.once.source.support=enabled` on the workers, `exactly.once.support=required` on the connector, and `transaction.boundary=poll` (the default for Debezium). Debezium documents it from 3.3 for MariaDB, MongoDB, MySQL, Oracle, PostgreSQL and SQL Server. | Off by default. Debezium's own page still opens with "at-least-once" and says it has no internal deduplication layer. It also says it is unclear whether the implementation is fully correct, that no comprehensive study exists, and that Jepsen reports on Redpanda and Bufstream raise concerns about Kafka transactions. It lists KAFKA-17734, KAFKA-17754 and KAFKA-17582 as open; as of 2026-10-09 KAFKA-17754 (a delayed EndTxn causing aborted reads and lost writes) is marked resolved in Apache JIRA via KIP-890, and the other two remain open. |
| Kafka → Kafka (Kafka Streams, transactional consume-process-produce) | Yes, inside Kafka, when enabled | Kafka Streams with `processing.guarantee=exactly_once_v2`, or transactional producers using `sendOffsetsToTransaction` (a [Kafka transaction](https://sandgraal.github.io/letstalkcdc/glossary/#kafka-transaction)), make the output writes and the consumer offsets atomic. | The scope is Kafka topics only, and consumers must set `isolation.level=read_committed` (the default is `read_uncommitted`). Related transaction issues remain open. |
| Kafka → an external sink (database, warehouse load, search index, HTTP call) | No, not as delivery | Exactly-once *processing*: an idempotent upsert keyed on the primary key, applied only if the change's source log position is newer than the one stored, with deletes kept as delete markers. Optionally also [store the offsets in the sink's own transaction](https://sandgraal.github.io/letstalkcdc/glossary/#offsets-in-sink-transaction) with the data, where the sink supports one. | Kafka's transaction does not reach into the sink. If you commit offsets separately from the sink write, a crash between the two replays the event and the sink must absorb it. Storing the offsets in the sink's own transaction closes that window for this hop when the sink supports it. An idempotent, position-ordered upsert is still the default because it also covers replays, backfills and duplicates from the first hop, so it is required even if the first hop is exactly-once. |
| End to end, across independent systems | No | Compose the hops: ALO (or opt-in EOS) transport, then an idempotent, position-ordered sink, so the *observable effect* is exactly-once. | No single transaction spans the source database, Kafka and the destination, so the guarantee is per sink, not global. |

Read the full caveats on [Debezium's exactly-once delivery page](https://debezium.io/documentation/reference/stable/configuration/eos.html) before relying on the first row. For the settings behind each hop, what each guarantee really covers, and how to check what your own pipeline gives, continue with [Is CDC exactly-once? Per hop](https://sandgraal.github.io/letstalkcdc/is-cdc-exactly-once/).

How a CDC pipeline behaves during failures is defined by its data delivery guarantees:

- **At-Most-Once:** The weakest guarantee. A message is sent once, but if a failure occurs before it's processed, the message is lost forever. Unsuitable for critical data.
- **At-Least-Once:** The most common default. The system ensures every message is delivered, but a message might be delivered more than once during a retry. This prevents data loss but requires consumers to handle duplicates.
- **Exactly-Once Processing:** The effective goal. The system delivers every message at least once, and the consumer is designed to process each unique message precisely one time, even if it receives duplicates.

## The Problem: Duplicates in At-Least-Once Systems

Imagine a consumer reads an event from a Kafka topic, processes it (writes to a database), and then crashes before it can commit the topic offset. When the consumer restarts, it will re-read the same event, leading to duplicate processing. The interactive demo below walks through this failure scenario.

### 1. Consume Message

The consumer service pulls a message (`Order #123`) from the message broker.

### 2. Process & Write to Sink

The service processes the order and successfully inserts a record into the `orders` table in the downstream database.

### 3. CRASH! 💥

Before the service can acknowledge the message by committing its offset to the broker, the service crashes. The broker assumes the message was never processed.

### 4. Restart & Re-process

The service restarts. Since the offset was not committed, it fetches the same message (`Order #123`) again and inserts a *duplicate record* into the `orders` table.

🎬

Ready to start

## The Solution: Idempotent Consumers

For the ordering and delete settings of specific targets, see [Which Row Wins in Your Target](https://sandgraal.github.io/letstalkcdc/which-row-wins/).

**Idempotency** is the property of an operation that allows it to be applied multiple times without changing the result beyond the initial application. An idempotent consumer can safely process the same message multiple times with no side effects. This requires two things:

1. **A Unique, Deterministic Event ID:** Every change event must have a unique identifier. This can be a UUID from an outbox table or a composite key of the source table's primary key and the transaction's log position.
2. **[Deduplication](https://sandgraal.github.io/letstalkcdc/glossary/#deduplication) Logic at the Sink:** The consumer uses this ID to check if the event has already been processed before applying the change. Common patterns include:
   - **Using `MERGE` or `UPSERT`:** The sink database handles the logic of creating a new record or updating an existing one atomically. This is the preferred method.
   - **Using a Deduplication Table:** The consumer first tries to `INSERT` the event ID into a `processed_events` table. If it succeeds, it proceeds; if it fails (due to a primary key violation), it knows the event is a duplicate and can be safely ignored. The ID insert and the sink write must happen in the **same transaction**: if the ID is recorded and the process crashes before the sink write, the replayed event is skipped as a duplicate and the change is lost permanently. This needs a primary key or unique constraint on the event ID, in the same transactional store as the sink. In PostgreSQL a unique violation aborts the transaction, so use `INSERT ... ON CONFLICT DO NOTHING` and check the row count.
   - **Staging + MERGE:** Land events into a staging table keyed by `event_id`, then `MERGE` into the target to make replays safe.

*Commit order:* write to sink → then commit offsets. If offsets commit first, a crash can drop data; idempotent sinks tolerate replays after restart.

### Naive Consumer

```
// Pseudocode: may create duplicates
for (event of stream) {
  // Simple insert will create a new
  // record for every retry.
  insert_into_sink(event.payload);
  commit_offset();
}
```

### Idempotent Consumer

```
// Pseudocode: safe from duplicates
for (event of stream) {
  // MERGE/UPSERT handles existing records
  // based on a primary key.
  upsert_into_sink(
    event.key,
    event.payload
  );
  commit_offset();
}
```

**These dedupe replays only.** Keyed on the primary key alone, `upsert_into_sink(event.key, event.payload)` lets a late, older change overwrite a newer row, and the two event-ID `MERGE` statements below leave the table unchanged when they see an event again (they re-apply the same payload) but do nothing about order. The sink still needs the position-ordered upsert (apply a change only if its source log position is greater than the one stored, as the per-hop table above says; see [Making Sinks Bulletproof](https://sandgraal.github.io/letstalkcdc/partitioning/#recon)).

### Warehouse MERGE (Snowflake-style)

```
MERGE INTO dw.orders AS t
USING (SELECT :event_id AS event_id, :order_id AS order_id, :payload::variant AS p) s
ON t.event_id = s.event_id
WHEN NOT MATCHED THEN
  INSERT (event_id, order_id, payload) VALUES (s.event_id, s.order_id, s.p)
WHEN MATCHED THEN
  UPDATE SET payload = s.p;  -- idempotent overwrite
```

Untested: not run in Snowflake. It dedupes replays by event ID only; it does not order changes.

### BigQuery MERGE (idempotent)

```
MERGE `dw.orders` t
USING (SELECT @event_id AS event_id, @order_id AS order_id, @payload AS payload) s
ON t.event_id = s.event_id
WHEN NOT MATCHED THEN
  INSERT (event_id, order_id, payload) VALUES (s.event_id, s.order_id, s.payload)
WHEN MATCHED THEN
  UPDATE SET payload = s.payload;
```

Untested: not run against a live BigQuery project. It dedupes replays by event ID only; it does not order changes.

## The Transactional Outbox Pattern (Solving the Dual-Write Problem)

A common anti-pattern is the "dual-write," where an application first writes to its database and *then*, in a separate network call, tries to publish a message. If the application crashes between these two steps, the systems become inconsistent. The **Transactional [Outbox](https://sandgraal.github.io/letstalkcdc/glossary/#outbox) Pattern** solves this.

![Transactional outbox pattern sequence diagram showing atomic database transaction writing both business data and event record, followed by CDC relay publishing to event bus](https://sandgraal.github.io/letstalkcdc/diagrams/outbox-pattern.svg)

Outbox pattern: Write business data and event atomically, then publish via CDC

1. An application writes both its business data (an `orders` record) and an event record to an "outbox" table within the same single, atomic database transaction.
2. A log-based CDC process monitors the outbox table. When it detects the committed transaction in the database log, it reliably reads the event from the log and publishes it to a message bus like Kafka.
3. This guarantees that an event is published if, and only if, the corresponding business transaction was successfully committed to the database. Data consistency is preserved.

**Important scope note:** Outbox makes the write *atomic* — an event is published if and only if the business transaction committed, so no events are lost or invented. But the publish step itself is *at-least-once* by default: a relay that crashes after publishing but before recording its own progress will re-emit the event. (Opting in to Kafka Connect exactly-once source support, above, narrows that first hop, with the caveats listed there.) Either way, outbox does *not* make delivery exactly-once into your sinks — you still need idempotent consumers to absorb the duplicates. The relay options, Debezium's router and the consumer guard are on [Transactional Outbox and Relay](https://sandgraal.github.io/letstalkcdc/transactional-outbox/).

### Exactly-Once Semantics Knowledge Check

Test your understanding of EOS delivery guarantees and the transactional outbox pattern.

Q1

#### What does 'exactly-once semantics' (EOS) truly guarantee in distributed systems?

A Every message is physically delivered only once across the entire system

B The observable effect is as-if each message was processed exactly once, even if retries occur

C Messages are never duplicated or lost under any circumstances

D EOS is only a marketing term and no real system offers it on any hop

Q2

#### What is the primary purpose of the Transactional Outbox pattern?

A To improve database query performance

B To ensure events are published atomically with database changes in the same transaction

C To compress event payloads

D To route events to multiple topics

Q3

#### Why is achieving true end-to-end exactly-once semantics challenging in CDC pipelines?

A CDC tools don't support EOS

B It requires coordination across multiple independent systems (database, message broker, sink)

C Databases can't provide transactional guarantees

D EOS is trivial and always works out-of-the-box

Q4

#### How does Kafka Streams achieve exactly-once semantics within Kafka?

A By preventing all message duplication

B Using transactional producers and idempotent writes, coordinated with consumer offsets

C By always using a single partition

D Through manual deduplication in application code

Q5

#### What do you rely on for a hop that can't be exactly-once delivery, such as writing into an external sink?

A Give up and accept data corruption

B Implement idempotent operations so duplicate processing is safe

C Use only batch processing

D Disable all retries

**0/5** correct

---

CDC: The Missing Manual by Christopher Ennis (Let's Talk CDC), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Attribution is required.
