Message Queues Explained: Kafka vs RabbitMQ
What message queues are, why systems use them, and how Apache Kafka and RabbitMQ differ in architecture, delivery guarantees, ordering, retention and use cases, with producer and consumer code examples.
When one service calls another directly, both must be up, fast and ready at the same moment. A message queue breaks that coupling: a producer drops a message into a broker and moves on, and consumers process it when they can. Apache Kafka and RabbitMQ are the two most popular brokers, and they solve the problem in very different ways.
How a message queue works#
- Producer: the service that sends a message, such as "OrderPlaced".
- Broker: the server that stores messages and routes them.
- Consumer: the service that reads and processes messages.
Without a queue: Checkout ──HTTP──▶ Email Service (if Email is down, checkout fails)
With a queue: Checkout ──▶ [ Broker ] ──▶ Email Service
(returns immediately) (processes when ready, retries on failure)Why use a message queue?#
- Decoupling: producers don't need to know who consumes, or how many consumers there are.
- Load levelling: a burst of 50,000 requests sits in the queue while workers drain it at a steady rate.
- Resilience: if a consumer crashes, messages wait instead of being lost.
- Asynchronous work: slow tasks (emails, video encoding, reports) leave the request path, so users get fast responses.
- Fan-out: one event can feed many services: billing, analytics and notifications.
Point-to-point vs publish/subscribe#
| Model | Who receives a message | Example |
|---|---|---|
| Point-to-point (work queue) | Exactly one of the competing consumers | Image-resize jobs spread across workers |
| Publish/subscribe | Every subscribed group gets its own copy | "UserSignedUp" goes to email, CRM and analytics |
RabbitMQ: the smart broker#
RabbitMQ implements AMQP. Producers publish to an exchange; the exchange routes messages into queues using bindings; consumers read from queues. Once a consumer acknowledges a message, it is deleted.
| Exchange type | Routing rule |
|---|---|
| Direct | Routing key matches the binding key exactly |
| Topic | Wildcard patterns like order.*.created |
| Fanout | Copy to every bound queue |
| Headers | Match on message header values |
# pip install pika
import pika, json
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="emails", durable=True)
# Producer
ch.basic_publish(
exchange="",
routing_key="emails",
body=json.dumps({"to": "a@b.com", "template": "welcome"}),
properties=pika.BasicProperties(delivery_mode=2), # persistent
)
# Consumer
def handle(ch, method, props, body):
send_email(json.loads(body))
ch.basic_ack(delivery_tag=method.delivery_tag) # ack only after success
ch.basic_qos(prefetch_count=10)
ch.basic_consume(queue="emails", on_message_callback=handle)
ch.start_consuming()Kafka: the distributed log#
Kafka stores messages in an append-only log. A topic is split into partitions, each an ordered sequence of records with numeric offsets. Messages are not deleted when read; they're kept for a retention period (for example 7 days, or forever). Each consumer group tracks its own offset, so many groups can read the same data independently and even replay it.
Topic "orders"
Partition 0: [0][1][2][3][4][5] ◀── group "billing" at offset 4
Partition 1: [0][1][2][3] ◀── group "analytics" at offset 1
Partition 2: [0][1][2][3][4]
Same key (e.g. orderId) → same partition → ordered per key// npm install kafkajs
import { Kafka } from "kafkajs";
const kafka = new Kafka({ clientId: "shop", brokers: ["localhost:9092"] });
// Producer
const producer = kafka.producer({ idempotent: true });
await producer.connect();
await producer.send({
topic: "orders",
messages: [{ key: order.id, value: JSON.stringify(order) }],
});
// Consumer
const consumer = kafka.consumer({ groupId: "billing" });
await consumer.connect();
await consumer.subscribe({ topic: "orders", fromBeginning: false });
await consumer.run({
eachMessage: async ({ partition, message }) => {
await chargeCustomer(JSON.parse(message.value.toString()));
},
});Within a consumer group, each partition is read by at most one consumer. A topic with 12 partitions can be processed by up to 12 consumers in parallel, so choose the partition count with future throughput in mind.
Kafka vs RabbitMQ#
| Kafka | RabbitMQ | |
|---|---|---|
| Model | Distributed, partitioned commit log | Message broker with exchanges and queues |
| After consumption | Retained until retention expires | Deleted once acknowledged |
| Replay | Yes: reset the consumer offset | No (except with Streams) |
| Ordering | Guaranteed within a partition | Per queue, with a single consumer |
| Throughput | Very high (millions of msgs/sec) | High (tens of thousands per queue) |
| Routing | Simple: topic and key | Rich: direct, topic, fanout, headers |
| Consumer style | Pull | Push (with prefetch) |
| Priorities and per-message TTL | No | Yes |
| Best for | Event streaming, logs, analytics, event sourcing | Task queues, complex routing, RPC-style jobs |
Delivery guarantees#
| Guarantee | Meaning | How it happens |
|---|---|---|
| At-most-once | May be lost, never duplicated | Ack/commit before processing |
| At-least-once | Never lost, may be duplicated | Ack/commit after processing (the usual default) |
| Exactly-once | Processed once in effect | Kafka transactions plus idempotent producers, or idempotent consumers |
With at-least-once delivery, duplicates will happen after crashes and rebalances. Store processed message IDs, or use upserts keyed by a unique ID, so handling the same message twice has no extra effect.
-- Idempotent processing with a unique message ID
INSERT INTO processed_messages (message_id) VALUES ('evt-8f2c')
ON CONFLICT (message_id) DO NOTHING;
-- Only run the side effect if a row was actually insertedHandling failures: retries and dead-letter queues#
If a message keeps failing (bad data, a bug), retrying forever blocks the queue. Retry a few times with backoff, then move it to a dead-letter queue (DLQ) for inspection.
orders ──▶ consumer ──fail──▶ orders.retry (delay 30s) ──▶ consumer
└──fail x5──▶ orders.dlq (alert + manual review)Which should you choose?#
- Choose RabbitMQ for background jobs, work distribution, flexible routing, message priorities and simpler operations at moderate scale.
- Choose Kafka for high-volume event streams, multiple independent consumers of the same data, replay, stream processing and event sourcing.
- Managed alternatives include Amazon SQS/SNS, Google Pub/Sub, Azure Service Bus and Redis Streams for lighter needs.
Message queues are the backbone of event-driven microservices and a key tool for horizontal scaling.
Key takeaways#
- Message queues decouple producers from consumers, smooth traffic spikes and make systems resilient.
- RabbitMQ is a smart broker: exchanges route messages to queues, and messages are deleted after acknowledgement.
- Kafka is a partitioned, replayable log: messages are retained and each consumer group tracks its own offset.
- Kafka guarantees ordering per partition; use a message key to keep related events together.
- Assume at-least-once delivery: build idempotent consumers and use dead-letter queues.