Messaging and async

Queues vs logs

Why systems go asynchronous, how a message queue differs from a retained log, and how to choose between them for a given job.

Lesson11 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A shop’s checkout endpoint does five things before it answers the customer: it charges the card, writes the order, emails a receipt, notifies the warehouse and records the sale for analytics. Each call takes 50 to 200 ms, so a good checkout takes most of a second.

Then the email provider has a bad afternoon and takes 10 seconds to time out. Checkout now takes 10 seconds too, although the order was safely written in the first 300 ms. A week later a marketing campaign triples traffic for ten minutes, the warehouse API cannot keep up, and orders fail because of a system the customer never sees. The request path is as slow as its slowest call and as reliable as its least reliable one.

Engineers tried the obvious patches first. Running the slow calls on a background thread makes checkout fast, but a deploy or a crash loses whatever was still in memory. Writing a row to a jobs table and polling it survives restarts, and plenty of teams still do exactly this, but each one ends up rebuilding locking, retries and clean-up, and the polling load lands on the main database.

The idea that lasted is a broker: a separate, durable service that accepts a message from a producer, stores it, and hands it to a consumer later. Checkout writes the order, publishes “order placed”, and returns. That buys four things:

  • A shorter request path. The customer waits only for the work that must finish before the answer.
  • Failure isolation. If email is down, messages wait. Checkout does not notice.
  • Load levelling. A ten-minute spike becomes a backlog that drains over the next half hour, so consumers are sized for the average and not the peak.
  • Decoupling. A new consumer can be added without changing or redeploying the producer.

Brokers split into two families that look alike from a distance and behave very differently: the message queue and the log.

One event, two brokers: a queue and a log7 components: Order service, Message queue, Email worker 1, Email worker 2, Log, Billing, Analytics. Connections: Order service to Message queue (send); Message queue to Email worker 1; Message queue to Email worker 2; Order service to Log (append); Log to Billing; Log to Analytics.Order serviceproducerMessage queueSQS or RabbitMQEmail worker 1Email worker 2LogKafka topicBillingconsumer group AAnalyticsconsumer group Bsendappend

Step 1 of 9

An order service emits an event each time a customer checks out. Two kinds of broker could carry that event, and they make opposite choices about what happens after a consumer has read it.

Read the steps as text
  1. An order service emits an event each time a customer checks out. Two kinds of broker could carry that event, and they make opposite choices about what happens after a consumer has read it.
  2. Start with the queue. The producer sends two messages, and the broker holds them until a worker is free. Think of the queue as a to-do list of jobs that have not been done yet.
  3. Two email workers compete for the same queue. The broker hands message one to the first worker and message two to the second. Each message goes to exactly one of them, so adding workers adds throughput.
  4. Each worker acknowledges once its email is sent, and the broker deletes that message. Had a worker crashed before acknowledging, the broker would have handed its message to someone else. Once acknowledged, a message is gone for good.
  5. Now the log. The producer appends the same two events to the end of a partition, and each record is given the next offset. Reading a record does not remove it.
  6. Billing reads forward from its last position, then commits offset 2, meaning it has finished everything before that. The broker stores one number for the whole group. It does not track the state of each message.
  7. Analytics is a separate consumer group with its own offset. It reads the same two records later, at its own pace. Neither group affects the other, and the producer never needed to know that either exists.
  8. Next month a new fraud model needs the history. A new group, or an old one reset to offset 0, replays every record still inside the retention period. A queue cannot do this, because acknowledged messages were deleted.
  9. A queue is a to-do list: each message is acknowledged, deleted after it is consumed, and shared out among competing workers. A log is a history: records stay in order, each group keeps an offset, and many groups can read or replay it independently.
One event, two brokers: a queue and a log

The queue model

RabbitMQ and Amazon SQS are the usual examples. A queue holds work that has not been done yet, and the broker tracks every message individually:

  1. A producer sends a message and the broker stores it.
  2. A consumer receives it. The broker keeps the message but hides it from other consumers. SQS does this with a visibility timeout, 30 seconds by default.
  3. The consumer finishes and acknowledges. The broker deletes the message.
  4. If no acknowledgement arrives, because the consumer crashed or ran out of time, the broker delivers the message again.

Several consumers on one queue are competing consumers: each message goes to one of them. To go faster you start more workers, and there is nothing to reconfigure.

Per-message tracking is what makes the useful extras possible: retrying one message without touching its neighbours, delaying a message, expiring it, giving it a priority, or moving it to a dead-letter queue after repeated failures. RabbitMQ adds flexible routing, where producers publish to an exchange and bindings decide which queues get a copy.

The limits follow from the same design. A consumed message is gone, so you cannot replay last week’s traffic through a fixed consumer. Order is loose once several workers compete, because a redelivered message arrives after its successors. SQS standard queues promise only best-effort ordering. FIFO queues give strict order within a message group, at lower throughput.

The log model

Apache Kafka, which LinkedIn open-sourced in 2011, and Amazon Kinesis Data Streams are the usual examples. A log is an append-only sequence of records, split into partitions. Each record in a partition gets the next offset, and reading does not remove anything.

  • Retention is by time or size, not by consumption. Kafka keeps records for 7 days by default. Kinesis keeps them for 24 hours by default and up to 365 days if you pay for it.
  • Consumers track their own position. A consumer group commits the offset it has reached in each partition. The broker’s state per group is a handful of numbers.
  • Many groups read the same records independently. Billing, search indexing and analytics each see every record, at their own pace.
  • Replay is a normal operation. Reset a group’s offset and it reprocesses the retained history. This is how you rebuild a cache, backfill a new service, or recover from a consumer bug.
  • Order is strict within a partition. Records with the same key go to the same partition, so one customer’s events stay in sequence.

The costs are the mirror image of the queue’s strengths. Within a group, a partition is read by one consumer at a time, so parallelism is capped by the partition count. There is no per-message acknowledgement: a consumer cannot commit past offset 41 and come back to it later, so one bad record blocks its partition until you deal with it. Delays and priorities are not built in. The next lesson, Kafka: partitions and consumer groups, covers the mechanics.

Pub/sub: one event, many subscribers

Publish/subscribe is a delivery pattern, not a third kind of broker. The producer publishes to a topic, and every subscriber gets its own copy.

In the queue world you build it by giving each subscriber its own queue. An SNS topic fans out to several SQS queues, or a RabbitMQ fanout exchange copies each message to every bound queue. Each subscriber then scales with competing consumers on its own queue. In the log world it comes for free, because each consumer group is a subscriber.

One difference matters in design discussions. A queue-based subscriber added today receives messages published from today. A log-based subscriber added today can start from the oldest retained record.

Choosing between them

Question Queue Log
What does it hold? Work not yet done A history of events
After a consumer reads Deleted on acknowledgement Kept until retention expires
Ordering Best effort, or FIFO per group Strict within a partition
Scaling consumers Add workers freely One per partition per group
One message keeps failing Retried alone, then dead-lettered Blocks its partition until handled
Replay No Yes

Choose a queue when each message is a task that any one worker should do once: sending an email, resizing an image, calling a webhook. Tasks vary in duration, you want per-message retries and delays, and the order between tasks does not matter. A managed queue such as SQS is also the least operational work.

Choose a log when the message is a fact that several systems care about: order placed, page viewed, row changed. You want independent consumers, the option to replay, order per key, or very high throughput for clickstreams, metrics and change data capture.

Choose neither when the caller needs the result before it can continue. A queue does not make a synchronous dependency asynchronous. It only hides the wait. And at low volume a jobs table in the database you already run, read with SELECT ... FOR UPDATE SKIP LOCKED in PostgreSQL, is a reasonable queue with one system fewer to operate.

Going asynchronous has a price whichever model you pick. The system becomes eventually consistent: the customer sees “order placed” before the receipt exists. Messages can arrive twice, which is the subject of delivery semantics. A producer can outrun its consumers, which is backpressure. And a request that used to be one stack trace is now a trail across services that you need tracing to follow.

In the interview

Introduce a broker when a design has slow or unreliable work on the request path, bursty load in front of a system with fixed capacity, or one event that several services need.

Do not just say “add Kafka”. Say which model you want and why: “Sending the receipt is a task. Any worker can do it and order does not matter, so I would use a queue with a dead-letter queue. Order events feed billing, search and analytics and I want to be able to replay them, so I would use a log keyed by order ID.” Then state what you gave up: the consumers are eventually consistent, delivery is at least once so they must be idempotent, and you will monitor queue depth or consumer lag.

Key takeaways

  • A broker takes slow or unreliable work off the request path, isolates failures, levels out bursts and lets new consumers appear without changing the producer.
  • A queue holds work not yet done: each message is delivered to one of several competing consumers, acknowledged, and deleted.
  • A log holds a history: records are retained in order, each consumer group keeps its own offset, and any group can replay.
  • Pub/sub is a pattern, not a third model. Queues build it with one queue per subscriber; a log gets it from consumer groups.
  • Choose a queue for tasks, a log for facts that several systems need or that you may want to replay, and neither when the caller needs the answer now.
  • Going asynchronous costs you immediate consistency and introduces duplicates, lag and harder debugging.

Check yourself

1. A bug in the billing consumer mis-processed every order event for the last three days. The fix is deployed. Which property of the broker decides whether billing can reprocess those events?
2. Email, fraud and analytics each need every "order placed" event, and each service runs several instances. Using SNS and SQS, which shape is right?
3. Image resize jobs take between 1 second and 5 minutes, and their order does not matter. Why does a queue fit better than a Kafka topic?
4. Checkout must decline an order when the fraud score is high. Someone suggests putting the fraud check behind a queue to make checkout faster. What is wrong with that?
5. A new recommendations service is added a month after launch and wants to train on every order since day one. Orders were published to a RabbitMQ fanout exchange. What does the new service receive?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Name four things a broker buys you compared with calling a service directly.

A shorter request path, isolation from the consumer's failures, load levelling (bursts become backlog), and decoupling so new consumers need no producer change.

What happens to a message in a queue after a consumer acknowledges it?

The broker deletes it. If no acknowledgement arrives in time, the broker redelivers it, possibly to another consumer.

What is an offset, and who tracks it?

A record's position in a partition of a log. Each consumer group commits the offset it has reached; the broker does not track individual messages.

What limits consumer parallelism in each model?

A queue has no built-in limit: add competing workers. In a log, one consumer per partition per group, so the partition count is the cap.

How do you get pub/sub with queues, and with a log?

Queues: a topic or exchange that copies each message to one queue per subscriber (SNS to SQS, RabbitMQ exchanges). Log: each subscriber is its own consumer group.

When should you use neither a queue nor a log?

When the caller needs the result before it can continue, or when volume is low enough that a jobs table in your existing database does the job.

Review the deck