Outbox, CDC and idempotency

CDC
change data capture

Senior Frequently asked 6 min

On this page

The question

What is the dual-write problem?

30-second answer

A service that must change its database and publish a message does two writes to two systems with no shared transaction. A crash or a failure between them leaves them disagreeing: the order is saved but the event is lost, or the event is sent but the order rolls back. Retrying does not help when the process died. The fix is to make one write the source of the other: the transactional outbox, or change data capture on the database.

Understand it

A crash between the commit and the publish

Predict

OrderService saves order 42 in a database transaction and commits. Then it calls the Kafka producer to send OrderPlaced. The process crashes between the two.

After the restart, what do the database and Shipping know about order 42?
View as text

OrderService on top, with arrows to a database and to Kafka, and Shipping reading from Kafka. OrderService saves order 42 in a database transaction and commits. Then it calls the Kafka producer to send OrderPlaced. The process crashes between the two. The learner predicts what each side knows after the restart.

The commit succeeded, so order 42 is in the database for good. The send has not run yet. The database shows order 42.

The process dies before the send. Nothing was handed to Kafka, so nothing retries it. Shipping never hears of order 42, and nobody notices. Kafka and Shipping show nothing.

Sending first does not help. If the event goes out and then the commit fails, Shipping ships an order that does not exist. Kafka has the event and the database has no order.

The fix: insert the event into an outbox table in the same transaction as the order. Both commit or neither does, and a relay publishes it later. The database shows both the order and the outbox row.

OrderService on top, with arrows to a database and to Kafka, and Shipping reading from Kafka. OrderService saves order 42 in a database transaction and commits. Then it calls the Kafka producer to send OrderPlaced. The process crashes between the two. The learner predicts what each side knows after the restart.

The commit succeeded, so order 42 is in the database for good. The send has not run yet. The database shows order 42.

The process dies before the send. Nothing was handed to Kafka, so nothing retries it. Shipping never hears of order 42, and nobody notices. Kafka and Shipping show nothing.

Sending first does not help. If the event goes out and then the commit fails, Shipping ships an order that does not exist. Kafka has the event and the database has no order.

The fix: insert the event into an outbox table in the same transaction as the order. Both commit or neither does, and a relay publishes it later. The database shows both the order and the outbox row.

Takeaway: Writing to a database and to a broker are two separate writes with no shared transaction. A crash between them leaves the two disagreeing, whichever order you choose, until the event joins the database transaction.

The outbox relay and an idempotent consumer

Step by step

OrderService inserts order 42 and an outbox row holding OrderPlaced in one local transaction. They commit together or not at all.

Step 1 of 7
View as text

OrderService and its database on the left, with an orders table and an outbox table. On the right, a relay, Kafka and Shipping with its processed table. A marker shows where the event is.

OrderService inserts order 42 and an outbox row holding OrderPlaced in one local transaction. They commit together or not at all.

A relay reads unsent outbox rows: a scheduled poller, or change data capture such as Debezium reading the database log.

The relay publishes OrderPlaced to Kafka, with the outbox row ID as the event ID, and waits for the broker to acknowledge it.

The relay crashes before marking the row sent. After the restart the row still looks new, so it is published again. At-least-once means duplicates.

This time the relay marks the row sent. Nothing is ever lost now, but the topic holds two copies of the same event.

Shipping ships order 42 and records the event ID in a processed table, in the same transaction as its own changes.

The second copy carries an ID Shipping already recorded, so it is acknowledged and skipped. The outbox gives at-least-once; idempotency turns it into effectively once.

OrderService and its database on the left, with an orders table and an outbox table. On the right, a relay, Kafka and Shipping with its processed table. A marker shows where the event is.

OrderService inserts order 42 and an outbox row holding OrderPlaced in one local transaction. They commit together or not at all.

A relay reads unsent outbox rows: a scheduled poller, or change data capture such as Debezium reading the database log.

The relay publishes OrderPlaced to Kafka, with the outbox row ID as the event ID, and waits for the broker to acknowledge it.

The relay crashes before marking the row sent. After the restart the row still looks new, so it is published again. At-least-once means duplicates.

This time the relay marks the row sent. Nothing is ever lost now, but the topic holds two copies of the same event.

Shipping ships order 42 and records the event ID in a processed table, in the same transaction as its own changes.

The second copy carries an ID Shipping already recorded, so it is acknowledged and skipped. The outbox gives at-least-once; idempotency turns it into effectively once.

Takeaway: The outbox makes the event part of the database transaction, so it is never lost. The relay may publish it twice, so the consumer records event IDs and skips duplicates.

From two writes to one, and from at-least-once to effectively onceThe service writes the business row and the outbox row in one transaction. A relay, a poller or change data capture, publishes the outbox rows to the broker at least once. The consumer records each event ID with its own changes, so a duplicate is skipped and each event takes effect once.Consumer sideProducer sideat least onceBusiness row +outbox row:one transactionRelay: polleror CDCBrokerConsumer: skipIDs already seenEffect happensonce
From two writes to one, and from at-least-once to effectively onceThe service writes the business row and the outbox row in one transaction. A relay, a poller or change data capture, publishes the outbox rows to the broker at least once. The consumer records each event ID with its own changes, so a duplicate is skipped and each event takes effect once.Consumer sideProducer sideat least onceBusiness row +outbox row:one transactionRelay: polleror CDCBrokerConsumer: skipIDs already seenEffect happensonce
From two writes to one, and from at-least-once to effectively once

In code

@Entity
@Table(name = "outbox")
class OutboxEvent {
    @Id UUID id = UUID.randomUUID();                 // becomes the event ID consumers deduplicate on
    String aggregateId;
    String type;
    @Column(columnDefinition = "jsonb") String payload;
    Instant createdAt = Instant.now();
    Instant sentAt;                                  // null until the relay publishes it
}

@Transactional
public void place(Order order) {
    orders.save(order);
    outbox.save(OutboxEvent.of(order.id(), "OrderPlaced", json.write(OrderPlaced.from(order))));
}   // one commit: both rows, or neither
Write the order and its event in the same transaction
@Scheduled(fixedDelay = 500)
@Transactional
void relay() {
    // SKIP LOCKED lets several relay instances share the work without sending a row twice at once
    List<OutboxEvent> batch = outbox.findUnsent(100);   // SELECT ... WHERE sent_at IS NULL ORDER BY created_at FOR UPDATE SKIP LOCKED
    for (OutboxEvent e : batch) {
        kafka.send(new ProducerRecord<>(topicOf(e.type), e.aggregateId, e.payload))
            .get(5, TimeUnit.SECONDS);                     // wait for the broker's acknowledgement
        e.sentAt = Instant.now();
    }
}   // a crash before this commit resends the batch: consumers must be idempotent
A polling relay: publish unsent rows, then mark them sent
@KafkaListener(topics = "orders.placed", groupId = "shipping")
@Transactional
 Wrong void onWrong(OrderPlaced e) { shipments.create(e.orderId()); }        // a redelivery ships twice

@KafkaListener(topics = "orders.placed", groupId = "shipping")
@Transactional
void on(OrderPlaced e, @Header("eventId") UUID eventId) {
    // processed_events has a primary key on event_id
 Right     if (!processed.markIfNew(eventId)) return;         // INSERT ... ON CONFLICT DO NOTHING: false if seen
 Right     shipments.create(e.orderId());                     // same transaction: both, or neither
}
An idempotent consumer records the event ID with its own change
Change data capture, with Debezium reading the outbox from the database logThe service commits the order and the outbox row. Debezium, running in Kafka Connect, reads the new outbox row from the database's write-ahead log and publishes it to a Kafka topic. Shipping consumes it from there.ShippingKafkaDebeziumDatabaseOrderServicecommit order + outbox rowread write-ahead logOrderPlacedOrderPlaced
Change data capture, with Debezium reading the outbox from the database logThe service commits the order and the outbox row. Debezium, running in Kafka Connect, reads the new outbox row from the database's write-ahead log and publishes it to a Kafka topic. Shipping consumes it from there.ShippingKafkaDebeziumDatabaseOrderServicecommit order + outbox rowread write-ahead logOrderPlacedOrderPlaced
Change data capture: Debezium reads the outbox from the database log

Solve it

Customers are charged twice after the payment service restarts

The Payments service consumes PaymentRequested from Kafka, charges the card through a provider, and then lets Spring Kafka commit the offset. During a deploy, a few customers were charged twice for the same order. Find the cause and make charging safe.

  1. Find the window. The charge succeeded, but the instance stopped before the offset was committed. On restart, the same record was delivered again, and the card was charged again. Kafka delivers at least once.
  2. Accept duplicates as normal. Rebalances, crashes and retries all redeliver, so the fix belongs in the consumer, not in hoping the broker delivers once.
  3. Deduplicate locally. Record the event ID in a processed table, in the same transaction as the payment row, and skip IDs already seen.
  4. Deduplicate at the provider. The external charge is outside your transaction, so send an idempotency key, the order ID, and the provider returns the first result for a repeated key.
  5. Check. In a test, deliver the same record twice, and kill the consumer between the charge and the commit: one payment row, one provider charge.
@KafkaListener(topics = "payments.requested", groupId = "payments")
@Transactional
void on(PaymentRequested e) {
    if (payments.existsByOrderId(e.orderId())) return;                  // already handled: skip
    Charge c = provider.charge(e.amount(), e.card(),
        "order-" + e.orderId());                                        // idempotency key at the provider
    payments.save(new Payment(e.orderId(), c.id(), e.amount()));         // unique constraint on order_id
}
One payment per order, however often the request is delivered

How to answer

  • Sending inside a database transaction does not help; the broker is not part of it.
  • Sending first just reverses the failure, an event for an order that does not exist.
  • Distributed transactions across database and broker are rarely available, and slow when they are.
  • Listening to your own event to update your database is another, less common, way out.

Common mistakes

  • Assuming a send inside a method marked transactional is rolled back with the database. The message is already out.
  • Claiming the producer's retries fix it. They cover network errors, not a process that died before sending.

Follow-up questions

How does the transactional outbox pattern work?

In the same local transaction as the business change, the service inserts the event into an outbox table. Both commit or neither does. A separate relay then reads unsent rows and publishes them to the broker, marking each as sent, or a change data capture tool such as Debezium reads them from the database's log. Events are never lost, but can be published more than once.

  • Publish in creation order per aggregate, using its ID as the message key, to keep ordering.
  • Clean up sent rows, or the table grows without bound.
  • The outbox row's ID makes a natural event ID for consumers to deduplicate on.

See it in the infographic: The outbox relay and an idempotent consumer

How do you make a message consumer idempotent?

Make processing the same message twice have the same effect as once. Give each message a unique ID, and record processed IDs in the consumer's database in the same transaction as its changes; skip an ID already seen. Or make the operation naturally idempotent: set a status rather than toggle it, upsert by a business key, or use a unique constraint such as one payment per order.

  • At-least-once delivery plus an idempotent consumer gives effectively once processing.
  • External side effects, such as a card charge, need the provider's idempotency key.
  • Keep processed IDs long enough to cover the longest redelivery window.

See it in the infographic: The outbox relay and an idempotent consumer

Where do duplicate messages come from, even with a reliable broker?

From every retry that cannot know whether the first attempt worked. A producer resends after a lost acknowledgement. An outbox relay republishes rows it published but had not yet marked sent. A consumer that crashes or loses its partition in a rebalance before committing its offset gets the same records again. Brokers guarantee at-least-once because the alternative, at-most-once, loses messages.

  • Kafka's idempotent producer removes producer resend duplicates, not consumer redeliveries.
  • Committing the offset before processing turns duplicates into lost messages.
  • Design every consumer for duplicates and for out-of-order arrival.

See it in the infographic: The outbox relay and an idempotent consumer See it in the infographic: A crash between the commit and the publish

Does Kafka's exactly-once support solve the dual write to a database?

No. Kafka transactions make a write to several Kafka topics and offsets atomic, inside Kafka. A relational database is outside that transaction, so the order row and the Kafka write can still diverge. You still need an outbox, or to make Kafka the single source of truth.

Check yourself

1. A service commits order 42, then crashes before calling the Kafka producer. What is the state after the restart?
Show answers
  • The order exists; the event was never published: Correct. The commit stands and nothing ever retries a send that never started.
  • The order was rolled back: Incorrect. The transaction committed before the crash.
  • Kafka retried and delivered the event: Incorrect. Kafka never received anything to retry.
2. An outbox relay publishes a row, then crashes before marking it sent. What should consumers expect?
Show answers
  • The same event again, so they must deduplicate: Correct. The row still looks unsent after restart, so it is published again.
  • The event is lost: Incorrect. The row is still in the outbox, so it will be published.
  • Nothing changes; Kafka removes the duplicate: Incorrect. Kafka cannot know that two separate sends carry the same business event.