Systemsfor Aravinda
0 / 78 core
Week 5 · Messaging

Queues and logs

2 hours · core path

Read first: Idempotency and the exactly-once myth

In one sitting

A queue spreads work across competing consumers and deletes the message on ack, while a log keeps an ordered history and an offset per consumer so replay is normal. Sending email is work and wants the queue. A payment fact wants the log, because more than one system has to be able to read it again.

A request handler that does the slow work inline will eventually do too much of it. Something has to sit between “the user asked” and “the work finished.” Two machines get used for that job, and they are not interchangeable. A queue distributes tasks and then forgets them. A log records facts and lets every reader remember how far it got.

Core concepts

A queue is a buffer of work. Producers append messages. Consumers take them. Competing consumers means several workers pull from the same queue, and each message is given to one worker, not copied to all of them. When that worker acks, the broker drops the message or at least stops offering it. The depth of the queue is the work you have not finished. That depth is the thing you alert on.

This is a good shape when the message means “please do this,” and doing it once, by anyone, is the product. The web request can return as soon as the enqueue succeeds. The workers drain the queue at their own pace. A burst becomes depth instead of becoming failed requests, up to the point where depth itself becomes the incident.

Order on a queue is fragile. A single consumer can preserve the order the queue stored. The moment two workers are in flight, finish order is completion order, not enqueue order. Worker A takes message 1 and stalls on a slow downstream call. Worker B takes message 2 and finishes first. Anyone watching side effects sees 2 and then 1. If you need those side effects in order for one entity, a shared queue will not give you that once you scale the workers. The usual patch, a queue per entity, is you reinventing a partition key without admitting it.

A log is an append-only record. You write at the end. You do not remove a record because someone read it. The position of a record is its offset. Each consumer stores its own offset and moves that offset forward after it handles the record. Ten consumers means ten offsets, and they do not coordinate. One of them can be at the tip while another is still reading this morning. Replay is not a special recovery mode. Replay is “set the offset backward and read.”

Retention is how a log forgets. You keep records for a time, or until the log reaches a size, and then you drop the old end. The drop happens whether or not every consumer has read them. A consumer that was offline longer than the retention window comes back to a hole. Its offset refers to records that are no longer there. You choose the horizon on purpose, and you tell every reader what it is.

Deletion versus offset. On a queue, the ack is destruction of the only copy of that task. On a log, the ack is a pointer moving. The record remains available to this consumer if it rewinds, and to every other consumer at their own pace, until retention says otherwise. That single difference decides which tool you want. If losing the message on a bad ack is unacceptable because nobody else has the fact, you wanted a log, or you wanted the fact in a database and the message only as a hint. If keeping the message after the work is done is pointless and dangerous, because replaying it would repeat a side effect, you wanted a queue.

Who the readers are. Competing consumers split a stream. If you need two programs to each see every payment, they must not share one queue. Each payment would be taken by one of them, and the other would never hear about it. Two readers of a log each keep an offset and both see every record. Fan-out on a queue is an extra copy you have to remember to make, one queue per destination. Fan-out on a log is another reader. The cost shows up later, as storage and as the obligation to handle a replay without doubling the side effect. That obligation is Idempotency and the exactly-once myth. Doing the work twice has to be harmless, or you do not get to rewind.

The operational log people mean in this course is Kafka. The words for “how many times does the handler run” are Delivery guarantees. This page is only the choice of machine.

A worked example

Two streams leave the same checkout. One says “send the receipt email.” The other says “payment 8841 was captured for 40.” They feel similar in a diagram. They are not the same data.

Assumptions, said as assumptions:

  • 8 million receipt emails a day. A sketch, not a measured product.
  • Sending one email takes 200 ms of worker time, mostly waiting on the mail provider.
  • You run 20 email workers.
  • The peak hour is 4 times the daily average, and that peak lasts 2 hours. Both numbers are assumptions.
  • 1 million captured payments a day, a separate sketch.
  • A payment record is 400 bytes.
  • You keep the payment log for 30 days and store 3 replicas. Assumptions about the product, not a default of any one broker.
  • Three programs need every payment: the ledger, fraud scoring, and the receipt view.

A day has 86,400 seconds. The interview shortcut is about 100,000 seconds, and it is worth seeing both.

emails per second, average
  8,000,000 / 86,400 = 92.6
  shortcut: 8,000,000 / 100,000 = 80

peak, assumed 4x
  92.6 * 4 = 370 per second

workers so a steady load does not queue
  average: 92.6 * 0.200 = 18.5
  peak:    370 * 0.200 = 74
  at steady state, concurrency = arrival rate * residence time
  a peak that does not queue needs residence time to stay 0.200 s

service rate of the 20 workers you actually have
  20 / 0.200 = 100 emails per second

backlog growth during the peak
  370 - 100 = 270 per second
  270 * 7,200 seconds = about 1.95 million emails

drain rate once you are back to the average
  100 - 92.6 = 7.4 per second
  1.95e6 / 7.4 = about 260,000 seconds, about 3 days

Twenty workers are enough for the average day and not enough for the peak you just assumed. The queue will accept the burst, which is what you wanted, and then it will sit on roughly two million messages for most of three days, which is the receipt arriving on Thursday for a Monday purchase. Queue depth that does not fall after the peak is the symptom. The fix is more workers, a faster send, or a shorter peak, not a different brand of queue. At steady state, average concurrency equals arrival rate times residence time. A peak that must not queue needs about 74 workers so residence time can stay at the 200 ms send. Below that capacity there is no steady state, only a queue that grows for as long as the peak lasts. If you cannot name the arrival rate and the service time, you cannot size the fleet.

The email message is work. Worker A and worker B compete. Each receipt is sent by one of them. After the ack, the broker has nothing to rewind. That is what you want. A replay of Monday’s mail queue on Wednesday would send every receipt again.

Now the crash, because the ack is doing a destructive job. Each worker prefetches a small batch so it is not waiting on the broker for every message. Assume a prefetch of 10, which is an assumption. The worker has already handed the message to the mail provider, the provider has accepted it, and the process dies before the ack. The broker redelivers those 10. Those users get a second email. With 20 workers dying at once you could duplicate up to 200 sends. Annoying, visible, and usually survivable. The other crash is worse for this product: the worker acks first, then calls the provider, then dies in between. The broker will not redeliver. The receipt is simply missing. There is no second copy unless you still have the payment fact somewhere else and a job that can notice the gap.

payments per second, average
  1,000,000 / 86,400 = 11.6
  shortcut: 1,000,000 / 100,000 = 10

if ledger, fraud, and receipts share one queue
  each sees about 11.6 / 3 = 3.9 per second
  and misses about two thirds of payments

if each keeps an offset on a log
  each must handle the full 11.6 per second

storage, one copy
  1,000,000 * 400 bytes = 400 MB per day

three replicas, 30 days
  3 * 30 = 90 times one day of ingest
  90 * 400 MB = 36 GB

Put the ledger and fraud on one shared queue and you have built a silent correctness bug. They compete. Fraud scores the payments it happened to dequeue, and the ledger records a different subset. Both dashboards look healthy. The books do not balance against the risk model. Two offsets on one log fix the split. They do not split the 11.6. Each reader does all of it. People size a log consumer as if it were a worker pool and then watch it fall behind forever.

The 36 GB figure is the bill for being able to rebuild. It is three replicas times 30 days, which is 90 times a single day of ingest, times 400 MB. If fraud scoring is stopped for 31 days and retention is 30, the log no longer contains the days it missed. “We will catch up” is false once the old end has been deleted. You either retain long enough for the outage you are willing to have, or you export the log to a store that keeps it longer, or you accept that a long outage means a backfill from the payment database rather than from the log.

flowchart LR
  checkout[Checkout] --> mailQ[Email queue]
  mailQ --> workerA[Worker A takes one job]
  mailQ --> workerB[Worker B takes a different job]
  checkout --> payLog[Payment log]
  payLog --> ledger[Ledger offset]
  payLog --> fraud[Fraud offset]
  payLog --> receipt[Receipt offset]

The top path deletes on ack. The bottom path does not. The receipt email can still be a queue even though the payment is a log. The mail worker is one consumer of the fact, and its input can be “a row appeared” or “a log record was read,” but the thing it pulls in order to call the mail provider is work, and work wants competing consumers and deletion.

A second failure, on the payment side, is using the queue as the only memory of the capture. The handler acks as soon as the ledger insert is attempted, the insert rolls back, and the message is already gone. The card was captured. The ledger has no row. Nothing will retry, because a queue does not rewind. The log version of that mistake is different and usually kinder: the record is still there, the offset was not committed, and a new process reads it again. Kinder only if the insert is idempotent. A second insert of payment 8841 must not create a second credit.

Tradeoffs

Choice What you gain What you spend
Competing consumers on one queue The task runs once, load spreads, depth tells you the backlog The message is gone after ack, replay is not a feature, finish order is not enqueue order
One log, one offset per reader Every reader sees every fact, and a bad reader can rewind Storage for the retention window, and every reader must tolerate seeing a record again
A separate queue per downstream service Isolation of retries, so fraud’s outage does not block the email worker You can forget to enqueue a copy, and the copies drift out of agreement
Ack early, as soon as the handler starts A poison message cannot wedge the queue as easily A crash drops the work on the floor
Ack only after the side effect You do not lose the task when the process dies A crash after the side effect duplicates it, and a poison message retries until you quarantine it
Retain for a long time A consumer can be offline, and a new consumer can be born later Bytes, and a replay that surprises a handler which was not idempotent

The honest tradeoff in an interview is the duplicate against the loss. Email can survive a duplicate better than a loss if the duplicate is rare, but a missing password-reset mail is also a product failure, so you still ack after the provider accepts, and you make the send idempotent with a key when the provider supports it. A payment fact cannot treat loss as the normal case. Keep it where a rewind is possible, and make the apply idempotent anyway, because rewind causes duplicates.

A queue with no bound is a memory leak with extra steps. Depth felt like free insulation in the email sketch, and then it was a three-day delay. Put a limit on depth. When you hit it, fail the enqueue or shed the cheapest traffic. A checkout that cannot enqueue a receipt should have a defined behavior. Silently allocating memory until the broker dies is not a behavior.

Pitfalls

  • Two services sharing one queue when each needed every message. Symptom: each dashboard’s counts are low by a similar fraction, and the sum of the two counts matches the real total. Split them into two offsets or two queues on purpose.
  • Treating queue FIFO as an invariant once you run more than one worker. Symptom: debits land out of order, or two workers both read a balance of 12, both allow a debit, and the account goes negative. The queue did not lock the account. A constraint in the database, or a single ordered log per account, is what holds that invariant.
  • Acking before the side effect, because an example client did that by default. Symptom: the provider has an outage, your process crashes, and those users never get mail, while your queue depth looks wonderfully low.
  • A poison message with infinite retries. One malformed payload crashes the worker, the queue redelivers, the worker crashes again. Symptom: one message, a pegged worker, and a depth that does not move. Cap the attempts and park the message on a dead-letter queue you actually read.
  • Retention shorter than the outage you will have. Symptom: a consumer returns after a long incident and either errors on a missing offset or quietly starts at the tip and never processes the gap. Decide which of those you want before the incident.
  • Replaying a log into a handler that sends mail or charges a card. Symptom: the backfill is a second production incident. Replay into a projection that sets state, or gate the side effect behind a key.
  • Sizing log readers as a competing pool. Three fraud workers in one group share the stream. If you needed three full copies, you built one split copy. Watch “records in” per service, not just CPU.

In the interview

Say which object you have in the first five minutes. “This message is work, so it goes on a queue, competing consumers, ack after the provider accepts, and I will size the workers with arrival rate times service time.” Or: “This message is a fact three services all need, so it goes on a log, one offset each, retained for 30 days, and a replay has to be idempotent.” That sentence is the design. The box labeled “Kafka or SQS” is not.

Give one number. The email sketch is the pattern: daily volume, divided by 86,400, times the fraction of a second the work takes, equals how many workers the average needs. Then say the peak factor out loud so they can hear that it is an assumption. The bottleneck is either the worker’s downstream call or a hot entity you refused to isolate. The tradeoff is loss against duplication, and you pick it by saying when you ack.

Skip the vendor feature list. Skip a claim that your queue is exactly-once. If they ask how the payment gets onto the log without a crash window between the database and the broker, that question is the outbox, and you can say the shape in one sentence and keep moving unless they want it. If they ask what happens when the consumer dies mid-message, you are in delivery guarantees. Answer with the ack timing, not with a product name.

Check yourself

Ledger and fraud both need every payment. What happens if they pull from one shared queue?

They compete. Each payment is delivered to one of them. Each service quietly misses the payments the other took, and the two miss-sets add up to the whole stream. You wanted two offsets on a log, or two queues that are each a deliberate copy. A shared queue is the right tool only when either service is allowed to do the work.

Twenty email workers each prefetch 10 jobs and die after the mail provider has accepted the send, before ack. What do users see, and what is already gone?

Up to 200 receipts can go out a second time, because the broker still considers those messages unacked and will hand them out again. Nothing is gone yet. The opposite crash is the loss: ack first, die before the provider accepts, and those receipts will not be retried. The queue has already forgotten them.

Average arrivals are 92.6 emails per second and each send holds a worker for 200 ms. You have 20 workers. Why does a 4x peak lasting two hours take days to drain?

A steady peak that does not grow a queue needs arrival rate times service time workers. That is about 74, because 370 per second times 0.2 seconds is 74. It is the same identity as Little’s law once you require residence time to stay at the service time. Twenty workers complete 100 per second, so the queue grows by about 270 per second, roughly 1.95 million messages over 7,200 seconds. After the peak, spare capacity is only about 7 per second, so the drain is on the order of three days. The queue absorbed the burst and also hid a capacity error.

A payment log is retained for 30 days. Fraud scoring is down for 31. Can it catch up by reading the log?

No. Retention deletes the old end whether or not this consumer read it. A day of payments is gone from the log. Catch-up has to come from somewhere that still has the rows, or from a longer-lived export you made on purpose. “Lag” is only a delay while the records still exist.

You need debits on one account to apply in order. Why does adding consumers to a single FIFO queue not do that?

With two workers in flight, completion order is not dequeue order, and both workers can read the same balance before either writes. The queue is not a lock on the account. Order per account wants one ordered log for that key, or a database transaction that enforces the invariant. More competing consumers make the race wider.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Jay Kreps, Neha Narkhede, and Jun Rao.