DS·66
Messaging Systems
Asynchronous messaging from first principles: why decouple with a broker, queues versus topics versus logs, producers, consumers, acknowledgements, offsets, retention and replay. Compares the two big designs (the message queue, like RabbitMQ and SQS, and the distributed log, like Kafka, Pulsar and Kinesis) plus NATS, Redis Streams and cloud services, with competing consumers, fan-out, ordering, prefetch, dead-letter queues, backpressure, and client code in Java, Go, Python, Rust and Elixir.
Start here: queues and logs
Why put a broker in between?
When the order service calls the SMS service directly, both must be up at the same moment, the caller waits for the slowest step, and a burst of orders hits the SMS service at full force. A message broker sits between them: the producer hands a message to the broker, which stores it, and consumers take it when they're ready. That decouples services in time (the consumer can be down for an hour), in load (the broker absorbs bursts) and in knowledge (the producer doesn't know who consumes). Brokers come in two basic shapes.
Shape 1: a queue, where each message goes to one worker
await js.add_stream(StreamConfig(name="TASKS", subjects=["tasks.>"], retention=RetentionPolicy.WORK_QUEUE))
for i in range(1, 7): await js.publish("tasks.sms", json.dumps({"order": 100 + i}).encode())
# two workers pull from the same durable consumer, and acknowledge each task when done
1) work queue, 6 SMS tasks, 2 workers: {'w1': [101, 103, 105], 'w2': [102, 104, 106]} | messages left in the stream after acks: 0
In a queue, the workers are competing consumers: each task went to exactly one of them, and once acknowledged it was deleted. Adding workers adds throughput (the lab cut 200 jobs from 4.1 s to 1.6 s with four workers). This is the shape of RabbitMQ queues, Amazon SQS, Celery and Sidekiq: background jobs, emails, image processing.
Shape 2: a log, where every consumer reads everything
await js.add_stream(StreamConfig(name="ORDERS", subjects=["orders.>"])) # keep messages; don't delete on ack
for … : await js.publish("orders.placed", …)
2) log, 5 OrderPlaced events: kitchen reads [201, 202, 203, 204, 205] | loyalty reads [201, …, 205] | analytics reads [201, …, 205]
events still stored after all three consumed them: 5
a new consumer replaying from sequence 3: [203, 204, 205]
In a log, messages are kept (for a retention period or size) and each consumer keeps its own position: the kitchen, the loyalty service and analytics all read every event independently, and a brand-new consumer could replay history from any point. This is the shape of Kafka, Pulsar, Kinesis, Redis Streams and JetStream streams: event-driven architectures, change data capture, rebuilding a read model after a bug.
| Queue | Log | |
|---|---|---|
| Who receives a message | One consumer | Every consumer group |
| After acknowledgement | Deleted | Kept until retention expires |
| Replay | No | Yes, from any offset |
| Ordering | Usually per queue, weakened by competing consumers | Per partition (per key) |
| Typical use | Jobs and tasks | Events, streams, integration |
Acknowledgements and redelivery
3) received order 201, no ack; 1.2 s later it was delivered again: order 201, delivery attempt 2
A broker can't know whether a consumer processed a message until the consumer acknowledges it. If no acknowledgement arrives within the ack wait (1 second here), the broker assumes the consumer died and delivers the message again. That's what makes messaging reliable, and it means every consumer will sometimes see the same message twice: delivery is at-least-once (chapter 68). Consumers must therefore be idempotent, acknowledge only after the work is done, and treat the delivery count as a signal (a message on its fifth attempt is probably poison).
How deep to go in messaging
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain queues vs logs, producers, consumers, acknowledgements |
| L2 | Use RabbitMQ, SQS, Kafka or NATS correctly: acks, retries, dead letters, consumer groups |
| L3 | Explain delivery semantics, ordering, backpressure, retention and replay, exchanges and routing |
| L4 | Diagnose lost, duplicated, reordered and poison messages, lag and redelivery storms |
| L5 | Design messaging topologies, event contracts and retry/DLQ strategies for a system |
| L6 | Operate messaging platforms with capacity planning, multi-tenancy and governance |
Why messaging
Synchronous versus asynchronous communication
With synchronous request/response (HTTP, gRPC), the caller waits, and both sides must be up at the same time. If the downstream is slow or down, the caller is slow or failing too. Chains of synchronous calls multiply this: availability of the chain is the product of availabilities (five services at 99.9% each give about 99.5%).
Messaging inserts a broker between producer and consumer. The producer hands a message to the broker and moves on, and the consumer processes it when it can. This gives:
- Temporal decoupling: the consumer can be down; messages wait.
- Load levelling: bursts queue up instead of overloading consumers, which drain at their own pace.
- Scaling: add consumers to process in parallel (competing consumers).
- Fan-out: one event, many independent subscribers (billing, email, analytics) without the producer knowing them.
- Failure isolation: a broken consumer doesn't break the producer.
The costs: eventual consistency (the effect happens later), harder debugging (no single stack trace; you need tracing and correlation IDs, Vol. 7), duplicate and out-of-order delivery (chapter 68), operating the broker, and queue growth that hides problems until it's huge.
Messages, commands and events
What a message means shapes the design:
| Kind | Meaning | Naming | Receivers |
|---|---|---|---|
| Command | "Please do X" | Imperative: ChargeCard, SendEmail |
Exactly one logical handler; the sender expects it to happen |
| Event | "X happened" (a fact, immutable) | Past tense: OrderPlaced, PaymentFailed |
Zero or more subscribers; the publisher doesn't know or care who |
| Query / request-reply | "Tell me Y" over messaging | GetQuote + reply-to address + correlation ID |
One responder |
| Document | A snapshot of state | CustomerProfile |
Consumers that need the current state |
Event payloads range from thin ({orderId}, so consumers call back for details, which couples them and adds load) to fat / event-carried state transfer (all relevant data in the event, so consumers are autonomous, at the cost of a bigger contract to version). The envelope (ID, type, source, time, correlation and causation IDs, schema version) is standardised by CloudEvents (CNCF).
The vocabulary
The roadmap's terms, defined precisely:
| Term | Meaning |
|---|---|
| Producer (publisher) | Client that sends messages |
| Consumer (subscriber) | Client that receives and processes messages |
| Broker | Server that stores and routes messages (RabbitMQ node, Kafka broker) |
| Queue | A buffer where each message is delivered to one of the consumers, then removed once acknowledged (point-to-point) |
| Topic | A named channel where each message goes to every subscription (publish/subscribe). In Kafka, a topic is a partitioned log |
| Partition | An ordered, append-only shard of a topic; the unit of ordering and parallelism |
| Ack (acknowledgement) | A consumer's signal that a message was processed, so the broker can delete it or advance progress. Producers also receive acks from the broker confirming durable receipt |
| Offset | A message's position in a partitioned log; consumers track "next offset to read" |
| Retention | How long the broker keeps messages: until acked (queues) or by time, size or key compaction (logs) |
| Replay | Re-reading old messages by moving the offset back, which is possible only with log-based retention |
Two architectures: queue and log
The most important distinction in messaging is whether the broker is a queue or a log.
| Message queue (RabbitMQ classic/quorum queues, ActiveMQ, SQS, Azure Service Bus queues) | Distributed log (Kafka, Redpanda, Pulsar, Kinesis, Azure Event Hubs, Redis Streams) | |
|---|---|---|
| Model | Smart broker, simple consumer | Simple broker (append, serve by offset), smarter consumer |
| Delivery to consumers | Each message to one consumer (competing consumers); fan-out via exchanges or SNS-style topics | Each consumer group gets every message; within a group, each partition goes to one consumer |
| Consumer state | Broker tracks each message (unacked, delivered, redelivered) | Consumer tracks one offset per partition (committed to the broker) |
| After consumption | Deleted | Kept until retention; replayable |
| Ordering | FIFO per queue, but parallel consumers and redelivery break it | Strict per partition |
| Parallelism | Add consumers freely | Capped by partition count per group (Kafka 4.2's share groups relax this, chapter 67) |
| Per-message features | Priorities, per-message TTL, delayed delivery, routing keys, selective ack/nack | Mostly per-partition; skipping one bad message needs application logic |
| Throughput | Tens of thousands per second per queue (more with sharding) | Millions per second per cluster |
| Best for | Task queues, work distribution, complex routing, RPC-ish workflows | Event streaming, event sourcing, CDC, analytics pipelines, fan-out to many teams, replay |
The lines are blurring: RabbitMQ Streams add a log type with offsets and replay; Kafka share groups (queues for Kafka, KIP-932) add per-message acknowledgement; Pulsar does both natively (with "shared" and "key_shared" subscription types over a log).
Queues in depth
Competing consumers and work distribution
With competing consumers, many workers read one queue, and each message goes to one worker. This gives horizontal scaling and natural load balancing: faster workers take more.
Prefetch (RabbitMQ's basic.qos, SQS's max messages per receive) limits how many unacknowledged messages a consumer holds. Too high, and one slow consumer hoards messages while others idle (and they all redeliver on its crash). Too low, and round trips throttle throughput. Start around 10–50 for quick tasks, and use 1 for long, uneven ones.
Acknowledgement modes
| Mode | Behaviour | Guarantee |
|---|---|---|
| Auto-ack (ack on delivery) | Broker deletes as soon as it sends | At-most-once: crash mid-processing loses the message |
| Manual ack after processing | Consumer acks when done; on crash or connection loss, the broker redelivers | At-least-once: crash after processing but before ack causes a duplicate |
| Nack / reject | Consumer refuses: requeue, or route to a dead-letter exchange | Error handling |
SQS uses a visibility timeout instead of connection-scoped acks. A received message becomes invisible for N seconds. If it's not deleted in time, it reappears for another consumer. If processing takes longer than the timeout, two workers process it unless you extend visibility.
Dead-letter queues and poison messages
A poison message fails every time (bad data, a bug). With naive requeue, it loops forever and blocks or burns consumers. The fix:
- Count deliveries (RabbitMQ quorum queues'
x-delivery-countwith adelivery-limit; SQSmaxReceiveCountin a redrive policy). - After N failures, move the message to a dead-letter queue (DLQ).
- Alert on DLQ depth, inspect, fix, and redrive (replay) once fixed.
Separate transient failures (timeouts: retry with backoff, possibly via delay queues) from permanent ones (validation errors: DLQ immediately). Chapter 78 covers poison messages as a failure mode.
RabbitMQ's routing model (AMQP 0-9-1)
Producers publish to an exchange, never directly to a queue. Bindings connect exchanges to queues, with a routing pattern:
| Exchange type | Routes to queues whose binding… |
|---|---|
| direct | Key equals the message's routing key exactly |
| topic | Pattern matches dotted keys: order.*.eu (one word), order.# (zero or more words) |
| fanout | All bound queues (ignores key) |
| headers | Header values match |
Queue types: quorum queues (Raft-replicated, durable, the recommended default for anything important), streams (replicated append-only logs with offset-based consumption and replay), and classic queues (non-replicated in RabbitMQ 4; classic mirroring was removed). RabbitMQ 4.x also supports AMQP 1.0 natively as a core protocol.
Publisher confirms are the producer-side ack: the broker confirms once the message is safely stored (on a quorum of replicas for quorum queues). Without confirms, a broker crash silently loses "sent" messages.
Cloud queues and other brokers
| Service | Notes |
|---|---|
| AWS SQS | Fully managed queue. Standard (nearly unlimited throughput, at-least-once, best-effort order) or FIFO (ordered per message group ID, deduplication within a 5-minute window via MessageDeduplicationId, lower throughput limits). Long polling, visibility timeout, DLQ redrive |
| AWS SNS | Pub/sub fan-out to SQS queues, Lambda, HTTP, email; the SNS → many SQS pattern gives fan-out with per-subscriber queues |
| AWS EventBridge | Event bus with content-based routing rules, schema registry, cross-account delivery |
| Google Cloud Pub/Sub | Global pub/sub; ordering keys; exactly-once delivery option for pull subscriptions (within the service's scope); dead-letter topics; seek/replay by timestamp or snapshot |
| Azure Service Bus | Enterprise queues and topics with sessions (ordered groups), transactions, duplicate detection, scheduled messages |
| NATS / JetStream | Lightweight, very fast core pub/sub (at-most-once); JetStream adds persistence, streams, consumers with acks, replay, key-value and object stores. Popular in Go and edge systems |
| Redis Streams | Log data structure in Redis with consumer groups (XADD, XREADGROUP, XACK, pending entries lists); good for moderate scale when Redis is already there |
| Apache Pulsar | Separates serving (brokers) from storage (BookKeeper); multi-tenancy, geo-replication, tiered storage, queue and stream semantics |
| Postgres as a queue | SELECT … FOR UPDATE SKIP LOCKED (Vol. 4 ch. 59) and libraries like pgmq, River (Go), Oban (Elixir), Solid Queue (Rails); transactional with your data, fine up to moderate rates |
Logs in depth: offsets, retention, replay
Offsets and commit strategy
In a log, a consumer's progress is just a number per partition. When you commit it decides the delivery guarantee:
- Commit before processing gives at-most-once (crash after commit loses the message).
- Commit after processing gives at-least-once (crash before commit reprocesses it). This is the usual choice.
- Commit atomically with the output (the same transaction) gives effectively-once (chapter 68): Kafka transactions for Kafka-to-Kafka, or store the offset in your database in the same transaction as the side effect.
Retention policies
- Time-based: keep 7 days (
retention.ms). - Size-based: keep the last N GB per partition (
retention.bytes). - Compaction: keep the latest value per key forever (a changelog / table, chapter 67).
- Tiered storage: old segments are offloaded to object storage (S3) for cheap long retention (Kafka KIP-405, Pulsar, Redpanda).
Replay
Because a log retains data, consumers can rewind: reprocess after fixing a bug, backfill a new service from history, rebuild a read model or search index, or run a new analytics job over last month. That's the defining capability of logs, and the reason event-driven architectures built on Kafka can treat the log as a source of truth (event sourcing, Vol. 9) rather than just a transport.
Replay means consumers must be idempotent (chapter 74) and side effects (emails, payments) must be guarded, or replay re-sends them.
Ordering, backpressure and patterns
Ordering
- Total order across a whole topic requires a single partition (or queue with a single consumer), which caps throughput.
- Per-key order is what most systems actually need: hash the key (order ID, customer ID) to a partition, and all events for that key are ordered. Kafka partitions, SQS FIFO message groups, Pulsar key_shared, Service Bus sessions and RabbitMQ consistent-hash exchanges / single-active-consumer all provide variants.
- Parallel consumers on one queue break order, and so do retries via a separate retry queue (message 1 fails and goes to retry; message 2 succeeds first). If order matters, retry in place (blocking the key) or use version checks to reject stale updates.
Backpressure and flow control
When consumers fall behind, lag (log) or queue depth grows. Healthy systems:
- Monitor lag/depth and age of oldest message (the latter is the better SLO signal).
- Autoscale consumers on lag (KEDA on Kubernetes scales on Kafka lag, SQS depth or RabbitMQ queue length).
- Bound queues: RabbitMQ
x-max-lengthwithreject-publishoverflow pushes back on producers instead of running out of memory or disk. RabbitMQ also applies memory/disk alarms that block publishers. - Shed load or degrade rather than building unbounded backlogs whose messages are stale by the time they're processed.
Common patterns
| Pattern | Description |
|---|---|
| Competing consumers | Many workers, one queue: horizontal scaling |
| Publish/subscribe | One event, many independent subscribers |
| Request/reply | reply_to queue plus correlation ID to match responses |
| Claim check | Store the large payload in object storage; send a reference (messages should stay small, roughly under 1 MB) |
| Delayed / scheduled delivery | SQS delay seconds, Service Bus scheduled messages, RabbitMQ delayed-message plugin or TTL + DLX tricks |
| Priority queue | RabbitMQ x-max-priority; or separate queues per priority |
| Outbox | Write the message to an outbox table in the same DB transaction as the state change; relay to the broker (chapter 73) |
| Inbox / idempotent consumer | Record processed message IDs to discard duplicates (chapter 74) |
| Competing groups with sharding | Partition by key so each consumer owns a subset of keys (ordered per key, parallel overall) |
Client code across languages
The same at-least-once worker (manual ack after processing, bounded prefetch, DLQ on permanent failure) in several clients:
// Java: RabbitMQ with Spring AMQP (manual ack, quorum queue with dead-lettering)
@Bean Queue orders() {
return QueueBuilder.durable("orders").quorum()
.deliveryLimit(5) // poison-message protection
.deadLetterExchange("dlx").deadLetterRoutingKey("orders.dlq").build();
}
@RabbitListener(queues = "orders", ackMode = "MANUAL", concurrency = "4")
void handle(OrderPlaced evt, Channel ch, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
try {
service.process(evt); // must be idempotent
ch.basicAck(tag, false);
} catch (ValidationException e) {
ch.basicReject(tag, false); // permanent: dead-letter now
} catch (Exception e) {
ch.basicNack(tag, false, true); // transient: requeue (delivery count increments)
}
}
// Go: amqp091-go (manual ack, prefetch 20)
ch.Qos(20, 0, false)
msgs, _ := ch.Consume("orders", "worker-1", false /*autoAck*/, false, false, false, nil)
for d := range msgs {
var evt OrderPlaced
if err := json.Unmarshal(d.Body, &evt); err != nil {
d.Reject(false) // permanent → DLX
continue
}
if err := process(ctx, evt); err != nil {
d.Nack(false, true) // transient → requeue
continue
}
d.Ack(false)
}
# Python: SQS with boto3 (long polling, visibility timeout, delete after success)
while True:
resp = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10,
WaitTimeSeconds=20, VisibilityTimeout=60)
for m in resp.get("Messages", []):
try:
process(json.loads(m["Body"])) # idempotent!
sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])
except Exception:
pass # not deleted → reappears after the visibility timeout; redrive policy → DLQ after N receives
// Rust: async-nats JetStream pull consumer with explicit acks
let stream = js.get_stream("ORDERS").await?;
let consumer: PullConsumer = stream.get_or_create_consumer("billing", pull::Config {
durable_name: Some("billing".into()),
ack_policy: AckPolicy::Explicit,
max_deliver: 5, // then advisory → handle as dead letter
..Default::default()
}).await?;
let mut messages = consumer.messages().await?;
while let Some(msg) = messages.next().await {
let msg = msg?;
match process(&msg.payload).await {
Ok(_) => msg.ack().await?,
Err(_) => msg.ack_with(AckKind::Nak(Some(Duration::from_secs(5)))).await?, // redeliver later
}
}
# Elixir: Broadway pipeline over RabbitMQ (batching, concurrency, acks handled by the framework)
defmodule Billing.Pipeline do
use Broadway
def start_link(_) do
Broadway.start_link(__MODULE__, name: __MODULE__,
producer: [module: {BroadwayRabbitMQ.Producer, queue: "orders", qos: [prefetch_count: 50],
on_failure: :reject}], # rejected → dead-letter exchange
processors: [default: [concurrency: 8]])
end
def handle_message(_, %Broadway.Message{data: data} = msg, _) do
case Billing.process(Jason.decode!(data)) do
:ok -> msg
{:error, reason} -> Broadway.Message.failed(msg, reason)
end
end
end
Choosing
- Work queue / background jobs, routing, per-message retries and priorities → RabbitMQ, SQS, a Postgres-backed queue, or NATS JetStream.
- Event streaming, many independent consumers, replay, high throughput, stream processing, CDC → Kafka (or Redpanda, Pulsar, Kinesis, Event Hubs).
- Simple fan-out in AWS → SNS + SQS, or EventBridge for content-based routing.
- Already have Postgres and moderate volume → a transactional DB queue avoids dual writes entirely.
Lab: brokers under real conditions
NATS JetStream 2.11 (single server, file storage) on a 2-core machine, driven by the nats-py client. Each experiment applies equally to RabbitMQ, SQS, Kafka or Pulsar; only the API names change.
Experiment 1: what durability costs
20,000 messages of 100 bytes, published three ways:
core NATS (no persistence, no ack) 171,016/s
JetStream, async acks 40,234/s
JetStream, wait for each ack 5,323/s
Fire-and-forget messaging is fast and loses messages if anything restarts. Persisting each message and confirming it costs throughput: 4× with acknowledgements processed asynchronously (many publishes in flight, acks matched later) and 32× when the producer waits for each ack before sending the next, because every message then pays a full round trip. Production producers pipeline: Kafka's linger.ms, batch.size and max.in.flight.requests.per.connection, RabbitMQ's publisher confirms in batches, SQS's SendMessageBatch. Waiting per message is only for the rare case that genuinely needs it.
Experiment 2: scaling with competing consumers
200 jobs of 20 ms each, 1 competing worker: 4.13 s
200 jobs of 20 ms each, 4 competing workers: 1.58 s
Four workers sharing one consumer took 2.6× less time (not 4×: each fetches batches of five and processes them in sequence, and fetch round trips add up). The broker's max_ack_pending (here 100) caps how many unacknowledged messages can be outstanding: that's backpressure, stopping a slow consumer from being buried and bounding how many messages are redelivered if a worker dies. In RabbitMQ the equivalent is the prefetch count (basic.qos); in Kafka, consumers pull at their own pace and partitions bound parallelism.
Experiment 3: a poison message
Three payment messages; message 1 has corrupt card data and fails every time. The consumer uses max_deliver=3, negative acknowledgements with a 100 ms delay, and moves a message aside on its last failure:
id 0 ok; id 1 failed (delivery 1); id 2 ok; id 1 failed (delivery 2); id 1 failed (delivery 3) | moved to dead-letter list: [1]
The failing message didn't block the others (ids 0 and 2 succeeded between its attempts), retries were spaced out, and after three tries it was set aside instead of being retried forever. Without max_deliver, a poison message is redelivered endlessly, burning CPU and filling logs, and in a strictly ordered stream it blocks everything behind it. Every consumer needs a dead-letter destination (a DLQ in RabbitMQ and SQS, a dead-letter topic in Kafka), an alert on its size, and a tool to inspect and replay its contents after a fix.
Experiment 4: ordering with parallel consumers
50 orders, each publishing four status events in order (placed, paid, cooking, delivered), consumed by four consumers with small random processing delays:
4 consumers share one subject: 48 events processed after a later event of the same order
4 consumers, each owns orders with id % 4: 0 events processed after a later event of the same order
Sharing one consumer spread each order's events across workers, and their timing reordered 48 of them: some orders were "delivered" before "cooking", which would show a kitchen screen going backwards. Routing by key (each consumer owns a fixed set of orders) kept every order's events in sequence while still processing in parallel. That's exactly how Kafka works: the message key chooses the partition, each partition is read by one consumer in the group, and order is guaranteed per partition (chapter 67). The cost is that parallelism is limited by the number of partitions, and a hot key can't be spread.
Try it yourself
- Publish 20,000 messages with
publish_asyncin windows of 100, 1,000 and 10,000 outstanding acks. Where does throughput stop improving? - Kill a consumer (Ctrl-C) halfway through experiment 2 and count how many jobs were redelivered to the others.
- Implement experiment 3's dead-letter step by publishing the failed message to a
dlq.paymentssubject with its error and delivery count, then write a replay script. - Repeat experiment 4 with RabbitMQ's consistent-hash exchange or Kafka keys and confirm the same result.
Revision sheet: messaging systems
Key ideas
- Why messaging: temporal, load and knowledge decoupling; buffering bursts; fan-out to many consumers; integration between teams.
- Vocabulary: producer, consumer, broker, topic/subject, queue, partition, offset, consumer group, acknowledgement, prefetch, retention, dead-letter queue.
- Queues: competing consumers, ack/nack, visibility timeouts (SQS), prefetch (RabbitMQ), exchanges and routing (direct, topic, fanout, headers), priority and delayed messages, quorum queues.
- Logs: append-only partitions, offsets per consumer group, retention by time/size, compaction, replay, high throughput through sequential I/O and batching.
- Delivery: at-least-once by default; redelivery after missing acks; idempotent consumers; acknowledging after processing.
- Ordering: per queue or partition; broken by competing consumers, retries and redelivery; preserved by keys and single-active consumers.
- Backpressure: prefetch/max in-flight limits, pull consumers, bounded queues, lag monitoring.
- Patterns: work queues, pub/sub, request/reply, outbox, retry topics with delays, DLQs, claim check (large payloads in object storage).
- Systems: RabbitMQ, SQS/SNS, Azure Service Bus, Google Pub/Sub, Kafka, Pulsar, Redpanda, NATS JetStream, Redis Streams.
Numbers to remember
- Lab: durable publishing with async acks 4× slower than fire-and-forget, waiting for each ack 32× slower; 4 competing workers 2.6× faster; key-based routing eliminated 48 out-of-order events.
Pitfalls
- Acknowledging before processing; processing without idempotency.
- No
max_deliver/redrive policy; DLQs nobody watches. - Competing consumers on events that must stay ordered.
- Synchronous per-message publishing on hot paths.
- Unbounded prefetch; consumers holding thousands of unacked messages.
- Huge messages instead of references; no schema for message contracts.
Glossary
- Competing consumers: several consumers sharing a queue, each message to one.
- Consumer group: consumers sharing a log's partitions with a shared offset.
- Ack wait / visibility timeout: time before an unacknowledged message is redelivered.
- Prefetch / max ack pending: limit on unacknowledged messages per consumer.
- Dead-letter queue: where messages go after too many failed deliveries.
- Retention: how long a log keeps messages regardless of consumption.