Tiếng Việt · English
Receiving a command twice without doing it twice
The article Transactional outbox ended with an uncomfortable promise: a message is never lost, but it may arrive twice. It sounds harmless, until it lands in exactly the worst place. This article tells that story, and how dine's services cope with it.
The guest gets charged twice
A guest books a table; the order comes to 313,000 VND. order sends payment the command "charge 313,000 VND for order X".
Payment charges the money, records the transaction, and at exactly that moment the process restarts (a deploy, out of memory) before it can tell
Kafka "I have read up to this message". When it comes back, Kafka redelivers from the old position, which means the very same command, once more.
If payment just does what it is told, the guest is charged 626,000 VND for a 313,000 VND meal.
Nobody sends twice on purpose. Duplicates come from moments when the system is not sure whether the previous attempt finished:
- The sender dies after sending, before it can mark the message "sent". When it runs again, it sends once more (the outbox article runs into exactly this case in the section sent twice).
- The receiver finishes the work, but dies before telling Kafka how far it has read. As in the story above.
"Exactly once" would require every step along the way to never die midway, which does not exist. So the practical approach is: the system makes sure a message is never lost, and the receiver makes sure it never does the same work twice. An action that gives the same result whether you do it once or ten times is called idempotent. Setting an order's status to "cancelled" is naturally idempotent: cancelling twice is still cancelling. Taking stock, charging and refunding are not, and unfortunately those are the most important actions of all.
The first approach everyone thinks of: ask first, then act
Before charging, ask the database: "does order X already have a transaction?". If not, charge; if so, stop. In testing it always works. But two jobs (two processes reading the same topic) can perfectly well hold the same message and process it at the same time, for example when Kafka reassigns partitions between processes and the old job has not let go yet when the new one picks it up. Then:
This bug is very hard to see in testing, because it needs two jobs to interleave at exactly the wrong moment. It is the same "check, then act" bug that the article Two orders fighting over the last ingredients runs into again with the kitchen stock.
How dine does it: just write, and let the database block it
Instead of asking first, dine lets the database itself act as referee. Every command order sends carries the order's saga ID.
When a service processes a command, it writes a result row with that saga ID: payment writes a transaction, the kitchen writes a kitchen ticket, the table service
writes a reservation. The saga ID column is UNIQUE: the database does not allow two rows with the same ID.
The first time, the row is written normally. The second time, the database refuses with a duplicate key error (in MySQL, error 1062).
The receiver knows right away: this command has already been processed. Even if two jobs run at the same moment, the database lets exactly one of them
write, and the other gets the duplicate error. There is no gap between asking and acting anymore, because there is no asking step.
The "processed" mark must be in the same transaction as the main work
The result row is the "processed" mark. The most important detail is that this mark and the main work (charging, taking stock) are written in the same transaction. Split them into two steps, and there is always a gap:
- Work first, mark afterwards: die between the two and the work is done with no mark. The message arrives again, and the work is done again.
- Mark first, work afterwards: die between the two and there is a mark but no work. The message arrives again and is skipped; the work never gets done.
In one transaction there is no "between": either the mark and the work are both written, or nothing is. It is exactly the outbox trick, just used on the receiving side.
The next trap: spotting a duplicate and simply ignoring it
Once a duplicate is detected, can it just be silently ignored? No. There is one common case: the first attempt finished,
but the receiver died before its reply reached order. If the later attempt silently ignores the message, order
never gets a reply, waits for the full 5 seconds and cancels an order that was actually fine.
So when a duplicate arrives, all three services do the same thing: send the original reply again, rebuilt from the recorded result row.
No redoing the work, no recomputing the result. If the payment was declined the first time, the second time still answers "declined",
without trying to charge again. And order receiving two identical replies is fine too: applying the same result twice
still gives one result.
order never has to guess.Dedup is everywhere too, just like the outbox
The story does not stop at the three services. Their replies go back to order through Kafka, on the
saga-step-responses topic, so they travel the same road that can redeliver. And as just described, when a duplicate arrives,
the services deliberately resend the original reply. In other words, order is guaranteed to receive the same reply twice
at some point: "the kitchen has taken the stock for order X", and then again "the kitchen has taken the stock for order X".
So order has to be idempotent as well. It does not blindly act on each message; it looks at its own ledger
(saga_steps, saga_compensations) before deciding. Replies are recorded by saga ID and step name:
a reply identical to one already recorded changes nothing in the ledger, so it produces no new work. An "undo done" reply
that the ledger has no request for is ignored and logged. order only trusts its own ledger.
Just like the outbox, once you see it, you see dedup everywhere: every service that receives messages must dedup,
no exceptions. Every time order gets a new kind of reaction, or a new service joins the saga,
the first question is always: "what if this message arrives twice?".
Undo commands arrive twice too
Undo commands travel the same road, so they can also arrive twice. Refunding twice means losing real money.
Here dine uses a second technique: each result row has an extra column for the undo result. Before undoing, the service
locks that row (SELECT ... FOR UPDATE) and checks this column:
- Empty: undo, write the result into the column, send the reply.
- Already has a result: do nothing more, just resend the original reply.
The row lock is there so that two undo commands arriving almost together do not both see "empty": the second must wait for the first to finish, and by then the column has a result. For payment, even a result of "the bank refused the refund" is final and must not be recomputed. Sorting that case out is the job of a person, not of a redelivery.
Duplicates at the front door too
Before Kafka is even involved, there is a more familiar kind of duplicate: the guest presses Book a table twice in a row, thinking the first press did not register. There dine relies on a business rule: each person can have only one pending order at a time. The rule is checked inside the order-creation transaction, with a lock per guest, so two requests sent at the same moment still have to queue: the second one sees the order just created and is rejected.
Things to keep in mind
Looking back over the outbox and idempotency articles, one thing stands out: no component tries to do another component's job for it.
- The outbox has one job: getting the message out. It keeps sending until it can confirm the message was sent, that is, until marking it "sent" succeeds. If it cannot mark it, it sends again, without caring whether the receiver already got it. Precisely because it asks no one, it sends duplicates. And precisely because it asks no one, it stays simple and never loses a message.
- Idempotency has one job: guarding the door of its own service. It does not care who sent the message, how many times, or why it came back. It asks just one question: "have I already done this?", and the database answers.
The two know nothing about each other and do not coordinate, yet put together they are correct: a message is never lost, and work is never done twice. Try it the other way round: if the outbox wanted to avoid duplicates, it would have to ask the receiver "did you get it?" before every send. Then the two services would be tightly bound together, and that question could also get lost on the way, just like the message itself. A distributed system is correct not because its parts understand each other, but because each part does its own job well, even when the part next to it gets things wrong, is slow, or does things again.
A few practical points if you build this yourself:
- The key must stay the same across resends. dine uses the saga ID, which exists from the moment the order is created and never changes. If every resend generated a new ID, the database would see two different jobs and dedup would be useless.
- Each service has to do its own part. There is no single place that dedups for the whole system. Adding a new service means one more place that has to get this right.
- The "processed" mark must be kept longer than the window in which a message might be redelivered. At dine the mark is the result row itself, which stays there permanently, so this is not a concern.
And one last thing: idempotency is not a formula, and not a library you install and are done with. It is a goal:
however many times a message is sent, there is only one result. How you reach that goal is different for each person and each
piece of business logic. In this article alone dine used four different ways: a UNIQUE constraint on the saga ID for work commands,
a result column plus SELECT ... FOR UPDATE for undo commands, the "one pending order per guest" rule at the front door,
and the saga_steps ledger on order's side. Once you understand the goal, you can pick the way that fits your own work.
In short: don't try to guarantee each message arrives only once. Let the outbox make sure a message is never lost, and let every receiver
dedup for itself: a "processed" mark kept by the database with UNIQUE, written in the same transaction as the main work,
and on a duplicate, reply with the original result. When each part does its own job right, the whole system is right.
See it for yourself
Duplicates do not show up in the interface, and that is exactly the point: however many times a command arrives, the numbers across the pages still agree with each other. On the technical chart of the order detail page, when a service receives a duplicate command, that segment is clearly labelled "duplicate message": it does not redo the work, it only resends the original reply.
- Payment ledger Exactly one charge line per order, and a cancelled order has exactly one extra refund line.
- Kitchen The stock log per order: each order takes stock exactly once.
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.