Message Brokers Compared: Kafka vs RabbitMQ vs SQS/SNS vs NATS vs Redis Streams
Derar SattoufUpdated Backend & databases

Asynchronous messaging is one of those topics where the vocabulary hides the real decisions. "Queue", "topic", "stream", "event bus", and "pub/sub" get used interchangeably, and teams pick a broker because it is what the last company used. Then they discover that their job queue cannot replay history, that their event log cannot do per-message retries, or that their cheap managed queue cannot guarantee the ordering they assumed.
Start by deciding which of three models you need. A queue distributes work: each message is processed by one consumer, then removed. That's best for background jobs, and RabbitMQ and SQS are queue-first. A log is event streaming: messages are appended, retained, and read by many independent consumers at their own offsets, with replay. Kafka is log-first. Pub/sub is fan-out: each subscriber gets its own copy, and SNS and NATS subjects are fan-out first.
Almost everything gives at-least-once delivery. That means duplicates are normal and every consumer must be idempotent. "Exactly-once" is real only inside specific boundaries (Kafka transactions within Kafka, JetStream publish deduplication) and never magically extends to your database or third-party APIs. Ordering is per partition, per queue, or per message group, never global at scale. Choose a partition key (customer ID, order ID) so related events stay ordered, and accept that parallelism and strict ordering trade off.
Pick Kafka for high-throughput event streaming, replay, stream processing, and many consumers of the same data. Pick RabbitMQ for rich routing, task queues with priorities and per-message TTL, and request/reply. Pick SQS (plus SNS) when you are on AWS and want zero operations for queues and fan-out. Pick NATS for low-latency messaging, service-to-service request/reply, edge and IoT, with JetStream when you need persistence. Pick Redis Streams when you already run Redis and need a lightweight durable stream at modest scale. Operational cost often matters more than features: a self-managed Kafka cluster is a serious commitment, SQS is nearly free to operate, and NATS and Redis sit in between.
Whichever you pick, every consumer needs retries with backoff, a dead-letter queue, idempotency, bounded concurrency (backpressure), and lag monitoring. A broker without those is a place where messages silently pile up or vanish. Use the transactional outbox to publish events atomically with database writes; see event-driven architecture, outbox and idempotency.
All of these projects ship frequently, so versions matter. At the time of writing, Kafka is in its 4.x line (ZooKeeper removed, KRaft only; queue-like "share groups" (KIP-932) are arriving and their maturity depends on the release you run), RabbitMQ is in its 4.x line (quorum queues and streams are the modern defaults; classic queue mirroring is gone), and NATS JetStream is the persistence layer of NATS. Client library APIs change, so snippets show the shape and you should check exact signatures against the version you install.
Three models: queue, log, pub/sub
Most confusion disappears once you identify which model you need.
Queue: competing consumers
Producer --> [ m5 m4 m3 m2 m1 ] --> Consumer A (gets m1)
--> Consumer B (gets m2)
--> Consumer C (gets m3)
A message goes to ONE consumer. When acknowledged, it is deleted.Properties: work is shared, adding consumers scales throughput, messages are removed after processing, and the broker tracks per-message state (in flight, acknowledged, redelivered). There is no replay because the data is gone. Retries and dead-lettering are per message.
Log: partitioned, retained, replayable
Topic "orders" (3 partitions)
P0: [0][1][2][3][4] ...
P1: [0][1][2][3] ...
P2: [0][1][2][3][4][5] ...
Consumer group "billing": reads P0,P1,P2 split across its members, tracks offsets
Consumer group "analytics": reads the same data independently, at its own pace
Retention keeps data for N days or N bytes, regardless of who read it.Properties: messages are not deleted on consumption; consumers track a position (offset). Many independent consumer groups read the same data. You can replay by rewinding offsets, rebuild state, and add a new consumer next year that reads history. The cost is that the broker does not track per-message acknowledgment in the same way; a poison message blocks its partition unless the consumer handles it (skip, park, or dead-letter in application code).
Pub/sub: fan-out
Publisher --> topic "order.created" --> Subscriber 1 (gets copy)
--> Subscriber 2 (gets copy)
--> Subscriber 3 (gets copy)Properties: each subscriber gets every message. Pure pub/sub often has no persistence (a subscriber that is offline misses messages), which is why practical systems combine it with queues (SNS to SQS) or with a log (JetStream, Kafka).
The mapping
| System | Native model | Can it act like the others? |
|---|---|---|
| Kafka | Log | Queue-like via consumer groups (one consumer per partition); true per-message queue semantics are emerging via share groups (verify release status); fan-out via multiple groups |
| RabbitMQ | Queue with flexible routing (exchanges) | Fan-out via fanout/topic exchanges; log-like via Streams |
| SQS | Queue | Fan-out with SNS; no replay |
| SNS | Pub/sub | Usually paired with SQS for durability |
| NATS core | Pub/sub and request/reply, at-most-once | JetStream adds log and queue-like durable consumers |
| Redis Streams | Log with consumer groups | Queue-like through consumer groups and acks |
Delivery guarantees and ordering
Delivery semantics
| Semantics | Meaning | How it happens | Consumer burden |
|---|---|---|---|
| At-most-once | Messages may be lost, never duplicated | Fire and forget; ack before processing; NATS core | Tolerate loss |
| At-least-once | Never lost (if the broker is durable), may be duplicated | Ack after processing; redelivery on timeout or failure | Be idempotent |
| Exactly-once | Processed exactly once | Only within a bounded system with transactions or dedupe | Usually still be idempotent at the edges |
At-least-once with idempotent consumers is the practical standard. A duplicate arises whenever a consumer processes a message but crashes or times out before acknowledging, or the ack is lost in the network, or a rebalance moves a partition mid-batch. It is not a rare event.
What "exactly-once" really covers
- Kafka: idempotent producers (no duplicates from producer retries within a partition) and transactions (atomic writes across partitions plus offset commits) give exactly-once for read-process-write within Kafka (for example Kafka Streams). Writing to an external database or API is outside that boundary.
- NATS JetStream: publish-side deduplication using the
Nats-Msg-Idheader within a configurable window, plus double-ack for consumer acknowledgments, gives effectively-once for publish and consume of a stream, not for side effects. - SQS FIFO: deduplication by message deduplication ID within a five minute window prevents duplicate sends.
- RabbitMQ and Redis Streams: at-least-once; use publisher confirms and application-level idempotency.
The one defense that works everywhere is an idempotent consumer: record processed message IDs (or make the operation naturally idempotent) in the same transaction as the side effect.
-- Idempotency table; the unique key makes duplicate processing a no-op
CREATE TABLE processed_messages (
consumer text NOT NULL,
message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);// Idempotent handler: side effect and dedupe record commit atomically
async function handle(msg: { id: string; payload: OrderPaid }) {
await db.transaction(async (tx) => {
const inserted = await tx.query(
"INSERT INTO processed_messages (consumer, message_id) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING 1",
["billing", msg.id],
);
if (inserted.rowCount === 0) return; // already processed: skip safely
await tx.query("UPDATE invoices SET status = 'paid' WHERE order_id = $1", [msg.payload.orderId]);
});
}
type OrderPaid = { orderId: string };
declare const db: { transaction<T>(fn: (tx: { query(sql: string, params?: unknown[]): Promise<{ rowCount: number }> }) => Promise<T>): Promise<T> };Ordering
| System | Ordering guarantee | Key detail |
|---|---|---|
| Kafka | Strict order within a partition | Same key goes to the same partition (with the default partitioner); order across partitions is not defined. Changing partition count remaps keys |
| RabbitMQ | FIFO per queue, but redelivery, multiple consumers, and priority can reorder | With one consumer per queue and no requeue, order holds; with competing consumers it does not |
| SQS Standard | Best effort only | Do not rely on order |
| SQS FIFO | Strict order within a message group ID | Parallelism equals the number of distinct group IDs; throughput limits apply (verify current quotas and high-throughput mode) |
| NATS core | Per publisher per subject | Across publishers no guarantee |
| JetStream | Ordered within a stream; consumers see stream order, redeliveries can reorder for pull consumers with multiple workers | Ordered consumers give strict ordering for single readers |
| Redis Streams | Order within a stream by ID | Consumer groups with several consumers process concurrently, so completion order varies |
The universal pattern: choose a partition key that equals the unit of ordering (usually an aggregate ID such as order ID or account ID). Events for the same entity stay ordered; different entities process in parallel. If you need global ordering, you have a throughput ceiling of one partition or one consumer, so reconsider the requirement.
Hot keys and skew
A single very busy key (a celebrity account, one giant tenant) overloads its partition. Mitigations: sub-partition the key (key plus a bucket) if ordering allows, process per-key work in a dedicated queue, or accept lag for that key and alert on per-partition lag.
Comparison at a glance
Feature matrix
| Kafka | RabbitMQ | SQS and SNS | NATS and JetStream | Redis Streams | |
|---|---|---|---|---|---|
| Primary model | Distributed log | Broker with exchanges and queues (plus streams) | Managed queue and pub/sub | Lightweight messaging, JetStream for persistence | Append-only log in Redis |
| Replay | Yes, by offset or timestamp | Streams only; classic and quorum queues no | No | Yes (JetStream) | Yes, within retention |
| Retention | Time or size, effectively unlimited with tiered storage | Until consumed (queues); configurable for streams | Up to 14 days (SQS) | Limits, interest, or work-queue policy | Until trimmed (MAXLEN or MINID) |
| Ordering | Per partition | Per queue (with caveats) | FIFO per group (FIFO queues) | Per stream | Per stream |
| Routing | Topic and partition; consumers filter | Rich: direct, topic, fanout, headers exchanges | Filter policies on SNS subscriptions | Subject hierarchy with wildcards | Stream per key; consumers filter |
| Per-message ack, retry, DLQ | Application-level (retry topics) | Native (nack, requeue, dead-letter exchange, delivery limit) | Native (visibility timeout, redrive to DLQ) | Native (ack wait, max deliver, advisories) | Pending list, claim, application DLQ |
| Priorities, delays, TTL | No native priorities; delays via patterns | Per-queue TTL, per-message TTL, priority queues, delayed via plugins or TTL and DLX patterns | Delay up to 15 minutes, no priority | Some via consumer config; limited | Application-level |
| Throughput | Very high (millions of msgs/s on large clusters) | Tens of thousands per queue typical; streams much higher | Effectively unbounded (standard) | Very high (core), high (JetStream) | High for a single Redis node, bounded by memory |
| Latency | Low milliseconds; batching trades latency for throughput | Low milliseconds | Tens of milliseconds | Sub-millisecond core, low milliseconds JetStream | Sub-millisecond to milliseconds |
| Ops complexity | High self-managed; moderate managed | Moderate | Almost none | Low to moderate | Low if you already run Redis |
| Managed options | Confluent Cloud, Amazon MSK, Redpanda (Kafka-compatible), Aiven, others | CloudAMQP, Amazon MQ, vendor clouds | Native AWS | Synadia Cloud and others | ElastiCache, Upstash, Redis Cloud, and others |
| Best for | Event streaming, CDC, analytics, replay | Task queues, complex routing, RPC | AWS-native queues and fan-out | Service mesh messaging, edge, IoT, request/reply | Simple durable streams next to Redis |
Throughput and latency numbers vary enormously with message size, replication settings, acknowledgments, hardware, and client behavior. Benchmark with your own payloads before making a capacity claim, and treat vendor benchmark numbers as upper bounds under ideal conditions.
Consumer scaling models
| System | Parallelism unit | Cap on consumers doing useful work |
|---|---|---|
| Kafka | Partition | Number of partitions per consumer group |
| RabbitMQ | Consumers on a queue (with prefetch) | Practically unbounded; ordering lost |
| SQS Standard | Any number of pollers | Unbounded |
| SQS FIFO | Message group ID | Number of active groups |
| JetStream | Pull consumers share a durable consumer | Unbounded; ordering lost |
| Redis Streams | Consumers in a group | Unbounded; ordering lost |
This explains a common surprise: you cannot add 100 consumers to a Kafka topic with 12 partitions and get 100-way parallelism. Partition count is the ceiling, so plan it up front (and remember that increasing it later changes key-to-partition mapping).
Picking by use case
Background jobs and task queues
Examples: send email, resize image, generate report, call a slow third-party API.
Needs: per-message retry with backoff, dead-lettering, delays, concurrency control, visibility into failures, no need for replay.
Best fits: SQS (zero ops, AWS), RabbitMQ (rich features, priorities, delayed retry patterns), or a library-level job queue on top of Redis or Postgres (BullMQ, Sidekiq, Celery, Oban, River) when you want job semantics such as scheduling, unique jobs, and dashboards. Kafka is possible but awkward: no per-message retry or delay natively, and a poison message blocks a partition.
Event streaming and event sourcing
Examples: order events consumed by billing, inventory, analytics, and search indexers; change data capture; audit logs; building materialized views.
Needs: retention and replay, multiple independent consumers, ordering per entity, high throughput, schema evolution.
Best fit: Kafka (or a Kafka-compatible system such as Redpanda). JetStream and RabbitMQ Streams fit at smaller scale. Redis Streams works for modest volumes.
Fan-out notifications
Examples: one event triggers email, push, cache invalidation, and analytics, each owned by a different service.
Best fits: SNS to SQS on AWS (each subscriber has its own durable queue), RabbitMQ topic or fanout exchanges, NATS subjects (with JetStream if durability matters), or Kafka consumer groups if replay also matters.
Request/reply (RPC over messaging)
Examples: a service asks another for data with a timeout; scatter-gather queries.
Best fits: NATS (built-in request/reply, inboxes, and load-balanced queue groups are its sweet spot) and RabbitMQ (reply-to queues and correlation IDs; also supports direct reply-to). Avoid Kafka and SQS for synchronous-style RPC.
IoT and edge
Examples: many devices publishing telemetry, intermittent connectivity, constrained hardware.
Best fits: MQTT brokers (EMQX, Mosquitto, AWS IoT Core) at the device edge, bridged into Kafka or a cloud queue for processing; NATS also targets edge and leaf-node topologies, with JetStream for local persistence. RabbitMQ supports MQTT via a plugin.
Stream processing and analytics
Needs: windowing, joins, stateful processing. Best fit: Kafka with Kafka Streams, Flink, or ksqlDB-style tools; or a managed equivalent.
Quick selection table
| Use case | First choice | Second choice | Avoid |
|---|---|---|---|
| Background jobs on AWS | SQS | RabbitMQ, a Redis or Postgres job library | Kafka |
| Background jobs, self-hosted, rich semantics | RabbitMQ | BullMQ or similar, Postgres-based queue | Kafka |
| Event streaming with replay | Kafka | JetStream, RabbitMQ Streams | SQS, plain RabbitMQ queues |
| Fan-out to many services on AWS | SNS plus SQS | EventBridge (for routing rules), Kafka | Plain SQS alone |
| Request/reply | NATS | RabbitMQ | Kafka, SQS |
| IoT telemetry | MQTT broker plus Kafka | NATS | Heavy brokers on the device |
| Small team, already on Redis, modest volume | Redis Streams | RabbitMQ | A Kafka cluster you cannot operate |
| Cross-region streaming | Kafka with replication tooling (MirrorMaker 2, cluster linking) | NATS superclusters | Hand-rolled replication |
| Transactional outbox relay | Kafka or any broker plus a relay or CDC | SQS | Dual writes |
Kafka
Core concepts
- Topic: a named log, divided into partitions; each partition is an ordered, append-only sequence of records.
- Producer: appends records; the key determines the partition.
- Consumer group: consumers sharing a group ID divide the partitions among themselves; each partition is read by exactly one member of the group at a time. Different groups read independently.
- Offset: the consumer's position per partition, stored by Kafka in an internal topic.
- Replication: each partition has a leader and followers;
min.insync.replicaswithacks=alldefines durability. - KRaft: Kafka's built-in consensus layer. As of Kafka 4.0, ZooKeeper is gone and KRaft is the only mode, which simplifies operations (migrate from ZooKeeper on a 3.x release first if you are upgrading an old cluster; consult the migration guide).
Producer configuration that matters
| Setting | Recommended | Why |
|---|---|---|
acks | all | Wait for all in-sync replicas |
enable.idempotence | true | No duplicates from producer retries (default on in modern clients; verify) |
min.insync.replicas (topic or broker) | 2 with replication factor 3 | Survive one broker loss without data loss |
compression.type | zstd or lz4 | Less bandwidth and disk, often higher throughput |
linger.ms and batch.size | 5 to 20 ms, tune | Batching raises throughput at a small latency cost |
delivery.timeout.ms | Realistic upper bound | Bounds retry time |
| Key | Aggregate ID | Preserves per-entity order |
Topic creation
kafka-topics.sh --bootstrap-server broker:9092 --create \
--topic orders.v1 --partitions 12 --replication-factor 3 \
--config min.insync.replicas=2 \
--config retention.ms=604800000 \
--config cleanup.policy=delete
# Compacted topic keeps only the latest value per key (state, changelogs)
kafka-topics.sh --bootstrap-server broker:9092 --create \
--topic customers.state.v1 --partitions 6 --replication-factor 3 \
--config cleanup.policy=compactCompaction deserves a mention: with cleanup.policy=compact, Kafka retains at least the latest record per key, making a topic behave like a replicated key-value changelog. It is how you bootstrap new consumers with current state without replaying all history.
Producer and consumer in TypeScript (kafkajs-style API)
The widely used kafkajs API is shown. The project's maintenance pace has slowed, and Confluent offers a JavaScript client with a KafkaJS-compatible interface (@confluentinc/kafka-javascript); verify which client is appropriate for your version and support needs, and check the exact configuration shape.
// kafka/producer.ts
import { Kafka, CompressionTypes, logLevel } from "kafkajs";
const kafka = new Kafka({ clientId: "orders-service", brokers: ["broker:9092"], logLevel: logLevel.WARN });
const producer = kafka.producer({ idempotent: true, maxInFlightRequests: 5 });
export async function publishOrderCreated(order: { id: string; customerId: string; totalCents: number }) {
await producer.send({
topic: "orders.v1",
acks: -1, // all in-sync replicas
compression: CompressionTypes.GZIP,
messages: [
{
key: order.customerId, // per-customer ordering
value: JSON.stringify({ type: "OrderCreated", id: order.id, ...order }),
headers: { "event-id": crypto.randomUUID(), "schema-version": "1" },
},
],
});
}
await producer.connect();// kafka/consumer.ts: manual commits, retry topic, and DLQ topic
import { Kafka } from "kafkajs";
const kafka = new Kafka({ clientId: "billing", brokers: ["broker:9092"] });
const consumer = kafka.consumer({ groupId: "billing-v1" });
const producer = kafka.producer({ idempotent: true });
const MAX_ATTEMPTS = 5;
await Promise.all([consumer.connect(), producer.connect()]);
await consumer.subscribe({ topics: ["orders.v1", "orders.v1.retry"], fromBeginning: false });
await consumer.run({
autoCommit: false,
partitionsConsumedConcurrently: 3,
eachMessage: async ({ topic, partition, message, heartbeat }) => {
const attempt = Number(message.headers?.["attempt"]?.toString() ?? "0");
try {
await handleIdempotently(message); // see "Delivery guarantees and ordering"
await consumer.commitOffsets([{ topic, partition, offset: (BigInt(message.offset) + 1n).toString() }]);
} catch (err) {
const isPermanent = err instanceof ValidationError; // never retry what cannot succeed
if (isPermanent || attempt + 1 >= MAX_ATTEMPTS) {
await producer.send({
topic: "orders.v1.dlq",
messages: [{
key: message.key,
value: message.value,
headers: { ...message.headers, "error": String(err), "origin-topic": topic, "attempts": String(attempt + 1) },
}],
});
} else {
await producer.send({
topic: "orders.v1.retry",
messages: [{ key: message.key, value: message.value, headers: { ...message.headers, attempt: String(attempt + 1), "not-before": String(Date.now() + backoffMs(attempt)) } }],
});
}
// Commit so the partition is not blocked; the failure now lives in retry or DLQ.
await consumer.commitOffsets([{ topic, partition, offset: (BigInt(message.offset) + 1n).toString() }]);
}
},
});
function backoffMs(attempt: number) {
return Math.min(60_000, 1000 * 2 ** attempt) + Math.floor(Math.random() * 500);
}
class ValidationError extends Error {}
declare function handleIdempotently(m: unknown): Promise<void>;The retry topic design is the Kafka answer to "per-message retry". The consumer of the retry topic must honor the not-before header (sleep or pause the partition until due). Variants use several retry topics with increasing delays (5 seconds, 1 minute, 10 minutes) so a delay never blocks fresh traffic. Poison messages go to the DLQ topic with the error and origin recorded, and an operator tool (or a separate consumer) can replay them after a fix.
Rebalances
When consumers join, leave, or time out, partitions are reassigned, and processing pauses. Reduce pain by using cooperative sticky assignment (partition.assignment.strategy with the cooperative sticky assignor, or the newer consumer group protocol from KIP-848 in recent versions; verify availability and defaults in your version), static membership (group.instance.id) for Kubernetes deployments so rolling restarts do not trigger rebalances, and by keeping max.poll.interval.ms above your worst-case batch processing time. Slow processing that exceeds the poll interval gets the consumer kicked out, leading to duplicate processing and rebalance storms.
Schema registry
Without a contract, producers and consumers drift apart. A schema registry (Confluent Schema Registry and compatible implementations such as Apicurio, plus AWS Glue Schema Registry) stores versioned schemas (Avro, Protobuf, or JSON Schema) and enforces compatibility modes at registration time.
| Compatibility mode | Allowed change | Upgrade order |
|---|---|---|
| BACKWARD (common default) | New schema can read old data: delete fields, add optional fields with defaults | Upgrade consumers first |
| FORWARD | Old schema can read new data | Upgrade producers first |
| FULL | Both | Any order |
| NONE | Anything | Chaos |
Messages carry a small schema ID header (magic byte plus ID), so consumers fetch the right schema. Rules of thumb: always add fields with defaults, never repurpose a field, version topics (orders.v1) only for real breaks, and run compatibility checks in CI.
# Check a candidate schema against the latest registered version
curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data @candidate-schema.json \
http://registry:8081/compatibility/subjects/orders.v1-value/versions/latestKafka strengths and costs
| Strengths | Costs |
|---|---|
| Massive throughput, durable, replicated log | Operationally heavy when self-managed: brokers, storage, upgrades, rebalancing, capacity |
| Replay and many independent consumers | No native per-message retry, delay, or priority |
| Rich ecosystem: Connect, Streams, Flink, CDC (Debezium) | Partition count is a long-term design decision |
| Strong ordering per key | Consumer group rebalances and lag need active management |
| Managed offerings reduce ops | Managed offerings can be expensive at scale (networking and storage egress) |
RabbitMQ
Core concepts
- Exchange: receives messages from producers and routes them to queues by rules. Types:
direct(exact routing key),topic(pattern with*and#),fanout(broadcast),headers. - Queue: stores messages for consumers. Modern queue types: quorum queues (replicated with Raft, the default choice for durable, safe queues), streams (append-only log with replay, for high throughput and fan-out), and classic queues (non-replicated; classic mirrored queues were removed in RabbitMQ 4.0, so do not plan around them).
- Binding: connects an exchange to a queue with a routing pattern.
- Acknowledgments and publisher confirms: consumers ack after processing; publishers wait for broker confirmation.
- Prefetch: how many unacknowledged messages a consumer may hold, which is RabbitMQ's backpressure knob.
Producer --> Exchange "orders" (topic)
|-- binding "order.created.#" --> Queue "billing" --> Consumer(s)
|-- binding "order.*.eu" --> Queue "eu-ops" --> Consumer(s)
'-- binding "#" --> Queue "audit" --> Consumer
A failed message: nack(requeue=false) --> Dead-letter exchange --> Queue "billing.dlq"Topology with retries and a DLQ
RabbitMQ has first-class dead-lettering. A durable retry pattern uses a TTL queue that dead-letters back to the work queue after a delay.
// rabbit/topology.ts
import amqp from "amqplib";
export async function setup(ch: amqp.Channel) {
await ch.assertExchange("orders", "topic", { durable: true });
await ch.assertExchange("orders.dlx", "direct", { durable: true });
// Main work queue: quorum queue, dead-letters failures to the DLX, bounded redelivery
await ch.assertQueue("billing", {
durable: true,
arguments: {
"x-queue-type": "quorum",
"x-dead-letter-exchange": "orders.dlx",
"x-dead-letter-routing-key": "billing.retry",
"x-delivery-limit": 5, // quorum queues count redeliveries; verify behavior in your version
},
});
await ch.bindQueue("billing", "orders", "order.created.#");
// Retry queue: messages wait here, then expire back to the main queue
await ch.assertQueue("billing.retry", {
durable: true,
arguments: {
"x-queue-type": "quorum",
"x-message-ttl": 30_000,
"x-dead-letter-exchange": "orders",
"x-dead-letter-routing-key": "order.created.retry",
},
});
await ch.bindQueue("billing.retry", "orders.dlx", "billing.retry");
// Final parking lot
await ch.assertQueue("billing.dlq", { durable: true, arguments: { "x-queue-type": "quorum" } });
await ch.bindQueue("billing.dlq", "orders.dlx", "billing.dead");
}Per-queue TTL gives a single fixed retry delay. For exponential backoff, create several retry queues with increasing TTLs and pick one by attempt number, or use the delayed message approaches available for your version (verify plugin availability and recommended practice in the current docs). Quorum queues also have a native x-delivery-limit that dead-letters a message after N redeliveries, which is useful for poison-message protection with nack(requeue=true).
Producer with publisher confirms and consumer with manual ack
// rabbit/producer.ts
import amqp from "amqplib";
const conn = await amqp.connect(process.env.AMQP_URL!);
const ch = await conn.createConfirmChannel(); // enables publisher confirms
export async function publish(routingKey: string, body: unknown, messageId: string) {
ch.publish("orders", routingKey, Buffer.from(JSON.stringify(body)), {
persistent: true, // survive broker restart (with durable queue)
messageId, // used for idempotent consumers
contentType: "application/json",
timestamp: Date.now(),
headers: { attempt: 0 },
});
await ch.waitForConfirms(); // do not assume delivery without the broker's confirmation
}// rabbit/consumer.ts
import amqp from "amqplib";
const conn = await amqp.connect(process.env.AMQP_URL!);
const ch = await conn.createChannel();
await ch.prefetch(20); // backpressure: at most 20 unacked messages in flight
await ch.consume("billing", async (msg) => {
if (!msg) return;
const attempt = Number(msg.properties.headers?.attempt ?? 0);
try {
await handleIdempotently(msg.properties.messageId, JSON.parse(msg.content.toString()));
ch.ack(msg);
} catch (err) {
if (err instanceof PermanentError || attempt >= 4) {
// Route to the dead-letter path without requeue
ch.publish("orders.dlx", "billing.dead", msg.content, {
persistent: true,
headers: { ...msg.properties.headers, error: String(err) },
});
ch.ack(msg);
} else {
// Republish to the retry queue with an incremented attempt, then ack the original
ch.publish("orders.dlx", "billing.retry", msg.content, {
persistent: true,
messageId: msg.properties.messageId,
headers: { ...msg.properties.headers, attempt: attempt + 1 },
});
ch.ack(msg);
}
}
});
class PermanentError extends Error {}
declare function handleIdempotently(id: string | undefined, body: unknown): Promise<void>;Several operational notes: handle connection and channel errors with reconnect logic (amqplib does not reconnect on its own); one channel per consumer thread of control; never share a channel across concurrent publishers without care; set heartbeats; and keep queues short, because RabbitMQ performance degrades when queues hold millions of messages (use streams for deep backlogs and replay).
RabbitMQ Streams
Streams are append-only, replicated, non-destructive logs inside RabbitMQ, with offset-based consumption and high throughput. They give RabbitMQ a Kafka-like replay and fan-out capability without a separate system. Use them for large fan-out and replay; keep quorum queues for task semantics. Streams have their own client protocol and libraries for the highest throughput; check the current documentation for client support in your language.
RabbitMQ strengths and costs
| Strengths | Costs |
|---|---|
| Flexible routing; priorities; per-message TTL; dead-lettering | Not designed for huge retained backlogs in classic or quorum queues |
| Mature, multi-protocol (AMQP, MQTT, STOMP) | Cluster operations and network partitions need care |
| Excellent for task queues and RPC patterns | Throughput per queue is lower than Kafka partitions |
| Streams add replay | Ordering degrades with competing consumers and redelivery |
SQS and SNS
Core concepts
- SQS Standard: at-least-once, best-effort ordering, nearly unlimited throughput.
- SQS FIFO: exactly-once processing semantic via deduplication (within a window), strict ordering per message group ID, with throughput quotas (a high-throughput mode exists; verify current limits).
- Visibility timeout: when a consumer receives a message, it becomes invisible for N seconds. If not deleted by then, it reappears (redelivery). Set it to comfortably exceed your processing time, and extend it for long jobs.
- Long polling: set
WaitTimeSecondsup to 20 to reduce empty responses and cost. - Redrive policy and DLQ: after
maxReceiveCountreceives, a message moves to the DLQ. A DLQ "redrive" feature moves messages back to the source after a fix. - Retention: up to 14 days.
- Message size: historically 256 KiB, with a larger maximum introduced in 2025 (verify the current limit); for big payloads store the body in S3 and send a pointer.
- Delay queues and message timers: delay delivery up to 15 minutes.
- SNS: pub/sub topics that fan out to SQS queues, Lambda, HTTP endpoints, email, and more, with filter policies so subscribers receive only what they need. SNS FIFO topics preserve ordering into SQS FIFO queues.
+--> SQS "billing-q" (+ DLQ) --> billing workers
Publisher --> SNS ---+--> SQS "search-q" (+ DLQ) --> indexer workers
"order-events" '--> SQS "analytics-q" (+ DLQ) --> Lambda
(filter policies per subscription)This SNS-to-SQS fan-out is the standard AWS pattern: each consumer owns a durable queue with its own retry and DLQ, and slow consumers do not affect others.
Infrastructure (Terraform)
resource "aws_sqs_queue" "billing_dlq" {
name = "billing-dlq"
message_retention_seconds = 1209600 # 14 days
}
resource "aws_sqs_queue" "billing" {
name = "billing"
visibility_timeout_seconds = 60
receive_wait_time_seconds = 20
message_retention_seconds = 345600
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.billing_dlq.arn
maxReceiveCount = 5
})
}
resource "aws_sns_topic" "order_events" {
name = "order-events"
}
resource "aws_sns_topic_subscription" "billing" {
topic_arn = aws_sns_topic.order_events.arn
protocol = "sqs"
endpoint = aws_sqs_queue.billing.arn
raw_message_delivery = true
filter_policy = jsonencode({ type = ["OrderCreated", "OrderPaid"] })
}You also need a queue policy allowing the SNS topic to send to the queue; check the AWS documentation for the exact policy document.
Consumer in TypeScript with partial failure handling
// sqs/consumer.ts
import { SQSClient, ReceiveMessageCommand, DeleteMessageBatchCommand, ChangeMessageVisibilityCommand } from "@aws-sdk/client-sqs";
const sqs = new SQSClient({});
const QUEUE_URL = process.env.QUEUE_URL!;
const CONCURRENCY = 10;
let running = true;
process.on("SIGTERM", () => { running = false; }); // finish the current batch, then exit
async function pollLoop() {
while (running) {
const res = await sqs.send(new ReceiveMessageCommand({
QueueUrl: QUEUE_URL,
MaxNumberOfMessages: CONCURRENCY, // up to 10
WaitTimeSeconds: 20, // long polling
MessageSystemAttributeNames: ["ApproximateReceiveCount"],
}));
const messages = res.Messages ?? [];
if (messages.length === 0) continue;
const results = await Promise.allSettled(messages.map(async (m) => {
await handleIdempotently(m.MessageId!, JSON.parse(m.Body!));
return m;
}));
const toDelete = results.flatMap((r, i) => r.status === "fulfilled" ? [{ Id: String(i), ReceiptHandle: messages[i].ReceiptHandle! }] : []);
if (toDelete.length) await sqs.send(new DeleteMessageBatchCommand({ QueueUrl: QUEUE_URL, Entries: toDelete }));
// Failed messages are NOT deleted: they reappear after the visibility timeout,
// and after maxReceiveCount the redrive policy moves them to the DLQ.
// Optionally apply backoff by raising the visibility timeout per receive count:
await Promise.all(results.flatMap((r, i) => {
if (r.status === "fulfilled") return [];
const count = Number(messages[i].Attributes?.ApproximateReceiveCount ?? 1);
return [sqs.send(new ChangeMessageVisibilityCommand({
QueueUrl: QUEUE_URL,
ReceiptHandle: messages[i].ReceiptHandle!,
VisibilityTimeout: Math.min(900, 30 * 2 ** (count - 1)),
}))];
}));
}
}
pollLoop();
declare function handleIdempotently(id: string, body: unknown): Promise<void>;If you consume with Lambda, enable partial batch responses (ReportBatchItemFailures) so one bad message does not force the whole batch to retry, and set the queue's visibility timeout to at least six times the function timeout (AWS guidance; verify). Lambda's event source mapping also handles scaling, so you configure maximum concurrency rather than writing a poll loop.
SQS strengths and costs
| Strengths | Costs |
|---|---|
| No servers; scales automatically; highly durable | AWS only; no replay; 14 day maximum retention |
| Native DLQ, redrive, delays, FIFO | Standard queues can deliver duplicates and out of order |
| Cheap at modest volume; pairs with Lambda | Priced per request; high volume plus polling costs add up (verify current pricing) |
| SNS gives managed fan-out and filtering | FIFO has throughput quotas and group-based parallelism |
| IAM-based security, KMS encryption | Latency is tens of milliseconds, not microseconds |
For routing between AWS services and SaaS events with rules and schema discovery, also look at Amazon EventBridge, which complements SNS and SQS rather than replacing them.
NATS and JetStream
Core NATS
NATS core is a very fast, lightweight messaging system: subjects (hierarchical names such as orders.created.eu), wildcards (* one token, > the rest), publish and subscribe, queue groups (competing consumers across subscribers), and built-in request/reply with automatic inboxes. Core NATS is at-most-once: if no subscriber is listening or a subscriber is slow, the message is gone. That is a feature for ephemeral signals and RPC, and a limitation for anything that must not be lost.
JetStream
JetStream is the persistence layer built into the NATS server. You define streams that capture messages on given subjects, with configurable storage (file or memory), replication (1, 3, or 5), retention policy, and limits. Consumers read from streams: durable, with acknowledgment policies, redelivery, and filtering.
| Concept | Options |
|---|---|
| Stream retention | limits (by age, size, count), interest (keep while consumers exist), workqueue (delete when acked) |
| Consumer type | Pull (recommended; client controls batch size, natural backpressure) or push |
| Ack policy | explicit (recommended), none, all |
| Redelivery | ack_wait, max_deliver, backoff list |
| Dedup | Nats-Msg-Id header within the stream's duplicate window |
| Delivery | all, last, new, by sequence, or by time (replay) |
Because JetStream supports workqueue retention, per-message ack and redelivery, and also limits retention with replay, it covers both queue and log models in a single, small, easy-to-run server (single binary, clustering built in).
Setup and clients (TypeScript, modular nats.js)
The nats.js client was reorganized into modular packages in its 3.x line; the imports below follow that layout. Verify package names and APIs against the version you install (older versions use a single nats package).
// nats/setup.ts
import { connect } from "@nats-io/transport-node";
import { jetstreamManager, AckPolicy, RetentionPolicy, StorageType } from "@nats-io/jetstream";
const nc = await connect({ servers: "nats://nats:4222" });
const jsm = await jetstreamManager(nc);
await jsm.streams.add({
name: "ORDERS",
subjects: ["orders.>"],
retention: RetentionPolicy.Limits,
storage: StorageType.File,
num_replicas: 3,
max_age: 7 * 24 * 60 * 60 * 1_000_000_000, // 7 days, in nanoseconds
duplicate_window: 2 * 60 * 1_000_000_000, // dedupe window, in nanoseconds
});
await jsm.consumers.add("ORDERS", {
durable_name: "billing",
ack_policy: AckPolicy.Explicit,
filter_subject: "orders.created.>",
ack_wait: 30 * 1_000_000_000,
max_deliver: 5,
backoff: [1e9, 5e9, 30e9, 120e9], // redelivery backoff in nanoseconds
});// nats/publish.ts
import { connect } from "@nats-io/transport-node";
import { jetstream } from "@nats-io/jetstream";
const nc = await connect({ servers: "nats://nats:4222" });
const js = jetstream(nc);
// msgID enables server-side deduplication within the stream's duplicate window
const ack = await js.publish("orders.created.eu", JSON.stringify({ id: "ord_1" }), { msgID: "evt-ord_1-created" });
console.log("stored in", ack.stream, "seq", ack.seq, "duplicate?", ack.duplicate);// nats/consume.ts: pull consumer with explicit ack, nak with delay, and term for poison messages
import { connect } from "@nats-io/transport-node";
import { jetstream } from "@nats-io/jetstream";
const nc = await connect({ servers: "nats://nats:4222" });
const js = jetstream(nc);
const consumer = await js.consumers.get("ORDERS", "billing");
const messages = await consumer.consume({ max_messages: 50 }); // client-side batching and backpressure
for await (const m of messages) {
try {
await handleIdempotently(m.headers?.get("Nats-Msg-Id") ?? String(m.seq), JSON.parse(m.string()));
m.ack();
} catch (err) {
if (err instanceof PermanentError) {
m.term(); // stop redelivery; publish to your own DLQ subject beforehand if needed
} else {
m.nak(5_000); // redeliver in 5 seconds
}
}
}
class PermanentError extends Error {}
declare function handleIdempotently(id: string, body: unknown): Promise<void>;Dead-lettering in JetStream is not a built-in queue. When a message exceeds max_deliver, the server publishes an advisory on a subject like $JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.<stream>.<consumer>. You run a small subscriber that reads that advisory, fetches the original message by stream sequence, and writes it to a DLQ stream. Alternatively, publish to a DLQ subject yourself and term() the message in your handler.
Request/reply, the NATS sweet spot
// Service side: queue group load-balances across instances
import { connect } from "@nats-io/transport-node";
const nc = await connect({ servers: "nats://nats:4222" });
const sub = nc.subscribe("pricing.quote", { queue: "pricing-workers" });
(async () => {
for await (const m of sub) {
const req = m.json<{ sku: string }>();
m.respond(JSON.stringify({ sku: req.sku, priceCents: 1999 }));
}
})();
// Client side: request with a timeout, no reply queue plumbing needed
const reply = await nc.request("pricing.quote", JSON.stringify({ sku: "SKU-1" }), { timeout: 1000 });
console.log(reply.string());NATS strengths and costs
| Strengths | Costs |
|---|---|
| Tiny, fast, easy to operate; single binary | Smaller ecosystem than Kafka and RabbitMQ |
| Request/reply, queue groups, wildcards are first class | JetStream operations (replication, limits, cluster sizing) still need care |
| JetStream adds persistence, replay, work queues | No native DLQ (build with advisories) |
| Leaf nodes and superclusters suit edge and multi-region | Stream processing ecosystem is thin compared with Kafka |
| Good for IoT and service meshes | Per-subject streams can surprise people used to topic-partition models |
Redis Streams
Core concepts
Redis Streams (XADD, XREAD, XREADGROUP, XACK, and friends) are an append-only log inside Redis, with IDs that combine a millisecond timestamp and a sequence, consumer groups with a pending entries list (PEL) tracking delivered but unacknowledged messages, and commands to claim stale messages from crashed consumers (XAUTOCLAIM).
Durability depends on your Redis configuration: persistence (AOF with an appropriate fsync policy, RDB snapshots), replication (asynchronous by default, so a failover can lose recent writes), and memory limits. It is a good fit for modest-volume streams where Redis is already part of the architecture, and a poor one for durable, huge, long-retention event logs.
A licensing note: Redis changed its license in 2024 and again added an open source option (AGPL) with Redis 8; the Valkey project (a Linux Foundation fork) is a common alternative that supports the same stream commands. Check which server your platform provides and its license terms.
Python example with consumer groups, claim, and DLQ
# redis_streams/worker.py
import json
import time
import redis
r = redis.Redis(host="redis", port=6379, decode_responses=True)
STREAM = "orders"
GROUP = "billing"
CONSUMER = "worker-1"
DLQ_STREAM = "orders:dlq"
MAX_DELIVERIES = 5
IDLE_RECLAIM_MS = 60_000
# Create the group once (id "0" = from the beginning; "$" = only new messages)
try:
r.xgroup_create(STREAM, GROUP, id="0", mkstream=True)
except redis.ResponseError as e:
if "BUSYGROUP" not in str(e):
raise
def process(fields: dict) -> None:
payload = json.loads(fields["data"])
# Idempotent side effect keyed on the message id or a business id goes here
...
def delivery_count(msg_id: str) -> int:
# XPENDING with a one-id range returns [message_id, consumer, idle_ms, times_delivered]
rows = r.xpending_range(STREAM, GROUP, min=msg_id, max=msg_id, count=1)
return rows[0]["times_delivered"] if rows else 1
def handle(msg_id: str, fields: dict) -> None:
try:
process(fields)
r.xack(STREAM, GROUP, msg_id)
except Exception as exc: # narrow this to your transient error types in real code
if delivery_count(msg_id) >= MAX_DELIVERIES:
r.xadd(DLQ_STREAM, {**fields, "error": str(exc), "origin_id": msg_id})
r.xack(STREAM, GROUP, msg_id) # remove from the pending list
# else: leave it pending; it will be reclaimed after IDLE_RECLAIM_MS
def main() -> None:
while True:
# 1) Reclaim messages stuck with dead or slow consumers
_next, claimed, _deleted = r.xautoclaim(STREAM, GROUP, CONSUMER, min_idle_time=IDLE_RECLAIM_MS, start_id="0-0", count=20)
for msg_id, fields in claimed:
handle(msg_id, fields)
# 2) Read new messages; block up to 5s; bounded batch is the backpressure
resp = r.xreadgroup(GROUP, CONSUMER, {STREAM: ">"}, count=20, block=5000)
for _stream, entries in resp or []:
for msg_id, fields in entries:
handle(msg_id, fields)
if __name__ == "__main__":
main()# redis_streams/producer.py
import json
import redis
r = redis.Redis(host="redis", port=6379, decode_responses=True)
# MAXLEN with ~ trims approximately and efficiently; size it to your retention needs
r.xadd("orders", {"data": json.dumps({"type": "OrderCreated", "id": "ord_1"})}, maxlen=1_000_000, approximate=True)Operational notes: trim streams (MAXLEN or MINID) or memory will grow without bound; unacknowledged messages stay in the PEL forever unless claimed or acked; use WAIT or a replicated, persistent deployment if loss on failover is unacceptable; and note that a Redis Cluster stores each stream on one shard (one key), so a single stream does not scale horizontally (shard by splitting into several streams).
Redis Streams strengths and costs
| Strengths | Costs |
|---|---|
| Very simple if you already run Redis; low latency | Memory bound; durability depends on your setup |
| Consumer groups, acks, claim give queue semantics | No built-in DLQ or per-message delay |
| Easy to operate and inspect with redis-cli | A single stream is a single key, so no partition-style horizontal scaling |
| Good for moderate event volumes and internal pipelines | Not meant for large, long-retention logs |
Cross-cutting concerns
Retries, backoff and dead-letter queues
The rules apply to every broker:
- Classify errors. Transient (timeouts, 503s, deadlocks) retry; permanent (validation, missing referenced data that will never appear, schema mismatch) go to the DLQ immediately. Retrying a permanent error just delays the inevitable and burns capacity.
- Use exponential backoff with jitter. Fixed delays create synchronized retry storms.
- Bound attempts. Five to ten attempts is typical. Beyond that, dead-letter.
- Keep the DLQ observable. Alert on DLQ depth greater than zero, store the error and origin metadata, and provide a tested redrive tool that replays messages after a fix.
- Do not block the main flow. In log systems, move failing messages to a retry or DLQ topic and commit the offset; in queue systems, rely on visibility timeouts or
nackwith delays. - Beware of retry amplification. If a downstream is down and each of five layers retries five times, one failure becomes 3,125 calls. Retry at one layer, and use circuit breakers.
| Broker | Native retry | Native DLQ | Delay support |
|---|---|---|---|
| Kafka | No | No (retry and DLQ topics) | Pattern: delay topics |
| RabbitMQ | nack/requeue, delivery limit on quorum queues | Yes (dead-letter exchange) | TTL plus DLX pattern, or plugin (verify) |
| SQS | Visibility timeout and redelivery | Yes (redrive policy) | Per-queue and per-message delay up to 15 minutes |
| NATS JetStream | nak with delay, ack_wait, backoff list | Via advisories (build your own) | nak delay and backoff |
| Redis Streams | PEL plus XAUTOCLAIM | No (separate stream) | Application level |
Idempotency
The delivery guarantees section showed the dedupe-table approach. Alternatives: naturally idempotent operations (set a value, upsert by key), conditional writes with version checks, and unique constraints on business identifiers (one invoice per order). Choose message IDs carefully: use a stable ID created at the source (the event ID in the outbox row), not the broker's per-delivery ID, so that a re-published message is recognized. For the producer side, atomically combine the state change and the event with the transactional outbox; that story, including relays and CDC, is covered in event-driven architecture, outbox and idempotency.
Backpressure and concurrency control
A consumer that takes everything the broker offers will fall over. Bound the work in flight:
| Broker | Backpressure knob |
|---|---|
| Kafka | max.poll.records, partitionsConsumedConcurrently, pausing and resuming partitions, and fetch size settings |
| RabbitMQ | prefetch (QoS), consumer count |
| SQS | MaxNumberOfMessages, number of concurrent pollers, Lambda maximum concurrency |
| NATS JetStream | Pull consumer batch size, max_ack_pending, max_messages |
| Redis Streams | COUNT per read, number of consumers |
Also bound downstream pressure: a worker pool with a semaphore sized to the database connection pool or the third-party rate limit. If the downstream is slow, the correct behavior is for messages to wait in the broker, not for consumers to pile up unbounded in-memory queues. Autoscale consumers on lag or queue depth (KEDA supports scalers for Kafka, RabbitMQ, SQS, and others), but remember that autoscaling above the partition count in Kafka does nothing.
Poison messages
A message that crashes the consumer every time is a poison message. Symptoms: a Kafka partition stuck at one offset with lag climbing, an SQS message cycling until maxReceiveCount, a RabbitMQ message requeueing in a hot loop. Defenses: catch exceptions per message, limit attempts, dead-letter, and make the deserializer failure path explicit (do not crash the consumer on an invalid payload; park it).
Message design
- Envelope: include
id,type,version,occurredAt,source,correlationId, andtraceparentfor distributed tracing. The CloudEvents specification standardizes such an envelope. - Payload size: keep messages small; store large blobs in object storage and send references (the claim check pattern).
- Events versus commands: events are facts in the past tense (
OrderPaid), commands are requests (SendReceipt). Commands usually go to queues with one consumer, events to topics with many. - Thin versus fat events: thin events (IDs only) force consumers to call back; fat events carry state and reduce coupling to the producer's API but must be versioned carefully.
- Never put secrets or unnecessary personal data in messages, as retention and replay multiply the exposure. Encrypt sensitive fields when you must carry them.
Monitoring: lag, depth, and age
The single most important health signal for any messaging system is: are consumers keeping up? Measure it in terms of lag and age, not only throughput.
| Broker | Primary signals | How to get them |
|---|---|---|
| Kafka | Consumer group lag per partition, produce and fetch rates, under-replicated partitions, request latency, ISR shrinks, rebalance frequency | kafka-consumer-groups.sh --describe, JMX metrics, exporters such as kafka_exporter and Burrow-style lag evaluators, managed service dashboards |
| RabbitMQ | Ready and unacked messages per queue, consumer count, publish and ack rates, memory and disk alarms, quorum queue health | Built-in Prometheus plugin, management UI |
| SQS | ApproximateNumberOfMessagesVisible, ApproximateAgeOfOldestMessage, DLQ message count, NumberOfMessagesDeleted versus sent | CloudWatch |
| NATS JetStream | Consumer num_pending, num_ack_pending, redeliveries, stream size, cluster health | nats consumer info, Prometheus exporter |
| Redis Streams | Stream length, pending count per group, idle time of oldest pending, consumer lag fields in XINFO GROUPS (recent versions) | XINFO STREAM, XINFO GROUPS, XPENDING, exporters |
# Kafka: per-partition lag for a group
kafka-consumer-groups.sh --bootstrap-server broker:9092 --describe --group billing-v1
# GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
# RabbitMQ: queues sorted by backlog
rabbitmqctl list_queues name messages_ready messages_unacknowledged consumers
# NATS: consumer state
nats consumer info ORDERS billing
# SQS: backlog and oldest message age
aws sqs get-queue-attributes --queue-url "$QUEUE_URL" \
--attribute-names ApproximateNumberOfMessagesVisible ApproximateNumberOfMessagesNotVisible
# Redis: pending summary for a group
redis-cli XPENDING orders billingWhat to alert on
| Alert | Why | Typical threshold |
|---|---|---|
| Consumer lag or backlog growing for N minutes | Consumers are slower than producers, or stuck | Based on SLO: lag expressed as time, not only count |
| Age of oldest message above X | Directly measures delay experienced by users | Your end-to-end latency budget |
| DLQ depth greater than zero | Messages are failing permanently | Any non-zero, with a ticket and runbook |
| Consumer count at zero | Nobody is processing | Immediate |
| Redelivery or retry rate spike | A dependency is failing | Relative to baseline |
| Under-replicated partitions or quorum loss | Durability at risk | Any |
| Broker disk, memory, or file descriptor pressure | Impending outage | 80 percent |
| Rebalance frequency (Kafka) | Unstable consumers | More than a few per hour |
Express lag in time wherever possible ("the billing consumer is 14 minutes behind") because it maps to user impact and to an SLO. Propagate a trace context in message headers so you can follow a request from the HTTP handler through the broker to the consumer in your tracing system (OpenTelemetry messaging semantic conventions describe the attributes).
Cost and operations
| System | Cost drivers | Operational load | Notes |
|---|---|---|---|
| Kafka (self-managed) | Broker instances, local or network storage with replication factor 3, cross-AZ replication traffic, engineering time | High: capacity planning, upgrades, partition rebalancing, monitoring, security | Tiered storage can reduce disk cost; verify availability in your version or vendor |
| Kafka (managed: MSK, Confluent Cloud, Redpanda Cloud, Aiven, others) | Throughput, storage, partitions, network egress and cross-AZ traffic, connectors | Moderate | Easy to over-provision; networking charges often surprise |
| RabbitMQ | Instances (3 for quorum), storage, engineering time | Moderate | Managed options remove most of it |
| SQS and SNS | Per request, per payload chunk, data transfer | Near zero | Long polling and batching cut request counts; cost grows with polling inefficiency |
| NATS | Small instances (3 for JetStream clusters), storage | Low to moderate | Efficient on resources |
| Redis Streams | Memory (the dominant factor), replicas | Low if Redis is already run | Memory is expensive per GB compared with disk |
Cost control habits: batch on both ends (producers and consumers), compress payloads, set retention to what you genuinely need, store large bodies in object storage, delete unused topics and queues, right-size partition counts (each partition has overhead), and keep traffic inside one availability zone where design allows (for example Kafka rack-aware fetching from follower replicas, in versions that support it). Check current provider pricing pages instead of trusting estimates, since pricing models change.
Security basics
Encrypt in transit (TLS everywhere, mTLS between services where possible), authenticate clients (SASL or mTLS for Kafka, per-user credentials and vhosts for RabbitMQ, IAM for SQS and SNS, accounts and JWTs for NATS, ACLs for Redis), authorize per topic, queue, or subject with least privilege, encrypt at rest, restrict who can read DLQs (they contain real data), and never expose a broker's admin interface to the internet.
Decision tree
Do you need to REPLAY history or have many independent consumers of the same data?
|-- YES --> Throughput above ~100k msgs/s or stream processing needed?
| |-- YES --> Kafka (or Redpanda / managed Kafka)
| '-- NO ---> Already on NATS? JetStream. Already on RabbitMQ? Streams.
| Already on Redis and volume modest? Redis Streams.
| Otherwise: managed Kafka is still the safe default.
'-- NO --> Is it background work (jobs) with retries, delays, DLQ?
|-- YES --> On AWS and want zero ops? SQS.
| Need priorities / complex routing / self-hosted? RabbitMQ.
| Want scheduling UI and unique jobs? A job library over Redis or Postgres.
'-- NO --> Is it request/reply or very low latency service messaging?
|-- YES --> NATS (core), or RabbitMQ with reply-to.
'-- NO --> Is it fan-out notification to several services?
|-- On AWS --> SNS to SQS (add EventBridge for rules).
|-- Elsewhere --> RabbitMQ topic exchange or NATS subjects
| (JetStream if durability is required).
'-- Devices at the edge --> MQTT broker bridged to your backbone.Questions to settle before choosing
- What is the peak and average message rate, and the message size?
- Do you need replay, or is "done is done" acceptable?
- What ordering do you need, and what is the ordering key?
- How many independent consumer applications will read the same events?
- What latency is acceptable end to end?
- What is your tolerance for loss and for duplicates?
- Who will operate it, and what is their experience?
- What is the retention requirement (including compliance)?
- Which cloud and compliance constraints apply?
- What happens when a consumer is down for a day?
Lab: build and break a reliable consumer
Time: about 90 minutes. Use whichever broker you intend to adopt; the exercise is the same. The steps use RabbitMQ locally, and map directly to the other brokers.
Step 1: start a broker.
docker run -d --name rabbit -p 5672:5672 -p 15672:15672 rabbitmq:4-managementStep 2: create topology with a main quorum queue, a retry queue with a 10 second TTL, and a DLQ (see the RabbitMQ section).
Step 3: write a producer that publishes 1,000 messages with stable messageId values, 5 percent of which carry "poison": true.
Step 4: write a consumer with prefetch(10), an idempotency table in SQLite or Postgres, retry on transient errors (simulate a random 20 percent failure), and DLQ routing on poison messages.
Step 5: verify the invariants.
- Every message ID appears in the processed table at most once, even though some were delivered multiple times.
- All poison messages ended in the DLQ, and none cycled forever.
- Killing the consumer with
kill -9mid-run does not lose any message (restart and count).
Step 6: apply backpressure. Make the handler sleep 500 ms and observe messages_unacknowledged plateau at the prefetch value, not climb.
Step 7: observe and alert. Watch queue depth and DLQ count in the management UI; write down the alert thresholds you would set.
Step 8: practice redrive. Fix the bug that made messages "poison", then move DLQ messages back to the main queue and verify they process.
Production readiness checklist
- Delivery semantics documented per flow; consumers are idempotent with a stable message ID.
- Producers use confirmations (acks all, publisher confirms, or
PubAck) and the transactional outbox for DB-coupled events. - Ordering key chosen deliberately; hot-key behavior understood.
- Retry with backoff and jitter, bounded attempts, error classification, and a DLQ with a tested redrive tool.
- Backpressure configured (prefetch, batch size, concurrency) and aligned with downstream limits.
- Schemas versioned with compatibility checks in CI (registry, Protobuf with
buf, or JSON Schema). - Lag, age, backlog, DLQ, and consumer-count alerts exist with runbooks.
- Retention, capacity, and partition counts sized and reviewed; storage alarms set.
- TLS, authentication, and least-privilege authorization configured; DLQ access restricted.
- Graceful shutdown on SIGTERM (finish or release in-flight messages) and a tested restart.
- Failure drills done: broker restart, consumer crash, poison message, downstream outage, backlog of a day's size.
- Trace context propagated through message headers.
Migration notes
Moving between brokers
Migrations are safest as dual-run with idempotent consumers.
- Abstract the transport. Put publish and consume behind a small interface in your code (
publish(event),subscribe(topic, handler)), with business logic outside. - Dual publish via the outbox. The outbox relay writes each event to both the old and new broker. Because the outbox is the source of truth, you do not get partial dual writes.
- Consume on the new broker in shadow mode. Run new consumers that process into a shadow store, and compare results with the old path.
- Cut over consumers per group, gated by a feature flag, once the shadow comparison matches. Idempotency keys make overlap safe.
- Stop the old publish path, drain the old broker, and decommission.
Specific paths
| From | To | Notes |
|---|---|---|
| RabbitMQ to Kafka | Map exchanges and routing keys to topics and keys; replace per-message retry with retry topics; replace priorities and TTL features by redesign; accept the loss of per-message acknowledgment semantics | Do this when you need replay and many consumers; not when you merely feel Kafka is "more serious" |
| Kafka to RabbitMQ or SQS | Typically when you discover you only used Kafka as a job queue | Drop partition ordering assumptions consciously; use FIFO or message groups only where needed |
| SQS to Kafka | Use the SNS and SQS fan-out as the bridge; consume SQS and publish to Kafka via a connector or a relay while consumers migrate | Watch for ordering assumptions you never had |
| Self-managed Kafka to managed Kafka or Redpanda | Mirror topics (MirrorMaker 2 or cluster-linking features), then move consumers, then producers | Preserve offsets with offset translation tools, or replay |
| Kafka ZooKeeper cluster to 4.x | Move to KRaft on a 3.x release using the documented migration, then upgrade to 4.x | Plan a rollback point; test in staging |
| Redis lists or Pub/Sub to Redis Streams | Streams add persistence and consumer groups; dual-write during transition | Check memory and trimming policy first |
| Redis Streams to a "real" broker | When volume or durability outgrows Redis | Replace consumer groups with the target's groups; port idempotency logic unchanged |
| NATS core to JetStream | Create streams capturing existing subjects; move critical flows to durable consumers; keep core for RPC | Subjects stay the same, which makes the move gentle |
Change safety rules
- Never change a topic's partition count blindly when ordering matters; create a new topic and migrate.
- Version event types and topics deliberately; keep consumers tolerant of unknown fields.
- Test restore and replay paths, not only the happy path.
Where this usually goes wrong
- Assuming exactly-once end to end. It ends at the broker's boundary. Make consumers idempotent.
- Using Kafka as a job queue. No per-message retries, delays, or priorities; one poison message blocks a partition.
- Using a queue where you need replay. When a new consumer needs last month's events, a deleted-on-ack queue cannot help.
- Adding consumers beyond the partition count. Extra consumers sit idle.
- Acking before processing. A crash then loses the message. Ack after the side effect commits.
- No DLQ, or a DLQ nobody watches. Failed messages disappear silently.
- Retrying permanent errors forever or without backoff and jitter, which creates retry storms.
- Visibility timeout shorter than processing time (SQS). The message becomes visible again while still being processed, producing duplicates.
- Unbounded prefetch or batch sizes. Memory blowups and head-of-line blocking.
- Dual writes (database then broker) without an outbox. Crashes between the two produce phantom or missing events.
- Ignoring schema evolution. A producer deploy breaks every consumer; use a registry or contract tests.
- Hot partition keys. One tenant overloads one partition while others idle.
- Long processing inside Kafka poll loops. Exceeding
max.poll.interval.mstriggers rebalances and duplicates. - Treating Redis Streams as infinitely durable. Without persistence and trimming, you lose data or memory.
- Monitoring broker CPU but not lag. Everything looks green while consumers are hours behind.
- Choosing for scale you do not have. A Kafka cluster for 50 messages a second is a lot of operational debt for little gain.
When NOT to use a message broker
- A synchronous request needs an immediate answer. Use a direct call (HTTP or gRPC). Messaging adds latency, failure modes, and complexity. (Request/reply over NATS is an exception because that is its designed role.)
- You have a single service and a database. A database-backed job table or a library such as a Postgres-based queue (using
SELECT ... FOR UPDATE SKIP LOCKED) gives you transactional enqueue with no new infrastructure. Move to a broker when you need fan-out, replay at scale, or throughput beyond what the database comfortably handles. - You need strict global ordering at high throughput. No broker gives it; redesign the ordering requirement.
- The "events" are really queries. If a service needs another service's data to render a page, do not replace a read with a message dance; consider a read model, cache, or API call.
- Your team cannot operate it. A broker is a production dependency that needs upgrades, monitoring, and on-call. If you cannot staff that, use a managed service or avoid it.
- Workflows with long-lived state and human steps. A workflow engine (Temporal, Step Functions, and similar) models retries, timers, and compensation better than hand-rolled choreography.
- Tiny scale. Cron plus a table can be the right answer.
Common questions
Is Kafka overkill for most teams? Often, yes, for pure job queues. It is the right tool for event streaming and replay at scale. If you only need background jobs, SQS, RabbitMQ, or a job library are simpler and cheaper to run.
RabbitMQ Streams or Kafka? Streams cover many replay and fan-out needs inside RabbitMQ, with a simpler footprint. Kafka wins on ecosystem (Connect, Streams, Flink, CDC tooling), very large scale, and stream processing.
What is the difference between SNS and EventBridge? SNS is high-throughput pub/sub fan-out with simple filtering; EventBridge is an event bus with richer content-based rules, schema registry, SaaS integrations, and archive and replay, at lower throughput and different pricing. They are often combined with SQS.
How many partitions should I create? Enough to cover your target consumer parallelism with headroom (for example a multiple of the expected consumer count), but not thousands per topic without reason; each partition adds overhead in metadata, file handles, and recovery time. Plan for growth because increasing the count later changes key placement.
How do I guarantee ordering with retries? You mostly cannot with parallel retries. Options: retry in place for the same key before moving on (blocking that key only), route all of a key's messages through one worker, or design handlers to be order-insensitive using version numbers and last-writer-wins checks.
What about MQTT, Pulsar, Redpanda, and others? MQTT is the standard for constrained devices and is usually bridged into a backbone broker. Pulsar offers segment-based storage with multi-tenancy and both queue and stream semantics, with a larger operational footprint. Redpanda is Kafka API compatible with a different implementation. Evaluate them against the same questions as in the decision tree above.
Links worth keeping
- Apache Kafka documentation
- Kafka 4.0 release announcement
- Confluent Schema Registry documentation
- RabbitMQ documentation
- RabbitMQ: quorum queues and streams
- RabbitMQ vs Apache Kafka (official comparison)
- Amazon SQS Developer Guide
- Amazon SNS Developer Guide
- NATS documentation and JetStream concepts
- Redis Streams documentation
- Valkey
- CloudEvents specification
- OpenTelemetry messaging semantic conventions
- KEDA scalers
- Related on this site: event-driven architecture, outbox and idempotency