Messaging: Pub/Sub, Event Buses, RabbitMQ, and Kafka
Messaging lets one part of a system hand information to another without requiring both parts to finish their work at the same time. Imagine checkout recording an order, billing creating an invoice, and notifications sending a receipt. Checkout can publish that the order was placed; each interested service processes that fact at its own pace.
This decoupling introduces responsibilities: deciding who receives a message, how long it survives, what happens after failure, and how to observe unfinished work. Asynchronous communication can absorb a burst of orders, but it cannot make an overloaded billing service infinitely fast.
Read the concepts first, then run the labs. Pub/sub is a distribution pattern, an event bus is a communication abstraction, and an event stream is an evolving sequence of events. RabbitMQ and Kafka are products that can implement messaging patterns. These terms describe different aspects of a system and can overlap.
Messages, commands, and events
A message is an envelope carrying data. A producer creates it; a consumer processes it. A broker is a separate service that accepts and distributes messages. A queue buffers deliveries for workers. A topic is a named subject or destination; its exact storage and routing meaning depends on the product.
A command asks an owner to do something: ReserveStock may succeed or fail. An event states something that already happened: OrderPlaced should describe a committed fact. Name events in the past tense and avoid making every consumer understand the publisher’s private database schema.
Use an event identifier for deduplication, a business identifier for routing, a schema version for interpretation, and a timestamp for investigation. A correlation identifier connects messages belonging to the same workflow. An order identifier alone is not a unique event identifier: one order can produce many events.
{
"eventId": "evt-1",
"type": "OrderPlaced",
"version": 1,
"orderId": "order-42",
"occurredAt": "2026-11-04T10:00:00Z",
"correlationId": "checkout-7"
}The short lab messages keep only eventId and orderId to make the transport operations visible. Real consumers should validate the envelope and payload before changing business state.
Publish/subscribe
In publish/subscribe, the publisher addresses a subject rather than listing recipients. Independent subscriptions express interest in that subject. Publishing OrderPlaced can trigger billing and email without checkout calling either service directly. Adding an analytics subscription does not require changing checkout.
flowchart LR
Checkout -->|Publish OrderPlaced| Subject[Orders subject]
Subject -->|Independent subscription| Billing[Billing queue or group]
Subject -->|Independent subscription| Email[Email queue or group]
Billing -->|Competing worker| B1[Billing worker 1]
Billing -->|Competing worker| B2[Billing worker 2]Fan-out and load balancing are different. Billing and email each need the event, so they need independent subscriptions. Two billing workers share one subscription’s work. Putting billing and email on one work queue would let one take an event the other never receives.
Pub/sub alone promises neither persistence nor replay. A temporary subscription may miss everything published while it is absent. A durable subscription can retain pending work, subject to expiry and capacity policies. Ask what happens when the subscriber disconnects before choosing a transport.
Example: 100 orders published to two independent subscriptions create 100 billing deliveries and 100 email deliveries. Adding a second billing worker divides the billing work; it does not intentionally create another 100 billing actions. Failure and redelivery can still cause duplicates.
Event bus
An event bus centralizes registration and dispatch so publishers do not depend directly on each handler. Inside an application, it may be a small object holding callbacks. Across services, the same term may refer to broker-backed infrastructure. Always specify the process boundary and delivery contract when someone says “the bus.”
The example registers billing and email handlers, then publishes one order. Both print order-42. Dispatch is synchronous and local: a slow handler delays the publisher, a thrown error stops later handlers, and a process crash loses the event. There is no queue, durable storage, retry, or cross-process delivery.
# bus.py — Python 3; python bus.py
from collections import defaultdict
class EventBus:
def __init__(self):
self.handlers = defaultdict(list)
def subscribe(self, name, handler):
self.handlers[name].append(handler)
def publish(self, name, event):
for handler in list(self.handlers[name]):
handler(event)
bus = EventBus()
bus.subscribe("OrderPlaced", lambda e: print("Billing", e["orderId"]))
bus.subscribe("OrderPlaced", lambda e: print("Email", e["orderId"]))
bus.publish("OrderPlaced", {"eventId": "evt-1", "orderId": "order-42"})Run this example locally using the instructions in its first comment. Keep subscriptions scoped to their owner and remove them when that owner is destroyed. A long-lived bus retaining callbacks to closed screens or completed requests causes leaks and repeated handling. A bus also hides dependencies if every module publishes arbitrary strings with undocumented payloads.
Use a direct function call when the caller needs an immediate result and owns the sequence of operations. Use a local bus for independent reactions within the same application. Introduce a broker when work must cross processes or survive application restarts; replacing callbacks with a broker also adds operational and failure-handling work.
Event streams
An event stream is a sequence of events over time. In a retained log, reading does not delete records. Each reader tracks its position and can revisit retained history. This is useful when analytics needs yesterday’s orders or a new projection must rebuild its state. A transient stream abstraction does not automatically provide durable history.
A partition is an ordered portion of a log. An offset is a record’s position within that partition, not a global event number or timestamp. Ordering within one partition does not imply a total order across all partitions. Route related events by a stable key when their relative order matters.
flowchart LR
Producer -->|Key order-42| P0[Partition 0: offsets 0 1 2 3]
Producer -->|Key order-99| P1[Partition 1: offsets 0 1 2]
P0 -->|Own position| Billing[Billing consumer group]
P1 -->|Own position| Billing
P0 -->|Separate position| Analytics[Analytics consumer group]
P1 -->|Separate position| AnalyticsSuppose billing has committed offset 8 in a partition: its next record is offset 8. It processes that record and commits 9. Analytics can still be at offset 3. Billing’s progress does not advance analytics or delete the records.
Retention bounds replay. Time or size policies can remove old segments even if a consumer is behind. Compaction retains a recent value per key rather than every intermediate event; it is not a complete audit history. An event stream is also not automatically event sourcing: event sourcing makes events the authoritative history from which domain state is reconstructed.
RabbitMQ: routing and queues
In RabbitMQ’s AMQP 0-9-1 model, producers publish to an exchange. Bindings tell that exchange how to route deliveries into queues. Consumers receive from queues. The exchange routes; the queue stores pending deliveries. A queue name can be addressed through the default exchange, which has implicit bindings to queues.
Inside and outside the broker
The broker contains the exchanges and queues. Producers and consumers are application processes outside it. This runtime message flow uses a fanout exchange: each bound queue receives a copy, while the billing workers compete for deliveries from their shared queue. For one queued copy, one worker receives a delivery at a time; redelivery is still possible after failure.
flowchart TB
Producer[Producer: checkout application]
subgraph Broker["RabbitMQ broker"]
Exchange["Exchange: orders - fanout"]
BillingQueue[(Queue: billing)]
EmailQueue[(Queue: email)]
Exchange -->|Binding: copy to billing| BillingQueue
Exchange -->|Binding: copy to email| EmailQueue
end
Producer -->|Publish OrderPlaced| Exchange
BillingQueue -->|Deliver to an available worker| Billing1[Consumer: billing worker 1]
BillingQueue -->|Deliver to an available worker| Billing2[Consumer: billing worker 2]
EmailQueue -->|Deliver independent copy| Email[Consumer: email worker]A fanout exchange sends to every bound queue. A direct exchange matches an exact routing key. A topic exchange matches dot-separated words: orders.* matches orders.created, while orders.# can also match deeper keys such as orders.eu.created. A headers exchange matches message headers rather than the routing key.
How exchange bindings choose queues
These are three separate routing examples. Solid arrows show the path taken by the illustrated publication. Dashed arrows show configured bindings that do not match it, so those queues receive no copy. In topic bindings, * matches exactly one word and # matches zero or more words; neither is a regular expression.
flowchart TB
subgraph Fanout["Fanout: every bound queue receives a copy"]
FP[Producer] -->|Publish: routing key ignored| FX[Fanout exchange]
FX -->|Bound queue: receives copy| FQ1[(Billing queue)]
FX -->|Bound queue: receives copy| FQ2[(Email queue)]
end
subgraph Direct["Direct: exact routing key match"]
DP[Producer] -->|Publish key: orders.created| DX[Direct exchange]
DX -->|Binding orders.created: match| DQ1[(Invoice queue)]
DX -.->|Binding orders.cancelled: no delivery| DQ2[(Cancellation queue)]
end
subgraph Topic["Topic: dot-separated word matching"]
TP[Producer] -->|Publish key: orders.eu.created| TX[Topic exchange]
TX -->|Binding orders.#: match| TQ1[(All order events queue)]
TX -->|Binding orders.*.created: match| TQ2[(Created orders queue)]
TX -.->|Binding orders.*: no delivery| TQ3[(Two-word keys queue)]
endGive billing and email separate queues bound to the orders exchange. Multiple billing consumers can share the billing queue. Queues buffer work when consumers are slow; prefetch limits unacknowledged deliveries sent to a consumer. Choose it alongside processing time and memory limits rather than assuming that larger is always faster.
A consumer acknowledgement tells RabbitMQ that this delivery was handled. A publisher confirm tells the publisher that the broker accepted responsibility under the selected queue and persistence configuration. Neither says that the other side’s business transaction finished. An unroutable publication may still be confirmed; use mandatory publishing and handle returned messages when no matching queue is an error.
Publisher confirms and consumer acknowledgements
The exchange and queue are both inside the broker; the producer and consumer are outside. This successful-path timeline assumes a matching binding and publisher confirms enabled. The broker confirms acceptance independently of consumer processing. The confirm is shown before delivery for readability, but the consumer can receive and process the message before the producer observes that confirm.
sequenceDiagram
participant P as Producer application
box RabbitMQ broker
participant X as Exchange
participant Q as Queue
end
participant C as Consumer application
P->>X: Publish OrderPlaced
X->>Q: Route using matching binding
Note over X,Q: Broker accepts responsibility under configured durability
X-->>P: Publisher confirm from broker
Q->>C: Deliver message with manual acknowledgement
Note over C: Complete durable business processing
C-->>Q: Consumer acknowledgement to broker
Note over Q: Acknowledged queue delivery can be removedDurable queues and exchanges survive broker restarts, but messages also need appropriate persistence settings. Quorum queues add replication and have availability requirements. Acknowledged queue deliveries are normally removed; RabbitMQ Streams are a separate retained-log feature with replay. “RabbitMQ cannot replay” is therefore too broad.
Exchange routing, acknowledgements and publisher confirms, and RabbitMQ Streams describe these contracts.
RabbitMQ local lab
With Docker running, start an isolated local broker. Wait for the diagnostic command to succeed before running the selected program. Loopback port bindings keep this unauthenticated lab setup local; guest credentials are for this exercise only.
docker run -d --name messaging-rabbit -p 127.0.0.1:5672:5672 rabbitmq:4-management
docker exec messaging-rabbit rabbitmq-diagnostics -q pingEach program creates two exclusive temporary queues, binds both before publishing, waits for a publisher confirm, reads one message from each queue, then acknowledges after printing. Expect Billing and Email to print the same order. Temporary queues disappear when the connection closes, so this demonstrates fan-out rather than offline durability.
# rabbit.py — python -m pip install 'pika>=1.3,<2'; python rabbit.py
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
ch = connection.channel()
ch.exchange_declare(exchange='orders.lab', exchange_type='fanout')
queues = [ch.queue_declare(queue='', exclusive=True).method.queue for _ in range(2)]
for queue in queues:
ch.queue_bind(exchange='orders.lab', queue=queue)
ch.confirm_delivery()
ch.basic_publish('orders.lab', '', b'{"eventId":"evt-1","orderId":"order-42"}')
for name, queue in zip(['Billing', 'Email'], queues):
method, _, body = ch.basic_get(queue, auto_ack=False)
if method is None:
raise RuntimeError('Expected delivery')
print(name, body.decode())
ch.basic_ack(method.delivery_tag)
connection.close()Use a separate folder for each lab. The comments name the client dependency, file, and execution method; Java examples use a Maven dependency and an IDE main entry point. Versions identify the API used, not a recommendation to deploy those exact versions. No broker client is installed in this website.
For a production worker, declare a named durable queue with an explicit queue type, publish persistent messages, handle returned publications and failed confirms, and acknowledge only after durable processing. The single-message get operation here makes the trace short; long-running workers normally register a consumer and set prefetch.
Kafka: partitions and offsets
Kafka stores records in partitioned topics. Producers append records; consumers fetch them. Each partition has a leader and can have replicas. Replication factor is the number of copies, not the number of independent subscribers. Broker acknowledgement settings and minimum in-sync replicas together affect write availability and durability.
A topic distributed across brokers
A topic is a logical collection of partitions, not a separate server. Here, orders has three partitions spread across three brokers, with replication factor two: each partition has one leader and one follower on different brokers. Solid arrows show producer writes to leaders; dashed arrows show record replication to followers. The key-to-partition mapping is illustrative and assumes a stable partitioner and partition count.
flowchart TB
Producer[Producer: checkout application]
subgraph Cluster["Kafka cluster - topic: orders"]
subgraph Broker1["Broker 1"]
P0L[(Partition 0 leader)]
P2F[(Partition 2 follower)]
end
subgraph Broker2["Broker 2"]
P1L[(Partition 1 leader)]
P0F[(Partition 0 follower)]
end
subgraph Broker3["Broker 3"]
P2L[(Partition 2 leader)]
P1F[(Partition 1 follower)]
end
P0L -.->|Replicate partition 0| P0F
P1L -.->|Replicate partition 1| P1F
P2L -.->|Replicate partition 2| P2F
end
Producer -->|Key order-42| P0L
Producer -->|Key order-99| P1L
Producer -->|Key order-7| P2LIn a classic consumer group, each partition is assigned to one consumer at a time. Consumers in the same group divide the partitions; different groups read independently. Three partitions allow at most three consumers in that group to actively own partitions. A rebalance changes ownership when membership or subscriptions change, so workers must handle interruption and redelivery.
Sharing work within a group, reading independently across groups
This is one stable assignment snapshot. Billing worker 1 owns partitions 0 and 1; billing worker 2 owns partition 2. The analytics group independently reads all three. Arrows show records returned in response to consumer fetches, not broker push delivery. Followers are omitted here to focus on consumption. Within billing, a fourth consumer would have no partition to own while the topic still has only three partitions.
flowchart TB
subgraph Cluster["Kafka cluster - orders partition leaders"]
P0[(Partition 0)]
P1[(Partition 1)]
P2[(Partition 2)]
end
subgraph Billing["Consumer group: billing"]
B1[Billing consumer 1]
B2[Billing consumer 2]
end
subgraph Analytics["Consumer group: analytics"]
A1[Analytics consumer 1]
end
P0 -->|Fetch response: partition 0| B1
P1 -->|Fetch response: partition 1| B1
P2 -->|Fetch response: partition 2| B2
P0 -->|Independent fetch response| A1
P1 -->|Independent fetch response| A1
P2 -->|Independent fetch response| A1A key such as order-42 normally keeps that order’s records on one partition with a consistent partitioner. Adding partitions can change key placement, so plan ordering requirements before resizing. Concurrent processing can also complete side effects out of order even if records were fetched in order.
A committed offset is a restart position. Commit after successful work to allow retry after a crash; commit before work and a crash may skip that work. The earliest reset policy is used when no valid committed position exists. It does not rewind an established group. To replay, use a new group or deliberately reset a stopped group’s offsets within retained history.
Reading position, committed position, and lag
This snapshot uses one non-transactional partition with contiguous offsets 0 through 11. Its log-end offset is 12, the next append position. Billing has committed 8 but its consumer has returned records through offset 9 to the application, so its consumer position is 10. Returning records does not prove business processing is complete. After a restart it resumes at committed offset 8, not at its previous in-memory position 10. Its committed-offset lag is 12 minus 8, or four records in this example; offsets are positions and this subtraction is not always an exact record count in compacted or transactional logs.
flowchart LR
subgraph Log["One partition - retained records remain after reading"]
Earlier["Offsets 0 to 7: before committed position"]
R8["Offset 8: returned to application"]
R9["Offset 9: returned to application"]
R10["Offset 10: not yet returned"]
R11["Offset 11: not yet returned"]
End["Log-end offset 12: next append"]
Earlier --> R8 --> R9 --> R10 --> R11 --> End
end
Commit["Committed offset 8: restart here"] -.-> R8
Position["Consumer position 10: next application record"] -.-> R10A crash between processing and committing
The group coordinator stores the group’s committed offsets; partition leaders serve the records. Here the billing consumer durably records an invoice and processed event identifier together, then crashes before committing offset 9. Its replacement resumes at offset 8 and sees the same event again. The database deduplication check prevents a second invoice, and the consumer can then commit 9. The committed offset advances progress without deleting the event from the partition.
sequenceDiagram
participant L as Partition leader
participant G as Group coordinator
participant C as Billing consumer
participant D as Billing database
Note over G: Billing committed offset is 8 for this partition
C->>L: Fetch from offset 8
L-->>C: Record at offset 8 with eventId evt-1
C->>D: Transaction: invoice and processed eventId
D-->>C: Database commit succeeds
Note over C: Crash before committing offset 9 to Kafka
Note over C: Replacement consumer starts
C->>G: Read committed offset for this partition
G-->>C: Resume at offset 8
C->>L: Fetch from offset 8 again
L-->>C: Same record and eventId
C->>D: Check processed eventId in transaction
D-->>C: Already processed - skip duplicate invoice
C->>G: Commit next offset 9
G-->>C: Offset storedProducer idempotence handles certain retry duplicates in Kafka’s log. Transactions can atomically write Kafka output and commit input offsets when configured correctly, with consumers using read_committed. They do not automatically make an external payment, email, or database update exactly once. See the Kafka design documentation for the scope of these guarantees.
Kafka local lab
Start a separate local Kafka broker and explicitly create a three-partition topic. Retry the topic creation command after startup if the broker is not ready. A single broker with replication factor one is a learning environment with no replica failover.
docker run -d --name messaging-kafka -p 127.0.0.1:9092:9092 apache/kafka:4.1.0
docker exec messaging-kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --if-not-exists --topic orders.lab --partitions 3 --replication-factor 1The selected program publishes an order keyed by order-42, starts a new billing group from the earliest retained position, prints received data, then commits after processing. Unique group names make replay visible on repeated runs. The JavaScript and TypeScript workers stay running until Ctrl+C; the other programs stop after a record or batch.
# kafka_lab.py — python -m pip install 'confluent-kafka>=2.6,<3'; python kafka_lab.py
import uuid
from confluent_kafka import Producer, Consumer, KafkaException
p = Producer({'bootstrap.servers': 'localhost:9092'})
def delivered(error, message):
if error:
raise KafkaException(error)
p.produce('orders.lab', key='order-42', value='{"eventId":"evt-1","orderId":"order-42"}', callback=delivered)
if p.flush(10):
raise RuntimeError('Publish timed out')
c = Consumer({'bootstrap.servers': 'localhost:9092', 'group.id': 'billing-' + str(uuid.uuid4()),
'auto.offset.reset': 'earliest', 'enable.auto.commit': False})
try:
c.subscribe(['orders.lab'])
while True:
message = c.poll(10)
if message is None:
raise RuntimeError('No record received')
if message.error():
raise KafkaException(message.error())
print('Billing', message.value().decode())
c.commit(message=message, asynchronous=False)
break
finally:
c.close()Run twice and observe that old records are still available. With several retained records, a one-record program may print an earlier record and exit; it is not guaranteed to print the event it just published. A real billing service needs a stable group identifier so restarts resume rather than replay the entire history.
Experiment using Kafka’s command-line consumer: two terminals with the same group divide partitions; a third with a different group receives an independent view. Leave the first two running while publishing. With only one order key, only one partition carries traffic, so do not expect both workers to print.
docker exec -it messaging-kafka /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders.lab --group lab-workers --from-beginning
# Run this in another terminal for an independent subscription:
docker exec -it messaging-kafka /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders.lab --group lab-analytics --from-beginningWhen finished, remove only the containers created for these labs. Removing the Kafka container also discards its lab history because no persistent volume was configured.
docker rm -f messaging-rabbit messaging-kafkaFailures and delivery guarantees
At-most-once accepts possible loss to avoid retries. At-least-once retries uncertain deliveries and therefore allows duplicates. Exactly-once claims need a stated boundary: a broker transaction is not the same thing as one business effect in an unrelated system.
Consider billing: it commits an invoice, then crashes before acknowledging the RabbitMQ delivery or committing the Kafka offset. The replacement worker receives the order again. A unique constraint on the event identifier, recorded in the same database transaction as the invoice, prevents creating a second invoice. Deduplication state stored only in memory disappears on restart.
sequenceDiagram
participant Broker
participant Worker
participant DB as Billing database
Broker->>Worker: Deliver evt-1
Worker->>DB: Transaction: insert processed ID and invoice
DB-->>Worker: Commit succeeds
Note over Worker: Crash before acknowledgement or offset commit
Broker->>Worker: Redeliver evt-1 after recovery
Worker->>DB: Check processed ID in transaction
DB-->>Worker: Already processed; skip duplicate effect
Worker->>Broker: Acknowledge or commit next offsetA deduplication transaction cannot atomically protect an email or remote payment unless that external system participates. Pass a stable idempotency key to providers that support it, record attempts, and reconcile uncertain outcomes. Retain deduplication records for at least the period in which duplicate work can return, including deliberate replay.
The dual-write problem happens when checkout commits its order but crashes before publishing OrderPlaced. A transactional outbox writes both the order and an outgoing event row in one database transaction. A relay publishes pending rows and marks progress. A crash after publish but before marking still creates duplicates, so the relay and consumers need idempotency.
Retry temporary failures with bounded exponential backoff and jitter. Invalid payloads should not loop forever. After a limit, quarantine them with the error, event identifier, and attempt count; alert an owner and provide a controlled redrive path. RabbitMQ dead-letter routing and Kafka retry topics need explicit policy. Moving a failed event aside can break per-order ordering if later events proceed.
Backpressure limits work in flight. Bound consumer concurrency, prefetch, batch size, and internal buffers. If 100 orders arrive each second but workers finish 80, backlog grows by 20 per second. Adding a broker delays overload; recovery requires more processing capacity, lower input, or an explicit shedding policy.
Evolve schemas additively where possible. Consumers should tolerate unknown optional fields, but validate required fields and business invariants. Deploy compatible readers before writers; test old retained events against new readers before replaying history. Never assume JSON alone provides schema compatibility.
Choosing and operating a system
| Need | Starting point | Main question |
|---|---|---|
| Immediate result within one application | Direct call | Does the caller own the sequence? |
| Independent local reactions | In-process event bus | Is losing events on restart acceptable? |
| Routed work and independent queues | RabbitMQ exchanges and queues | What are acknowledgement, retry, and durability policies? |
| Retained history and independent replay | Kafka topics or RabbitMQ Streams | What are ordering, retention, and consumer lag limits? |
These are starting points, not exclusive product capabilities. RabbitMQ can retain streams, and Kafka groups can distribute processing. Choose using the workload, delivery semantics, client support, operational experience, and measured failure recovery rather than a universal throughput ranking.
Track queue depth or consumer lag, oldest pending event age, processing latency, retry rate, dead-letter volume, and publish errors. An empty queue can still hide failed publishing. Trace correlation identifiers across producer and consumer logs and distinguish message receipt from successful business completion.
Use TLS, separate service credentials, and permissions limited to required destinations in deployed systems. Avoid secrets and unnecessary personal data in messages. Retention, replay, logs, and dead-letter destinations all create additional copies that require access control and deletion policies.
Before shipping, test a consumer crash after its database commit, a broker outage during publish, an invalid event, a slow subscriber, and replay after a schema change. Acceptance means expected business effects, bounded retries, visible failures, and a recovery procedure that operators can actually execute.
Sources and further reading
- RabbitMQ tutorials — clients, work queues, routing, and pub/sub.
- RabbitMQ queues and confirms — queue lifecycle and reliability.
- Kafka quickstart and design — local setup and log semantics.
- KafkaJS consumers, Confluent Python client, and Rust rdkafka — client-specific consumption APIs.
- Go AMQP client and Rust lapin — RabbitMQ client APIs used in these examples.