6 minute read

“Exactly once” cannot be evaluated as one boolean property of a framework. Kafka can make a producer write each logical record once to a partition, a processor can restore deterministic state, and an external database can still receive an effect twice. The unit of guarantee, its failure domain, and the commit boundary all matter.

This comparison uses the same incident at each layer: a job reads a debit event, updates an account balance, writes a result, and crashes after the downstream write succeeds but before the local progress record is known to be durable. The important question is which component knows that the write happened.

The same uncertain failure at transport, processor, and sink boundaries

One failure, three boundaries

Suppose event payment-1842 is accepted at Kafka offset 91:

Kafka offset 91 -> processor state -> sink transaction
                         |                  |
                         +-- balance +$42 --+
                                  ?

The process writes +$42 to the sink, then fails before acknowledging offset 91 or completing its checkpoint. Recovery has no generic way to distinguish these cases:

  1. the sink write was lost, so the event must be applied;
  2. the sink write committed, so it must not be applied again;
  3. the response was lost and the transaction’s outcome is unknown.

Replaying the event is safe only when the sink makes its second attempt converge. Kafka transactions, framework checkpoints, and idempotent sinks solve different parts of that uncertainty. A checkpoint alone does not roll back an HTTP request or a database commit made outside the checkpoint protocol.

Kafka: idempotence and transactions inside the log

Kafka’s idempotent producer closes duplicates caused by producer retries within a producer session. The broker recognizes the producer ID and sequence number and will not append the same sequence twice. Kafka transactions extend the atomic boundary to reads and writes across multiple output partitions and to a consumer position stored in __consumer_offsets.

A Kafka Streams-style read-process-write loop needs three things:

Properties props = new Properties();
props.put("bootstrap.servers", "kafka-1:9092,kafka-2:9092");
props.put("application.id", "balances-v4");
props.put("processing.guarantee", "exactly_once_v2");
props.put("enable.idempotence", "true");

For raw producers and consumers, the equivalent protocol is explicit:

producer.initTransactions();
producer.beginTransaction();
try {
  ProducerRecord<String, String> result =
      new ProducerRecord<>("balance-changes-v1", key, value);
  producer.send(result).get();
  producer.sendOffsetsToTransaction(
      offsets,
      new ConsumerGroupMetadata("balance-processor"));
  producer.commitTransaction();
} catch (Exception uncertain) {
  producer.abortTransaction();
  throw uncertain;
}

Consumers must use read_committed to hide aborted and in-progress output. A transaction is atomic in Kafka, but it is not automatically atomic with PostgreSQL, an HTTP endpoint, or an object-store manifest. Also, “exactly once” does not mean that an input producer which retries with a new producer identity or a newly generated event ID will be recognized as the same business operation. Preserve a stable business event ID at the producer boundary.

Flink checkpoints coordinate input positions and keyed operator state at a consistent point in the dataflow. After task failure, Flink can restore state and source offsets from the same completed checkpoint, then replay newer records. This is a processing guarantee, not yet a universal output guarantee.

For Kafka-to-Kafka, Flink’s KafkaSink can participate in checkpoint-completion semantics. Configure delivery and consumer visibility together:

env.enableCheckpointing(Duration.ofSeconds(30).toMillis());
env.getCheckpointConfig().setCheckpointingMode(
    CheckpointingMode.EXACTLY_ONCE);

KafkaSink<BalanceChange> sink = KafkaSink.<BalanceChange>builder()
    .setBootstrapServers("kafka-1:9092")
    .setRecordSerializer(
        KafkaRecordSerializationSchema.builder()
            .setTopic("balance-changes-v1")
            .setValueSerializationSchema(new JsonSchema<>())
            .build())
    .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
    .setTransactionalIdPrefix("balances-v4")
    .build();

EXACTLY_ONCE sinks generally stage a transaction during a checkpoint and complete it only after Flink finalizes that checkpoint. An old transaction is aborted or resolved during recovery. Kafka readers downstream must use read_committed; otherwise they can observe uncommitted records and mistake visibility for correctness.

A sink can join this protocol only if it supports transactional preparation, finalization, and recovery. A SinkFunction that performs an irreversible database call in invoke has no such coordination. For that case, use an event-ID uniqueness constraint, an atomic upsert, or an outbox. Exactly-once Flink state plus at-least-once external side effects still gives at-least-once end-to-end behavior.

Beam: the contract depends on the runner

Apache Beam defines a portable programming and windowing model; its delivery guarantee is supplied by a particular runner and connector. A runner can checkpoint source progress, bundle finalization, state, and timers. Beam bundle failure commonly means deterministic transforms execute again. It does not make arbitrary non-deterministic ParDo behavior safe.

For example, a Beam dedupe state cell must be keyed and durable:

public class DedupePayment extends DoFn<Payment, Payment> {
  @StateId("seen")
  private final StateSpec<SetStateSpec<String>> seen =
      StateSpecs.set();

  @ProcessElement
  public void process(
      @Element Payment payment,
      @StateId("seen") SetState<String> seen,
      OutputReceiver<Payment> out) {
    if (seen.contains(payment.id()).read() == null) {
      seen.add(payment.id());
      out.output(payment);
    }
  }
}

That state should have a retention policy matching the maximum source and replay delay. It cannot prove that an external side effect from an earlier bundle committed exactly once. Google Cloud Dataflow and other runners may provide effectively-once output for supported connectors through checkpointing and sink-specific commit mechanisms, but runner capabilities and sink version must be documented and tested. Portable Beam code is not itself an exactly-once transaction spanning every destination.

Spark Structured Streaming: micro-batches and sink-specific commit

Spark records source offsets, state, and completed batches in a checkpoint directory. On restart, it resumes from committed progress. By default, a deterministic transformation and a sink that correctly integrates with Spark’s batch-ID transaction model can produce one logical write per batch.

For an arbitrary database, implement convergence in the sink rather than assuming Spark provides it:

events.writeStream
  .foreachBatch { (batch: Dataset[Payment], batchId: Long) =>
    batch.withColumn("batch_id", lit(batchId)).createOrReplaceTempView("input")
    batch.write
      .format("jdbc")
      .option("url", jdbcUrl)
      .option("dbtable", "stage_payment_batch")
      .mode("append")
      .save()

    executeMerge(
      """MERGE INTO account_event AS target
         USING (SELECT * FROM stage_payment_batch) AS source
         ON target.event_id = source.event_id
         WHEN NOT MATCHED THEN INSERT ..."""
    )
  }
  .option("checkpointLocation", "s3://checkpoints/balances/v4")
  .start()

The staging table must isolate batch retries and the merge must run atomically with a unique event_id. For append-only Parquet, a separate commit manifest or a table format with atomic commits is usually needed. A path write plus a Spark checkpoint is not one distributed transaction. Kafka sink support, availability of idempotent sink behavior, and Spark version also matter; verify the selected connector rather than relying on a generic “exactly once” label.

Comparison matrix

System Restores processor/source progress Native coordinated output boundary End-to-end statement
Kafka producer Sequence per producer session Kafka partitions Idempotent appends inside Kafka; no external sinks
Kafka transactions Consumer offsets plus topic writes Multi-partition Kafka records Atomic Kafka read-process-write with read_committed
Flink + transactional sink Consistent source offsets and operator state Supported Kafka/JDBC/filesystem sink depending on connector Exactly once at the coordinated boundary; otherwise idempotent side effects
Beam runner + supported I/O Runner-managed state and source progress Runner- and sink-specific Effectively once only for documented runner/sink combinations
Spark Structured Streaming Query offsets, state, batch commits Batch-aware transaction only where the sink implements it At-least-once risk remains for arbitrary external writes

Verify the claim with the same crash

Use an integration test that pauses after the downstream effect commits but before the framework records completion. Then:

  1. confirm the stable payment-1842 event ID;
  2. stop the process at that pause point;
  3. restart from the previous durable checkpoint or transaction;
  4. replay offset 91;
  5. assert one sink effect, while allowing two processing attempts;
  6. verify two concurrent copies of the event cannot both win.

For a relational sink, a unique key plus one transaction is the practical invariant:

BEGIN;
INSERT INTO applied_event (event_id, payload_hash)
VALUES ('payment-1842', 'sha256:...')
ON CONFLICT (event_id) DO NOTHING;

-- Execute the balance update only if the insert returned a row.
UPDATE account_balance
SET cents = cents + 4200
WHERE account_id = 'account-7';
COMMIT;

The second command must be conditional on the insert winning. An unconditional update after ON CONFLICT still duplicates the effect.

Keep event IDs long enough to cover producer retries, source retention, maximum outage, and deliberate backfill. A 24-hour in-memory dedupe cache does not survive a seven-day replay. Name the transport, processor-state, and sink guarantees separately in design documents. That vocabulary is less impressive than a single “exactly once” label, but it tells an operator precisely where duplicates can appear and how recovery is expected to behave.