Chapter 10 / 24 · System Design

Streams and the log

Placing an order owes work to six other systems. An append-only log lets the order service record it once and lets each reader catch up in its own time.

A log is an ordered, append-only record of what happened, which many readers can follow at their own pace. It lets one service write down an event once and lets every other service react to it later, without the first service knowing they exist. This chapter takes the outbox from the writes chapter and connects it to a log, then works through the places where such a design usually goes wrong: the relay that ships events, duplicate deliveries, and one bad event that stops a reader.

The situation is the moment a customer taps “Place order”. The order row commits. Then, before the customer’s food is on its way, at least six other things have to happen: the restaurant tablet must ring, rider assignment must start looking for a rider, the customer needs a push notification, fraud scoring wants to see the payment, analytics wants a record, and an invoice email must eventually go out. Last chapter also promised a customer_orders copy that has to learn about every order.

Why the order request cannot call everyone

The first version usually does the obvious thing: after inserting the order, the order service calls each of those systems in turn, inside the customer’s request. It is easy to read and it works in testing. It fails in production in two separate ways.

Latency adds up. Six calls at 30 to 80 ms each put several hundred milliseconds on every order, all of it spent on work the customer is not waiting for. Availability multiplies. If each of the six downstream systems answers successfully 99.9% of the time, the chance that all six succeed is 0.999 to the power 6, about 99.4%. At 1 million orders a day, that is around 6,000 orders a day where some call failed and the order service has to decide what to do: fail the order the customer already paid for, or carry on and leave, say, the restaurant tablet unaware.

The common next step is to fire those calls off in background threads so the request returns quickly. That fixes latency and quietly makes correctness worse. The calls now live only in the memory of one process. If that process is restarted by a deploy at 20:00, every call it was holding is gone, and nothing records that they were ever owed.

What we need is a durable place to write “order 8812 was placed” once, in a form that survives crashes, that any number of systems can read, and that keeps events in order. The writes chapter already provides the first half: the outbox row written in the same transaction as the status change. This chapter supplies the second half, the log that outbox rows are shipped to.

What a log is, mechanically

old → new01234567appendanalytics · offset 2search indexer · offset 5cache invalidator · offset 7one ordered history, many readers at their own pace — rewind an offset and the past replays
A log is one ordered history. Producers append at the end; each consumer remembers only its own offset and reads at its own pace.

A log is a sequence of records, each given a position called its offset when it is appended. Records are never edited in place. A consumer reads from some offset forward and periodically saves the offset it has reached. That saved number is the whole of a consumer’s state. If the search indexer is slow, its offset falls behind; nobody else waits for it. If we deploy a new consumer next month, it can start from the oldest retained record and read history as if it had always been there.

Kafka is the system most teams mean by this, and its vocabulary is worth having. A topic is a named log, such as order-events. A topic is split into partitions, each an independent log with its own offsets. A record’s key decides its partition, through a hash, so records with the same key always land in the same partition and stay in the order they were written. There is no ordering across partitions. Records are kept for a retention period, say seven days, whether or not anyone has read them.

Consumers come in consumer groups. Every group receives every record; that is how notifications and analytics both see each event. Within one group, each partition is read by exactly one member at a time, which is how a group spreads work across several machines while keeping each partition’s order intact.

Dabba’s volumes are modest for a log. About eight events per order (the six status changes, payment confirmation and rider assignment) at today’s dinner-hour average of 42 orders a second is about 340 events a second; at the design target of 150 orders a second, 1,200. A single Kafka partition can take tens of thousands of small records a second. So the partition count for order-events is not chosen for throughput. It is chosen for how many consumer machines we might want to run in parallel, which brings us to the first prediction.

Predict first

order-events has 48 partitions, keyed by order id. The notifications team is behind on a busy night and scales its consumer group from 24 instances to 60. What do the new instances do? And if another team had instead keyed the topic by event type (all “placed” events together, all “cancelled” events together), what could rider assignment see?

Show the worked answer

Only 48 of the 60 instances get a partition. The other 12 sit idle, because within a group a partition is read by one member at a time. Parallelism in a consumer group is capped by the partition count. If notifications needs more, the fix is either more partitions or doing less work per event (for example, batching calls to the push provider).

Keying by event type breaks the one guarantee consumers rely on. “Placed” and “cancelled” for the same order would sit in different partitions, read independently. Rider assignment can process the cancellation first, ignore it because it has never heard of the order, then process the placement and send a rider to collect food that nobody will cook.

Choose the partition key from the order the readers need

The rule that falls out of that answer is: key by the entity whose events must be seen in order. For order-events that is the order. Keying by restaurant id would also work, since every event of an order shares its restaurant, and it would additionally keep each restaurant’s events in order, which the tablet might like. The cost is skew: a cloud kitchen running six brands from one kitchen sends all its events to one partition. Keying by order id spreads load evenly and gives exactly the ordering consumers need.

Rider locations are a separate topic, rider-locations, keyed by rider id. At 50,000 riders reporting every 5 seconds that is 10,000 records a second, the stream the storage chapter routes into the location-history store; here the partition count is chosen for throughput as well as parallelism. Keeping them out of order-events means a slow location consumer never delays a restaurant learning about an order.

One warning about partition counts: increasing them later changes which partition a key hashes to. For a while, old events for order 8812 sit in partition 5 and new ones go to partition 17, and a consumer can see them out of order. So we pick a generous count at the start (Dabba uses 48 for order-events, about double the consumer parallelism it expects to need even at ten times today’s volume) rather than plan to grow it.

From the outbox to the log

The writes chapter closed the gap between committing an order and announcing it. Recall the two failures it removed: commit then publish, and a crash in between leaves a paid order the kitchen never hears about; publish then commit, and a rolled-back order gets cooked anyway. Its answer was the outbox table, written in the same transaction as the status change, with a relay that publishes new rows afterwards. Now we decide where the relay publishes to, and look at the relay itself, because it is where the next set of bugs lives.

We extend the outbox row by one column, order_id, so that the relay can use it as the partition key, and the relay appends each row to order-events. After sharding there is one outbox per shard and one relay per shard, each shipping only its own shard’s rows.

Here is how the relay goes wrong the first time someone scales it. The relay on db-3 falls behind during a dinner spike, so a second relay instance is started against the same outbox. Both run the polling query. Relay A picks up rows 1001 to 1500, relay B, a moment later, rows 1501 to 2000 plus a few that A has not yet marked. Row 1180 is order_ready for order 8812 and row 1620 is order_picked_up for the same order. B is faster and appends 1620 first. The log now says the order was picked up before it was ready, and rider assignment, which reads in log order, sees an order picked up by a rider it has not yet sent.

The order inside a partition is only as good as the order in which events are appended to it. Two fixes keep it. Run exactly one active relay per outbox, with a lease so that a standby takes over only when the active one stops, or split the work so that each relay owns a fixed subset of order ids, for example by order_id mod 4, and so publishes every event of a given order itself, in outbox order. The cost of the first is throughput capped at one process per shard, which at a few hundred events a second is ample. The cost of the second is a little more configuration. Either is better than a log whose order cannot be trusted.

order servicestatus changeone transactionorders · 8812 → PLACEDoutbox · order_placedrelayone per shardorder-eventsrestaurant tabletrider assignmentnotificationseither both rows commit or neither does · the relay may send twice, never zero timesconsumers dedupe by event id, because at-least-once is the price of never losing one
The outbox from the writes chapter, connected to a log: the order change and its event commit together, and one relay per shard ships events in outbox order. The relay may send an event twice; it never loses one.
BEGIN;
  UPDATE orders SET status = 'PLACED' WHERE id = 8812 AND status = 'PAYMENT_PENDING';
  INSERT INTO order_events (order_id, status, at) VALUES (8812, 'PLACED', now());
  INSERT INTO outbox (event_id, order_id, type, payload)
    VALUES ('ev-8812-2', 8812, 'order_placed', '{...}');
COMMIT;

-- the single relay for this shard, in a loop
SELECT * FROM outbox WHERE sent_at IS NULL ORDER BY id LIMIT 500;
-- append each to order-events, keyed by order_id, in this order
UPDATE outbox SET sent_at = now() WHERE id IN (...);

The relay itself can crash between appending to the log and marking the rows sent. On restart it sends those rows again. So the outbox does not give exactly-once delivery; it gives at-least-once, which is a much easier promise to keep. Instead of polling the table, the relay can also read the database’s replication log for inserts into outbox; that is change data capture, and the next chapter uses it for more than events.

The relay’s health needs its own number: the age of the oldest unsent outbox row. If it passes a few seconds at dinner, restaurants are hearing about orders late, whatever the consumers’ dashboards say. The other costs are small: one extra row per event, already paid in the writes chapter, and a cleanup job that deletes sent rows after a day.

At-least-once means every reader handles the second copy

Duplicates come from two directions. The relay may send twice, as above. And consumers themselves follow a read, act, save-offset cycle: if a consumer sends the push notification and then crashes before saving its offset, it reads the same event again after restart and sends the notification again.

How much a duplicate hurts depends on what the consumer does. A second “your order is on the way” push is annoying. A second rider assignment request might pull two riders to the same restaurant. A second refund is money. Each consumer has to decide how it recognises an event it has already handled, and the cheapest tool is the event id the outbox assigned.

When the consumer’s effect is a database write, it records the event id in a processed_events table with a unique index, in the same transaction as the effect. A second copy hits the unique index, and the consumer skips it. When the effect is an external call, such as the payment provider’s refund API or the push provider, the consumer passes the event id as the provider’s idempotency key if the provider supports one. Where none exists, we accept that a rare duplicate push is the cost of never dropping one.

Kafka does offer transactions that give exactly-once processing for a consumer that reads from one topic and writes to another. That guarantee covers the Kafka side only. The moment a consumer sends a push or calls a bank, we are back to idempotency, and the design must say how each consumer provides it.

One bad event can stop a partition

Here is a failure that every log-based system eventually meets. A new rider app version has a bug that leads to one order_picked_up event with a null restaurant id. It lands in partition 7 at 20:04. The analytics consumer reads it, throws an exception while building its row, and crashes. It restarts, reads its last saved offset, which is just before the bad event, reads the bad event again, and crashes again.

Partition 7 is now stuck for analytics. Every other partition carries on, so the overall dashboard looks almost normal, and lag on partition 7 grows quietly. If the same bug were in the restaurant tablet consumer instead, one in 48 restaurants would stop receiving orders at dinner, and only those restaurants would notice.

The fix has three parts. First, measure lag per partition and in seconds, not only in record counts: “partition 7 is 14 minutes behind” is the alert, and it fires well before anyone complains. Second, bound retries: after three failed attempts, the consumer writes the event to a dead-letter topic with the error, alerts, and moves on. Third, think about what moving on breaks. For analytics, skipping one event is fine and it can be replayed after a fix. For a consumer that needs per-order ordering, skipping order_picked_up and then processing order_delivered leaves the state wrong. Those consumers should park every later event for the same order alongside the bad one, so the order is held back while everything else flows.

The cost is a dead-letter topic to watch and a replay tool to write. Without them, a single malformed record holds a partition hostage until someone notices.

Queue or log

Logs and queues are often mentioned together, and they solve different problems. The difference is what happens to a message after it is read.

PropertyQueue (SQS, RabbitMQ style)Log (Kafka style)
After a message is processedIt is deletedIt stays until retention expires
Number of independent readersUsually one kind of workerAny number of groups, each sees everything
OrderingWeak or per group, often traded for throughputStrict within a partition
Replay last weekNot possibleReset the offset
Per-message retry and delayBuilt inBuilt by the consumer
Fits at Dabba“Resize this photo”, “send this invoice email”“Order 8812 was placed”, rider locations

A useful test: is the message a task for someone to do, or a fact about something that happened? Tasks belong in queues, where each one is done once and deleted. Facts belong in logs, where many readers each draw their own conclusions and a new reader can arrive later.

When a log is more than the problem needs

A Kafka cluster is a system to run: brokers, disks, upgrades, partition rebalancing, consumer-group tuning. A team with one database and two consumers can get most of the benefit from the outbox table alone, with a worker that polls it and calls the consumers directly. That keeps the atomic write and the at-least-once delivery, and drops the cluster until there are enough readers to justify it.

At the other end, some teams make the log the source of truth itself. In event sourcing, the current state of an order is computed by replaying its events, and the orders table is only a cached projection. That suits domains that are ledgers by nature, like Dabba’s restaurant payouts, where every change must be explained forever. For orders in general it adds work everywhere: every schema change becomes an event versioning problem, and every read is a projection to maintain. Dabba keeps the orders table as the truth and the log as the record of changes to it.

We would revisit the log if Dabba ever needed cross-region ordering of events, which a single partitioned log does not provide, or if consumer count stayed at one or two for years, in which case the cluster is overhead.

The log now carries every change to Dabba’s orders, and several systems want to build their own versions of that data: the customer history copy, a search index over restaurants and menus, and an analytics warehouse. The next chapter, on derived data, is about building those copies so that they agree with the source within a stated time, and can be thrown away and rebuilt.