SD/Lesson 5 of 8/6 min read
Message Queues and Async Processing
Why async, message queues vs pub/sub vs logs, Kafka partitions and consumer groups, delivery guarantees, idempotency, dead-letter queues, backpressure and the outbox pattern.
On this page
Why go async
Synchronous call chains couple the caller to every downstream service: if the email service is slow, sign-up is slow; if it is down, sign-up fails. Moving non-critical work to the background:
- Decouples producers from consumers (they can be deployed, scaled and fail independently).
- Absorbs spikes: the queue buffers bursts; workers drain it at their own pace.
- Cuts latency: respond to the user as soon as the critical part is done.
- Enables retries without blocking the user.
Typical async work: sending email and notifications, video transcoding, generating thumbnails, updating search indexes, analytics events, fan-out of feed posts.
Message Queue
A message queue holds messages from producers until a consumer takes and acknowledges them. Each message is processed by one consumer (point-to-point), so adding workers scales processing (competing consumers).
producer ──▶ [ m5 m4 m3 m2 m1 ] ──▶ worker A
──▶ worker BA message broker is the server that runs queues and topics: RabbitMQ, Amazon SQS, ActiveMQ, Redis streams, Kafka.
Publish-Subscribe
In publish-subscribe, a producer publishes to a topic and every subscriber gets its own copy. One OrderPlaced event can trigger billing, inventory, email and analytics independently, and new subscribers can be added without touching the producer.
| Queue | Pub/sub | |
|---|---|---|
| Each message goes to | One consumer | Every subscriber |
| Use | Distribute work | Broadcast events |
| Examples | SQS, RabbitMQ queue | SNS, Google Pub/Sub, RabbitMQ fanout |
Event Streaming
Event streaming platforms store messages in an append-only, replicated log that consumers read at their own offset. Messages are kept for a retention period (days or forever), not deleted on consumption, so consumers can replay history.
Kafka
Kafka is the dominant streaming platform.
- A topic is split into partitions; each partition is an ordered log replicated across brokers.
- Producers choose the partition by key (
hash(user_id)), so all events for one key stay ordered. - Ordering is guaranteed only within a partition, not across a topic.
- Throughput scales with the number of partitions.
Consumer Group
Consumers sharing a consumer group ID split a topic's partitions between them: each partition is read by exactly one consumer in the group. Different groups each read the full stream independently (pub/sub semantics).
topic orders: P0 P1 P2 P3
group billing: C1 C1 C2 C2 (2 consumers share 4 partitions)
group search: C1 C1 C1 C1 (independent copy)More consumers than partitions leaves the extra consumers idle, so partition count caps parallelism.
| RabbitMQ (queue) | Kafka (log) | |
|---|---|---|
| Model | Broker pushes, deletes on ack | Consumers pull, retention-based |
| Replay | No | Yes |
| Ordering | Per queue (weak with many consumers) | Per partition |
| Throughput | High | Very high |
| Routing | Rich (exchanges, bindings) | By topic and key |
Delivery Guarantees
| Guarantee | Meaning | How |
|---|---|---|
| At-most-once | May be lost, never duplicated | Ack before processing |
| At-Least-Once Delivery | Never lost, may be duplicated | Ack after processing; redeliver on timeout |
| Exactly-Once | Effect happens once | At-least-once + idempotent or transactional processing |
At-least-once is the practical default. A worker can crash after doing the work but before acking, so the message is delivered again.
Exactly-once delivery across a network is impossible in general. What systems call "exactly-once" (Kafka transactions) is exactly-once processing within their boundary. Across external side effects, you get it by making consumers idempotent.
Idempotency
An operation is idempotent if doing it twice has the same effect as doing it once. Under at-least-once delivery, every consumer must be.
Techniques:
- Idempotency key: each message carries a unique ID; the consumer records processed IDs (in the same transaction as the effect) and skips duplicates.
- Natural idempotency:
SET balance = 100is idempotent;balance = balance + 10is not. - Conditional writes:
UPDATE ... WHERE version = 7.
The same idea applies to APIs: payment APIs accept an Idempotency-Key header so client retries do not charge twice.
Dead-Letter Queue
A message that keeps failing (malformed payload, a bug) would be retried forever and block or waste workers. After N attempts, move it to a dead-letter queue (DLQ) for inspection, alerting and manual replay.
Retry with exponential backoff and jitter (1 s, 2 s, 4 s ... plus randomness) so a recovering dependency is not hammered by synchronized retries.
Backpressure
When producers outpace consumers, the queue grows without bound, latency explodes and memory runs out. Backpressure is any mechanism that pushes the slowdown back to producers:
- Bounded queues that reject or block when full.
- Rate limiting producers.
- Autoscaling consumers on queue depth or consumer lag.
- Load shedding: drop low-priority work first.
Monitor queue depth and consumer lag; they are the early warning signs.
Outbox Pattern
Problem: a service must update its database and publish an event. Doing both separately (dual write) can leave them inconsistent: the DB commit succeeds but the publish fails, or vice versa.
Outbox pattern: in the same local transaction, write the business row and an outbox row describing the event. A separate relay (a poller, or change data capture with Debezium) reads the outbox and publishes to the broker, retrying until it succeeds.
BEGIN;
INSERT INTO orders (...) VALUES (...);
INSERT INTO outbox (event_type, payload) VALUES ('OrderPlaced', '...');
COMMIT;Result: at-least-once publishing that is consistent with the database. Consumers deduplicate with idempotency keys.
Sagas
A saga replaces a distributed transaction across services with a sequence of local transactions, each publishing an event that triggers the next. If a step fails, compensating transactions undo the earlier steps (refund the payment, release the inventory).
- Choreography: services react to each other's events. Loose coupling, but the flow is hard to see.
- Orchestration: a central coordinator tells each service what to do. Easier to follow and change.
Quick revision
- Async decouples services, absorbs spikes and moves slow work off the request path.
- Queue: one consumer per message. Pub/sub: every subscriber gets a copy. Log: retained and replayable.
- Kafka orders messages within a partition; partitions cap consumer-group parallelism.
- At-least-once is the default; make consumers idempotent to get exactly-once effects.
- Failed messages go to a DLQ after retries with exponential backoff and jitter.
- Use the outbox pattern to update the DB and publish an event consistently; sagas for multi-service workflows.