Every few months, a design review reaches the same moment. Someone asks, "We'll just turn on exactly-once, right?" The room relaxes, because surely the broker will take care of duplicates.
Here is my take after working on payment and inventory flows: exactly-once delivery is the wrong goal for application code. It isn't a feature you switch on. At best it is a property of a narrow pipeline, and it stops at the first side effect you actually care about. The goal worth designing for is at-least-once delivery plus idempotent processing. That combination is boring and testable, and it keeps working when the network, the broker, or your own process misbehaves. They will.
This post explains why, then shows a small pattern I use, with four PostgreSQL-backed tests that make the trade-offs concrete.
Full source and tests: github.com/1995mars/motdev-samples/tree/main/idempotent-consumer
Why the broker can't promise what you want
Picture a consumer's loop: receive a message, apply its effect, acknowledge it. The effect might be crediting loyalty points in a database. The acknowledgement goes to the broker, as a Kafka offset commit or a RabbitMQ ack.
Now kill the process between each step:
- Before applying the effect: the message was never acknowledged, so the broker redelivers it. Fine.
- After applying, before acknowledging: the points were credited, but the broker never heard back, so it redelivers. The effect runs twice.
- Acknowledge first, apply second: you've traded duplicates for loss. A crash right after the ack means the message is gone.
No ordering of "apply" and "acknowledge" survives every crash point, because the two steps live in two different systems. Making them atomic would require a distributed commit between your database and the broker for every message. That's the Two Generals problem wearing a production badge, and no configuration flag makes it disappear.
So the broker offers you a choice: at-most-once (ack first, may lose) or at-least-once (ack after, may duplicate). For anything involving money, stock, or customer trust, losing messages is not acceptable. That leaves at-least-once, which means duplicates will happen. Duplicates aren't a broker bug. They're the contract.
What Kafka's exactly-once actually covers
Kafka does advertise exactly-once semantics, and the feature is real. But its scope is precise, and that scope is exactly what gets forgotten in design reviews:
- The idempotent producer (on by default since Kafka 3.0) stops producer retries from writing the same record to a partition twice.
-
Transactions let an application read from Kafka, write to Kafka, and commit its consumer offsets atomically. Downstream consumers with
isolation.level=read_committedsee all of it or none of it. Kafka Streams wraps all of this up asprocessing.guarantee=exactly_once_v2.
Read the boundary carefully: Kafka in, Kafka out. The moment your handler writes to PostgreSQL, calls a payment API, or sends an email, that effect is outside Kafka's transaction. If the process dies after the database commits but before the Kafka transaction commits, Kafka aborts its part and redelivers. Your database already has the effect.
This isn't a knock on Kafka. Its documentation says this plainly. The problem is the shorthand. When a team says "we have exactly-once," it often means "we set a flag," while the handler that writes to the database is quietly still at-least-once.
The pattern: an inbox table in the same transaction
If duplicates are guaranteed, the consumer has to make them harmless. The simplest reliable way is an inbox table: one row per message the consumer has applied, written in the same transaction as the effect.
-- The side effect: points credited when an order is paid.
CREATE TABLE loyalty_points (
user_id BIGINT PRIMARY KEY,
points BIGINT NOT NULL DEFAULT 0
);
-- One row per message this consumer has applied.
-- Same database, same transaction as the effect.
CREATE TABLE inbox (
consumer TEXT NOT NULL,
message_id TEXT NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
The event carries an id that the producer assigns once:
public record OrderPaid(String messageId, long userId, long points) {}
And the handler claims the id before applying the effect:
@Service
public class InboxHandler {
static final String CONSUMER = "loyalty";
private final JdbcTemplate jdbc;
public InboxHandler(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
/** @return true if this delivery applied the effect, false if it was a duplicate. */
@Transactional
public boolean handle(OrderPaid event) {
int claimed = jdbc.update("""
INSERT INTO inbox (consumer, message_id) VALUES (?, ?)
ON CONFLICT DO NOTHING
""", CONSUMER, event.messageId());
if (claimed == 0) return false; // already applied
jdbc.update("""
INSERT INTO loyalty_points (user_id, points) VALUES (?, ?)
ON CONFLICT (user_id) DO UPDATE
SET points = loyalty_points.points + EXCLUDED.points
""", event.userId(), event.points());
return true;
}
}
Three properties make this work:
-
The message id is stable. The producer assigns it once, and it doesn't change across retries. A random id generated at consume time defeats the whole idea. If the upstream system doesn't provide one, derive it from the business event, for example
order-1001-paid. - The record and the effect share one transaction. Either both commit or neither does. If the process dies in between, the inbox row rolls back too, so the redelivery is processed normally.
-
The database resolves concurrent duplicates. If two deliveries of the same message run at the same time (a consumer group rebalance can cause this), the second
INSERT ... ON CONFLICTwaits on the first transaction's row lock. When the first commits, the second sees the conflict and does nothing.
The consumer acknowledges the message after handle returns, whether it applied the effect or skipped a duplicate. Either way, the message is done.
The consumer column lets several services share one inbox table without stepping on each other: the loyalty service and the email service can each process order-1001-paid exactly once on their own terms.
Tests instead of arguments
Arguments about delivery guarantees tend to stay abstract. Tests don't. The demo fires the same OrderPaid event at three different handlers, several times and concurrently, against a real PostgreSQL started by Testcontainers.
The helper simulates at-least-once delivery. It releases all deliveries at once so they actually race:
static final OrderPaid PAID = new OrderPaid("order-1001-paid", ALICE, 50);
static void deliver(int times, Consumer<OrderPaid> handler) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(times);
CountDownLatch start = new CountDownLatch(1);
List<Future<?>> done = new ArrayList<>();
for (int i = 0; i < times; i++) done.add(pool.submit(() -> {
start.await();
handler.accept(PAID);
return null;
}));
start.countDown();
for (Future<?> f : done) f.get(30, TimeUnit.SECONDS);
pool.shutdown();
}
1. The naive handler applies every delivery:
@Test
void naiveConsumerCreditsEveryRedelivery() throws Exception {
deliver(5, naive::handle);
assertThat(points()).isEqualTo(250); // five deliveries, five credits
}
2. The inbox handler applies it once, even with all five deliveries racing:
@Test
void inboxConsumerCreditsOnceUnderConcurrentRedelivery() throws Exception {
deliver(5, inbox::handle);
assertThat(points()).isEqualTo(50);
assertThat(jdbc.queryForObject("SELECT count(*) FROM inbox", Integer.class)).isEqualTo(1);
}
3. A crash after the effect but before commit leaves no trace, so the retry succeeds. The demo uses a small FaultInjector that throws right after the points are credited, inside the transaction:
@Test
void crashBeforeCommitLeavesNothingAndTheRetryApplies() {
faults.failNext();
assertThatThrownBy(() -> inbox.handle(PAID)).hasMessageContaining("simulated crash");
assertThat(points()).isZero();
assertThat(jdbc.queryForObject("SELECT count(*) FROM inbox", Integer.class)).isZero();
assertThat(inbox.handle(PAID)).isTrue(); // broker redelivers, effect applied once
assertThat(inbox.handle(PAID)).isFalse(); // and any later duplicate is skipped
assertThat(points()).isEqualTo(50);
}
4. The test I wish more teams wrote. It targets the most common shortcut: deduplicating with a fast store that sits outside the transaction, usually a Redis SETNX. You mark the message as seen first, then apply the effect. The demo uses an in-memory set to stand in for Redis:
public void handle(OrderPaid event) {
if (!seen.add(event.messageId())) return; // committed immediately, outside the transaction
tx.executeWithoutResult(status -> {
Points.credit(jdbc, event);
faults.afterEffect();
});
}
@Test
void dedupeOutsideTheTransactionLosesTheMessage() {
faults.failNext();
assertThatThrownBy(() -> dedupeFirst.handle(PAID)).hasMessageContaining("simulated crash");
dedupeFirst.handle(PAID); // the redelivery is treated as a duplicate
assertThat(points()).isZero(); // the customer never gets the points
}
The effect rolled back, but the "seen" marker didn't. The redelivery gets skipped, and the message disappears silently. That's at-most-once dressed up as deduplication. It's arguably worse than the naive handler: a double credit at least shows up in reconciliation reports, while a missing credit only shows up as a customer support ticket.
All four pass:
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 -- in dev.motdev.inbox.IdempotentConsumerTest
Run them yourself with mvn test (Docker required for Testcontainers).
When the effect isn't in your database
The inbox works because the record and the effect commit together. When the effect is an HTTP call to someone else's system, you can't put it in your transaction. In that case:
- Pass an idempotency key downstream. Payment providers such as Stripe accept one for exactly this reason. Use the message id, or a value derived from it, so a retry of the same message is the same request to them.
- Record the intent, then reconcile. Write "payout requested" in your transaction, call the partner, and treat a timeout as unknown, not failed. Then ask the partner for the real status before deciding anything.
- Accept that email is at-least-once. A duplicate "your order has shipped" email is annoying. Design so that's the worst duplicate you can produce.
Common objections
"The dedupe table will grow forever." Keep rows for as long as a duplicate could still arrive: the broker's retention, plus your longest replay window, plus a safety margin. Then delete old rows in batches. A primary-key lookup on a table with a few million rows is cheap.
"Why not make the effect itself idempotent?" You should, whenever you can. SET status = 'PAID' is already idempotent. points = points + 50 is not. The inbox is the general tool for the second kind.
"Ordering matters too." It does, and it's a separate problem. Deduplication says nothing about a "cancelled" event overtaking a "paid" event. Use per-key ordering (Kafka's partition key), version numbers on the entity, or reject state transitions that make no sense given the current state.
Takeaway
Asking the broker for exactly-once means asking it to solve a problem that lives in your handler. Put the guarantee where the effect happens: assume every message arrives at least once, give each message a stable id, and record that id in the same transaction as the change it causes. Then write a test that crashes the handler halfway through, and watch it pass.
Further reading
- Apache Kafka documentation: Message Delivery Semantics
- Confluent: Exactly-Once Semantics Are Possible: Here's How Kafka Does It
- Stripe API reference: Idempotent requests
I write about backend engineering and system design (Java, Spring Boot, Kafka, PostgreSQL/Oracle) at Mọt Dev and on YouTube at @1995mars. The other half of this story, publishing events reliably from the producer side with a transactional outbox, is coming next.
Top comments (4)
把 Redis SETNX 放在事务外会丢消息那个测试最值得写进团队规范,很多系统就是这么悄悄丢数据的。另外 ordering 那段值得单独强调:去重只保证同一条消息不重复生效,cancel 事件跑到 pay 前面这类乱序还得靠版本号或事件时间戳来挡,inbox 表本身拦不住。
Thanks, and agreed on both points.
That fourth test is the one I'd put in a team checklist too. The "mark first, apply second" shortcut looks harmless in code review, and it only fails when the process dies halfway, which is why it ships so easily.
On ordering: you're right, the inbox only answers "has this message been applied?", not "is this the next message?". One small note on the fix: I'd lean on a per-entity version or sequence number assigned by the producer rather than event timestamps. Timestamps from different producers can disagree because of clock skew, and two events can share the same millisecond. A monotonic version per order (or the producer's own state transition, e.g. you can't go from CANCELLED to PAID) gives you a deterministic answer.
A practical combo: keep Kafka's partition key = order id so events for one order arrive in order in the normal case, and store last_applied_version on the entity so the consumer can reject or park anything stale after a replay or a producer-side retry. Might be worth a follow-up post of its own.
credits once
Exactly, once per message id, even with five concurrent redeliveries. The test that proves it is inboxConsumerCreditsOnceUnderConcurrentRedelivery in the repo.