Handbooks / System Design / Chapter 8
Queues and Async Processing
7 pages · ~5 min✓ Reviewed
Builds on Storage: Blobs, Files and Search. Next up: CAP, Consistency and Reliability.
Queues vs Pub/Sub Mental Model
1. Queue vs Pub/Sub
| Queue | Pub/sub | |
|---|---|---|
| Each message goes to | one consumer in a competing group | every subscriber |
| Use for | work distribution | fan-out |
| Examples | SQS, RabbitMQ queue | SNS, Redis pub/sub, Kafka groups (full copy each) |
2. Broker and Retention
- Producer
- Broker
- Consumer
Kafka Basics: Topics, Partitions, Offsets
1. Topic, partition, offset
- A topic is split into partitions
- Each partition is an append-only ordered log
- Ordering holds only within a partition, never across
- Offset = a message's position in its partition
- Consumer commits offsets to resume where it left off
m00
m1
Delivery Guarantees and Idempotent Consumers
1. Commit Order Sets the Guarantee
| Offset commit | Crash means | |
|---|---|---|
| At-most-once | before processing | message lost, no duplicates |
| At-least-once | after processing | redelivery, duplicates possible |
Failures: Retries, Dead-Letter Queues and Backpressure
1. Retry Safely
- Retry only transient errors: timeouts, 503, throttling
- Delay grows exponentially, plus random jitter
- Set a max attempt cap, then stop retrying
- Never retry in a tight loop
python
delay = min(cap, base * 2 ** attempt) time.sleep(random.uniform(0, delay))
full jitter avoids synchronized retry storms
2. Dead-Letter Queue
- Receiveconsumer
- Failsretry again
- N attemptsmaxReceiveCount
- DLQmoved aside
Event-Driven Design Pitfalls
1. Event Shape
| Notification | State transfer | |
|---|---|---|
| Carries | order placed + ID | full order data |
| Consumer | calls back for details | no callback |
2. Coordination
Messaging Cheat Sheet
1. Pick the Model
| Model | Delivered to | Example |
|---|---|---|
| Queue | one consumer per message | SQS, RabbitMQ |
| Pub/sub | every subscriber | SNS, Redis |
| Kafka | each group gets a full copy; replayable | partitioned log |
Check yourself
A consumer charges a card via an API, crashes before committing the offset, then restarts. What happens, and what is the fix?
- Offset uncommitted, so the message is redelivered and the card is charged twice
- Pass the message ID as the payment API's idempotency key
- Optionally also record the ID in a dedupe table
A topic has 4 partitions and the group has 6 consumers. What runs in parallel?
- Only 4 consumers get a partition; 2 sit idle
- Max parallelism = partition count