Tiếng Việt · English
Transactional outbox: writing to the database and sending to Kafka without drifting apart
At first I thought sending a message from order to Kafka was the simplest part of the whole system:
save the order, then send it off, that's it. It turned out not to be simple at all. This article is about why, and how dine solves it with
the transactional outbox.
When you press Book a table, order has two jobs to do
- Write to MySQL. The
orderstable stores the order. A few other tables come with it:order_items(the dishes),sagasandsaga_steps(tracking which step the order is at with each service). Taken together, this is the MySQL job. - Send a message to Kafka, to the
order-eventstopic, so the table, kitchen and payment services can start working.
The approach everyone thinks of first is to do them one after the other: write to MySQL, then send to Kafka. In testing it works every time. The problem only shows up when one of the two jobs fails halfway, and in practice that happens sooner or later: the process is killed during a deploy, runs out of memory, Kafka is restarting, the network is flaky.
Two ways it breaks
Case 1: MySQL is written, but sending to Kafka fails
The order is in the database, but the message never reaches Kafka. The consequences:
- No service knows the order exists. Nobody holds the table, nobody takes the stock, nobody charges the money.
- The guest sees the order stuck at "processing" forever.
- Worst of all, there is no error for anyone to see. The order just sits there until the guest asks about it.
Case 2: the message reaches Kafka, but writing to MySQL fails
This happens when the code sends to Kafka first and writes to MySQL afterwards, or sends to Kafka inside the transaction and then the
COMMIT fails. The message has gone out, but the order is not in the database. The consequences are even worse than case 1:
- Three services do real work for an order that does not exist: a table is held, stock is taken, the guest is charged.
- When the three services reply,
orderfinds no order to match them to, so nobody steps in to undo anything. The table stays held, and the money charged sits there with no order to refund.
Both cases have the same root: MySQL and Kafka are two separate systems, and no transaction can span both (the article Why saga instead of 2PC explains why dine does not use two-phase commit here). Swapping the order of the two jobs only swaps one case for the other; it does not make the problem go away.
The fix: an outbox
The idea of the outbox is very simple: don't send the message right away, write it down first.
In one single MySQL transaction, order writes to the orders, order_items,
sagas and saga_steps tables, and also writes the message into one more table called outboxes.
Everything lives in one database, so the database can guarantee it: either everything is written, or nothing is.
The two original jobs then become:
- Job 1 is done. The order is in MySQL the moment the transaction commits. The API answers the guest right away, without waiting for Kafka.
- Job 2 becomes data. The message sits in the
outboxestable with the status "waiting to send". A background job keeps scanning the table (every 100ms at dine), picks up the waiting messages and sends them to Kafka. Every message that is sent successfully is marked "sent". If a send fails, the message stays there and the next scan sends it again.
Why the outbox fixes both cases
- Case 1 (an order without a message) can no longer happen. The order and the message are written in the same transaction.
If there is an order, there is definitely a message in
outboxes. If Kafka is down, the message just waits longer; once Kafka is back, the job sends it. No message is ever forgotten. - Case 2 (a message without an order) can no longer happen either. The job can only read what has been committed. If the transaction fails, neither the order nor the message exists, so there is nothing to send.
The "write to two places" problem becomes "write to one place". Writing to one place correctly is something databases have done well for a long time.
On the diagram of the order detail page, the Kafka box sometimes shows "command still in the outbox, not sent": that is exactly the window where the message has been written but the job has not reached it yet.
Once you see it, you see outboxes everywhere
The problem above is not unique to creating orders. It shows up anywhere a single action has to write to two different storage systems that do not share a transaction: a database and a message queue, a database and a search index, a database and an external service.
In dine, the way out is only half the story. When the table service, the kitchen or payment finishes its work, it has to do exactly the same two jobs
as order: write the result into its own MySQL, then send its reply to saga-step-responses.
If the kitchen takes the stock but its reply never arrives, order waits out the 5 seconds and cancels an order the kitchen had already completed.
So all three services have outboxes of their own. Undo commands go through the outbox too.
The whole system has four outboxes, and no message leaves a service without passing through that service's outbox.
Outside dine, you will meet exactly this shape in very familiar places:
- Signing up, then sending a welcome email. If the user is saved but the email never goes out, the user waits forever. If the email goes out but saving the user fails, someone gets a welcome email for an account that does not exist.
- Saving a product, then updating the search index. This is exactly where
dine.productwill end up if dish search is added (the article How I started building dine mentions CQRS). The read side is only correct if every change on the write side reaches it, and the outbox is how you make sure it does. - Taking a payment, then notifying a partner by webhook. Once the money is charged, the partner has to find out, even if the network to the partner is down at that moment.
The tell-tale sign is simple: whenever you see a line of code that says "save, then send" or "send, then save", ask "what if it dies right between these two lines?". If the answer is "the data drifts apart", that spot needs an outbox.
The remaining risk: a message can be sent twice
There is still one gap that cannot be avoided. The job sends the message to Kafka successfully, but dies before it can mark it "sent" in MySQL (killed during a deploy, or the database connection drops at exactly that moment).
The next time the job runs, it sees the message is still not marked, so it starts over: it sends that message to Kafka again. (At dine, a message whose job died mid-send is put back to "waiting to send" after about 30 seconds, so the job picks it up again.)
The outbox guarantees a message is never lost, but it may arrive twice (at-least-once). There is no way to write to the database and send to Kafka "exactly once" with an outbox alone. So the receiving side must tolerate duplicates: when it gets "hold a table for order X" a second time, it recognizes it has already done that and does not hold another table. The article Receiving a command twice without doing it twice explains how dine does it.
Another price: about 100 ms slower
The message does not go out immediately; it waits for the job's next scan. The order detail page can measure this, because all four services
record what they do. This is the kitchen leg of a real order, from the moment order writes the message
into the outbox to the moment it has received the kitchen's reply:
| Segment | Time |
|---|---|
| Waiting in order's outbox | 52 ms |
| Kafka delivers to the kitchen | 0 ms |
| Kitchen processing (take stock, write the reply into the kitchen's outbox) | 11 ms |
| Waiting in the kitchen's outbox | 44 ms |
| Kafka delivers back, order updates the saga | 6 ms |
96 out of 113 ms is outbox wait. The job scans every 100 ms, so a freshly written message waits about half an interval on average, around 50 ms, and a round trip passes through two outboxes.
There is nothing special about 100 ms. It is simply the pause I chose between two MySQL scans: short enough that a person booking a table cannot notice it, sparse enough that the database is not asked constantly when there are no orders at all. Another system might choose 10 ms, 1 second, or several seconds, depending on how fast its work needs to be.
If you need it close to instant, there are a few ways:
- Scan more often. The simplest, but the database gets asked more, even when there is nothing to send.
- Tell the job as soon as there is work. After committing, the API calls the job directly over a fast connection (gRPC, for example) so the job sends right away instead of waiting for the next scan. The scan stays, only to sweep up messages whose notification was missed. The core is still the outbox: the notification only makes it faster, and if it is lost the message is still safe in the table.
- Read MySQL's binlog directly (change data capture, for example Debezium) to know about new outbox rows immediately, with no scanning. In exchange, you have a whole extra system to operate.
For dine, being about 100 ms slower in exchange for a simple table-scanning job is a very good deal.
Can you avoid the outbox?
You can avoid the outboxes table, but not the problem. Each way around it just moves the difficulty somewhere else:
| Approach | Idea | The price |
|---|---|---|
| Write to only one place | Drop Kafka and call the services directly over HTTP. | The problem is still there: the other side holds the table and this side dies before recording it, and things drift apart anyway. You also lose the ability to resend while the other side is down. |
| Kafka as the only write | order only sends to Kafka, then reads Kafka back itself to write MySQL. Only one write remains. |
The API cannot say "order created" right away. Checks that need the database (one pending order per guest) become much harder. |
| Read the binlog instead of an outbox table | Debezium reads changes to the orders table directly. |
Receivers depend on order's internal table structure: change one column and the other side breaks. People usually keep the outbox table and let Debezium read that. |
| A shared transaction (2PC) | One transaction spanning both MySQL and Kafka. | Kafka cannot take part in this kind of transaction. The article Why saga instead of 2PC explains why dine would not want it anyway. |
| Accept the drift, reconcile later | Just write and send, and periodically run a job that finds drifted orders and fixes them. | Only suits work that is not urgent and where drifting is cheap. And that reconciliation job, if you think about it, is a slow outbox. |
Kafka does have transactions, but they only cover things inside Kafka (read from this topic, write to that one), not MySQL. So the short answer is: as long as you write to two systems, you need a way to keep them from drifting apart, and the outbox is the simplest way, needing nothing but the database you already have.
The outbox and idempotency always come as a pair
dine uses Kafka so its services talk to each other asynchronously, through messages, instead of calling each other directly.
(Strictly speaking, most of order's messages are commands, like "hold a table for order X", rather than
pure "event-driven" style, where services only react to things that have already happened. But the problem here is exactly the same.)
Once services with their own databases talk through messages, you almost certainly need both an outbox and idempotency:
- The outbox takes care of the sending side: a message is never lost, even if the service dies halfway.
- Idempotency takes care of the receiving side: if a message arrives twice, the work is still done only once.
Without the outbox, work gets lost. Without idempotency, work gets done twice. With both, a message may travel several times, but the result is as if each piece of work happened exactly once. Idempotency is needed even without an outbox, because Kafka itself can redeliver a message to the receiver. The next article covers how dine's receiving side does it: Receiving a command twice without doing it twice.
See it for yourself
Open a sample order and press Show technical chart below the diagram. You will see the API answer as soon as it has written the order,
while sending to Kafka is done afterwards by a different process (cmd/saga). Any recent order on the
home page also has a timing bar split into segments like the table above, in the section
"How order reacts to each reply".
- Success The normal path: write the order and the outbox, the job sends to Kafka, the 3 services reply through their own outboxes.
- One service goes silent The message is still sent correctly; the receiver just never answers. The outbox cannot save a dead service; the timeout does.
Spotted a mistake, or have a question? Write to [email protected].
dine is a personal project about distributed systems, written in Go: orchestrated sagas, transactional outbox, Kafka. More articles.