Broadcast, gossip and ordering guarantees
Every balance change has several listeners. Each needs a different guarantee about missing and reordered events, at a different price.
This chapter lets you say, for each consumer of a stream of events, what it needs: every event or most of them, in which order, and relative to what. Once you can say that precisely, you can buy the cheapest mechanism that provides it, instead of paying for the strongest one everywhere or discovering in production that you bought too little.
Every committed transfer in the wallet produces balance-change events. The notification service tells Ravi he received money. The fraud model scores each debit. The history service builds the transaction list in the app. Analytics counts volume. And the followers from the last chapter are, in a sense, listeners too: they apply the same changes. These consumers want different things, and the differences decide the design.
One event, many listeners
Start by asking each listener two questions: what happens if it misses an event, and what happens if it sees two events in the wrong order?
| Listener | If an event is missing | If events are reordered | What it needs |
|---|---|---|---|
| Notifications | Ravi is not told; mildly bad | Rarely matters | Every event, duplicates suppressed |
| Fraud model | A fraudulent debit goes unscored | A debit before its funding credit looks like an overdraft | Every event, per-account order, causal across accounts |
| History service | The statement is wrong | Spending appears before the money that funded it | Every event, per-account order, causal across accounts |
| Analytics | A rounding error in a daily total | Irrelevant for aggregates | Most events, any order |
| Followers | The copy diverges | The copy diverges | Every event, in one order identical everywhere |
The right-hand column is a ladder. From weakest to strongest: best-effort delivery (most events, no order), reliable delivery (every event, no order), FIFO (each sender’s events in the order it sent them), causal (anything an event depends on is delivered before it), and total order (every listener sees every event in the same sequence). Each rung costs more than the one below, in messages, metadata, latency or availability. The rest of the chapter is about what each rung costs and where the wallet needs it.
Getting every event out at least once
Reliability fails first at the source. The obvious code commits the transfer and then publishes an event to a message broker. If the wallet crashes between the two steps, the transfer exists and the event does not; Ravi never hears about the money. Publishing first and committing second is worse: if the commit then fails, listeners hear about a transfer that never happened. Writing to two systems without a transaction spanning both is called a dual write, and it is one of the most common sources of drift between services.
The usual fix is an outbox. The wallet inserts the event into an outbox table in the same transaction as the transfer. Either both exist or neither does. A separate relay process reads new outbox rows, publishes them to the broker, and marks them sent. If the relay crashes after publishing but before marking, it publishes the same event again when it restarts. So the guarantee is at least once, and every consumer must handle duplicates, typically by remembering the event ids it has processed. This is the same pattern as the idempotency key in the RPC chapter, applied on the receiving side.
There is a textbook version of reliable broadcast that is worth knowing because it explains why systems are built the way they are. If a sender crashes partway through sending to ten listeners, some got the event and some did not. To repair that without the sender, each listener re-sends every new event to all others the first time it sees it. Every listener then gets it as long as any one did, at a cost of roughly n² messages for n listeners. Real systems rarely do this. They put the event into a replicated, durable log such as a Kafka topic, and each listener reads the log at its own pace. Once the log has accepted the event, reliability is the log’s job, and the log solves it with the replication from the last chapter.
The consumer’s side: remembering what it has done
At-least-once delivery moves the duplicate problem to every consumer, and how a consumer handles it decides whether duplicates are harmless. Consider the history service, which adds a row to Asha’s transaction list for each event. A Kafka consumer reads a batch of events, processes them, and then commits its offset, the position in the partition up to which it has finished. If it crashes after processing and before committing, it restarts from the old offset and processes the same events again.
If the history rows are keyed by event id and the insert ignores a row that already exists, reprocessing is harmless. If the consumer instead increments a counter, such as “number of transfers this month”, reprocessing double-counts. The fix that works in general is the mirror image of the outbox, sometimes called an inbox: the consumer records the ids of processed events, or simply its offset, in its own database, in the same transaction as the effect. On restart, it reads its position from its own database rather than from the broker. The effect and the record of having done it are atomic, which is the same reasoning as the idempotency key in the RPC chapter.
Two operational questions follow. The first is how long to remember. A consumer that tracks individual event ids needs to keep them for longer than any redelivery could arrive, which for a broker that retains a week of data could in principle be a week. Tracking the offset per partition avoids that, because the offset alone says which events are done.
The second is what to do with an event the consumer cannot process. Suppose a bug in the wallet publishes one event with a malformed amount. The history service fails on it, does not commit, restarts, and fails on it again. Because the partition is ordered, everything behind that event, all of Asha’s later activity and everyone else hashed to that partition, waits. Ordered delivery means one bad event can block a partition indefinitely. Consumers usually handle this by moving the failing event to a separate dead-letter topic after a few attempts and carrying on, which unblocks the partition and breaks the order for that account. Which of those is worse is a decision for each consumer: the history service might stop and page someone, while analytics skips and logs.
Per-sender order, and where it stops
FIFO delivery needs only a sequence number per sender. The receiver keeps, for each sender, the next number it expects, and holds back anything that arrives early until the gap is filled. A Kafka partition provides this for free: it is a single ordered log, and consumers read it in order. If the wallet publishes events keyed by account id, every event for Asha’s account lands in the same partition and is consumed in the order the leader committed it. The fraud model never sees Asha’s debit before the top-up that funded it.
That covers order within an account. A transfer touches two accounts, and Asha’s and Ravi’s events may land in different partitions, consumed at different speeds.
A reconciliation job reads all partitions and checks, every second, that the sum of all balance changes it has seen equals total top-ups minus total withdrawals. Asha’s events are in partition 4, Ravi’s in partition 9, and the job reads each partition with its own thread. Asha sends Ravi ₹500. What does the job report?
Show the worked answer
It depends on which thread is ahead. If partition 9 is ahead, the job sees Ravi’s +₹500 before Asha’s −₹500 and reports ₹500 created from nothing. If partition 4 is ahead, it reports ₹500 destroyed. A moment later both events have been read and the books balance.
On a busy system, with thousands of transfers per second crossing partitions, the job will almost never see a balanced total, and its alerts become noise that people learn to ignore.
There are three fixes. Publish one event per transfer, containing both legs, keyed by transfer id, so the two halves can never be separated. Or have Ravi’s credit event name the debit it depends on, and have the job hold back the credit until it has seen the debit. Or check the totals only at positions in every partition that form a consistent cut, a set of positions where every event included has all its causes included too.
Causal delivery: carrying what you depended on
The second fix in that answer is causal delivery, and it generalises. Each event carries a record of the events it depends on. A receiver delivers an event to its application only after delivering everything in that record. For the wallet, Ravi’s credit event says “after Asha’s debit, account asha, sequence 4,417”. The history service receives the credit, checks whether it has processed Asha’s sequence 4,417, and if not, keeps the credit in a buffer until it has.
The general version uses the vector clocks from the time chapter. With one entry per sender, a receiver delivers a message from sender j when the message’s entry for j is exactly one more than the receiver has delivered from j, and every other entry is no greater than what the receiver has already delivered. Anything else waits.
The costs are the metadata on every event and the hold-back buffer. If Asha’s debit event is delayed, perhaps because partition 4’s consumer is slow, Ravi’s credit waits too, and so does everything that depends on Ravi’s credit. A lost dependency stalls a whole causal chain until it is fetched. In practice, causal delivery is easier to provide for a few explicit dependencies, such as a credit naming its debit, than for full vectors over many senders.
Total order is the consensus problem
The followers are the strictest listeners. If two followers apply the same transfers in different orders, they can disagree about whether Asha’s second debit was allowed. Followers need total order: every one of them applies every change in the same sequence.
With a healthy leader, total order is cheap. The leader is a single sequencer: it decides the order by appending to its log, and everyone else follows the log. The difficulty is entirely in failure. When the leader dies, the replacement must agree with everyone on exactly which entries the old sequence contained, including those that reached some followers and not others, and must never assign a different event to a position someone has already acted on.
That is the consensus problem in another form. If you have total-order broadcast, you can solve consensus: everyone broadcasts a proposal and everyone picks the first one delivered, which is the same for all. If you have consensus, you can build total-order broadcast: run consensus once per log position to agree on which event goes there. The two problems are equivalent, so total order can never be cheaper than consensus once failures are included. This is why a Kafka partition, which looks like a simple ordered log, depends on a consensus-based controller to decide which replica leads each partition.
The wallet’s event partitions show what is at stake. Suppose the producer writes with acks=1, so the partition leader acknowledges an event as soon as it has written it locally. The leader acknowledges Asha’s debit event at offset 5,002 and crashes before any follower has fetched it. A follower that stopped at offset 5,001 becomes the new leader, and the next event for that partition, another user’s top-up, is written at offset 5,002. Consumers that had already read the old 5,002 before the crash saw a debit there; consumers that read after see a top-up. Two consumers disagree about the content of the same position in a log that was supposed to be totally ordered. With acks=all and a minimum number of in-sync replicas, an acknowledged event is on every replica eligible to become leader, so the new leader’s log contains it, and the positions mean the same thing to everyone. The difference between those two settings is the difference between a single sequencer and a fault-tolerant one.
Gossip, for information that may lag
At the other end of the ladder is information where a few seconds of disagreement is harmless: which wallet servers are alive, which feature flags are on, rough load figures for each server. Pushing these reliably to every node is more machinery than they need. Gossip spreads them the way rumours spread. Every second, each node picks a few random peers and exchanges what it knows. A node that hears something new passes it on in the next round.
The arithmetic is why it works. If each informed node tells three others per round, the number of informed nodes can roughly quadruple each round while most are still uninformed. In a cluster of 1,000 nodes, about five rounds reach most of them, since 4⁵ is just over 1,000, and a few more rounds catch the stragglers that kept picking informed peers. At one round per second, a change reaches the whole cluster in roughly ten seconds. Each node sends a fixed number of messages per round however large the cluster grows, and there is no central node to overload or lose.
Gossip is often paired with anti-entropy, a background process in which two replicas compare their data and repair differences. Comparing a million keys one by one would be expensive. A Merkle tree hashes the keys into a tree of hashes; two replicas compare root hashes, and only descend into subtrees whose hashes differ. With a fanout of 16, a million keys fit in a tree five levels deep, so finding one differing key means exchanging a few dozen hashes instead of a million values.
The weakness is in the name. Gossip is probabilistic and eventually consistent, so it must never carry information an invariant depends on. Suppose the wallet gossips which server owns which shard of accounts. During a handover, some API servers still believe server A owns shard 7 when server B now does. That is acceptable only if the receiving server checks ownership itself and rejects requests for shards it does not own, so the API can refresh and retry. Stale gossip used as a hint is fine; stale gossip used as authority is a split brain waiting for a slow round.
Buying the cheapest sufficient rung
| Guarantee | Typical mechanism | What it costs | Wallet use |
|---|---|---|---|
| Best effort | Fire and forget | Almost nothing | Client-side metrics |
| Reliable | Outbox plus a durable log, consumer dedup | An outbox write per transaction; dedup state | Notifications |
| FIFO per key | Partition by account id | Parallelism limited to the number of partitions | Per-account fraud features |
| Causal | Explicit dependencies, hold-back buffers | Metadata; a delayed event stalls its dependents | History, reconciliation |
| Total order | Single leader’s log, replaced by consensus | Consensus on failover; one sequencer’s throughput | Followers |
| Eventual | Gossip, anti-entropy | Seconds of disagreement | Membership, flags |
Overbuying is a real failure mode, not just a waste. A team that wants analytics to see events “in the right order” might put all events through one partition. That gives total order and caps the whole pipeline at the throughput of one partition and one consumer. On the day volume doubles, analytics falls hours behind, and nothing in the analytics actually depended on that order. Underbuying shows up the other way, as the reconciliation alerts nobody trusts. Revisit a listener’s rung when its job changes: the day the fraud model starts blocking payments instead of scoring them afterwards, its ordering needs change too.
We have now seen twice that the hard part of a single leader is replacing it. The next chapter, Consensus, is the mechanism for that: how three wallet replicas agree on a leader and on a log, so that no acknowledged transfer is lost and no two leaders ever accept writes in the same term.