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
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.
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
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.
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.
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:
- Publish first, then build state from the event. The service publishes the event and updates its own database by consuming that same event, so the stream is the only source of truth. This fits stateless processors. A service that validates new requests against its own state, as Order Service does, would read stale data.
- Idempotent writes, acknowledged late. Without a transaction across the two tables, make each write an idempotent upsert and acknowledge the incoming command only after both writes succeed. A retry of the command then fills in whichever write is missing. Wrapping the two writes in a try/catch or adding compensating actions only narrows the gap; it does not close it.
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.
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.
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.
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.
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.
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.
Capture changes at the database itself and turn them into events. Whatever wrote the row, the change is seen, so nothing can be missed.
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:
| Approach | Good | Watch 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 log | Every 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 component | Events 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.
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.
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.
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.
So acknowledge after processing, accept that duplicates will come, and make them harmless.
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.
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.
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.
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.
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.
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.
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.
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.
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.
| Pessimistic | Optimistic | |
|---|---|---|
| How | Take a distributed lock (Consul, ZooKeeper, Redis) or a database transaction, then work alone. | No lock. Check at write time that nothing changed. |
| Best when | Conflicts are likely, for example a popular daily special at lunch. | Conflicts are rare, for example a restaurant editing its opening hours. |
| Risks | A 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. |
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.
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.
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.
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.
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.
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.
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.
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).
| Limit | What to do |
|---|---|
| Hotspots: a coarse key (cuisine instead of restaurant) sends most events to one partition | Choose a key with enough granularity and variety, several times the number of partitions. |
| Momentary hotspots: a restaurant's big promotion | Accept 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 data | Create topics with more partitions than you need today. |
| A service that mixes events with a synchronous API | Turn the API request into a command on the same partitioned queue, or fall back to locking. |
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
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Transactional outbox | A crash between saving data and publishing loses or invents events | An outbox table per service and a relay to run; slight delay |
| Polling publisher | Moving outbox rows to the broker simply | Database load from polling; latency set by the poll interval |
| Transaction log tailing | Moving outbox rows fast and at scale | Vendor-specific; another component to operate |
| Change data capture | Publishing 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 processing | Messages lost when a consumer crashes mid-message | Redelivery creates duplicates |
| Idempotent consumer | Duplicates from at-least-once delivery apply work twice | A processed-ids table to keep and clean, or events that carry state |
| Retry limit and dead letter queue | A poison message blocks the queue forever | Parked messages need people to inspect and replay them |
| Optimistic or pessimistic concurrency | Two instances update the same data at once | Retries under contention, or locks with latency and failure modes |
| Versioned events | An old event overwrites newer state | A version on every event and a check in every consumer |
| Partitioning by routing key | Races and ordering across instances and threads | Key choice and partition count fixed early; hotspots |
Recap
- Saving data and publishing an event are two writes, so FTGO saves the event in an outbox table in the same local transaction and lets a relay publish it.
- The relay polls the outbox or tails the database log, and change data capture also publishes changes made by code you cannot touch, such as stored procedures and support scripts.
- Delivery is at least once, so consumers acknowledge after processing and are idempotent, either by tracking processed ids or by events that carry state.
- A retry limit and a dead letter queue stop a poison message from blocking a queue; with a durable log, rewinding the offset after a fix is often simpler.
- Concurrent instances need optimistic or pessimistic concurrency control, and versioned events let consumers ignore events that arrive late.
- Partitioning by a well-chosen key sends each entity through one partition, one instance and one thread, which removes races by design.
Quick check
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.
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.
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.
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.
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.