Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

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.

Sumit KumarUpdated Oct 11, 20264 min readSystem Design
Message Queues Explained: Kafka vs RabbitMQ

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#

Message queue architecture: producers publish messages to a broker, which delivers them to consumers; Kafka partitioned log compared with RabbitMQ exchanges and queues
  • 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.
Text
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#

ModelWho receives a messageExample
Point-to-point (work queue)Exactly one of the competing consumersImage-resize jobs spread across workers
Publish/subscribeEvery 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 typeRouting rule
DirectRouting key matches the binding key exactly
TopicWildcard patterns like order.*.created
FanoutCopy to every bound queue
HeadersMatch on message header values
Python
# 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.

Text
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
JavaScript
// 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()));
  },
});
Parallelism in Kafka

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#

KafkaRabbitMQ
ModelDistributed, partitioned commit logMessage broker with exchanges and queues
After consumptionRetained until retention expiresDeleted once acknowledged
ReplayYes: reset the consumer offsetNo (except with Streams)
OrderingGuaranteed within a partitionPer queue, with a single consumer
ThroughputVery high (millions of msgs/sec)High (tens of thousands per queue)
RoutingSimple: topic and keyRich: direct, topic, fanout, headers
Consumer stylePullPush (with prefetch)
Priorities and per-message TTLNoYes
Best forEvent streaming, logs, analytics, event sourcingTask queues, complex routing, RPC-style jobs

Delivery guarantees#

GuaranteeMeaningHow it happens
At-most-onceMay be lost, never duplicatedAck/commit before processing
At-least-onceNever lost, may be duplicatedAck/commit after processing (the usual default)
Exactly-onceProcessed once in effectKafka transactions plus idempotent producers, or idempotent consumers
Make consumers idempotent

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.

SQL
-- 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 inserted

Handling 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.

Text
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.