Chapter 06 of 27 · Part 4: Transactional messaging and domain events

Transactional messaging and idempotent consumers

A service that saves data and then publishes a message can crash in between, and a consumer can receive the same message twice, late, or at the same moment as another instance. This chapter makes FTGO's messaging reliable end to end: publish exactly what was saved, and handle every message safely.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 5 FTGO's services started talking through a broker: channels, queues and topics, at-least-once delivery, durable logs and sharded channels. That left two problems open: saving data and publishing a message are not one atomic step, and consumers will see duplicates and messages out of order.

This chapter

How does Order Service publish exactly the events it saved, and how do consumers such as Kitchen and Restaurant Service stay correct when messages repeat, fail, race or arrive late? By the end you can apply the transactional outbox, choose a relay or change data capture, write idempotent consumers, park poison messages, and remove races by partitioning.

Saving and publishing are two writes: the transactional outbox

Problem

Order Service handles a new order. It inserts the order into its database, commits, and then publishes OrderCreated to the broker. One evening the process crashes between those two steps. The customer sees "order placed", but Kitchen never hears about it, so no ticket is created and no food is cooked. Swap the steps and the opposite happens: the event goes out, the database insert fails, and the restaurant cooks an order that does not exist.

This is the dual-write problem. The database and the broker are two separate systems, and there is no ordinary transaction that covers both. A distributed transaction across them (two-phase commit) is slow, and many modern brokers do not support it. Once the stream of events and the database disagree, every consumer inherits the mismatch.

Solution · Transactional outbox

Write the message into an OUTBOX table in the service's own database, in the same local transaction as the business data. Either both rows commit or neither does. A separate message relay then reads the outbox and publishes each row to the broker.

Transactional outbox The service writes data and the message in one local transaction. A relay then publishes it. Order service Database transaction ORDER table INSERT / UPDATE OUTBOX table INSERT message Message relay reads outbox Broker
One local ACID transaction. No distributed transaction needed.

If the broker is down, the OrderCreated row simply waits in the outbox. The relay publishes it when the broker comes back, and the row is deleted (or marked as sent) once it is published.

Two alternatives exist, each with limits:

Cost

Every service needs an outbox table, and something has to run the relay. Messages now leave the service a little later than the commit. Which raises the next question: how does the relay find new rows quickly without hammering the database?

Moving outbox rows to the broker: polling or log tailing

The outbox makes saving and publishing atomic. The relay decides how fast and how cheaply the rows reach the broker.

Problem

At lunch peak Order Service writes hundreds of outbox rows a minute (an illustrative number). A relay that runs SELECT * FROM OUTBOX every 100 milliseconds adds constant load to the database Order Service needs for its own work. Polling once a minute instead means Kitchen sees new orders up to a minute late.

Solution · Polling publisher or transaction log tailing

A polling publisher queries the outbox on a timer; it is simple and fine at low scale. Transaction log tailing reads the database's commit log instead and turns each inserted outbox row into a message; it is fast and scales, but takes more work to run.

Two ways to run the relay Polling publisher Query OUTBOX on a timer Simple, fine at low scale Polling costs add up Transaction log tailing Read the DB commit log Fast and scalable More work, e.g. Debezium

A common middle way: the service publishes right after the commit for speed, and a poller sweeps the outbox on startup and after failures to catch anything that was missed. Log tailing is a form of change data capture (CDC), with tools such as Debezium doing the reading.

Cost

Log tailing ties you to the database vendor's log format and adds a component to operate. Both relays also assume the service's code writes to an outbox. Much of FTGO's data is still changed by the old monolith, whose code nobody wants to touch.

When you cannot change the code: change data capture

CDC is not only a relay for the outbox. Pointed at ordinary business tables, it publishes changes that no code ever announced.

Problem

FTGO's new Restaurant Service must stay in sync with menus that the monolith still edits. The team adds a call to the new service in every monolith code path they can find. Then the data drifts: a stored procedure updates prices, the support team runs fix-up scripts, and an ops spreadsheet writes straight to the table.

A side example shows how common this is. One team migrated inventory out of a retailer's monolith by calling the new service from every flow. It looked perfect in test, then drifted in production. Stored procedures hundreds of lines long, data fixes by support teams and "mushroom applications" such as spreadsheets were all changing the data behind the code's back. The same applies to vendor monoliths whose code you cannot change at all.

Solution · Change data capture

Capture changes at the database itself and turn them into events. Whatever wrote the row, the change is seen, so nothing can be missed.

CDC with SQL Server and Kafka The transaction log fills a CDC table; an ETL component polls it by log sequence number and publishes stock events. Stock table writes Tx log every change CDC table LSN, op code ETL poller batches Events in Kafka Inventory new service Operation codes: 1 delete, 2 insert, 3 row before update, 4 row after update. Poll after the last LSN, cap the batch (for example 1000 rows), map 2 to StockCreated and 4 to StockChanged.

In this side example SQL Server copies every change from its transaction log into a CDC table, tagged with a log sequence number (LSN) and an operation code. A small ETL (extract, transform, load) component polls for rows after the last LSN it handled and publishes domain events to Kafka. There are several ways to build the capture:

ApproachGoodWatch out
Query with a watermark (timestamp, id or version)Works on any database. Flexible filters and bulk load of existing data.Heavy queries load the database. Several updates between polls collapse into one. Deletes need soft delete.
Read the database logEvery change including deletes, with before and after values. Lighter on the database.Depends on the vendor. Exposes the table model, so translate it into domain events. High volume needs retention rules.
Framework (Kafka Connect, NiFi)Configuration instead of code.Hard to debug locally, limited customization, leaks the database model.
Custom ETL componentEvents with domain meaning (a stock update may really mean a reservation).More code to write and run. With many teams, one per bounded context.

The ETL must also load the current state into the stream first, so a new service starts with complete data. Over time the new service becomes the owner of the data and the ETL is retired. If you need only the latest state rather than every change, SQL Server's lighter Change Tracking feature, which compares row versions, may be enough.

Cost

CDC exposes table structure unless you translate it, and it is one more pipeline to run. Like every relay, it publishes at least once: if it crashes after publishing but before saving its position, it publishes the same change again. Consumers must expect duplicates.

Every message may arrive twice: idempotent consumers

The outbox guarantees that nothing is lost. The price is that some things arrive twice.

Problem

The relay publishes OrderCreated for order 4521. The broker stores it, but its acknowledgement is lost in the network. The relay cannot tell whether the publish failed or only the ack, so it publishes again. Kitchen Service receives the event twice and creates two tickets. The restaurant cooks the meal twice.

How a duplicate is born Order svc Broker Kitchen svc publish event ack lost in network retry publish event event (duplicate) The producer cannot tell if the publish or the ack failed.

The same happens on the consumer side: if Kitchen processes a message and crashes before acknowledging it, the broker delivers it again. Why not ask the broker for exactly-once delivery? Kafka does offer it, using sequence numbers and transactions across topics, at a reported cost of about 3 percent compared with at-least-once. But it covers only the flow inside the broker. The moment Kitchen writes to its own database or calls another service, that step needs its own protection.

First, decide when to acknowledge. Acknowledging on receipt avoids duplicates but loses work: if Kitchen crashes or is redeployed mid-message, the message is gone (a message leak). Auto-commit of offsets is the usual cause.

When to acknowledge Ack first Ack, then process Crash: message leaks Process first Process, then ack Crash: reprocessed Auto-commit of offsets is the usual cause of leaks. Use manual acks.

So acknowledge after processing, accept that duplicates will come, and make them harmless.

Solution · Idempotent consumer

Make handling a message twice have the same effect as handling it once. Either record the id of every processed message and skip repeats, or design the message so that applying it again changes nothing.

The tracking approach uses a PROCESSED_MESSAGES table with the message id as its primary key. Kitchen inserts the id in the same local transaction as the new ticket. If the insert fails on the key, the message is a duplicate and Kitchen skips it.

Handling duplicate messages Message arrives id: xyz Insert id in table processed-ids table Insert fails? it is a duplicate Process once same transaction Brokers promise at-least-once delivery, so handlers must be idempotent or track message ids.

The design approach changes what the event says. Take Restaurant Service's count of portions left for a daily special. A StockOut event that says "subtract 1" subtracts again on every replay. A StockChanged event that says "now 5 left" can be applied any number of times. Instead of message ids, a consumer can also remember the last processed version of each entity.

Making a handler idempotent Change the event StockOut qty 1 Replay twice: minus 2 StockChanged now 5 Replay twice: still 5 Remember the event Store processed ids Or processed versions Skip any repeat Replay is harmless StockChanged is safe but says less about intent, so weigh the trade-off.
Cost

The processed-ids table grows and needs cleanup, and state-carrying events lose some of the intent behind a change. Idempotency makes a repeat safe, but it does not help a message that fails every time it is processed.

A message that always fails: retries and dead letters

Redelivery is how at-least-once recovers from a crash. For some messages it becomes an endless loop.

Problem

One OrderCreated event has a malformed delivery address. Kitchen's handler throws on it every time. The broker's lock on the message expires, the message goes back to the queue, and the next Kitchen instance crashes on it too. Meanwhile every order behind it waits, and restaurants receive no tickets.

A message like this is a poison message. Retrying helps only for errors that can succeed next time, such as a dependency that was briefly down; retry those with a growing wait and a little random jitter. A validation error will fail forever.

Solution · Retry limit and dead letter queue

Set a maximum retry count on every queue. After the limit, the broker moves the message to a dead letter queue, where people can inspect it, fix the cause and replay it, while the rest of the stream keeps flowing.

Poison messages and the dead letter queue A message that crashes every worker keeps returning to the queue. A retry limit moves it to a dead letter queue where people can inspect and replay it. Queue Worker crashes Dead letter queue lock expires, message returns after the retry limit people view, fix and replay Set a maximum retry count on every queue.
Rewind or dead-letter? With a durable broker such as Kafka, fixing the code and moving the consumer's offset back is often simpler than a dead letter queue, because the events are still in the log. A dead letter queue pays off when many good events have arrived after the bad one and should not wait.
Cost

Someone must watch the dead letter queue and decide what to do with each message, and a replayed message arrives long after its neighbors. Reliable delivery is now in place, but FTGO runs several instances of each consumer, and they can step on each other.

Two instances sell the last portion: concurrency control

In the monolith a lock in memory protected shared data. With many instances, each running many threads, an in-memory lock protects nothing.

Problem

A restaurant has one portion of its daily special left. Two customers order it within the same second. Restaurant Service runs two instances, and each picks up one OrderCreated. Both read "1 left", both write "0 left", and both orders are accepted for a single portion. At thousands of events per second, a race that looks unlikely happens every day.

Two instances sell the last unit Both instances read stock 1 and both write 0, so two orders are accepted for one unit. Instance 1 Database Instance 2 read stock = 1 read stock = 1 write stock = 0 write stock = 0 two orders, one unit

There are three families of fixes. Pessimistic: ask permission first, by taking a lock. Optimistic: go ahead, and apologize (retry) if someone else changed the data meanwhile. By design: arrange the flow of events so the clash cannot happen, which the last section of this chapter covers.

Solution · Optimistic concurrency control

Read the row together with its version or last-change timestamp. When writing, update only if that value is unchanged. If zero rows were updated, someone else got there first: read again and retry.

Optimistic update with a version column The update only applies if the timestamp is unchanged since the read; zero affected rows means retry. Read stock + timestamp Calculate reserve a portion Guarded update WHERE ts = old 0 rows: retry stock changed A SQL UPDATE ... WHERE LatestChangeTimestamp = ? is enough. Elasticsearch, Cassandra and event stores use the same idea.
PessimisticOptimistic
HowTake a distributed lock (Consul, ZooKeeper, Redis) or a database transaction, then work alone.No lock. Check at write time that nothing changed.
Best whenConflicts are likely, for example a popular daily special at lunch.Conflicts are rare, for example a restaurant editing its opening hours.
RisksA fixed lock key makes the service single-threaded, so lock per restaurant. A crashed or partitioned instance can lose its lock yet still write. Long transactions hurt.Under contention, ten buyers mean one success and nine retries, which costs more than a lock. Retries must be idempotent.
The size of what you lock matters. Locking or versioning per restaurant lets different restaurants run in parallel. One lock for every restaurant of a cuisine would serialize far more work.
Cost

Locks add latency and new failure modes; optimistic retries waste work under contention. Both assume the events themselves arrive in a sensible order, and they do not always.

Events that arrive late: versions

Chapter 5's sharded channel keeps order per key, but retries, replays and other paths can still deliver an older event after a newer one.

Problem

Order Service keeps its own copy of how many portions are left, fed by Restaurant Service's events. Restaurant publishes "2 left" and then "1 left". A retry delays the first one, so Order Service applies "1 left" and then "2 left". The app now offers a portion that does not exist.

Solution · Versioned events

Give every event the version of the aggregate it describes. The consumer stores the version it last applied and ignores any event with a lower one, when only the latest state matters.

Out-of-order events and versions The consumer stores version 22, then receives version 21 late and ignores it. Published v21 stock 2 v22 stock 1 Arrives v22 first v21 later Consumer state is v22 ignores v21 Causes: publisher clock skew, broker or network issues, retries, replays, concurrent consumers at different speeds.

An aggregate version is the safest marker. Timestamps are easy to add but are not strictly sequential across machines, and truly sequential ids are hard to generate in a distributed system. Partial events such as StockIn and StockOut make this worse: a consumer cannot skip one of them, and they are not idempotent, so they are fragile under reordering.

Cost

Every event carries a version and every consumer stores and checks it. Versions detect a late event; they do not stop two threads from processing versions 21 and 22 at the same time, so they still need a concurrency strategy next to them. Locks, retries and version checks all react to clashes after the fact.

Make the clash impossible: partition by key

The better answer is to arrange things so that two instances never work on the same restaurant at the same time.

Problem

Restaurant Service's locks on popular restaurants become a bottleneck at lunch, and optimistic retries pile up. The team wants all orders for one restaurant handled one after another, without any locks, while thousands of other restaurants are still handled in parallel.

A Kafka topic is a distributed, append-only log split into partitions. Order is guaranteed only inside a partition, and within one consumer group each partition is read by exactly one instance. A consumer is cheap: it is little more than an offset pointer, so another group, such as Kitchen, can read the same partitions at its own pace.

Topic, partitions and consumer groups Producers write to partitions, and one instance per consumer group reads each partition at its own offset. Order service instances publish with a routing key Partition 0 offset 0 1 2 3 ... Partition 1 offset 0 1 2 3 ... Partition 2 offset 0 1 2 3 ... Restaurant 1 group: restaurant Restaurant 2 group: restaurant Restaurant 3 group: restaurant A fourth instance would sit idle. Another group, such as kitchen, reads the same data at its own offsets.
Solution · Partition by routing key, end to end

Publish every order event with the restaurant id as the routing key. All orders for one restaurant land in the same partition, are read by the same instance, and arrive in order. Inside the instance, route messages to worker threads by the same key, so one restaurant is never handled by two threads at once.

End-to-end partitioning One routing key sends all events for a restaurant through one partition, one instance and one thread. Producer key: restaurant Partition same key same partition Instance one consumer per partition Thread route by key inside service Result no locks in order Different restaurants still run in parallel on other partitions and threads.

The distributed race becomes a local one, and the local one disappears because each key has one thread. The service is parallel across restaurants and sequential within one. The broker also balances the load: if an instance dies, Kafka reassigns its partitions to the others, with no external load balancer. A burst of orders does not need a rate limiter either; it becomes consumer lag rather than rejected requests, and that lag is the signal to scale out (see chapter 22).

LimitWhat to do
Hotspots: a coarse key (cuisine instead of restaurant) sends most events to one partitionChoose a key with enough granularity and variety, several times the number of partitions.
Momentary hotspots: a restaurant's big promotionAccept rare spikes. Avoid recovery jobs that dump many events with one key.
The number of partitions caps scaling, and adding partitions does not re-route old dataCreate topics with more partitions than you need today.
A service that mixes events with a synchronous APITurn the API request into a command on the same partitioned queue, or fall back to locking.
Cost

Partitioning needs a good key chosen up front and enough partitions for future scale. With it, FTGO's events flow reliably, once in effect, and in order. What they do not settle is what an event should contain, or how Order Service can change OrderCreated next year without breaking Kitchen, Accounting and Notification.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Transactional outboxA crash between saving data and publishing loses or invents eventsAn outbox table per service and a relay to run; slight delay
Polling publisherMoving outbox rows to the broker simplyDatabase load from polling; latency set by the poll interval
Transaction log tailingMoving outbox rows fast and at scaleVendor-specific; another component to operate
Change data capturePublishing changes made by code you cannot change (stored procedures, scripts, vendor systems)Leaks table structure unless translated; a pipeline to run and bootstrap
Acknowledge after processingMessages lost when a consumer crashes mid-messageRedelivery creates duplicates
Idempotent consumerDuplicates from at-least-once delivery apply work twiceA processed-ids table to keep and clean, or events that carry state
Retry limit and dead letter queueA poison message blocks the queue foreverParked messages need people to inspect and replay them
Optimistic or pessimistic concurrencyTwo instances update the same data at onceRetries under contention, or locks with latency and failure modes
Versioned eventsAn old event overwrites newer stateA version on every event and a check in every consumer
Partitioning by routing keyRaces and ordering across instances and threadsKey choice and partition count fixed early; hotspots

Recap

Quick check

Order Service publishes OrderCreated right after committing the order, and the broker is down for a minute. What goes wrong, and which pattern fixes it?
Show answer

Orders saved during that minute are never announced, so Kitchen creates no tickets. Use the transactional outbox: save the order and an outbox row in one local transaction, and let a relay or CDC publish the row once the broker is back.

Kitchen Service acknowledges messages on receipt and is redeployed in the middle of lunch. What happens, and what should change?
Show answer

Messages that were acknowledged but not yet processed are lost (a message leak), so some orders never become tickets. Acknowledge after processing, and make ticket creation idempotent, for example with a processed-ids table, because redelivery after a crash will now create duplicates.

Restaurant Service routes order events by restaurant id, so each restaurant's events go to one partition. Is the race on the last portion gone?
Show answer

The race between instances is gone, because one instance owns that partition. Threads inside the instance can still race, so route messages to threads by the same key, or use a local lock.

Still open

Events now flow reliably and are handled safely. But nothing yet says what an event should contain, what metadata it needs, or how to change its shape without breaking the services that consume it.

Next: 07 Domain events: design and schema evolution →

The outbox pattern: common questions

What is the transactional outbox pattern?

The service writes the event to an outbox table in the same database transaction as the data change. A relay then publishes it to the broker, so neither is lost if a crash happens in between.