This post is part of Working with events, a series about messages in distributed systems.
Messages get lost, and messages arrive twice. This post is about living with that, at both ends of the pipe.
At the receiving end, the trouble comes from the broker: it can hand you the same message twice, and no setting makes that go away for good. The sane answer is to accept duplicates and make them harmless, with consumers that notice when they have already done the work.
At the sending end, the trouble is in your own service: saving an invoice and publishing the event that announces it are two separate writes, and either can fail without the other. The outbox ties them together, and the inbox does the same on the consumer’s side. Underneath both ends lies the same fact: no transaction covers your database and the network, so exactly once is something you build, out of at least once and a record of what you have already done.
Delivery guarantees: messages will be lost or duplicated
When you tell people that messages can be lost, or that they can arrive twice, the usual reaction is disbelief: that cannot be. As Eduardo Ferro put it during the talk, well, it can. Life is like that. There is a thing called physics, electrons have their limits, and networks and servers fail at the worst possible moment.
Every broker gives you some delivery guarantees, and which ones depends on the broker. The good news, if you use Kafka, is that it can give you all of them, one way or another. What matters is knowing which one you are using, because each one leaves a different problem on your side.
At most once
The broker hands you the message and does not wait for you to confirm that you received it and processed it. If something goes wrong halfway, the message is lost.
Matías Nabarro found the right analogy: it is like sending messages over UDP. Send, send, send, and never look back.
It sounds bad, but it is useful. If what you are sending are thermostat readings, I do not care about losing a few. That is not the same as “this invoice has been issued”, and that is why it pays to know this bit of theory.
At least once
Here the broker waits. When it hands you a message, it waits for a while for you to confirm that you received it and did your work. If that time passes without a confirmation, the message is marked as not delivered (I am simplifying), and the broker will send it to you again.
What could have happened? Maybe you did process it, and what never reached the broker was your confirmation. I always say: imagine that the server shuts down halfway. I shout “here is your message”, you hear it, and the server dies before you can say “OK”. Or the connection drops.
So at least once guarantees that the message will arrive, maybe more than once. As a receiver, you need mechanisms so that, if the same message arrives twice, you do not do the work twice. Or, again, sometimes you do not care: if what you receive are metrics, a duplicate is harmless.
Salvador Madrid asked exactly the right question: when does the offset move on to the next message?
With Kafka, it moves when you commit it, and when you do that decides your guarantee:
- Commit before processing, and a crash right after the commit loses the message: at most once.
- Commit after processing, and a crash right before the commit means the message will be processed again: at least once.
Exactly once
And then there is exactly once, the one everybody wants. The normal thing, at the design level, is to stay with at least once and make sure our processes are idempotent, because guaranteeing exactly once adds far too much complexity.
When a broker offers exactly-once semantics, it usually means within its own boundaries, for example reading from and writing to Kafka inside one transaction. The moment your consumer sends an email or calls a payment provider, you are back to at least once, and you need idempotency anyway. At least once plus idempotency is sometimes called effectively once: the message may arrive twice, but its effect happens only once.
Idempotency
f(f(x)) = f(x). Doing something twice has the same effect as doing it once.
Some operations are idempotent by nature: setting a customer’s email to a value, or marking invoice 33 as paid. Others are not: adding 100 loyalty points to a customer, or sending an email. For those, the usual techniques are:
- Remember what you processed. Store the ids of the messages you processed, ideally in the same transaction as the change they produced. This is usually called the idempotent consumer pattern, and the inbox, in the second part of this post, builds on it.
- Make the change conditional. Only apply it if the entity is still in the state, or the version, you expected, or if the message is newer than what you have.
- Pass the identity downstream. Send an idempotency key to external APIs, such as payment providers, so that they can detect retries too.
on OrderPaid(message):
if processed.contains(message.id): return # only a shortcut
begin transaction
processed.add(message.id) # unique: a duplicate fails here
points.add(message.customerId, message.total)
commit
The check at the top only saves work. What protects you is the unique constraint on the processed ids, inside the transaction: if two copies of the same message are processed at the same time, one of the transactions fails and changes nothing.
Even the operations that are idempotent by nature need care when messages can arrive out of order. If the email changes to A, then to B, and a late copy of the first message arrives, you are back to A. That is what the second technique is for: apply a change only if it is newer than what you have.
Life is not transactional
We tend to tell ourselves that everything is transactional. When you can afford it, great. But, as Eduardo said, that is a story we computer people tell ourselves. Life is not transactional; it is eventually consistent. One person takes your order for drinks and another one takes the food. There are five cooks in the kitchen, somebody mixes up a plate, and it gets fixed. That is reality.
I once argued about this with someone whose source of truth, they said, was the warehouse database. So if I rob your warehouse tomorrow, does your database reflect it automatically? No: your source of truth is your warehouse, and the database reflects what you believe you have. And theft is not the only kind of shrinkage. In retail, cheese loses water and weight as it ages, cured meats dry out and, as Matías pointed out, all of that can add up to a loss of around 10% in a couple of weeks. Against dogma, reality always wins.
Gregor Hohpe told a version of this story years ago in Starbucks Does Not Use Two-Phase Commit, and it has aged remarkably well.
Outbox and inbox: two writes that behave as one
So far the trouble was a message arriving twice, or not at all, on its way from the broker to the consumer. The publisher has a problem of its own, and it starts before any broker gets involved. Here is the classic scenario. I want to issue an invoice, and I want to publish an event saying that the invoice has been issued. When does the invoice exist: when the event has been published, or when the invoice has been saved in the database? When it has been saved, of course.
If you used event sourcing, saving the event would be saving the invoice, so this particular problem would not exist. You would still have to forward those events reliably to a broker, if you use one, but the event store would play the role of the outbox you are about to see. For everyone else, read on.
Two writes, one story
So, if the invoice does not exist until it is in the database, I publish the event after saving it. But what happens if the broker is down and the database is not? Or if the connection drops right after the commit? Then I have an invoice, and no event saying that it was issued. My distributed system is less reliable than it should be, and people will stop trusting it and stop using it.
“Fine,” I think, “then I publish the event first and save the invoice afterwards.” And if the database fails? Then the event is telling a story that is a lie. This is known as the dual write problem: two systems, two writes, and no transaction that covers both.
Outbox: the publishing guarantee
For these situations there is the outbox pattern. It is a trick that, in its classic form, needs a transactional database. Instead of publishing the event directly, I keep a table of events that I want to be published at some point.
Inside the same transaction I save both things: the invoice, and the message I want to publish eventually. Then a background process reads that outbox table every so often, sees what is still pending, and publishes it.
In short, the message is saved in the same transaction as the invoice, and delivering it becomes the job of another piece. That is how you make sure that the event will arrive at some point, which is the other key idea: in distributed systems, everything is eventual.
A few details matter in practice. The relay can find pending messages by polling the table, or by reading the database’s transaction log with change data capture, which avoids the polling delay. And the relay gives you at-least-once publishing: if it crashes after publishing a message but before marking it as sent, it will publish it again. Consumers need to be idempotent anyway, as we saw in the first part of this post. The relay should mark a message as sent only after the broker confirms it; otherwise the outbox can lose the very message it was supposed to protect. And if several relays read the same outbox, messages can go out in a different order from the one in which they were written, so when the order matters, use a single relay, or one per group of entities.
Publishing from legacy code
The outbox is also useful in legacy systems. At a previous company we had 7,000 stored procedures (I say “we had” because I am no longer there; they still have them). On the way towards a rich domain model, if I want to publish an event from any of those stored procedures without feeding the beast even more, what do I do? Since we already used the outbox pattern, the stored procedure just writes the message into the outbox table, and we know it will be published at some point.
The other options are triggers and change data capture. If you want to know what changed in a database, the first thing that comes to mind is a trigger, but a trigger sits on one table. Change data capture reads the database’s logs to find out everything that happened in it. There are products that take that stream of changes and dump it into Kafka; Debezium is the best known.
Reading the outbox table with change data capture is fine, because the messages there already tell a story. Reading your business tables is different: what you get are changes of state, and there is no business narrative in “row 4521 of table INV_HDR changed column STATUS from 2 to 3”. You stop speaking the language of the business. In a legacy system with no events, where you still need to know every time an invoice changes, it can help. But it is not the story your domain would tell.
Inbox: the consumption guarantee
The inbox pattern is the mirror image. The typical question is: how do I know that an event has been processed? I consume it, but inside a database transaction, and until that transaction commits I do not want to tell the broker that the work is done.
As a consumer, I keep the tracking myself, in my own database. I work with a transactional system, the database is mine, and I want to mark the event as processed in the same transaction in which I change my data. That is how you get the guarantee. Kafka also has transactions of its own, but that is a different story.
A common variant adds one more step. A subscriber only copies incoming messages into an inbox table, and a processor takes them from there and, within one transaction, updates both the data and the tracking. The copy step decouples receiving from processing: a message is safe as soon as it is in the table, even if processing fails or is slow, so the subscriber can confirm it to the broker right away.
Questions to ask
- Which delivery guarantee does your broker offer, and which one are you actually using?
- What happens, in business terms, if this message is lost? And if it arrives twice?
- When does your consumer confirm or commit: before or after doing the work?
- Is every consumer idempotent? How do you know?
- Which side effects leave your transaction: emails, payments, calls to other APIs?
- Where is the real source of truth: in your database, or in the world?
- What happens if the broker is down when you save? And if the database fails after you publish?
- Are your data and your outgoing messages written in the same transaction?
- Who publishes the outbox, how often, and what happens when it crashes halfway?
- When you publish from legacy code, are you telling a business story or copying table changes?
- Do your consumers record what they processed in the same transaction as their changes?
Next in the series: events inside the service and in front of the user, from in-memory events to CQRS and eventual consistency.