"Exactly once" sounds simple: an event arrives, you process it, and the result happens once, never zero times and never twice. Distributed systems rarely offer anything that broad.
Kafka does provide exactly-once processing in important cases. Idempotent producers stop broker-level retries from creating duplicate records, and transactions can tie the offsets you consumed to the records you produced, atomically. Kafka's design documentation describes exactly-once for read-process-write workflows where both input and output stay inside Kafka.
The confusion starts when that gets stretched into "if I use Kafka's exactly-once semantics, everything my event causes happens exactly once". Picture a consumer that reads a payment event, updates PostgreSQL, sends an email, calls a payment API and then commits its Kafka offset. Only some of those steps are part of Kafka's transaction model. The database, the payment provider and the mail server don't join a Kafka transaction just because the event came from Kafka. So the useful question isn't whether exactly_once_v2 is enabled. It's where Kafka's guarantee ends, and what takes over after that.
“Exactly once” means several things
When someone says "we have exactly once", they could mean any of these:
- producer retries don't create duplicate Kafka records
- a consume → process → produce step commits atomically
- application state is updated once
- a database row changes once
- a customer is charged once
- an email is sent once
- an event can never be processed again
These aren't the same guarantee. The first two can be properties of Kafka itself, with the right configuration. The rest involve application logic or outside systems Kafka doesn't control. Before designing for exactly once, it helps to ask: exactly once where?
Idempotent producers
A producer sends order.created. Kafka appends the record, but the acknowledgement is lost on the way back. From the producer's side, a timeout doesn't say whether the broker stored the message, so it retries, and without protection you'd get two copies.
Kafka's idempotent producer handles exactly this. The broker tracks each producer's ID and a sequence number per message, so a retried send of the same record isn't appended twice:
That's valuable, but it solves one problem: a transport retry turning into a duplicate append. It doesn't help if the application sends the same business event twice, for example after losing its own state:
producer.send(
new ProducerRecord<>(
"payments",
paymentId,
paymentEvent
)
);
// application loses its own state
producer.send(
new ProducerRecord<>(
"payments",
paymentId,
paymentEvent
)
);
Those are two separate sends as far as Kafka is concerned, and it has no way to know they represent one intent. That needs a stable business identity, which comes up again below.
Kafka transactions
Transactions build on idempotence. Say a service reads from orders, validates each order and writes to validated-orders. Without atomicity, a crash in the wrong place causes duplicates: read A, produce B, crash before committing the offset, restart, read A again and produce B again.
Kafka transactions fix this read-process-write case by putting the produced records and the consumed offsets in the same transaction:
producer.beginTransaction();
for (
ConsumerRecord<String, Order> record
: records
) {
ValidatedOrder result =
validate(record.value());
producer.send(
new ProducerRecord<>(
"validated-orders",
record.key(),
result
)
);
}
producer.sendOffsetsToTransaction(
offsets,
consumer.groupMetadata()
);
producer.commitTransaction();
Now either the output becomes visible and the offset advances, or neither happens. This works because consumer offsets are themselves stored in Kafka, so one transaction coordinator can manage both progress and output. That's the heart of Kafka's exactly-once model. Confluent's Transactions in Apache Kafka is a thorough walkthrough of how it works.
Two details make it hold together:
Consumers have to read committed data. Aborted transactional records can still physically sit in the log. A consumer with isolation.level=read_uncommitted may see them; one with read_committed only sees records from committed transactions. The guarantee depends on downstream readers honouring that.
Stale producers get fenced. Suppose processor A loses connectivity for a while, processor B takes over its work, and then A reconnects. It wasn't dead, just cut off. Without protection, both might keep producing for the same logical processor. Kafka uses the transactional ID and a producer epoch to fence the old instance: once a newer producer registers with the same transactional ID, the old one can no longer commit. Exactly-once isn't only about deduplicating messages; it's also about controlling who owns the work after a failure.
Where the boundary ends
So far Kafka controls everything that matters: input offsets, transaction state, output records and producer identity. That's why it can coordinate them.
Now add PostgreSQL:
for (
ConsumerRecord<String, OrderEvent> event
: records
) {
orderRepository.updateStatus(
event.key(),
"PAID"
);
consumer.commitSync();
}
If the database commits and the process crashes before the offset commit, Kafka redelivers the event after a restart and the update runs again:
That's ordinary at-least-once processing. Swap the order (commit the offset, then update the database) and a crash in between means Kafka thinks the event is done while the database never changed. That's at-most-once. Process-then-commit risks duplicates; commit-then-process risks loss. The hard part is making the database commit and the Kafka offset commit atomic, and they belong to different transactional systems. producer.beginTransaction() doesn't enlist PostgreSQL, and BEGIN; ... COMMIT; in PostgreSQL doesn't enlist Kafka's coordinator.
Confluent's Transactions course and the blog post above are clear on this: if processing has side effects in other storage systems, the transaction APIs alone aren't enough. A simple way to picture it:
| Operation | Inside Kafka's transaction? |
|---|---|
| Output records to Kafka topics | Yes |
| Consumed offsets | Yes |
| Kafka Streams state stores and changelogs | Yes |
| PostgreSQL update | No |
| Payment API call | No |
| Sending an email | No |
| Writing a file | No |
Kafka's guarantee is real. It just has an edge.
Idempotent database writes
The most common approach is to accept at-least-once delivery and make the database change safe to repeat. If each event carries a stable event_id, the database can record which events it has processed:
CREATE TABLE processed_events (
event_id UUID PRIMARY KEY,
processed_at TIMESTAMPTZ
NOT NULL DEFAULT now()
);
The consumer then writes the marker and makes the business change in the same database transaction, skipping the change if the marker already existed:
BEGIN;
INSERT INTO processed_events(event_id)
VALUES ('84219000-...')
ON CONFLICT DO NOTHING;
-- only if the insert added a row:
UPDATE orders
SET status = 'PAID'
WHERE id = 'order_42';
COMMIT;
In Spring it might look like this:
@Transactional
public void handle(PaymentCompleted event) {
boolean firstTime =
processedEventRepository
.insertIfAbsent(event.eventId());
if (!firstTime) {
return;
}
orderRepository.markPaid(
event.orderId()
);
}
Kafka can now deliver the same event three times and the order is only marked paid once. This is often called effectively once: delivery may repeat, but the effect is idempotent. For many applications, that's the guarantee that actually matters.
Some operations don't need a dedupe table at all. SET status = 'PAID' gives the same result however many times it runs. SET balance = balance - 100 definitely doesn't. Useful idempotent shapes include setting a state, upserting by a stable business key, inserting under a unique constraint, compare-and-set transitions and version checks. Which one you need depends on the operation, which is another reason exactly once can't be just a Kafka setting.
The identity you deduplicate on matters too. Two different Kafka events, A and B, might both describe payment_123. Deduplicating on event ID lets both through. Often the right key is the business intent that should happen once (a payment ID, refund ID, invoice number or reservation), not the transport record carrying it. Retry-safe HTTP APIs and webhook consumers run into exactly the same thing.
External APIs and effects you can't undo
Now a consumer handles payment.requested by calling a payment provider:
async function handle(event: PaymentRequested) {
await paymentProvider.charge({
customerId: event.customerId,
amount: event.amount,
});
await commitKafkaOffset();
}
If the charge succeeds and the process crashes before committing the offset, Kafka redelivers and the charge is attempted again. Kafka can't roll back the first charge; the provider is outside its boundary. If the provider supports idempotency keys, use one based on the business operation:
await paymentProvider.charge(
{
customerId: event.customerId,
amount: event.amount,
},
{
idempotencyKey: `payment:${event.paymentId}`,
},
);
Now every redelivery refers to the same payment. That isn't Kafka's exactly-once; it's a separate mechanism combined with Kafka's delivery. End-to-end correctness is usually built this way, from several guarantees, each owned by a different system.
Some effects can't be made exactly once at all. If an SMTP server accepts an email and your consumer crashes before recording that, you can't always know whether the message went out. Retrying might send two; not retrying might send none. Unless the outside system offers some deduplication, no Kafka setting removes that ambiguity. What's acceptable depends on the effect: an occasional duplicate marketing email may be fine, while a duplicate $500 charge isn't. The design has to follow the business cost of a duplicate or a loss.
Designing around the boundary
One pattern I like is keeping the first processing step entirely inside Kafka, then writing to the database as a separate step:
The processor uses Kafka's transactional read-process-write. The database writer uses idempotent upserts and deduplication. That's not one global transaction; it's two boundaries you can each reason about clearly, which is usually better than pretending one system owns atomicity everywhere.
Kafka Streams makes the Kafka side easy:
Properties props = new Properties();
props.put(
StreamsConfig.PROCESSING_GUARANTEE_CONFIG,
"exactly_once_v2"
);
Kafka inputs, Kafka-backed state stores, Kafka outputs and consumer progress all take part in the transaction. But this doesn't:
stream.peek((key, value) -> {
stripe.charge(value);
});
The topology is exactly-once from Kafka's point of view, and the Stripe call still needs its own idempotency. It's worth writing that down explicitly in architecture docs.
Stronger guarantees also cost something. Transactions add coordination work, and a read_committed consumer can't see records from a transaction until it commits, which adds latency. So rather than starting with "can we turn on exactly once?", start with "what failure are we preventing, and what does the business need?" Sometimes at-least-once with an idempotent upsert is simpler and completely correct. Sometimes Kafka transactions remove a lot of application complexity. Financially sensitive effects can justify much more work; an analytics counter that tolerates a few duplicates may not be worth full deduplication. Correctness should be deliberate, not necessarily maximal everywhere.
Replay and determinism
Kafka deliberately lets consumers rewind and reprocess, and that's one of its strengths. But if an operator resets a consumer group to yesterday and replays five million events, should the system send five million emails again? Probably not. Rebuild an analytics projection? Quite possibly. So exactly-once processing can't mean "this event can never run again". Replay is a feature, and the application has to separate recomputing derived state from repeating irreversible effects. That might mean replay consumers suppress emails and payments, replays write into a new projection, or idempotency records are kept longer than Kafka's retention.
Determinism is a related but separate issue. If a processor calls an exchange-rate API and gets 0.90, crashes, and on retry gets 0.91, duplicate output may be suppressed correctly while the computation itself differs. If deterministic replay matters, put the external input in the event:
{
"orderId": "42",
"amountUsd": 100,
"exchangeRate": 0.9,
"exchangeRateTimestamp": "..."
}
Then replay uses the same input instead of consulting state that may have changed.
Composing guarantees
A real event-driven system mixes boundaries:
Each boundary can use different semantics on purpose, and a table like this tells reviewers far more than "Kafka = exactly once":
| Boundary | Guarantee |
|---|---|
| Producer → Kafka | Idempotent producer |
| Kafka input → Kafka output | Transactional exactly-once processing |
| Kafka → PostgreSQL | At-least-once + idempotent database transaction |
| Kafka → payment provider | At-least-once + provider idempotency key |
| Kafka → email | At-least-once; duplicates possible |
| Historical replay | Supported explicitly; irreversible effects suppressed |
The table says what happens during failure, and it turns vague arguments into answerable questions: which boundary is too weak, which duplicate or loss is unacceptable, and which system owns the idempotency?
Uber has two good examples. Their real-time ad event pipeline uses Kafka and Flink transactions, then gives each aggregated result a record UUID that serves as an idempotency key in the ad-budget service and a deduplication key in Hive, while Pinot's upsert support prevents duplicate records. Chaperone, their Kafka auditing system, writes each audit message with a UUID to a write-ahead log before sending it, resends unmarked entries after a crash, and deduplicates by UUID downstream. Neither relies on one global switch; both combine mechanisms.
Testing and observing it
Exactly-once claims should be tested by crashing at the awkward moments. For a Kafka-to-database consumer: after polling, during processing, after the database commit, before the offset commit, after the offset commit, during a rebalance, and on a database timeout with an unknown outcome. For transactional processing: after producing output, before committing, on abort, on restarting with the same transactional ID, and reading the output with read_committed. For an external API: the request reaches the provider, succeeds, the response is lost, the consumer crashes and Kafka redelivers. That last one quickly shows the gap between Kafka correctness and business correctness. A happy-path test tells you records flow; a crash test tells you what the system actually guarantees.
Monitoring should follow the same model. If Kafka shows a million consumed records and the payment provider shows 1,003,412 calls, that difference matters, and consumer throughput alone would never show it. Useful counters include events consumed and reprocessed, duplicates detected, business operations applied, idempotency hits, transaction aborts and reconciliation mismatches. If you promise one logical payment despite repeated deliveries, count logical payments separately from Kafka attempts.
Key takeaways
- Kafka's exactly-once covers producing to Kafka, consuming offsets and Kafka-backed state inside one transaction. Nothing outside Kafka joins it.
- Idempotent producers stop transport retries from duplicating records, not an application sending the same event twice.
- Transactions only hold if downstream consumers use
read_committed; fencing protects against zombie producers. - For databases and APIs, accept at-least-once delivery and make the effect idempotent, keyed on the business operation rather than the message.
- Some effects, like email, can't be made exactly once. Decide whether a duplicate or a loss is worse.
- Write down the guarantee at each boundary, test crash points, and plan for replay deliberately.
References
- Apache Kafka — Design — the official description of delivery semantics, idempotent producers, transactions and
read_committed. - Apache Kafka — KafkaProducer API — idempotence, transactional IDs and fencing from the producer's side.
- Confluent — Transactions in Apache Kafka — how transactions, the coordinator and zombie fencing work, their overhead, and why side effects in other systems fall outside them.
- Confluent Developer — Transactions — a shorter course module on the same model.
- Uber — Real-Time Exactly-Once Ad Event Processing with Apache Flink, Kafka, and Pinot — transactional stream processing combined with record UUIDs, idempotency keys and Pinot upserts.
- Uber — Introducing Chaperone — exactly-once auditing built from a write-ahead log, retries and UUID deduplication.
