System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·128

Messaging Architecture

Designing with asynchronous messages: why decouple, queues versus streams in depth, point-to-point, pub/sub and fan-out topologies, consumer groups and partition assignment, Kafka share groups, replay and retention, acknowledgements and delivery guarantees, retries with retry topics and delays, dead-letter queues and poison messages, ordering guarantees and their cost, deduplication, idempotent consumers and the inbox pattern, back-pressure and consumer lag, message design, request-reply over messaging, and choosing between RabbitMQ, SQS, Kafka, Pulsar, NATS and cloud services.

30 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: sending work instead of calling for it

When the orders service calls the kitchen service directly, both must be up and fast at the same moment. When it instead publishes a message ("order 42 placed") to a broker, the kitchen can pick it up when it's ready, several services can react to the same message, and a burst of orders waits in line instead of overwhelming anyone. That decoupling in time, load and knowledge is what messaging buys. It also means "done" now has to be defined carefully, because messages can arrive twice, late, or out of order.

Fan-out and work queues

3,000 messages published on orders.placed, with two ordinary subscribers (audit, analytics) and three kitchen workers in one queue group:

Text
audit: 3000   analytics: 3000   kitchen-1: 1006   kitchen-2: 1007   kitchen-3: 987

Ordinary subscribers each got every message (publish/subscribe fan-out). The queue group shared the messages: each went to one of the three workers (a work queue). The same message stream feeds both patterns at once.

At-least-once delivery, and why consumers must tolerate duplicates

With a persistent stream (JetStream) and explicit acknowledgements, a consumer fetched 10 orders, acknowledged 7 and then "crashed" without acknowledging the other 3:

Text
consumer A fetched 10, acked 7, crashed holding 3 un-acked
consumer B processed the remaining 93, including orders 7, 8 and 9,
  which the broker redelivered after the 2 s acknowledgement timeout

Nothing was lost: un-acknowledged messages come back. But if A had actually cooked order 7 and crashed just before acknowledging, B would cook it again. That is at-least-once delivery, the normal guarantee of real brokers, and it means consumers must be idempotent: processing the same message twice must have the same effect as once (check "already done?" by order ID before acting).

Publishers retry too. A retried publish of order 5 carrying the same message ID:

Text
published 100 orders + one retry of order 5 with the same Nats-Msg-Id → duplicate=True; stream holds 100

The broker recognised the ID and stored it once. Deduplication at the broker plus idempotent consumers is how systems get effectively once processing.

Absorbing a burst

20,000 orders published as fast as the client could (with the broker confirming each one), and a consumer limited to about 5,000 per second:

Text
burst published in 5.0 s (4,034/s, each awaiting the broker's confirmation)
consumer drained it: 5,000 at 1.2 s, 10,000 at 2.4 s, 15,000 at 3.6 s, 20,000 at 4.8 s

The stream held the backlog and the consumer worked through it at its own steady pace; nobody was overwhelmed and nothing was dropped. The cost is lag: the last order waited several seconds. For a kitchen that's fine; for a payment confirmation the user is staring at, it might not be.

How deep to go in messaging architecture

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 pub/sub, acknowledgements and why messaging decouples services
L2 Build producers and idempotent consumers with acks, retries and dead-letter handling
L3 Explain delivery guarantees, ordering per partition, consumer groups, retention and replay
L4 Diagnose lag, duplicates, poison messages, rebalancing storms and ordering bugs
L5 Design messaging topologies, partitioning, schemas and failure handling for a system
L6 Operate messaging platforms (Kafka, NATS, RabbitMQ, Pulsar) for many teams

Why messaging

Synchronous calls couple caller and callee in time (both must be up), rate (the callee must keep up) and often knowledge (the caller knows who handles the work). Messaging through a broker decouples them:

  • Temporal decoupling: producers keep working while consumers are down or slow; messages wait.
  • Load leveling: bursts become backlog rather than overload (chapter 130).
  • Scalability: add consumers to increase throughput.
  • Extensibility: publish an event once; new consumers subscribe without changing the producer.
  • Reliability: retries and dead-lettering for transient failures.

The price: eventual consistency, harder debugging (trace context must travel in message headers, Vol. 9 ch. 101), duplicate and out-of-order delivery to handle, and a broker to operate. Messaging fundamentals and delivery semantics are in Vol. 5 ch. 66–68; this chapter is about architecture.

Queue versus stream

Message queue Event stream (log)
Purpose Distribute work (commands/tasks) Distribute facts (events) to many readers
Consumption Each message processed by one consumer of the queue Each consumer group reads all records independently
After processing Message deleted (acknowledged) Records stay until retention expires; consumers track offsets
Replay No (once acked, gone) Yes: reset offsets to reprocess history
Ordering Usually best-effort; FIFO queues/groups per key Strict within a partition
Scaling consumers Add consumers freely (competing consumers) Parallelism ≤ partitions per group (share groups lift this in Kafka)
Per-message features Visibility timeouts, per-message ack/retry, delays, priorities, TTL Offsets per partition; per-record retry must be built (retry topics)
Typical tools RabbitMQ, SQS, Azure Service Bus queues, Cloud Tasks, Celery/Sidekiq/BullMQ backends Kafka, Redpanda, Kinesis, Event Hubs, Pulsar, Pub/Sub (both styles), NATS JetStream
queue: work distribution producer m5 · m4 · m3 → worker 1 worker 2 worker 3 each message → one worker;deleted when acked stream: retained, replayable log producer 0 1 2 3 4 5 6 7 analytics @2 search @5 billing @8 (caught up)
Queue versus stream. In a queue, each message goes to exactly one of the competing workers and disappears once acknowledged. In a stream, records are retained in an ordered, partitioned log; each consumer group keeps its own offset, so billing, search and analytics each read every event at their own pace, and any group can rewind to replay history.

Rules of thumb: use a queue for tasks that one worker should do (send this email, resize this image, charge this card), especially with per-message retries, delays and priorities. Use a stream for events that many independent consumers care about, when you need replay, ordering per key, or very high throughput. Many architectures use both: domain events on a stream; consumers turn relevant events into tasks on their own queues.

Topologies

Point-to-point

One producer (or many) sends to a queue consumed by one logical consumer (a pool of competing workers). Producer knows the work exists, not which worker does it.

Publish/subscribe and fan-out

A publisher sends to a topic; each subscription gets its own copy:

  • RabbitMQ: exchanges (direct, topic with routing-key patterns like order.*.eu, fanout, headers) route messages to bound queues; each consumer service binds its own queue.
  • AWS SNS → SQS fan-out: one SNS topic, an SQS queue per subscribing service (each with its own DLQ and retry settings); or EventBridge with content-based rules routing events to targets.
  • Google Pub/Sub: topics with multiple subscriptions (pull or push), filters, ordering keys, dead-letter topics.
  • Kafka: one topic, multiple consumer groups.

Fan-out gives each consumer independent failure handling and pace: billing being down doesn't block shipping.

Routing patterns

  • Content-based routing: route by message attributes (region, type, priority).
  • Topic hierarchies: orders.created, orders.cancelled, or one topic per aggregate type with event types in headers (choose based on ordering needs: events that must be ordered relative to each other belong in the same topic/partition).
  • Priority queues: separate queues per priority with dedicated or weighted consumers (more predictable than per-message priority in a shared queue).

Consumer groups

In Kafka (and similar logs), a consumer group is a set of consumers sharing the work of reading a topic:

  • Each partition is assigned to exactly one consumer in the group at a time; a consumer may own several partitions. This preserves per-partition ordering.
  • Parallelism is capped by the partition count: 12 partitions → at most 12 active consumers in the group; extras idle. Choose partitions for peak parallelism plus growth (they can be increased, but that changes key→partition mapping for keyed topics).
  • Rebalancing reassigns partitions when consumers join/leave/crash. Modern protocols reduce disruption: cooperative incremental rebalancing, static membership (avoid rebalances on restarts), and the next-generation consumer group protocol (KIP-848, broker-driven, GA in Kafka 4.0).
  • Offsets record each group's progress per partition; committing an offset after processing gives at-least-once; committing before processing gives at-most-once.
  • Consumer lag (latest offset − committed offset) is the key health metric: growing lag means consumers can't keep up (autoscale on it, chapter 124).

Share groups ("Queues for Kafka", KIP-932, production-ready in Kafka 4.2): consumers in a share group cooperatively consume records from the same partitions with per-record acknowledgement, delivery counts and redelivery on timeout, so parallelism isn't limited by partition count, at the cost of per-partition ordering. This brings queue semantics to Kafka topics.

Java
// Kafka consumer (Java): manual commits after processing → at-least-once, with idempotent handling
Properties p = new Properties();
p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
p.put(ConsumerConfig.GROUP_ID_CONFIG, "shipping");
p.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
p.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
p.put(ConsumerConfig.GROUP_PROTOCOL_CONFIG, "consumer");          // KIP-848 protocol
p.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 200);

try (var consumer = new KafkaConsumer<String, OrderEvent>(p, new StringDeserializer(), orderEventDeserializer)) {
    consumer.subscribe(List.of("orders.events"));
    while (running) {
        var records = consumer.poll(Duration.ofMillis(500));
        for (var r : records) {
            handleIdempotently(r.key(), r.value());                  // dedupe by event ID (inbox)
        }
        consumer.commitSync();                                        // commit after successful processing
    }
}

Replay and retention

Streams retain records for a configured time or size (or forever with compaction or tiered storage), enabling:

  • Reprocessing after fixing a consumer bug (reset the group's offsets to a timestamp and re-run, with idempotent handling).
  • Bootstrapping new consumers and read models from history (event-carried state, chapter 131).
  • Audit and debugging: what exactly was published?
  • Backfills to new systems (search index rebuild).

Retention design:

  • Time/size retention for event streams (days to weeks typical; months/years with tiered storage moving old segments to object storage, Kafka KIP-405, early access in 3.6 and production-ready since 3.9).
  • Log compaction keeps only the latest record per key (with tombstones for deletions): a topic becomes a durable, replayable table of current state ("changelog" topics, Kafka Streams state stores, configuration topics).
  • Archive raw events to object storage (Parquet/Iceberg) for long-term analytics and compliance.
  • Consider personal data in events: retention and the right to erasure apply (crypto-shredding: encrypt per-user fields with per-user keys and delete the key).
Shell
# Replay: reset the "search-indexer" group to a point in time (consumers stopped first)
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --group search-indexer \
  --topic products.events --reset-offsets --to-datetime 2026-10-24T00:00:00.000 --execute

Acknowledgements and delivery guarantees

Guarantee Meaning How
At-most-once Never redelivered; may be lost Ack/commit before processing; fire-and-forget producers
At-least-once Never lost (once accepted); may be duplicated Ack after processing; producer retries; durable broker settings
Exactly-once effect Each message affects state once At-least-once delivery + idempotent processing, or transactional processing within one system (Kafka transactions for read-process-write within Kafka)

Producer durability settings matter: Kafka acks=all with min.insync.replicas=2 and replication factor 3, plus enable.idempotence=true (default in modern clients) to prevent duplicates from producer retries; RabbitMQ publisher confirms with quorum queues; SQS returns after the message is stored redundantly.

Exactly-once across systems (consume from a broker, write to a database, call an API) requires idempotency in your code; no broker can provide it alone (Vol. 5 ch. 68).

Retries, retry topics and delays

Consumers fail for two kinds of reasons:

  • Transient (dependency timeout, rate limit, deadlock): retrying later likely succeeds.
  • Permanent (malformed message, business rule violation, missing referenced data that will never appear, a bug): retrying won't help.

Retry strategies:

  • Immediate in-process retries with backoff (a few attempts, milliseconds to seconds) for brief blips.
  • Broker redelivery: don't ack (SQS visibility timeout expires, RabbitMQ nack with requeue, Pub/Sub ack deadline), possibly with backoff settings (Pub/Sub retry policy, SQS changing visibility timeout per attempt).
  • Retry topics/queues with delays: in logs like Kafka, you can't skip a record and come back later within a partition without blocking it; instead, publish the failed record to orders.retry.1m, orders.retry.10m, consumed after the delay, then to the DLQ after the last attempt. This keeps the main partition flowing (at the cost of reordering for that key). Spring Kafka's @RetryableTopic automates it.
  • Delay queues: RabbitMQ with TTL + dead-letter exchange or the delayed-message plugin; SQS delay seconds; scheduled messages in Service Bus.
orders consumer retry.1mdelay 1 min retry.10mdelay 10 min fail fail dead-letter topicerror, attempts, origin fail alert · inspect · fix · redriveback to orders main topic keeps flowing · retries reorder the failed key's events (decide if acceptable)
Non-blocking retries with retry topics and a dead-letter queue. A record that fails in the main consumer is published to a 1-minute retry topic, then a 10-minute retry topic, each consumed only after its delay; if it still fails, it lands in the dead-letter topic with error details for inspection and redrive. The main topic keeps flowing for other records.
Java
// Spring Kafka: non-blocking retries with exponential delays and a DLT
@RetryableTopic(
    attempts = "4",
    backoff = @Backoff(delay = 60_000, multiplier = 10.0, maxDelay = 3_600_000),
    exclude = { ValidationException.class },              // permanent errors go straight to DLT
    dltTopicSuffix = ".dlt")
@KafkaListener(topics = "orders.events", groupId = "invoicing")
public void on(OrderEvent event) {
    invoicing.handle(event);                                // throws TransientException on timeouts
}

@DltHandler
public void dlt(OrderEvent event, @Header(KafkaHeaders.EXCEPTION_MESSAGE) String error) {
    alerts.raise("invoicing DLT", event.orderId(), error);
}

Always bound retries (attempt counts or maximum age), use exponential backoff with jitter (chapter 130), and distinguish permanent errors early.

Dead-letter queues and poison messages

A poison message fails every time (bad data, a bug); without protection it's retried forever, blocking a partition (stream) or burning resources (queue). A dead-letter queue/topic (DLQ) receives messages that exceeded retry limits or failed permanently:

  • Configure DLQs everywhere: SQS redrive policy (maxReceiveCount), RabbitMQ dead-letter exchanges (with quorum queues' delivery-limit), Pub/Sub dead-letter topics, Service Bus built-in DLQs, Kafka DLT via frameworks.
  • Store context: original topic/partition/offset, error message and stack trace, attempt count, timestamps, trace ID.
  • Alert on DLQ arrivals (they're failures someone must look at); dashboards of DLQ depth and age.
  • Provide redrive tooling: after fixing the bug, replay DLQ messages to the main queue (SQS redrive to source, custom tools).
  • Decide policies per message type: some can be discarded after inspection; payments never silently.

Ordering

What ordering costs

Global ordering across all messages requires a single sequence (one partition, one consumer): no parallelism. Systems therefore offer per-key ordering:

  • Kafka/Kinesis/Event Hubs: order within a partition; records with the same key go to the same partition (hash of key), so per-entity ordering holds as long as the partition count doesn't change.
  • SQS FIFO with message group IDs, Service Bus sessions, Pub/Sub ordering keys, RabbitMQ single active consumer or consistent-hash exchanges.

Ordering is fragile:

  • Retries that move a message aside (retry topics) let later messages for the same key overtake it; if strict per-key order matters, block the key (pause the partition, or park subsequent messages for that key until the failed one resolves).
  • Concurrency within a consumer (processing a batch in parallel threads) breaks order unless work is keyed to threads.
  • Producer retries can reorder unless idempotent producers are enabled (Kafka with enable.idempotence=true preserves order per partition with up to 5 in-flight requests).
  • Multiple producers for the same entity (two services emitting events about an order) have no shared order.

Designing to need less ordering

  • Make consumers commutative or version-aware: include an entity version or timestamp and ignore older updates (the projector example in chapter 127).
  • Send state rather than deltas where possible ("order status is now SHIPPED, version 7"), so the latest version wins regardless of arrival order.
  • Use per-key ordering only for streams where it's meaningful (an account's ledger entries), not by default for everything.

Deduplication and idempotency

At-least-once delivery means duplicates will happen: producer retries, consumer crashes after processing but before acking/committing, rebalances, redrives. Defences at several levels:

  • Broker-level deduplication: Kafka idempotent producers (per-session duplicates), SQS FIFO deduplication IDs (5-minute window), Service Bus duplicate detection, NATS JetStream message IDs (Nats-Msg-Id within a window). Useful but limited windows and scopes.
  • Idempotent consumers: the definitive fix. Approaches:
  • Natural idempotency: operations that are idempotent by nature (SET status = 'SHIPPED', upsert by key, delete).
  • Inbox / processed-messages table: record each processed message ID in the same database transaction as the side effect; skip if already present.
  • Version checks: apply only if the event version is newer than the stored version.
  • Idempotency keys for downstream calls: pass a stable key (derived from the message ID) to payment APIs and other services (Vol. 5 ch. 74).
Python
# Inbox pattern: process-and-record atomically (PostgreSQL), so redelivery is a no-op
def handle(msg) -> None:
    with db.transaction() as tx:
        inserted = tx.execute(
            "INSERT INTO inbox (consumer, message_id, received_at) VALUES (%s, %s, now()) "
            "ON CONFLICT DO NOTHING",
            ("shipping", msg.id),
        ).rowcount
        if inserted == 0:
            return                                       # duplicate: already processed
        create_shipment(tx, order_id=msg.payload["orderId"])
    # ack/commit only after the transaction commits

Keep inbox entries long enough to cover the redelivery window (and replays), then purge by age.

Back-pressure and consumer lag

  • Pull-based consumers (Kafka, SQS, Pub/Sub pull) naturally apply back-pressure: they take only what they can handle. Push-based delivery needs prefetch limits (RabbitMQ basic.qos) and flow control.
  • Monitor lag (records or time) and oldest message age; alert when they grow for longer than a threshold.
  • Autoscale consumers on lag (KEDA), up to the partition limit (or use share groups/queues).
  • When consumers persistently can't keep up: optimise processing (batching database writes), add partitions and consumers, shed or sample low-value messages, or slow producers (quotas).
  • Protect downstream systems: consumers scaled up to drain a backlog can overload the database they write to; cap concurrency.

Designing messages

  • Envelope with metadata: message/event ID (UUID), type, schema version, timestamp, producer, correlation ID and causation ID, trace context (W3C traceparent in headers), tenant ID; payload separately.
  • Schemas with a registry and compatibility rules (Avro, Protobuf, JSON Schema; Vol. 11 ch. 117). CloudEvents provides a standard envelope.
  • Size: keep messages small (KBs); put large payloads in object storage and send a reference (claim check pattern).
  • Semantics: commands (ShipOrder, addressed to one handler, may be rejected) vs events (OrderShipped, facts about the past, any number of subscribers); chapter 131.
  • Security: authenticate producers/consumers (mTLS, SASL/OAuth, IAM), authorise per topic, encrypt in transit, avoid sensitive data in messages or encrypt fields.
JSON
{
  "specversion": "1.0",
  "id": "8f3c0b7e-6a59-4c1f-9d6e-2b7a0c51e2f4",
  "source": "/orders-service",
  "type": "com.example.order.shipped.v1",
  "time": "2026-10-24T10:15:30Z",
  "subject": "order/9817",
  "datacontenttype": "application/json",
  "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
  "data": { "orderId": "9817", "carrier": "BlueDart", "trackingId": "BD123456", "version": 7 }
}

Request-reply over messaging

Sometimes you need a response asynchronously: send a request with a reply-to address (a per-instance or per-client queue) and a correlation ID; the responder publishes the result to that address; the requester matches by correlation ID with a timeout. Supported natively in RabbitMQ (direct reply-to), NATS (request/reply is a core feature), JMS; on Kafka, frameworks provide ReplyingKafkaTemplate. Use it for long-running operations where HTTP timeouts are a problem; otherwise plain RPC is simpler.

Choosing a broker

Need Good fits
Task queues with per-message ack, delays, priorities, flexible routing RabbitMQ (quorum queues), SQS, Azure Service Bus, Cloud Tasks
Serverless, fully managed, minimal ops SQS/SNS/EventBridge, Pub/Sub, Service Bus/Event Grid
High-throughput event streaming, replay, stream processing ecosystem Kafka (self-managed, Confluent, MSK, Aiven), Redpanda, Kinesis, Event Hubs (Kafka-compatible endpoint)
Multi-tenancy, geo-replication built in, tiered storage Apache Pulsar, Kafka with tiered storage and MirrorMaker 2/cluster linking
Lightweight, low-latency messaging, request-reply, edge/IoT, KV and object stores NATS (JetStream for persistence)
Simple jobs on an existing database Postgres-backed queues (SKIP LOCKED: River, Oban, Graphile Worker, pgmq), Redis streams
SQL
-- Postgres as a job queue: workers claim jobs without blocking each other
WITH next AS (
  SELECT id FROM jobs
  WHERE state = 'ready' AND run_at <= now()
  ORDER BY run_at
  FOR UPDATE SKIP LOCKED
  LIMIT 10
)
UPDATE jobs SET state = 'running', locked_at = now(), attempts = attempts + 1
FROM next WHERE jobs.id = next.id
RETURNING jobs.*;

Using the database you already have as a queue is often the simplest correct choice at moderate scale (thousands of jobs per second), with the bonus that enqueuing can be part of the same transaction as the business write (no dual-write problem, chapter 131).

Lab: fan-out, redelivery, deduplication and backlog

NATS Server 2.11.9 with JetStream (file storage) on the lab machine and the nats-py 2.16 asyncio client. NATS stands in for the general patterns; the Kafka equivalents are given alongside (Volume 5 covered Kafka's internals).

Experiment 1: two delivery patterns on one subject

Python
await nc.subscribe("orders.placed", cb=audit)                    # gets everything
await nc.subscribe("orders.placed", cb=analytics)                # gets everything
for i in range(3): await nc.subscribe("orders.placed", queue="kitchen", cb=worker[i])  # share
Text
analytics 3000, audit 3000, kitchen-1 1006, kitchen-2 1007, kitchen-3 987

Core NATS is at-most-once: a subscriber that isn't connected at publish time never sees the message. Kafka expresses the same two patterns as different consumer groups (each group sees everything) and members within a group (partitions are split among them); Kafka 4's share groups add queue-style per-message sharing.

Experiment 2: acknowledgements and redelivery

Python
await js.add_stream(StreamConfig(name="ORDERS", subjects=["shop.orders"], retention=RetentionPolicy.WORK_QUEUE))
await js.add_consumer("ORDERS", ConsumerConfig(durable_name="cooks", ack_policy=AckPolicy.EXPLICIT,
                                              ack_wait=2, max_deliver=5))
Text
publish 100 + retry of order 5 with Nats-Msg-Id "o-5" → duplicate=True; stream holds 100
consumer A: fetched 10, acked 7, then stopped without acking orders 7, 8, 9
consumer B: processed the remaining 93 (orders 7–99) in 2.0 s, including 7, 8, 9 redelivered after ack_wait
stream afterwards: 0 messages (work-queue retention removes acknowledged messages)

max_deliver=5 caps redeliveries: a poison message that crashes every consumer would otherwise loop forever. After the limit, JetStream emits an advisory you can route to a dead-letter subject for inspection; Kafka consumers implement the same with a retry topic and a DLQ. Choose ack_wait longer than the slowest normal processing time, or extend it with progress acks (m.in_progress()), or a slow-but-healthy consumer gets its work duplicated.

Experiment 3: burst and backlog

Text
20,000 × 100-byte messages published with confirmation: 5.0 s (4,034/s)
consumer at ~5,000/s: 5,000 at 1.2 s, 10,000 at 2.4 s, 15,000 at 3.6 s, 20,000 at 4.8 s

Publishing awaited each confirmation one at a time, so the rate was bounded by round trips (about 250 µs each), not by the broker; asynchronous publishing with a window of outstanding confirmations goes far faster, the same batching lesson as chapter 122. The lag metric to alert on is the consumer's pending count (JetStream num_pending, Kafka consumer lag), and the number to plan with is drain time = backlog ÷ (consume rate − produce rate).

Experiment 4: ordering

Within one subject (or one Kafka partition) messages are stored in order. With three workers in a queue group, order across workers is lost: worker 2 can finish order 11 before worker 1 finishes order 10. When order matters per entity (all events for order 42 in sequence), route by key: subject orders.<kitchen> with one consumer per subject, or Kafka partitioning by order ID, so each entity's messages go to one consumer, in order, while different entities proceed in parallel.

Try it yourself

  1. Make the consumer idempotent with a processed table keyed by order ID, kill it mid-batch, and show each order is cooked once.
  2. Publish a message that makes the consumer raise every time. Observe max_deliver and route the advisory to shop.dlq.
  3. Rewrite the publisher with js.publish_async (or a semaphore of 256 outstanding publishes) and measure the new rate.
  4. Model per-kitchen ordering with subjects shop.orders.k1 … k4 and four ordered consumers; verify sequence numbers per kitchen.

Revision sheet: messaging architecture

Key ideas

  • Why: decouple in time (consumer can be down), load (bursts buffered), and knowledge (publisher doesn't know consumers).
  • Queues vs streams: queues deliver and delete; streams retain an ordered log for replay and many independent consumers.
  • Topologies: point-to-point (work queue), pub/sub (fan-out), competing consumers, request/reply over messaging.
  • Delivery: at-most-once, at-least-once (normal), effectively-once via deduplication + idempotent consumers (+ transactions where supported).
  • Ordering is per partition/subject; route by entity key to keep per-entity order with parallelism.
  • Acks and redelivery: ack after processing; ack timeouts; max deliveries; dead-letter queues for poison messages.
  • Backpressure and lag: monitor pending/lag; drain time = backlog ÷ (consume − produce).
  • Schemas: versioned, compatible (Avro, Protobuf, JSON Schema with a registry).

Numbers to remember

  • Lab: queue group of 3 split 3,000 messages 1,006 / 1,007 / 987; each plain subscriber got all 3,000.
  • Lab: un-acked messages redelivered after ack_wait = 2 s; a duplicate publish with the same ID was stored once.
  • Lab: confirmed one-at-a-time publishing ≈ 4,000/s, bounded by round trips.

Pitfalls

  • Assuming exactly-once delivery; non-idempotent consumers.
  • Acking before processing (loses work on crash) or ack_wait shorter than processing.
  • No dead-letter handling, so a poison message blocks a partition.
  • Global ordering expectations with parallel consumers.
  • Unbounded backlogs nobody watches; retention shorter than worst-case downtime.
  • Messaging used for request/response that needs an immediate answer.

Glossary

  • Queue group / consumer group: consumers sharing a stream of work.
  • Ack wait / visibility timeout: time before an unacked message is redelivered.
  • DLQ: dead-letter queue for messages that repeatedly fail.
  • Consumer lag: messages produced but not yet consumed.
  • Idempotent consumer: one whose effect is the same however many times a message is processed.