Exactly-Once Semantics in Stream Processing

Exactly-once processing means results appear once within a boundary. Learn how Kafka transactions, checkpoints, and idempotent sinks shape that guarantee.

published: reading time: 15 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

Exactly-once semantics means a committed result appears once within a stated boundary, even if processing retries. Kafka transactions cover Kafka records and offsets; an external database needs its own transaction or idempotent write. At-least-once with idempotent effects is a practical starting point when the broker's durability and failure assumptions fit the workload.

Exactly-once semantics: guaranteeing data integrity in stream processing

“Exactly once” is meaningful only when the transaction boundary and failure assumptions are named. A record may be read and processed more than once after a crash; the goal is for committed output inside the stated boundary to appear as one successful result. Kafka transactions can coordinate Kafka output records with consumed offsets. A database or API is outside that boundary unless it participates in separate coordination or makes repeated effects idempotent.

This article focuses on stream-processing state and transaction boundaries. Exactly-Once Delivery covers broker delivery behavior, retries, and the limits of broker deduplication.

Why exactly-once is hard

Consider the canonical stream processing path:

Kafka (or other source) -> Processor -> Database (or other sink)

For a pipeline to produce one visible result, the guarantee must cover the failure cases and outputs that matter:

  1. The source position and output commit must be coordinated, or replay must be safe.
  2. The processing state must be restored consistently after failure.
  3. Every sink with externally visible effects must participate in the transaction or enforce idempotency.

These conditions are not met by enabling a broker or processor flag alone. State the source, outputs, transaction boundary, and failures covered before calling a pipeline exactly-once.

flowchart LR
    Source -->|1. read| Processor[Processor]
    Processor -->|2. process| DB[(Database)]
    Processor -->|3. commit offset| Source
    DB -->|4. ack| Processor

If the source position commits before the external write, a crash can lose the write. If the write succeeds before the position commits, a crash can replay the input and repeat the write. Without a shared transaction, the sink needs an idempotency key or a stored processed position.

The two-phase commit pattern

One option is two-phase commit (2PC), when both the processor and sink participate. The coordinator first asks each participant to prepare without exposing its effect. If they all prepare, it records and sends a commit decision; otherwise it aborts. The source position and sink output must both participate for the output and consumed position to advance together. Recovery depends on the coordinator’s durable decision, and a coordinator failure can leave participants waiting.

Flink checkpoints capture operator state and source positions so the job can restore a consistent processing point. End-to-end exactly-once output also depends on the sink: a transactional sink must commit in coordination with checkpoints, while other sinks need idempotent writes or their own recovery protocol. Enabling checkpointing does not make an arbitrary external sink exactly once.

// Flink: Enable exactly-once checkpointing
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(10000);  // Checkpoint every 10 seconds
env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
env.getCheckpointConfig().setCheckpointTimeout(60000);
env.getCheckpointConfig().enableExternalizedCheckpoints(
    ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

On failure, Flink restores state and source positions from the last successful checkpoint. The sink must restore or commit consistently with that checkpoint for the visible output to match it.

Kafka transactions

Kafka transactions can atomically commit consumed offsets and producer records written to Kafka. Consumers that need to ignore aborted transactional records must use read_committed. This boundary covers Kafka topics; it does not include an arbitrary database or API.

// Kafka Streams: exactly-once with transactions
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);

KafkaStreams streams = new KafkaStreams(builder.build(), props);

// The exactly-once_v2 setting uses Kafka transactions internally:
// - Consumer offsets are written to a consumer topic
// - Output records are written to output topics
// - Both are committed in a single transaction

Kafka’s idempotent producer prevents duplicate log entries from its own retry attempts. Application-level replay and effects in other systems still need the relevant transaction or idempotency strategy.

// Idempotent producer (already enabled by default)
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.RETRIES_CONFIG, Integer.MAX_VALUE);

The transactional outbox pattern

Kafka transactions cover Kafka records and offsets. When a processor writes to an external database, that write falls outside the Kafka transaction.

The outbox pattern solves the database-to-Kafka dual-write problem. The application writes its business change and an outbox row in one database transaction. A relay later publishes the row to Kafka. The relay can publish more than once if it crashes after sending but before recording progress, so consumers still need a stable event ID and idempotent handling.

flowchart LR
    App[Application] -->|1. begin tx| DB[(Database)]
    App -->|2. write to outbox| DB
    App -->|3. commit tx| DB
    DB -->|4. read outbox| Relay[Outbox Relay]
    Relay -->|5. publish to Kafka| Kafka
    Relay -->|6. mark published| DB

The database transaction makes the business change and outbox record atomic. The relay provides eventual, usually at-least-once publication; it does not make the Kafka publish and an unrelated database write one transaction. See Exactly-Once Delivery for broker retries, outbox use, and sink idempotency.

Idempotent consumers

Idempotency is one way to make retries safe. Reapplying the same input should leave the sink in the same state, or the sink should recognize a stable event ID and skip a repeated effect. Store the deduplication record and business update in the same database transaction when both are in that database.

An idempotent consumer ignores duplicates:

def process_order(event_id, order_id, order_data):
    """
    Idempotent order processing.
    Claims the event_id in the same transaction as the order update.
    """
    with db.transaction() as tx:
        inserted = tx.execute(
            "INSERT INTO processed_events (event_id) VALUES (%s) "
            "ON CONFLICT (event_id) DO NOTHING RETURNING event_id",
            event_id,
        ).fetchone()
        if inserted:
            tx.execute(
                "INSERT INTO orders (order_id, data) VALUES (%s, %s) "
                "ON CONFLICT (order_id) DO UPDATE SET data = EXCLUDED.data",
                order_id, order_data,
            )

The event ID claim and order update commit together. A retry after a successful commit finds the event ID and skips the update. This protects only effects included in that database transaction.

For stateful aggregation, make the update repeatable or coordinate state and output with a checkpoint-aware sink. Checkpointing helps restore processor state; it does not make an unrelated sink transactional.

When you need exactly-once

Stronger transaction or idempotency controls matter when duplicate effects are costly, for example:

  • Financial transactions: A payment must not be processed twice
  • Inventory updates: An item must not be reserved twice
  • Billing records: A customer must not be charged twice

For lower-cost effects, simpler delivery plus deduplication may be enough:

  • Metrics aggregation: If you miss one page view in a count of millions, the error is negligible
  • Click tracking: Same reasoning as metrics
  • Non-critical logs: Missing or duplicating a log entry rarely matters

Exactly-once processing has a cost. Checkpoints, transactions, or sink coordination add operational work and can add latency. For many pipelines, at-least-once processing with idempotent effects is simpler, provided its replay and durability assumptions fit the workload.

At-least-once vs exactly-once

At-least-once is often a practical starting point. The broker retries according to its durability, acknowledgment, and retention settings; consumers should expect duplicates, and the failure model still determines whether messages can be lost.

For many use cases, at-least-once with an idempotent sink produces the required result. Replaying a message is safe only if every visible effect is idempotent or deduplicated.

# This consumer uses a stable key so replay does not create another row.
@task
def load_orders_to_warehouse(orders):
    """
    Idempotent load: uses UPSERT (INSERT ON CONFLICT).
    Processing the same order twice produces the same result.
    """
    for order in orders:
        warehouse.execute("""
            INSERT INTO orders (order_id, data)
            VALUES (%s, %s)
            ON CONFLICT (order_id) DO UPDATE SET data = EXCLUDED.data
        """, order.order_id, order.data)

Measuring exactly-once

How do you know if your pipeline is truly exactly-once? You test it.

Chaos testing: Kill processes mid-execution. Restart. Verify that output is correct and no duplicates exist.

Inject duplicates: Intentionally inject duplicate messages into the stream. Verify that output contains each record exactly once.

Check output cardinality: For a given input, verify that output count matches input count (no duplicates, no losses).

Common exactly-once pitfalls

Assuming Kafka exactly-once covers external systems

Kafka can atomically commit Kafka output records and consumed offsets in a transaction. A database write, HTTP call, or object-store update is outside that boundary unless the sink has a separate coordination protocol.

If the database write succeeds but the Kafka offset does not commit, a crash can cause the input to be replayed and the write repeated. If the offset commits first and the database write fails, the effect can be missing. Store a stable event ID or source position with the database update in one database transaction, or use a sink that coordinates its commit with Kafka. Otherwise make the effect idempotent and accept the failure model of at-least-once processing.

An outbox addresses a different direction: it commits a database change and an outbox row together, then a relay publishes that row to Kafka. The relay may publish more than once, so downstream consumers still need idempotency.

Checkpointing too infrequently

Checkpoint frequency trades recovery work against checkpoint overhead. A longer interval can mean more input must be replayed after a failure; it does not by itself mean those events are lost.

For example, a job that crashes nine minutes after its last successful checkpoint may reprocess those nine minutes of input. The processor restores state from the checkpoint, but the visible result still depends on whether the sink commits consistently or handles repeated writes safely.

In Flink, checkpoint completion depends on state size and storage as well as the configured interval. A slow checkpoint can extend recovery exposure. Set timeouts and monitor checkpoint duration against the job’s recovery target.

Choose an interval from measured checkpoint cost, replay volume, and recovery objectives. Test failures in a staging environment and verify both restored state and sink output.

State store growth

Flink’s checkpointing persists operator state: window buffers, join hashes, session trackers. Under continuous input, state grows without bound unless you actively cap it. A windowed aggregation where the watermark never advances holds all its data indefinitely. A sessionization operator tracking open sessions accumulates entries as long as sessions stay open.

Watermark configuration can affect state cleanup. Flink cleans up window or session state when the watermark passes its expiration boundary. If a source emits events with infrequent timestamps, such as hourly batch files, the watermark may stall and state can accumulate. Monitor watermark progress and state size.

Configure TTL for state that may expire, and understand how the selected state backend performs cleanup. Also set a watermark strategy and allowed lateness that match the source’s event-time behavior.

Watch state size in development. Use Flink’s REST API to inspect state per operator and set alerts for unexpected growth. If the store doubles every hour, the watermark is probably stalled or a window is never closing.

Production failure scenarios

Duplicate output after crash during dual write

The consumer writes an order to the database, then crashes before committing its Kafka offset. On restart, Kafka can deliver the record again, and a plain insert may create a duplicate.

Kafka transactions coordinate Kafka output records and offsets, not the database write. The consumer can store the event ID or source position in the same database transaction as the business update, or make the update idempotent so a replay has no additional effect.

Use an outbox when a service must publish an event for a database change. It commits the business write and an outbox row in one database transaction; a relay then publishes the row, usually with at-least-once behavior. For a Kafka-to-database consumer, record the processed ID or offset alongside the database effect instead.

Checkpoint restore produces inconsistent window state

A stateful Flink job may crash while a window is open. A completed checkpoint captures a consistent point in the job’s state and input; on recovery, Flink restores that state and replays later input. The window’s partial state can therefore continue without counting the same pre-checkpoint records twice, provided the source and checkpoint protocol are configured correctly.

Visible output still depends on the sink. A transactional sink must commit consistently with the checkpoint. A non-transactional external sink may see repeated writes when input is replayed, so use idempotency or a sink-specific recovery protocol. Test failures around checkpoint completion and window emission, and compare sink output with an uninterrupted run.

Unique constraint race in idempotent consumers

Two instances process the same order_id at once. Both check and find no row, then attempt an insert. The database accepts one and rejects the other on the unique constraint.

The race window is between the SELECT and INSERT. If the same key arrives close together, both queries can find no row before either insert commits. The database then accepts one insert and rejects the other.

If the failed instance retries, it can detect the existing row and complete. Handle the uniqueness conflict as a duplicate where appropriate, and keep the processed event ID or business key in the same transaction as the effect.

For PostgreSQL, INSERT ... ON CONFLICT can make the state update atomic; MySQL has INSERT ... ON DUPLICATE KEY UPDATE. Choose the conflict action carefully so a repeated event does not overwrite newer state with stale data. Kafka producer idempotence does not deduplicate database writes.

Kafka exactly-once skipping writes to non-transactional sinks

Kafka transactions can atomically commit Kafka records and offsets, but a Parquet file or S3 upload is outside that transaction. A sink must coordinate commit with the consumed position or make writes repeatable. Otherwise a crash can leave the file and offset out of sync.

Use transactional sinks, or build a reconciliation process to detect and fill gaps.

Trade-off table: exactly-once approaches

Aspect Kafka Transactions Flink Checkpointing Spark Checkpointing Idempotent Consumer
Scope Kafka records + offsets Restores source and operator state; sink must coordinate Restores source and operator state; sink must coordinate Sink-side only
State management Local RocksDB Distributed RocksDB RocksDB No state
Recovery time Milliseconds Depends on checkpoint Depends on checkpoint Immediate
Throughput cost Low Medium Medium None
External sink support No Yes (if transactional) Yes (if transactional) Yes
Complexity Low High Medium Low
Exactly-once for aggregates No Only with compatible sink Only with compatible sink Only if updates are idempotent
Best for Kafka-native pipelines Stateful Flink jobs Stateful Spark jobs External database sinks

Kafka transactions for pure Kafka pipelines. Idempotent consumers with at-least-once delivery for external sinks. Flink or Spark checkpointing for stateful aggregations across arbitrary sources.

Capacity estimation

Transaction overhead

Kafka transactions add latency. The producer gathers records and commits atomically. Overhead depends on transaction size and transaction.timeout.ms.

# Small transactions: lower latency, higher per-transaction overhead
transaction.timeout.ms=10000
batch.size=16384

# Large transactions: higher latency, lower per-transaction overhead
transaction.timeout.ms=300000
batch.size=524288

A transaction committing every 10 seconds at 100K records/sec commits 1M records. The commit is a round-trip to the broker leader. At 10ms per round-trip, that is fine. At 500ms, it becomes a bottleneck.

Checkpoint storage

Checkpoint size drives recovery time and storage cost.

# Estimate Flink checkpoint size
# 10M state entries, 500 bytes per entry, 2x serialization overhead
state_entries=10_000_000
bytes_per_entry=500
serialization_factor=2

checkpoint_size_mb=$((state_entries * bytes_per_entry * serialization_factor / 1024 / 1024))
# ≈ 9.5 GB per checkpoint

# 3 checkpoints retained (recovery + cleanup gap):
total_storage_gb=$((checkpoint_size_mb * 3 / 1024))
# ≈ 28.5 GB

A 10GB checkpoint writing to S3 in 60 seconds requires ~170 MB/sec sustained bandwidth. Profile this before production.

Recovery time

Recovery time is checkpoint restore time plus replay time.

# Restore: read checkpoint from storage
checkpoint_size_gb=10
storage_read_bandwidth_mbps=500  # S3 or HDFS
restore_seconds=$((checkpoint_size_gb * 1024 / storage_read_bandwidth_mbps))
# ≈ 20 seconds for 10GB at 500 MB/sec

# Replay: records from the offset gap
# depends on processing rate

Flink also redistributes state across TaskManagers on recovery. A 10TB state with 100 partitions means ~100GB per TaskManager over the network. At 1Gbps, that is ~800 seconds. Use incremental checkpoints to reduce this.

Quick recap

  • Exactly-once describes one visible result within a stated boundary, not one physical read.
  • The hard part is crossing system boundaries. Kafka-to-Kafka is tractable. Kafka-to-database requires more.
  • Kafka transactions only cover Kafka. External sinks need idempotency or outbox.
  • At-least-once with idempotent effects is a practical starting point when its failure assumptions fit. Use stronger coordination where duplicate effects have a real cost and the boundary can be implemented.
  • Recovery time is checkpoint_interval plus replay. Size your interval by your recovery time objective.

Conclusion

Exactly-once behavior depends on the boundary you can actually coordinate. Name the source, output, commit protocol, and failure cases before choosing it.

Within Kafka, a transaction can commit output records and consumed offsets together when consumers read committed data. For an external database, use a sink transaction that also records the input position, or make the write idempotent. Flink or Spark checkpointing restores processor state; the sink still needs compatible commit or recovery behavior.

For many pipelines, at-least-once delivery with idempotent consumers is simpler and sufficient. Use stronger coordination when duplicate effects have a real cost and the required boundary can be implemented and tested.

For related reading, see Exactly-Once Delivery, Apache Kafka, Kafka Streams, and Apache Flink.

Category

Related Posts

Change Data Capture: Tracking Database Changes with CDC

Compare log-based, trigger-based, and polling CDC. See how snapshot handoff, offsets, duplicates, ordering, schema changes, and deletes affect consumers.

#data-engineering #cdc #database-replication

Dead Letter Queues: Handling Message Failures Gracefully

Design and implement Dead Letter Queues for reliable message processing. Learn DLQ patterns, retry strategies, monitoring, and recovery workflows.

#data-engineering #dead-letter-queue #kafka

Kafka Streams: Real-Time Stream Processing Applications

Kafka Streams is a client library for real-time stream processing. Learn stream primitives, state stores, exactly-once processing, and scaling.

#data-engineering #kafka-streams #stream-processing