Skip to content

Queues, pub/sub and streams

Phase 6 · Distributed systems · 13 min read · 10 Atlas cases linked

What you'll be able to do

  • Decide when to make work asynchronous and when not to.
  • Tell a queue, a pub/sub topic and a log (Kafka-style) apart.
  • Explain delivery guarantees and why consumers must be idempotent.

Why asynchronous

In a synchronous call the caller waits for the answer. That couples the caller's speed and availability to the callee's. A message broker in the middle decouples them:

  • Smooths bursts: a spike fills the queue instead of crashing the consumer.
  • Isolates failure: if the consumer is down, messages wait.
  • Moves slow work off the request path: the user gets a response now; the email, thumbnail or report is made later.
  • Fans out: one event can trigger many independent reactions.
A broker sits between producer and consumer and buffers messages, so each side runs at its own pace.

Don't use it when the caller genuinely needs the result right now, or when you can't tolerate the extra moving part and eventual completion.

Three shapes of messaging

Shape Delivery Consumers Typical use
Queue (SQS, RabbitMQ) Each message goes to one consumer, then is removed Competing workers Task processing, job queues
Pub/Sub topic (SNS, Google Pub/Sub) Each message goes to every subscriber Independent subscribers Fan-out of events (order placed → email, inventory, analytics)
Log / stream (Kafka, Kinesis) Messages are appended and kept; consumers track their own position (offset) Many groups, can replay Event streaming, analytics, event sourcing

The big difference with a log: reading does not delete. You can add a new consumer later and have it replay history, or rewind after a bug.

Kafka-style concepts in one paragraph

A topic is split into partitions (the same partitioning idea as the previous lesson). Order is guaranteed only within a partition, so you pick a key (e.g. order_id) that sends related events to the same partition. A consumer group shares the partitions among its members, so one partition is read by at most one member of the group: more consumers than partitions means idle consumers. Each group stores its offset (how far it has read).

Delivery guarantees

Guarantee Meaning Cost
At-most-once Never redelivered; may be lost Simple, lossy
At-least-once Never lost; may be delivered more than once Common default
Exactly-once Processed once Only with extra machinery (transactions, dedup); end-to-end it is really "at-least-once + idempotent processing"

Because duplicates happen (a consumer crashes after doing the work but before acknowledging), the practical rule is: make consumers idempotent. Doing the same message twice must have the same effect as doing it once. Typical tools: an idempotency key stored with the result, or an upsert instead of an insert.

Failure handling

  • Retries with backoff: retry transient errors after waiting longer each time, with jitter, so retries don't become a storm.
  • Dead-letter queue (DLQ): after N failures, move the message aside so one poison message doesn't block the queue. Alert on DLQ depth and have a way to replay.
  • Backpressure: if consumers can't keep up, queue length (lag) grows. Scale consumers on lag, and decide what happens when the queue is full (reject, drop, or slow producers).
  • Ordering: if order matters, ensure all messages for one entity share a partition key, and know that retries can reorder messages.

Interview angle

When you draw a queue, answer four questions out loud: what happens if the consumer crashes mid-message (duplicates → idempotency), what happens to poison messages (DLQ), how you notice lag (metrics), and what ordering you need (partition key).

For AI engineers

For AI engineers

An inference API may accept a request quickly, then place it on a queue for GPU workers. If requests arrive at 120 per second and workers finish 100 per second, the backlog grows by 20 per second: 1,200 waiting after one minute. A queue absorbs a short burst; it does not create capacity. Set a backlog or waiting-time limit, then slow or reject new work when that limit is reached. Watch consumer lag alongside GPU utilization before adding workers.

Batch scoring jobs can use the same queue shape: each task names a batch, and a worker acknowledges it only after writing the result. If the worker dies after writing but before acknowledging, the batch returns. Store a task ID with the output so the second attempt does not duplicate it. Malformed records need a bounded retry count and a dead-letter queue for inspection; otherwise they can consume worker time indefinitely.

A RAG ingestion pipeline often starts with a document-updated event. Separate consumers can extract text, update an index, and record audit data. A retained log lets a new indexer replay old events; independent consumer groups keep its position separate from the audit consumer's. Key events by document ID when updates to one document must stay ordered. Events for different keys may run out of order, and a retry still needs an idempotent index update. Training-data and user-feedback events have the same risk: if a replay counts one feedback event twice, your aggregates and later training set can change.

Common mistakes

  • Letting the queue grow without a bound or an overload policy. Measure lag and waiting time; decide when producers must slow down or receive a rejection.
  • Retrying a malformed record forever. Cap attempts, move it to a dead-letter queue, alert on that queue, and define how to repair or replay it.
  • Assuming the broker gives end-to-end exactly-once effects. A worker can finish a side effect and crash before its acknowledgment reaches the broker.
  • Writing a consumer that repeats a charge, count, or index insertion on redelivery. Use a durable idempotency key with the effect.
  • Assuming order across partitions. Choose a key that keeps one entity's events together, and handle duplicates even when that partition is ordered.
  • Adding more consumers than partitions in one group and expecting more parallelism. The extra consumers have no partition to read.

Check yourself

A payment consumer crashes after charging the card but before acknowledging the message. The broker redelivers. How do you avoid charging twice?

Make the handler idempotent: store an idempotency key (e.g. the message or payment ID) with the result; on redelivery, find the key and return the previous result instead of charging again.

You need all events for one customer processed in order, and you want 20 consumers. How?

Use a log/stream with at least 20 partitions and partition by customer_id. All events for a customer go to one partition (so they're ordered), and the 20 consumers each own some partitions.

One malformed message makes a consumer fail forever and the queue stops moving. What pattern fixes it?

Limit retries and send the message to a dead-letter queue, so the rest of the queue continues. Alert on DLQ growth and fix/replay the poison message later.

Lab

Build an in-memory queue and partitioned topic in code/async-messaging/. Add visibility timeouts, acknowledgments, redelivery, and a dead-letter queue. Track each consumer group's offsets, replay events, assign partitions, and measure lag. Make a feedback consumer safe to run twice after redelivery. Run cd code/async-messaging && PYTHONPATH=starter python -m pytest tests -q.

Real systems that use this

The linked Atlas cases cover: EventBridge, SNS and Azure pub/sub reference architectures, Confluent/Kafka components, Spotify giving each event type its own topic and pipeline so one failing type doesn't affect another, Grab's self-service streaming platform, and IoT telemetry brokers.

Go deeper

  • Interactive: Designed to Scale – queues, pub/sub
  • Your handbook: Software Engineering Handbook, ch. 6 "Kiến trúc bất đồng bộ"
  • Later lessons here: delivery guarantees and idempotency in depth

See it in the wild

Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.