Skip to content

Broker Comparison & Decision Guide ​

"Many systems claim to provide “exactly-once” delivery semantics, but it is important to read the fine print, because sometimes these claims are misleading (i.e. they don’t translate to the case where consumers or producers can fail, cases where there are multiple consumer processes, or cases where data written to disk can be lost)." — Apache Kafka documentation, Design, "Message Delivery Semantics" (4.2)

Summary: one side-by-side matrix of RabbitMQ, Kafka and Redis Streams (plus NATS JetStream, Pulsar, SQS/SNS, Google Pub/Sub and Laravel's database/SQS drivers), and a decision guide built on it. Focus: choosing, migrating and keeping the choice reversible, not how any broker works inside. Learning goal: after this page you can pick a broker for a workload in five minutes, defend it with the matrix, name the anti-decisions, and put a Publisher/Consumer seam in your code so the choice can change.

This is the decision page of the Brokers group. It does not re-teach internals: RabbitMQ, Kafka and Redis Streams & Pub/Sub are the three deep dives, and other brokers surveys NATS JetStream, Pulsar, SQS/SNS and Google Pub/Sub. Every cell below is one clause; follow the link in the row's theme for the mechanism.

Page map ​

If you are looking forGo to
"Which broker for my workload?" in one minuteEverything in one minute, Decision tables
The 40-row side-by-side matrixThe comparison matrix
NATS, Pulsar, SQS/SNS, Pub/Sub, Laravel database/SQS columnsThe other columns
Why a comparison is hard to trustWhy comparisons mislead
Moving from Redis to RabbitMQ to Kafka, or running twoMigration and coexistence
Self-host versus managed costCost model sketch
"Do I even need a broker in Laravel?"The Laravel question
What not to doAnti-decisions
One interface, three adapters (Go and Laravel)Go, Laravel
How each broker proves "accepted, delivered, processed"Broker differences
Monolith to multi-regionIn architecture
A comparison lab (expected, not run)Lab

Everything in one minute ​

Table 1: philosophy. Each broker answers a different question first.

RabbitMQKafkaRedis Streams
Core ideaSmart broker routes messages to queues; a message is removed when ackedA partitioned, replicated, append-only log; the consumer owns a positionAn append-only log inside Redis with consumer groups
Best atTasks, commands, routing, retries, delay, request/replyEvent log, replay, many readers, stream processing, high volumeSmall, fast, in-stack streams where Redis already runs
Weakest atLong retention and replay of millions of events (use its streams)Per-message retry, delay, priorities, small low-volume setupsDurability by default, datasets bigger than RAM
You operateA broker clusterA broker cluster with partitions, retention, rebalancesRedis plus persistence and failover you configure

Table 2: workload to first pick.

WorkloadFirst pickWhy
Background tasks inside one Laravel appLaravel database or redis driverNo new infrastructure
Task queue with retries, priorities, delay, DLQ across servicesRabbitMQ (quorum queues)Built-in DLX, delivery limit, priorities, routing
Event bus many teams subscribe toKafka (or Pulsar)Independent consumer groups, retention
Event log you replayKafka, RabbitMQ streams, NATS JetStream, PulsarNon-destructive reads
Stream processing (joins, windows)KafkaKafka Streams / Flink ecosystem (stream processing)
Request/replyRabbitMQ or NATSReply-to and correlation are first-class (request-reply)
IoT / MQTT devicesRabbitMQ (MQTT plugin), NATS, or a managed IoT hubProtocol support
Cross-region fan-outPulsar geo-replication, Kafka mirroring, SNS/SQS, Pub/SubReplication across regions is a feature, not a script
ServerlessSQS/SNS (AWS), Pub/Sub (GCP)Managed, scale to zero, triggers

Table 3: five questions that decide most cases.

QuestionIf yesIf no
Must a new consumer read history?Log: Kafka, Pulsar, JetStream, RabbitMQ streamsQueue: RabbitMQ, SQS
Does one slow message have to be retried alone, later?Queue with per-message ack and DLQLog is fine
Is peak above roughly 10,000 messages/s sustained?Log with partitionsAnything works; pick by ops
Do you already run it and trust its persistence?Use it firstDo not add it for one feature
Is a managed service acceptable?Compare managed prices (cost model)Count operator time honestly

Why comparisons mislead ​

In plain words: "RabbitMQ vs Kafka" posts compare a post office with a library. One hands each letter to one person and forgets it; the other keeps every letter on a shelf and lets anyone read from any point.

Common misunderstanding: "There is a fastest broker." Throughput depends on message size, batching, acks, replication, fsync and the client. A number without those is advertising.

The line also moves. CloudAMQP's comparison, which is vendor opinion (it sells RabbitMQ hosting), was updated on 7 November 2026 and says: "Both now cover some of what the other does: RabbitMQ has streams for replay, and Kafka has share groups for queue-style work." The Kafka 4.2 design page confirms the Kafka half: share groups "offer an alternative to consumer groups, particularly when applications require finer-grained sharing of partitions and records". Confluent's overview (also a vendor) states "RabbitMQ messages are stored in memory, while Kafka messages are stored on disk"; RabbitMQ's own guide says a persistent message routed to a durable queue is confirmed after "persisting to disk". Use vendor pages for use-case lists and check facts against primary docs. Rules used on this page:

RuleConsequence
Facts (limits, defaults, protocol names) come from the product's own docs and are datedCells name the version where it matters
Throughput and latency are classes, never numbersBenchmark your payload before it decides anything (lab)
A feature that needs a plugin or a paid tier is named as such"Plugin" and "managed only" appear in cells
Anything not read from a primary source is marked "check"Google's Pub/Sub quota pages refuse automated fetches, so its size figure is flagged

Mechanics: the comparison matrix ​

Three brokers, forty rows. Rows are grouped: model (1–5), guarantees (6–13), consumption and routing (14–21), retention and size (22–28), platform (29–40). Read a row, then follow the link for the mechanism.

Table A: RabbitMQ, Kafka, Redis Streams Must-know ​

#DimensionRabbitMQKafkaRedis Streams
1ModelExchanges route to queues; queue types: classic, quorum, streamTopic of partitions, each an append-only logStream key (a log) with consumer groups
2Storage structurePer-queue message store; streams are a logSegment files per partitionIn-memory radix tree, persisted by AOF/RDB
3Unit of consumptionOne delivery, acked individuallyA record at an offset; commit moves a positionOne entry, acked individually in the group's pending list
4Ordering scopePer queue (single consumer); competing consumers and requeue can reorderPer partitionPer stream
5Ordering key storySingle active consumer or consistent-hash exchangePartition keyOne stream per key, or one stream
6Default delivery guaranteeAt-least-once with publisher confirms and manual ackAt-least-once (idempotent producer removes producer-retry duplicates)At-least-once via group pending list
7Exactly-once storyNone end to end; idempotent consumersTransactions give it inside Kafka; external effects need idempotencyNone; idempotent consumers (Redis 8.6 adds idempotent production, check your version)
8"Accepted" signalPublisher confirm (plus mandatory return)Produce callback with partition and offset (acks=all)XADD reply with entry id
9"Processed" signalbasic.ackCommitted offset (position)XACK
10PersistencePersistent messages in durable queues; quorum and stream queues always replicatedAlways on disk; flush policy is OS-driven by defaultOff by default unless AOF/RDB configured
11Durability knobQuorum queue (majority), confirmsacks=all, min.insync.replicas, replication factorAOF appendfsync, WAIT
12ReplicationRaft-based quorum queues; streams replicatedLeader and follower per partition, ISRAsynchronous primary/replica
13FailoverQuorum leader electionLeader election per partition (KRaft controller)Sentinel or Cluster promote a replica; can lose acked writes
14Consumer modelPush (basic.consume) with prefetch, or pull (basic.get)Pull with fetch batchesPull with blocking XREADGROUP
15Parallelism limitMany consumers per queueConsumers per group up to partition count (share groups lift it)Many consumers per group
16Fan-outBind several queues to an exchangeSeveral consumer groups on one topicSeveral groups on one stream
17RoutingDirect, topic, fanout, headers exchangesTopic and key onlyStream name only
18PrioritiesClassic and quorum queues support themNoneNone
19Delay / schedulingQuorum queues since 4.4 (x-opt-delivery-time); TTL + DLX earlierNone built inNone built in (sorted set pattern)
20RetryRequeue, delivery limit (default 20 on quorum queues since 4.0), DLX loopsClient side: retry topicsClient side: XPENDING + XAUTOCLAIM
21DLQBuilt in (DLX, at-least-once dead-lettering on quorum)Convention: a dead-letter topic you produce toConvention: another stream
22RetentionQueues: until acked or TTL; streams: size/ageTime/size, or compaction by key; tiered storage for old segmentsUntil trimmed (MAXLEN, MINID); bounded by RAM
23ReplayStreams onlyYes, seek to any offsetYes, read from any id
24Key compactionNoYes (cleanup.policy=compact)No
25Message sizemax_message_size default 16 MiB, max 512 MiB (config doc)max.message.bytes default 1048588Entry is a hash of fields; keep small, RAM-bound
26Throughput classMedium (per-message bookkeeping)High (batched sequential I/O)Medium to high, memory-bound
27Latency classLowLow to medium (batching adds latency)Lowest
28BackpressureConsumer prefetch, publisher flow control, memory alarmsConsumer pulls at its pace; broker quotasNone built in; trim policy and XLEN monitoring
29Multi-tenancyVirtual hosts with per-vhost permissionsTopics, ACLs, client quotasKey prefixes, ACLs, logical DBs (not in Cluster)
30ProtocolsAMQP 0-9-1, AMQP 1.0, MQTT 5.0 (plugin), STOMP, streams protocolKafka protocol (plus HTTP REST proxies as add-ons)RESP
31Schema supportNone built in (content-type header)Not in Apache Kafka; Confluent Schema Registry or ApicurioNone
32TransactionsAMQP tx.select on a channel (slow)Producer transactions and read_committed (KIP-98)MULTI/EXEC, Lua scripts
33Ops complexityMedium: cluster, queue types, memory/disk alarmsHigh: partitions, retention, rebalances, controller quorumLow if Redis already runs; failover is yours
34Scaling outMore queues and nodes; a single queue lives on its replicasAdd partitions and brokersCluster shards by key; one stream is on one shard
35Hosting optionsSelf-host, CloudAMQP, Amazon MQ, Kubernetes operatorSelf-host, Confluent Cloud, Amazon MSK, AivenSelf-host, Redis Cloud, ElastiCache, Memorystore
36LicensingApache 2.0 and MPL 2.0 (open source)Apache 2.0Check the license of your Redis version; Valkey is the BSD fork
37Laravel supportPackage vladimir-yuldashev/laravel-queue-rabbitmqPackage mateusjunges/laravel-kafka (needs ext-rdkafka)Redis facade; built-in redis driver uses lists, not streams
38Go client maturityamqp091-go (official RabbitMQ team)franz-go (pure Go, active), kafka-gogo-redis (mature, typed)
39ObservabilityManagement UI, Prometheus plugin, queue depth, unackedConsumer lag per partition, JMX metricsXINFO, XPENDING, INFO
40SecurityTLS, SASL, per-vhost configure/write/read permissionsTLS, SASL (PLAIN, SCRAM, GSSAPI, OAUTHBEARER), ACLsTLS, ACLs, AUTH

Rows 6–13 are unpacked in delivery guarantees and acknowledgment; 4–5 in ordering; 14–15 in competing consumers; 17–18 in routing; 19–21 in retry and delay and DLQ; 28 in backpressure; 31 in schema evolution; 39 in observability; 40 in security.

RoutingReplayThroughputLatencyOps easeDelay/DLQRabbitMQKafkaRedis Streams1 = weak, 5 = strongJudgement, not a benchmark

The radar condenses six axes of the matrix into a shape. It is a judgement from the table above, not a benchmark: RabbitMQ is wide on routing and delay/DLQ, Kafka is tall on replay and throughput, Redis Streams is strongest on latency and ease.

The other columns Important ​

Brief on purpose; details are in other brokers. "Check" marks a figure not read from a primary source here.

#DimensionNATS JetStreamPulsarSQS / SNSGoogle Pub/SubLaravel database / sqs drivers
1ModelStreams capture subjects; consumers read themTopics with subscriptions; segment storageSQS queue; SNS topic fans out to queuesTopic and subscriptionsA jobs table; an SQS queue
2OrderingPer streamPer partition (Key_Shared per key)SQS FIFO per message group; Standard best effortPer ordering key when enabledTable: by id, not guaranteed; SQS Standard unordered
3DeliveryAt-least-once with ack; Nats-Msg-Id dedup windowAt-least-once; transactionsStandard at-least-once; FIFO dedupAt-least-once; exactly-once delivery option per subscriptionAt-least-once (lock then delete)
4Persistence and replicationFile or memory storage; replicated in a clusterBookKeeper, replicatedManaged, multi-AZManaged, regionalYour database; SQS managed
5Consumer modelPull and push consumers; AckExplicit, AckAll, AckNoneExclusive, Failover, Shared, Key_Shared subscriptionsPoll with visibility timeout (default 30 s, max 12 h)Pull, push, streaming pull; ack deadlineWorker polls (queue:work)
6RoutingSubject wildcardsTopics, topic patternsSNS filter policies to SQSSubscription filtersNamed queues, priority order
7DelayNot a core feature (check)Delayed delivery on Shared subscriptionsSQS delay up to 15 minNot a core feature (check)Laravel delay(); SQS capped at 15 min
8DLQMaxDeliver and advisoriesRetry letter and dead letter topicsRedrive policyDead-letter topicfailed_jobs table
9Retention and replayLimits, work queue or interest policies; replayRetention plus tiered storage; seekSQS: 4 days default, 60 s to 14 days, no replayDefault 7 days, up to 31 days; seek needs retained acked messagesUntil processed; no replay
10Message sizemax_payload default 1 MB (config up to 64 MB)Default 5 MB1 MiB (larger via S3 extended client, up to 2 GB)Check the quotas pageRow size / 1 MiB
11ThroughputHigh, small messagesHighStandard: very high; FIFO: 300 TPS per partition per API (higher with high-throughput mode)High, autoscalingLow to medium
12Multi-tenancyAccountsTenants and namespaces (first class)AWS accounts and IAMProjects and IAMApplication level
13ProtocolsNATS protocol, MQTT support (check)Pulsar protocolHTTPS APIgRPC and RESTn/a
14Schema supportNone built inBuilt-in schema registryNoneTopic schemas (Avro, Protocol Buffers)None
15TransactionsBatch publish, no multi-stream tx (check)YesFIFO dedup onlyNone across topicsDatabase transaction (afterCommit)
16Ops complexityLow to mediumHigh (brokers plus BookKeeper)None (managed)None (managed)Lowest
17HostingSelf-host, Synadia CloudSelf-host, StreamNativeAWS onlyGCP onlyWherever your DB or AWS runs
18LicensingApache 2.0Apache 2.0Proprietary serviceProprietary serviceMIT (Laravel)
19LaravelNo first-party; use a clientNo first-partyBuilt in (sqs driver)Community packagesBuilt in
20Go clientnats.go (official)pulsar-client-go (official)AWS SDK v2cloud.google.com/go/pubsubn/a
21Observabilitynats CLI, monitoring endpointsAdmin API, PrometheusCloudWatchCloud Monitoringqueue:monitor, Horizon (redis)
22SecurityTLS, accounts, JWT/NKeysTLS, JWT, authorizationIAM, KMSIAM, CMEKDB permissions

The facts above come from the products' own documentation pages saved for this chapter: NATS JetStream, Pulsar messaging, SQS quotas, the Pub/Sub API definition and Laravel queues. Google's documentation site returned HTTP 403 to automated fetches, so Pub/Sub retention and exactly-once come from the API definition and its message-size figure is left as "check".

Concept catalogue ​

Queue versus log Must-know ​

In plain words: a queue forgets a message once somebody handled it; a log keeps it and only remembers where each reader is.

Common misunderstanding: "A log is just a queue that keeps messages longer." No: with a log there is no per-message "done". A reader moves a position, so one failed record cannot be retried alone without extra machinery.

Definition: in a queue broker (RabbitMQ classic/quorum queues, SQS) each delivery is acknowledged and then deleted. In a log broker (Kafka, Pulsar, JetStream, RabbitMQ streams, Redis Streams) records are retained by policy and consumers hold positions. Redis Streams sits between: the entry stays, but the group tracks per-entry acks in its pending list.

Queue (RabbitMQ quorum queue)               Log (Kafka partition)
1 publish m1, m2, m3                        1 produce r0, r1, r2
2 consumer A receives m1                    2 group G reads r0
3 A acks m1  -> m1 deleted                  3 G commits offset 1  -> r0 stays on disk
4 A fails m2 -> m2 requeued, retried alone  4 G fails r1  -> G stops at r1 (no per-record nack)
5 a new consumer sees only m2, m3           5 a new group reads r0, r1, r2 from the start

Real scenario: order confirmation emails are a queue (each is done once, a poison message goes to a DLQ). "OrderPlaced" is a log (billing, shipping and analytics each read it, and a new service in six months wants to rebuild from day one).

NeedQueueLog
Per-message retry and DLQNativeYou build it (retry topics)
New consumer reads historyNoYes
Many independent readersBind more queuesAdd a group
Storage grows withBacklogRetention window

How to use it: pick by the first two rows. If both are needed, use a log for the fact stream and a queue for the work it triggers (EDA).

Delivery guarantee versus proof Must-know ​

In plain words: "at-least-once" is a promise about retries; it says nothing about whether your side effect happened.

Common misunderstanding: "A publisher confirm / returned offset / XADD id means the message was processed." Each only means the broker accepted it.

Definition: three facts exist for every message: accepted, delivered, processed. The consumer proves the third by acknowledging after its side effect. RabbitMQ's rule: "A consuming application should not acknowledge messages until it has done whatever it needs to do with them: recorded them in a data store, forwarded them on, or performed any other operation."

1 publisher  -> broker      publish
2 broker     -> publisher   confirm / offset / XADD id    (accepted)
3 broker     -> consumer    delivery                      (delivered)
4 consumer   -> database    INSERT the effect
5 consumer   -> broker      ack / commit / XACK           (processed)
-- crash between 4 and 5 => redelivery => the effect runs twice => needs an idempotent consumer

Real scenario: a payment consumer acks first for speed, crashes after, and the charge is lost with no retry. Opposite order: it charges, crashes before the ack, and charges twice unless an inbox rejects the duplicate.

BrokerAcceptedProcessed
RabbitMQConfirm; quorum queue: majority of replicasbasic.ack
KafkaProduce callback with offset (acks=all)Committed offset = next offset to read
Redis StreamsXADD id on the primaryXACK empties the pending entry

How to use it: the three adapters in Go and Laravel make this contract the interface: Publish returns on accepted, a Handler that returns nil acknowledges. Verification programs per broker are in Broker differences.

Ordering unit Important ​

In plain words: every broker orders something small, never "everything".

Common misunderstanding: "Kafka guarantees order." It guarantees order per partition. Two keys that hash to different partitions have no mutual order.

Definition: the ordering unit is the queue (RabbitMQ), the partition (Kafka), the stream (Redis Streams), the message group (SQS FIFO), the ordering key (Pub/Sub). Parallel consumers over one unit give up order unless coordinated (ordering).

Kafka, key = customer id, 3 partitions
1 order-1 (cust A) -> p0 offset 10
2 order-2 (cust B) -> p2 offset 4
3 order-3 (cust A) -> p0 offset 11    A's events stay ordered
-- B versus A: no relative order

Real scenario: a ledger needs per-account order, not global order, so the account id is the key (Kafka partition key, SQS MessageGroupId, Pub/Sub ordering key).

How to use it: choose the entity whose events must be ordered and map it to the broker's unit; never promise "global order" to a consumer.

Retention and replay Important ​

In plain words: retention decides how long a message is still on the shelf; replay is reading it again.

Common misunderstanding: "RabbitMQ can replay." Classic and quorum queues cannot; replay needs RabbitMQ streams. And XACK in Redis does not delete the entry, only trimming does.

Definition: SQS keeps a message 4 days by default (60 s to 14 days) and deletes it on DeleteMessage. Pub/Sub keeps unacked messages 7 days by default (10 minutes to 31 days) and replays acked ones only with retain_acked_messages. Kafka keeps by time/size or compacts by key. JetStream chooses between limits, work queue and interest retention.

1 Day 0   deploy consumer v1 (bug: drops field "currency")
2 Day 9   bug found
3 log broker: reset offset to day 0, run v2, rebuild the read model
4 queue broker: those messages are gone; restore from the database or the outbox

Real scenario: rebuilding a search index or a read model after a bug; auditing which events a service saw.

BrokerReplayBound by
RabbitMQ queuesNoBacklog and TTL
RabbitMQ streamsYesSize/age
KafkaYesTime/size, disk
Redis StreamsYesMAXLEN/MINID, RAM
SQSNo14 days max
Pub/SubWith seek31 days max

How to use it: decide the replay requirement before the broker; if it is "yes, months", a log (or the outbox table as the source of truth) is required.

Operational weight Important ​

In plain words: the cheapest broker is the one your team already knows how to restart at 3 a.m.

Common misunderstanding: "Managed means no operations." You still own topic design, consumer lag, retries and cost.

Definition: weight is the sum of cluster state to manage (partitions, controller quorum, queue types), upgrade path, capacity planning and the on-call runbook. Kafka's metadata now lives in KRaft; its documentation notes ZooKeeper-to-KRaft migration needs a bridge release (3.9).

Real scenario: a four-person team adopted a three-broker Kafka cluster for 50 messages/s of email jobs and spent more time on consumer rebalances than on the product.

BrokerMain operational chores
RabbitMQMemory/disk alarms, queue type choice, quorum membership, shovel/federation across sites
KafkaPartition count, retention, under-replicated partitions, rebalances, controller quorum
Redis Streamsmaxmemory, persistence, failover, trimming
SQS/SNS, Pub/SubQuotas, cost, redrive policy

How to use it: count the on-call people; if the answer is one, prefer managed or the stack you already run.

Decision under change Good to know ​

In plain words: the first choice is rarely the last; keep it cheap to change.

Common misunderstanding: "An abstraction over brokers hides every difference." It cannot: ordering unit, retries and replay differ. The seam in this page only promises the intersection.

Definition: a narrow Publisher/Consumer interface (accepted on publish, ack on handler success, idempotent handlers) plus the outbox lets you move one consumer group at a time (migration).

How to use it: see the adapters below.

Choosing ​

By workload Must-know ​

WorkloadRecommendationExtra techniqueReason
Task queue (emails, thumbnails)Laravel database/redis; RabbitMQ when cross-service; SQS on AWSIdempotent job, backoff (retry)Per-message retry matters more than throughput
Event busKafka, Pulsar; RabbitMQ topic exchange at small scaleOutbox, versioned schema (schema)Independent subscribers
Event log / replayKafka, Pulsar, JetStream, RabbitMQ streamsCompacted topics for stateNon-destructive reads
Stream processingKafka (Kafka Streams, Flink)Exactly-once inside KafkaEcosystem
Request/replyRabbitMQ (reply-to), NATSCorrelation id, timeoutNative pattern
IoT / MQTTRabbitMQ MQTT plugin, NATS, managed IoTBridge to Kafka for analyticsProtocol
Cross-regionPulsar geo-replication, SNS+SQS, Pub/Sub; Kafka mirroring; RabbitMQ shovel/federationRegional ownership of dataLatency and failure domains
ServerlessSQS/SNS, Pub/SubRedrive, small payloadsManaged triggers

By team and ops maturity Important ​

Team situationRecommendationReason
1–3 developers, one appDatabase or Redis queueOne thing to run
Small team, several services, needs retries/DLQRabbitMQ managedBuilt-in reliability features
Platform team exists, many consumersKafka (managed if possible)Operating it is a job
Cloud-native, no ops hire plannedSQS/SNS or Pub/SubNo servers
Already run Redis wellRedis Streams for light casesReuse skills

By scale Important ​

Sustained rateRetention needTypical fit
Under 100 msg/sHoursDatabase/Redis queue or any broker; do not add Kafka
100–10,000 msg/sHours to daysRabbitMQ, Redis Streams, SQS
10,000–100,000 msg/sDays to weeksRabbitMQ streams, Kafka, Pulsar, JetStream
Over 100,000 msg/sWeeks, replayKafka or Pulsar with partitions planned

These bands are rules of thumb from the chapter's experience of the classes in the matrix, not measurements; validate with the lab.

By consistency needs Important ​

NeedRecommendationReason
No message lost, everOutbox plus quorum queue or Kafka acks=allConfirm then durable replication
Loss acceptable (cache invalidation hint)Redis pub/sub or Redis listCheapest
Strict per-entity orderKafka key, SQS FIFO group, single-active-consumer queueOrdering unit
Atomic "DB write and publish"Transactional outbox + relay or CDCNo broker offers a cross-system transaction
Atomic consume-transform-produceKafka transactionsInside Kafka only

Solutions: migration and coexistence ​

Order servicebusiness tables +outbox tableOutbox relaydual publishRabbitMQcommands, tasks, delayKafkaevents, replay, streamsOld Redis queuedraining, then removedWorkersidempotentAnalytics,search, CDCOld workersone group at a timeDashed = migration path being retired. Duplicates during overlap are normal.

Redis, RabbitMQ, Kafka Must-know ​

In plain words: move traffic gradually and let both brokers carry the same facts for a while.

Common misunderstanding: "Dual write is safe if both calls succeed." One can fail; write once to an outbox and let a relay publish to both.

1 Add outbox table; relay publishes each row to old AND new broker
2 Deploy idempotent consumers (inbox) on the new broker, shadow mode
3 Compare counts and lag, per consumer group
4 Switch one consumer group at a time; the old consumer drains, then stops
5 Stop dual publish; delete the old queue after the retention window
-- during 1-4 duplicates are expected; the inbox makes them harmless
PathTypical triggerWhat changesWatch for
Laravel database -> RedisTable polling loadDriver name, QUEUE_CONNECTIONRedis persistence
Redis -> RabbitMQNeed retries, DLQ, routing, durabilityConsumers and topologyPrefetch, ack semantics
RabbitMQ -> Kafka (events)Many readers, replayKeys become partition keysPer-message retry disappears
Kafka -> RabbitMQTopic was really a work queueOffsets are droppedYou lose replay
Any -> managed same-protocolOps costEndpoint and credentialsQuotas, versions

Coexistence Important ​

In plain words: many companies run two brokers on purpose: queue for commands, log for events.

Common misunderstanding: "Two brokers means a failed migration." Often it is the stable end state.

PairDivision of labour
RabbitMQ + KafkaCommands and tasks vs domain events and analytics
Redis + KafkaCache and light work vs durable event log
SQS + KafkaAWS-native jobs vs cross-team events
Laravel database + RabbitMQIn-app jobs vs service integration

Bridge with a relay consumer (RabbitMQ to Kafka) only at the edge, and keep the outbox as the single producer. See event-driven architecture.

Cost model sketch ​

In plain words: cost is machines, storage, network and people, in that order of surprise.

Common misunderstanding: "Managed is always more expensive." A managed queue with per-request pricing can be far cheaper than a cluster plus an on-call rota below some volume.

Model, with symbols (prices are inputs you fill from the vendor's current page; none are quoted here):

monthly self-host  = nodes x node_price
                   + retained_bytes x replication_factor x disk_price
                   + cross_AZ_traffic x network_price
                   + ops_hours x hourly_rate
monthly managed    = units x unit_price      (requests, throughput units, partitions)
                   + retained_bytes x storage_price
                   + egress x network_price

Worked sizing with assumed load of 1,000 messages/s of 1 KB, retained 7 days, replication factor 3:

QuantityCalculationResult
Messages per month1,000 x 86,400 x 302.592 billion
Ingest1,000 x 1 KBabout 1 MB/s
Retained data1 MB/s x 604,800 sabout 605 GB
Stored with replication 3605 GB x 3about 1.8 TB
SQS requests (send, receive, delete, no batching)2.592 billion x 3about 7.8 billion
Cost driverSelf-hostManaged
Capacity planningYou, ahead of timeVendor, with quotas
Idle costAlways onOften scales to zero (SQS, Pub/Sub)
Cross-AZ replication trafficCounted on your billIn unit price or separate line
On-callYour peopleVendor for the platform, you for consumers
Break-evenHigh steady volume, platform team existsSpiky or low volume, small team

Anti-decisions ​

Anti-decisionWhy it failsInstead
Kafka for a 100 msg/s task queueOne slow job stalls a partition, no per-message retry, delay or DLQ; a cluster to run for no volumeLaravel database/redis queue or RabbitMQ (Kafka share groups change this: check your version and client)
Redis pub/sub for anything that must not be lostPub/sub is fire-and-forget: no subscriber means the message is gone; no ack, no replay (Redis Streams & Pub/Sub)Streams with persistence, or RabbitMQ
RabbitMQ classic queues as an event storeMessages vanish on ack; a new consumer cannot read last monthStreams or Kafka
Redis Streams as system of recordRAM-bound; failover can lose acked writes (durability)A database plus outbox
Laravel redis driver mistaken for StreamsIt uses lists and sorted sets (queue internals)Redis::xadd for streams
A broker to avoid a transactionNo broker commits atomically with your databaseOutbox
One mega-topic/queue for everythingCannot tune retention, ordering or ACLs per useTopic per event type or bounded context

The Laravel question ​

In plain words: start with the queue you already have; add a broker when a concrete limit, not a fashion, appears.

Common misunderstanding: "A serious system needs Kafka or RabbitMQ." Laravel 13 documents built-in drivers: "the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver that will execute jobs immediately" (queues). Many systems never need more.

The database driver claims jobs with a locking read; the framework picks FOR UPDATE SKIP LOCKED on MySQL 8.0.1+, MariaDB 10.6+, PostgreSQL 9.5+ and Vitess 19+ (DatabaseQueue source), so several workers do not block each other:

sql
-- what the database driver does per pop, simplified (PostgreSQL)
BEGIN;
SELECT * FROM jobs
 WHERE queue = 'default'
   AND (reserved_at IS NULL OR reserved_at <= extract(epoch FROM now()) - 90)
   AND available_at <= extract(epoch FROM now())
 ORDER BY id
 LIMIT 1
 FOR UPDATE SKIP LOCKED;
UPDATE jobs SET reserved_at = extract(epoch FROM now()), attempts = attempts + 1 WHERE id = $1;
COMMIT;

When to add a broker:

SignalMeaningNext step
Jobs table polling dominates DB CPU or row churn hurtsDatabase is the wrong placeRedis driver, then RabbitMQ
Another language/service must consumeNeeds a protocol, not a Laravel job payloadRabbitMQ or Kafka with a documented message contract
Need retries per message across services, DLQ, routingQueue featuresRabbitMQ
Need replay or many independent readersLogKafka
Need cloud-managed, no serversOperationsSQS (built-in driver)
Need delay longer than 15 minutes on SQSSQS cap ("maximum delay time of 15 minutes")RabbitMQ delay or scheduler + database
1 Monolith, jobs in `jobs` table, 20 jobs/s            -> keep
2 Peak 800 jobs/s, DB CPU rising                        -> QUEUE_CONNECTION=redis (+ Horizon)
3 Second service in Go must react to OrderPlaced        -> outbox -> RabbitMQ topic exchange
4 Analytics wants to replay 90 days of events           -> add Kafka for the event stream, keep RabbitMQ for commands

Related: the Laravel queue internals page, and durable jobs.

Go ​

Example ​

One Publisher and one Consumer interface with three adapters. The contract is the intersection of the three brokers: Publish returns when the broker has accepted the message; a handler returning nil acknowledges; an error leaves the message for redelivery; handlers are idempotent. Compile-only: main exits unless BROKER is set.

go
// Package main shows one Publisher/Consumer seam with three adapters.
// The contract is deliberately small: it is the intersection of what the three
// brokers can promise, so application code never names a broker feature.
package main

import "context"

// Message is the broker-neutral envelope. Key drives ordering: the Kafka
// partition key, the Redis stream field, the RabbitMQ routing key suffix.
type Message struct {
	Key     string
	Body    []byte
	Headers map[string]string
}

// Handler returns nil to acknowledge. Any error means "do not acknowledge":
// the adapter leaves the message for redelivery. Handlers must be idempotent,
// because every adapter gives at-least-once delivery.
type Handler func(ctx context.Context, m Message) error

// Publisher returns only after the broker has accepted the message
// (publisher confirm, produce callback, XADD reply). It does not mean processed.
type Publisher interface {
	Publish(ctx context.Context, topic string, m Message) error
	Close() error
}

// Consumer blocks until ctx is cancelled. group names the competing-consumer
// set: the queue name, the consumer group id, the stream group.
type Consumer interface {
	Consume(ctx context.Context, topic, group string, h Handler) error
	Close() error
}
go
package main

import (
	"context"
	"errors"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"
)

type rabbitPublisher struct {
	conn *amqp.Connection
	ch   *amqp.Channel
}

func newRabbitPublisher(url string) (*rabbitPublisher, error) {
	conn, err := amqp.Dial(url)
	if err != nil {
		return nil, err
	}
	ch, err := conn.Channel()
	if err != nil {
		conn.Close()
		return nil, err
	}
	if err = ch.Confirm(false); err != nil { // publisher confirms on
		conn.Close()
		return nil, err
	}
	return &rabbitPublisher{conn: conn, ch: ch}, nil
}

// Publish uses the default exchange: routing key == queue name == topic.
func (p *rabbitPublisher) Publish(ctx context.Context, topic string, m Message) error {
	headers := amqp.Table{}
	for k, v := range m.Headers {
		headers[k] = v
	}
	conf, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, "", topic, true, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		MessageId:    m.Key,
		Headers:      headers,
		Body:         m.Body,
	})
	if err != nil {
		return err
	}
	acked, err := conf.WaitContext(ctx)
	if err != nil {
		return err
	}
	if !acked {
		return errors.New("rabbitmq: publish nacked")
	}
	return nil
}

func (p *rabbitPublisher) Close() error { return p.conn.Close() }

type rabbitConsumer struct{ conn *amqp.Connection }

func newRabbitConsumer(url string) (*rabbitConsumer, error) {
	conn, err := amqp.Dial(url)
	if err != nil {
		return nil, err
	}
	return &rabbitConsumer{conn: conn}, nil
}

// Consume treats group as the queue name; competing consumers share the queue.
func (c *rabbitConsumer) Consume(ctx context.Context, topic, group string, h Handler) error {
	ch, err := c.conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()
	if err = ch.Qos(20, 0, false); err != nil { // prefetch bounds in-flight work
		return err
	}
	q, err := ch.QueueDeclare(group, true, false, false, false, amqp.Table{"x-queue-type": "quorum"})
	if err != nil {
		return err
	}
	// Bind the group queue to the topic through the default exchange only
	// when names match; real topologies would declare an exchange here.
	if q.Name != topic {
		return fmt.Errorf("rabbitmq adapter: group %q must equal topic %q on the default exchange", group, topic)
	}
	msgs, err := ch.ConsumeWithContext(ctx, q.Name, "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range msgs {
		hdr := map[string]string{}
		for k, v := range d.Headers {
			if s, ok := v.(string); ok {
				hdr[k] = s
			}
		}
		if err = h(ctx, Message{Key: d.MessageId, Body: d.Body, Headers: hdr}); err != nil {
			_ = d.Nack(false, true) // requeue
			continue
		}
		_ = d.Ack(false) // ack after the side effect
	}
	return ctx.Err()
}

func (c *rabbitConsumer) Close() error { return c.conn.Close() }
go
package main

import (
	"context"

	"github.com/twmb/franz-go/pkg/kgo"
)

type kafkaPublisher struct{ cl *kgo.Client }

func newKafkaPublisher(brokers []string) (*kafkaPublisher, error) {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.RequiredAcks(kgo.AllISRAcks()), // acks=all
	)
	if err != nil {
		return nil, err
	}
	return &kafkaPublisher{cl: cl}, nil
}

// Publish waits for the produce result, so a nil error means the leader and
// the in-sync replicas accepted the record.
func (p *kafkaPublisher) Publish(ctx context.Context, topic string, m Message) error {
	rec := &kgo.Record{Topic: topic, Key: []byte(m.Key), Value: m.Body}
	for k, v := range m.Headers {
		rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
	}
	return p.cl.ProduceSync(ctx, rec).FirstErr()
}

func (p *kafkaPublisher) Close() error { p.cl.Close(); return nil }

type kafkaConsumer struct{ brokers []string }

func newKafkaConsumer(brokers []string) *kafkaConsumer { return &kafkaConsumer{brokers: brokers} }

// Consume stops at the first failing record and does not commit it: Kafka has
// no per-message nack, so "do not acknowledge" means "stop and re-poll".
func (c *kafkaConsumer) Consume(ctx context.Context, topic, group string, h Handler) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(c.brokers...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		return err
	}
	defer cl.Close()
	for ctx.Err() == nil {
		fetches := cl.PollFetches(ctx)
		if err = fetches.Err0(); err != nil && ctx.Err() == nil {
			return err
		}
		it := fetches.RecordIter()
		for !it.Done() {
			r := it.Next()
			hdr := map[string]string{}
			for _, kh := range r.Headers {
				hdr[kh.Key] = string(kh.Value)
			}
			if err = h(ctx, Message{Key: string(r.Key), Body: r.Value, Headers: hdr}); err != nil {
				break // leave the rest uncommitted; the group redelivers
			}
			if err = cl.CommitRecords(ctx, r); err != nil {
				return err
			}
		}
	}
	return ctx.Err()
}

func (c *kafkaConsumer) Close() error { return nil }
go
package main

import (
	"context"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

type redisPublisher struct{ rdb *redis.Client }

func newRedisPublisher(addr string) *redisPublisher {
	return &redisPublisher{rdb: redis.NewClient(&redis.Options{Addr: addr})}
}

// Publish returns the XADD reply: the entry is on the primary, nothing more.
// Durability still depends on AOF and replication settings.
func (p *redisPublisher) Publish(ctx context.Context, topic string, m Message) error {
	values := map[string]any{"key": m.Key, "body": m.Body}
	for k, v := range m.Headers {
		values["h:"+k] = v
	}
	return p.rdb.XAdd(ctx, &redis.XAddArgs{Stream: topic, Values: values}).Err()
}

func (p *redisPublisher) Close() error { return p.rdb.Close() }

type redisConsumer struct{ rdb *redis.Client }

func newRedisConsumer(addr string) *redisConsumer {
	return &redisConsumer{rdb: redis.NewClient(&redis.Options{Addr: addr})}
}

func (c *redisConsumer) Consume(ctx context.Context, topic, group string, h Handler) error {
	err := c.rdb.XGroupCreateMkStream(ctx, topic, group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}
	for ctx.Err() == nil {
		res, err := c.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: group, Consumer: "worker-1",
			Streams: []string{topic, ">"}, Count: 10, Block: 2 * time.Second,
		}).Result()
		if err == redis.Nil {
			continue // block timeout, nothing new
		}
		if err != nil {
			return err
		}
		for _, s := range res {
			for _, x := range s.Messages {
				msg := Message{Headers: map[string]string{}}
				for k, v := range x.Values {
					str, _ := v.(string)
					switch {
					case k == "key":
						msg.Key = str
					case k == "body":
						msg.Body = []byte(str)
					case strings.HasPrefix(k, "h:"):
						msg.Headers[strings.TrimPrefix(k, "h:")] = str
					}
				}
				if h(ctx, msg) != nil {
					continue // stays in the pending entries list (XPENDING)
				}
				if err = c.rdb.XAck(ctx, topic, group, x.ID).Err(); err != nil {
					return err
				}
			}
		}
	}
	return ctx.Err()
}

func (c *redisConsumer) Close() error { return c.rdb.Close() }
go
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
)

// factory is the only place that knows which broker runs. Everything else
// depends on Publisher and Consumer.
func factory(kind string) (Publisher, Consumer, error) {
	switch kind {
	case "rabbitmq":
		url := os.Getenv("AMQP_URL")
		p, err := newRabbitPublisher(url)
		if err != nil {
			return nil, nil, err
		}
		c, err := newRabbitConsumer(url)
		return p, c, err
	case "kafka":
		brokers := strings.Split(os.Getenv("KAFKA_BROKERS"), ",")
		p, err := newKafkaPublisher(brokers)
		return p, newKafkaConsumer(brokers), err
	case "redis":
		addr := os.Getenv("REDIS_ADDR")
		return newRedisPublisher(addr), newRedisConsumer(addr), nil
	}
	return nil, nil, fmt.Errorf("unknown BROKER %q", kind)
}

func main() {
	kind := os.Getenv("BROKER")
	if kind == "" {
		fmt.Println("set BROKER=rabbitmq|kafka|redis (plus its address variable) to run")
		return
	}
	pub, con, err := factory(kind)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer pub.Close()
	defer con.Close()

	ctx := context.Background()
	if err = pub.Publish(ctx, "orders", Message{Key: "order-42", Body: []byte(`{"order_id":42}`)}); err != nil {
		fmt.Fprintln(os.Stderr, "publish:", err)
		os.Exit(1)
	}
	fmt.Println("accepted by", kind)
}

The Go angle ​

The standard library has no broker client; each ecosystem client mirrors its broker. amqp091-go exposes channels, NotifyReturn and a deferred confirmation you wait on; franz-go has a produce callback with Partition and Offset, DisableAutoCommit and CommitRecords; go-redis is a typed wrapper whose XAdd, XReadGroup, XAck read like the Redis docs. Notice what the adapter cannot hide: RabbitMQ uses the group as a queue name, Kafka stops at the first failing record because it has no per-record nack, and Redis leaves a failed entry in the pending list for XAUTOCLAIM. That is the honest cost of the seam. Import paths: amqp091-go, franz-go kgo, go-redis.

Laravel ​

Example ​

The same seam in PHP: two interfaces, three publisher adapters (php-amqplib, ext-rdkafka, the Redis facade), one Redis Streams consumer, and a service provider that binds the interface from config('messaging.broker'). RabbitMQ and Kafka consumers normally run inside the package's own worker; wrap them the same way.

php
<?php

namespace App\Messaging;

/**
 * Returns after the broker accepted the message (confirm, produce report,
 * XADD reply). It never means "processed".
 */
interface Publisher
{
    /** @param array<string,string> $headers */
    public function publish(string $topic, string $key, string $body, array $headers = []): void;
}
php
<?php

namespace App\Messaging;

use Closure;

interface Consumer
{
    /**
     * Blocks and calls $handler(string $key, string $body, array $headers).
     * Returning normally acknowledges; throwing leaves the message for
     * redelivery. Handlers must be idempotent: delivery is at-least-once.
     */
    public function consume(string $topic, string $group, Closure $handler): void;
}
php
<?php

namespace App\Messaging;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;

/** php-amqplib directly: the Laravel package publishes without waiting for confirms. */
final class RabbitMqPublisher implements Publisher
{
    public function __construct(private readonly AMQPStreamConnection $connection) {}

    public function publish(string $topic, string $key, string $body, array $headers = []): void
    {
        $channel = $this->connection->channel();
        $accepted = false;
        $returned = null;
        $channel->set_ack_handler(function () use (&$accepted) {
            $accepted = true;
        });
        $channel->set_return_listener(function ($code, $text) use (&$returned) {
            $returned = $text;
        });
        $channel->confirm_select();
        $channel->basic_publish(
            new AMQPMessage($body, [
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
                'message_id' => $key,
                'application_headers' => new AMQPTable($headers),
            ]),
            '',
            $topic,
            true, // mandatory: unroutable messages come back as basic.return
        );
        $channel->wait_for_pending_acks_returns();
        $channel->close();

        if (! $accepted || $returned !== null) {
            throw new RuntimeException('rabbitmq publish failed: '.($returned ?? 'nack'));
        }
    }
}
php
<?php

namespace App\Messaging;

use RdKafka\Conf;
use RdKafka\Producer;
use RuntimeException;

/** ext-rdkafka directly: the flush result is the only "accepted" signal we need here. */
final class KafkaPublisher implements Publisher
{
    private readonly Producer $producer;

    public function __construct(string $brokers)
    {
        $conf = new Conf;
        $conf->set('bootstrap.servers', $brokers);
        $conf->set('acks', 'all');
        $conf->set('enable.idempotence', 'true');
        $this->producer = new Producer($conf);
    }

    public function publish(string $topic, string $key, string $body, array $headers = []): void
    {
        $this->producer->newTopic($topic)->producev(RD_KAFKA_PARTITION_UA, 0, $body, $key, $headers);
        $this->producer->poll(0);
        if ($this->producer->flush(10000) !== RD_KAFKA_RESP_ERR_NO_ERROR) {
            throw new RuntimeException('kafka flush failed or timed out');
        }
    }
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;

/** The Redis facade, because Laravel's redis queue driver uses lists, not streams. */
final class RedisStreamPublisher implements Publisher
{
    public function publish(string $topic, string $key, string $body, array $headers = []): void
    {
        $fields = ['key' => $key, 'body' => $body];
        foreach ($headers as $name => $value) {
            $fields['h:'.$name] = $value;
        }
        Redis::xadd($topic, '*', $fields); // an id means "on the primary", not "durable"
    }
}
php
<?php

namespace App\Messaging;

use Closure;
use Illuminate\Support\Facades\Redis;
use Throwable;

final class RedisStreamConsumer implements Consumer
{
    public function consume(string $topic, string $group, Closure $handler): void
    {
        try {
            Redis::xgroup('CREATE', $topic, $group, '0', true); // MKSTREAM
        } catch (Throwable) {
            // BUSYGROUP: the group already exists
        }

        while (true) {
            $read = Redis::xreadgroup($group, 'worker-1', [$topic => '>'], 10, 2000);
            foreach ($read[$topic] ?? [] as $id => $fields) {
                $headers = [];
                foreach ($fields as $name => $value) {
                    if (str_starts_with($name, 'h:')) {
                        $headers[substr($name, 2)] = $value;
                    }
                }
                try {
                    $handler($fields['key'] ?? '', $fields['body'] ?? '', $headers);
                } catch (Throwable) {
                    continue; // stays in the pending entries list for XAUTOCLAIM
                }
                Redis::xack($topic, $group, [$id]);
            }
        }
    }
}
php
<?php

namespace App\Providers;

use App\Messaging\KafkaPublisher;
use App\Messaging\Publisher;
use App\Messaging\RabbitMqPublisher;
use App\Messaging\RedisStreamPublisher;
use Illuminate\Support\ServiceProvider;
use InvalidArgumentException;
use PhpAmqpLib\Connection\AMQPStreamConnection;

/** The only class that knows which broker runs: change MESSAGING_BROKER, not callers. */
final class BrokerServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Publisher::class, function () {
            return match (config('messaging.broker')) {
                'rabbitmq' => new RabbitMqPublisher(new AMQPStreamConnection(
                    config('messaging.rabbitmq.host'), 5672,
                    config('messaging.rabbitmq.user'), config('messaging.rabbitmq.password'),
                )),
                'kafka' => new KafkaPublisher(config('messaging.kafka.brokers')),
                'redis' => new RedisStreamPublisher,
                default => throw new InvalidArgumentException('unknown messaging.broker'),
            };
        });
    }
}

The Laravel angle ​

Laravel 13's own drivers are database, sqs, redis, beanstalkd, sync and null; RabbitMQ and Kafka are not built in. For jobs the connection name is already a seam: change QUEUE_CONNECTION and the connection entry in config/queue.php and jobs run unchanged, but only for task queues. Events on Kafka or Streams need their own consumers, which is what the interface above is for. Package facts used on this page: vladimir-yuldashev/laravel-queue-rabbitmq allows illuminate/queue up to ^13.0 in its composer.json (its README support table is stale) and does not wait for publisher confirms, so the adapter uses php-amqplib directly. mateusjunges/laravel-kafka needs PHP 8.2+, Laravel 12+ and ext-rdkafka; its send() returns a flush result, not an offset, so the adapter uses RdKafka\Producer. Redis Streams use the Redis facade, assuming phpredis (xadd, xreadgroup, xack signatures differ in Predis). Delayed jobs on SQS are capped at 15 minutes.

Broker differences ​

Here the comparison itself is the topic, so each subsection summarises the broker's philosophy and shows how to prove "accepted, delivered, processed" on it. All three programs exit quietly when their environment variable is missing.

RabbitMQ ​

Philosophy: a smart broker with dumb-enough consumers. Routing, retries, TTL, DLX and per-message acks live in the broker. The evidence chain is confirm (accepted) then queue depth (ready) then ack (processed). A confirm for a routable message means it "has been accepted by all the queues"; for a quorum queue that is a majority of replicas. Two traps: an unroutable message is also confirmed, so publish mandatory and listen for basic.return; and queue depth counts only ready messages, so a delivered-but-unacked message already looks gone. The programs close the consuming channel before the final check, because unacked deliveries are "automatically requeued when the channel (or connection) on which the delivery happened is closed".

go
// Command rabbitmq proves one message was delivered and processed end to end:
// publisher confirm -> queue depth -> consume -> ack -> depth after the channel
// that held the delivery is closed.
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

const queue = "verify.orders"

func main() {
	url := os.Getenv("AMQP_URL") // e.g. amqp://guest:guest@localhost:5672/
	if url == "" {
		fmt.Println("set AMQP_URL to run this check")
		return
	}
	if err := run(url); err != nil {
		fmt.Fprintln(os.Stderr, "FAIL:", err)
		os.Exit(1)
	}
}

func run(url string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	conn, err := amqp.Dial(url)
	if err != nil {
		return err
	}
	defer conn.Close()

	pub, err := conn.Channel()
	if err != nil {
		return err
	}
	if _, err = pub.QueueDeclare(queue, true, false, false, false, amqp.Table{"x-queue-type": "quorum"}); err != nil {
		return err
	}

	// 1. Publisher confirm: the broker accepted the message (for a quorum queue,
	// a majority of replicas hold it). This says nothing about any consumer.
	if err = pub.Confirm(false); err != nil {
		return err
	}
	// A confirm also arrives for a message that matched no queue, so ask for
	// mandatory publishing and listen for the basic.return that precedes it.
	returns := pub.NotifyReturn(make(chan amqp.Return, 1))
	conf, err := pub.PublishWithDeferredConfirmWithContext(ctx, "", queue, true, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		MessageId:    "order-42",
		Body:         []byte(`{"order_id":42}`),
	})
	if err != nil {
		return err
	}
	acked, err := conf.WaitContext(ctx)
	if err != nil || !acked {
		return fmt.Errorf("publisher confirm failed (acked=%v, err=%v)", acked, err)
	}
	select {
	case r := <-returns:
		return fmt.Errorf("confirmed but unroutable: %s", r.ReplyText)
	default:
	}
	fmt.Println("confirm: broker acked the publish")

	// 2. Depth through a passive declare: no management plugin, no HTTP API.
	// Messages counts READY messages only, not delivered-but-unacked ones.
	ready, err := depth(conn)
	if err != nil {
		return err
	}
	fmt.Println("depth before consume:", ready)

	// 3. Consume with manual ack; ack only after the side effect succeeded.
	cons, err := conn.Channel()
	if err != nil {
		return err
	}
	deliveries, err := cons.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	select {
	case d := <-deliveries:
		fmt.Printf("consumed %s redelivered=%v\n", d.MessageId, d.Redelivered)
		// ...write to the database here...
		if err = d.Ack(false); err != nil {
			return err
		}
	case <-ctx.Done():
		return ctx.Err()
	}

	// 4. Closing the consuming channel requeues anything still unacked, so a
	// depth of 0 afterwards proves the ack was applied, not merely that the
	// message left the "ready" state.
	if err = cons.Close(); err != nil {
		return err
	}
	ready, err = depth(conn)
	if err != nil {
		return err
	}
	if ready != 0 {
		return fmt.Errorf("message was requeued, depth=%d", ready)
	}
	fmt.Println("depth after ack and channel close: 0 -> processed")
	return nil
}

// depth uses a throwaway channel because a failed passive declare closes it.
func depth(conn *amqp.Connection) (int, error) {
	ch, err := conn.Channel()
	if err != nil {
		return 0, err
	}
	defer ch.Close()
	q, err := ch.QueueDeclarePassive(queue, true, false, false, false, amqp.Table{"x-queue-type": "quorum"})
	if err != nil {
		return 0, err
	}
	return q.Messages, nil
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Queue;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

/**
 * php artisan verify:rabbitmq
 *
 * Uses vladimir-yuldashev/laravel-queue-rabbitmq for the queue side and its
 * dependency php-amqplib directly for publisher confirms, because the package
 * publishes without waiting for them.
 */
class VerifyRabbitMq extends Command
{
    protected $signature = 'verify:rabbitmq';

    protected $description = 'Publish with a confirm, consume, ack, then prove the queue is empty';

    private const QUEUE = 'verify.orders';

    public function handle(): int
    {
        $queue = Queue::connection('rabbitmq');
        $queue->declareQueue(self::QUEUE, true, false, ['x-queue-type' => 'quorum']);

        // 1. Publisher confirm on a channel of our own.
        $cfg = config('queue.connections.rabbitmq.hosts.0');
        $conn = new AMQPStreamConnection($cfg['host'], $cfg['port'], $cfg['user'], $cfg['password'], $cfg['vhost']);
        $channel = $conn->channel();

        $outcome = null;
        $channel->set_ack_handler(function (AMQPMessage $m) use (&$outcome) {
            $outcome = 'ack';
        });
        $channel->set_nack_handler(function (AMQPMessage $m) use (&$outcome) {
            $outcome = 'nack';
        });
        // A confirm also arrives for a message that matched no queue, so publish
        // as mandatory and listen for the basic.return that precedes the ack.
        $unroutable = null;
        $channel->set_return_listener(function ($code, $text) use (&$unroutable) {
            $unroutable = $text;
        });
        $channel->confirm_select();
        $channel->basic_publish(
            new AMQPMessage('{"order_id":42}', ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]),
            '',
            self::QUEUE,
            true,
        );
        $channel->wait_for_pending_acks_returns();
        $conn->close();

        if ($outcome !== 'ack' || $unroutable !== null) {
            $this->error('publish failed: '.($unroutable ?? $outcome));

            return self::FAILURE;
        }
        $this->info('confirm: broker acked the publish');

        // 2. size() is a passive queue.declare: ready messages only.
        $this->line('depth before consume: '.$queue->size(self::QUEUE));

        // 3. pop() is basic.get; delete() sends basic.ack (see RabbitMQJob::delete).
        $job = $queue->pop(self::QUEUE);
        if ($job === null) {
            $this->error('nothing to consume');

            return self::FAILURE;
        }
        $this->line('consumed '.$job->getRawBody());
        // ...write to the database here...
        $job->delete();

        // 4. Close the package's connection (the broker requeues anything
        // unacked), then look at the queue from a brand-new connection.
        $queue->close();
        $verify = new AMQPStreamConnection($cfg['host'], $cfg['port'], $cfg['user'], $cfg['password'], $cfg['vhost']);
        [, $ready] = $verify->channel()->queue_declare(self::QUEUE, true, true, false, false, false, new AMQPTable(['x-queue-type' => 'quorum']));
        $verify->close();

        if ($ready !== 0) {
            $this->error("message was requeued, depth={$ready}");

            return self::FAILURE;
        }
        $this->info('depth after ack and reconnect: 0 -> processed');

        return self::SUCCESS;
    }
}

Kafka ​

Philosophy: a dumb broker, a smart log. The broker stores and replicates; consumers own positions. The evidence chain is produce callback (partition and offset) then committed offset (position). With acks=all the leader waits for "the full set of in-sync replicas", and the offset is real (with acks=0 it is always -1). A committed offset is the next offset to read, so after processing record n the group shows n+1. It is a position, not a receipt: committing a later record silently covers an earlier failed one. The program asks the group coordinator (kadm.FetchOffsets, getCommittedOffsets) instead of trusting its bookkeeping. Idempotent production removes producer-retry duplicates; it does not make your consumer idempotent (delivery guarantees).

go
// Command kafka proves one record was delivered and processed end to end:
// produce callback (partition+offset) -> consume -> commit -> committed offset.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/twmb/franz-go/pkg/kadm"
	"github.com/twmb/franz-go/pkg/kgo"
)

const (
	topic = "verify.orders"
	group = "verify-workers"
)

func main() {
	brokers := os.Getenv("KAFKA_BROKERS") // e.g. localhost:9092
	if brokers == "" {
		fmt.Println("set KAFKA_BROKERS to run this check")
		return
	}
	if err := run(strings.Split(brokers, ",")); err != nil {
		fmt.Fprintln(os.Stderr, "FAIL:", err)
		os.Exit(1)
	}
}

func run(brokers []string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.RequiredAcks(kgo.AllISRAcks()), // acks=all: wait for the in-sync replicas
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
		kgo.DisableAutoCommit(), // we commit after the side effect, not on a timer
	)
	if err != nil {
		return err
	}
	defer cl.Close()

	// 1. Produce with a callback. The callback fires once the broker has
	// answered (or retries are exhausted); r.Partition and r.Offset are the
	// coordinates of the committed record.
	type where struct {
		partition int32
		offset    int64
		err       error
	}
	done := make(chan where, 1)
	rec := &kgo.Record{Topic: topic, Key: []byte("order-42"), Value: []byte(`{"order_id":42}`)}
	cl.Produce(ctx, rec, func(r *kgo.Record, err error) {
		done <- where{r.Partition, r.Offset, err}
	})
	w := <-done
	if w.err != nil {
		return fmt.Errorf("produce failed: %w", w.err)
	}
	fmt.Printf("produced to %s[%d] at offset %d\n", topic, w.partition, w.offset)

	// 2. Consume until we see that exact record.
	var got *kgo.Record
	for got == nil {
		fetches := cl.PollFetches(ctx)
		if err = fetches.Err(); err != nil {
			return err
		}
		fetches.EachRecord(func(r *kgo.Record) {
			if r.Partition == w.partition && r.Offset == w.offset {
				got = r
			}
		})
	}

	// ...write to the database here, then commit. The committed offset is the
	// NEXT offset to read, so it is record offset + 1.
	if err = cl.CommitRecords(ctx, got); err != nil {
		return fmt.Errorf("commit failed: %w", err)
	}

	// 3. Ask the group coordinator what it has stored, independently of the
	// client's own bookkeeping.
	offs, err := kadm.NewClient(cl).FetchOffsets(ctx, group)
	if err != nil {
		return err
	}
	committed, ok := offs.Lookup(topic, w.partition)
	if !ok || committed.Err != nil {
		return fmt.Errorf("no committed offset for %s[%d]", topic, w.partition)
	}
	if committed.At < w.offset+1 {
		return fmt.Errorf("committed %d is behind produced %d", committed.At, w.offset)
	}
	fmt.Printf("group %s committed offset %d -> processed offset %d\n", group, committed.At, w.offset)
	return nil
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
use RdKafka\Conf;
use RdKafka\KafkaConsumer;
use RdKafka\Message;
use RdKafka\Producer;
use RdKafka\TopicPartition;

/**
 * php artisan verify:kafka
 *
 * mateusjunges/laravel-kafka sits on ext-rdkafka. The package's send() returns
 * only a flush result, so the produce side uses RdKafka\Producer directly to
 * read the delivery report (partition + offset); the consume side uses the
 * package with manual commit.
 */
class VerifyKafka extends Command
{
    protected $signature = 'verify:kafka';

    protected $description = 'Produce with a delivery report, consume, commit, then read the committed offset';

    private const TOPIC = 'verify.orders';

    private const GROUP = 'verify-workers';

    public function handle(): int
    {
        $brokers = config('kafka.brokers');

        // 1. Delivery report callback: fires when the broker has answered.
        $report = null;
        $conf = new Conf;
        $conf->set('metadata.broker.list', $brokers);
        $conf->set('acks', 'all');
        $conf->set('enable.idempotence', 'true');
        $conf->setDrMsgCb(function ($producer, Message $m) use (&$report) {
            $report = $m->err === RD_KAFKA_RESP_ERR_NO_ERROR
                ? ['partition' => $m->partition, 'offset' => $m->offset]
                : ['error' => $m->errstr()];
        });

        $producer = new Producer($conf);
        $producer->newTopic(self::TOPIC)->produce(RD_KAFKA_PARTITION_UA, 0, '{"order_id":42}', 'order-42');
        if ($producer->flush(10000) !== RD_KAFKA_RESP_ERR_NO_ERROR || ! isset($report['offset'])) {
            $this->error('produce failed: '.json_encode($report));

            return self::FAILURE;
        }
        ['partition' => $partition, 'offset' => $offset] = $report;
        $this->info("produced to ".self::TOPIC."[{$partition}] at offset {$offset}");

        // 2. Consume with manual commit; commit only after the side effect.
        Kafka::consumer([self::TOPIC], self::GROUP, $brokers)
            ->withManualCommit()
            ->withOption('auto.offset.reset', 'earliest')
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($partition, $offset) {
                if ($message->getPartition() !== $partition || $message->getOffset() !== $offset) {
                    return;
                }
                // ...write to the database here...
                $consumer->commit($message);
                $consumer->stopConsuming();
            })
            ->build()
            ->consume();

        // 3. Ask the group coordinator what it has stored. The committed
        // offset is the NEXT offset to read, so it is the record offset + 1.
        $conf = new Conf;
        $conf->set('metadata.broker.list', $brokers);
        $conf->set('group.id', self::GROUP);
        $committed = (new KafkaConsumer($conf))
            ->getCommittedOffsets([new TopicPartition(self::TOPIC, $partition)], 10000)[0]
            ->getOffset();

        if ($committed < $offset + 1) {
            $this->error("committed {$committed} is behind produced {$offset}");

            return self::FAILURE;
        }
        $this->info("group committed offset {$committed} -> processed offset {$offset}");

        return self::SUCCESS;
    }
}

Redis Streams ​

Philosophy: a log as a data structure inside a database you already run. The evidence chain is XADD id then XPENDING count then XACK then XPENDING count. XADD returning an id proves the entry exists on the primary now, nothing more: Redis states that "by default the asynchronous replication will not guarantee that XADD commands or consumer groups state changes are replicated", that "AOF must be used with a strong fsync policy if persistence of messages is important", and that WAIT makes loss "very unlikely", not impossible (streams, WAIT). After XACK the entry remains in the stream; only the pending list shrinks.

go
// Command redis proves one entry was delivered and processed end to end:
// XADD id -> XREADGROUP -> XPENDING count -> XACK -> XPENDING count.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

const group = "workers"

// A fresh stream per run keeps old pending entries out of the counts.
var stream = fmt.Sprintf("verify:orders:%d", time.Now().UnixNano())

func main() {
	addr := os.Getenv("REDIS_ADDR") // e.g. localhost:6379
	if addr == "" {
		fmt.Println("set REDIS_ADDR to run this check")
		return
	}
	if err := run(addr); err != nil {
		fmt.Fprintln(os.Stderr, "FAIL:", err)
		os.Exit(1)
	}
}

func run(addr string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()
	defer rdb.Del(context.Background(), stream)

	// Create the group (and the stream) once; BUSYGROUP means it already exists.
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}

	// 1. XADD returns the entry id the server assigned. A non-error reply means
	// the entry is in the stream in the primary's memory; whether it survives a
	// crash depends on AOF/replication settings, not on this reply.
	id, err := rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: stream,
		Values: map[string]any{"order_id": 42},
	}).Result()
	if err != nil {
		return err
	}
	fmt.Println("XADD id:", id)

	// 2. Deliver to a consumer of the group; ">" means "never delivered before".
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group:    group,
		Consumer: "worker-1",
		Streams:  []string{stream, ">"},
		Count:    1,
		Block:    2 * time.Second,
	}).Result()
	if err != nil {
		return err
	}
	var got string
	for _, s := range res {
		for _, m := range s.Messages {
			got = m.ID
		}
	}
	if got == "" {
		return fmt.Errorf("nothing delivered")
	}

	// 3. Delivered but not acknowledged: the entry sits in the group's PEL.
	p, err := rdb.XPending(ctx, stream, group).Result()
	if err != nil {
		return err
	}
	fmt.Println("XPENDING before XACK:", p.Count)

	// ...write to the database here, then acknowledge...
	if err = rdb.XAck(ctx, stream, group, got).Err(); err != nil {
		return err
	}

	p, err = rdb.XPending(ctx, stream, group).Result()
	if err != nil {
		return err
	}
	if p.Count != 0 {
		return fmt.Errorf("still pending: %d", p.Count)
	}
	fmt.Println("XPENDING after XACK: 0 -> processed", got)
	return nil
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

/**
 * php artisan verify:redis-stream
 *
 * Laravel's redis queue driver uses lists and sorted sets, not streams, so this
 * goes through the Redis facade. Method signatures below are phpredis's
 * (REDIS_CLIENT=phpredis); Predis orders its arguments differently.
 */
class VerifyRedisStream extends Command
{
    protected $signature = 'verify:redis-stream';

    protected $description = 'XADD, XREADGROUP, check XPENDING, XACK, check XPENDING again';

    private const GROUP = 'workers';

    public function handle(): int
    {
        // A fresh stream per run keeps old pending entries out of the counts.
        $stream = 'verify:orders:'.bin2hex(random_bytes(4));

        Redis::xgroup('CREATE', $stream, self::GROUP, '0', true); // MKSTREAM

        // 1. XADD returns the id the server assigned. It proves the entry is in
        // the stream on the primary, not that it is durable or consumed.
        $id = Redis::xadd($stream, '*', ['order_id' => 42]);
        $this->info("XADD id: {$id}");

        // 2. Deliver to one consumer of the group.
        $read = Redis::xreadgroup(self::GROUP, 'worker-1', [$stream => '>'], 1, 2000);
        $got = array_key_first($read[$stream] ?? []);
        if ($got === null) {
            $this->error('nothing delivered');

            return self::FAILURE;
        }

        // 3. Delivered but unacknowledged: the entry is in the group's PEL.
        $this->line('XPENDING before XACK: '.Redis::xpending($stream, self::GROUP)[0]);

        // ...write to the database here, then acknowledge...
        Redis::xack($stream, self::GROUP, [$got]);

        $pending = (int) Redis::xpending($stream, self::GROUP)[0];
        Redis::del($stream);

        if ($pending !== 0) {
            $this->error("still pending: {$pending}");

            return self::FAILURE;
        }
        $this->info("XPENDING after XACK: 0 -> processed {$got}");

        return self::SUCCESS;
    }
}

In production systems ​

  • RabbitMQ quorum queues. A confirm is sent once a quorum holds the message; at-least-once dead-lettering re-publishes "with publisher confirms turned on internally"; since 4.0 the delivery limit defaults to 20 (confirms, DLX, quorum queues).
  • RabbitMQ 4.4 delay. Publishers set x-opt-delivery-time; the delayed-message-exchange plugin repository says "This Project is No Longer Maintained".
  • Kafka share groups. Records are acquired under a lock that defaults to 30 seconds (share.record.lock.duration.ms) and delivery attempts are counted (design).
  • Redis. Stream and group state go to AOF and RDB and replicate asynchronously, so a failover can lose acknowledged writes unless you use WAIT and a strong fsync policy (persistence).
  • SQS. Default retention 4 days (60 s to 14 days), visibility timeout default 30 s up to 12 h, FIFO 300 transactions per second per partition per API without high-throughput mode (quotas).
  • Pub/Sub. Retention up to 31 days on a topic; subscription default 7 days; exactly-once delivery is a per-subscription flag whose guarantee is "not resent before the acknowledgment deadline" and "an acknowledged message will not be resent", while publisher retries can still create distinct messages (API definition).
  • Laravel. The database queue driver locks rows with FOR UPDATE SKIP LOCKED on supported engines (Illuminate\Queue\DatabaseQueue).

In architecture: from a single process to a distributed system ​

Under ~100 jobs/s, one app,jobs only from your own code?yesLaravel databaseor redis drivernoMust consumers re-read historyor many teams read the same data?yesnoOver ~10k msg/s, partitions and an opsteam available, or managed Kafka?yesnoKafka (or Pulsar)partitioned logRabbitMQ streams orNATS JetStreamNeed routing, per-message retry,priorities, delay or a DLQ?yesnoRabbitMQ (quorum)or SQS on AWSRedis Streams if youtrust its persistenceTie-breakers: what the team can operate at 3 a.m.; whether a managed service exists;whether the cloud already has SQS/SNS or Pub/Sub; MQTT devices point to RabbitMQ or NATS.

Monolith ​

One Laravel app, one database. Jobs go to the database driver (or redis once polling hurts). Delayed and failed jobs are covered by delay() and failed_jobs. Adding a broker here is cost without benefit; keep the Publisher interface only if you expect a second consumer language soon. Example: order confirmation emails at 5 jobs/s.

Modular monolith ​

Modules publish integration events in process or through the same queue, with the outbox inside the module's own transaction. Each module owns its event types; the broker choice is still the database or Redis. Example: Billing listens to OrderPlaced from Sales, with the event class as the contract (domain events vs integration events).

Microservices ​

Services need a protocol and independent deploys, so a real broker appears. A typical split: RabbitMQ topic exchange for commands and service events, with quorum queues, DLX and a delivery limit; Kafka only if several teams need replay. Every handler is idempotent (inbox); long flows use a saga; service-to-service style is chosen in service communication and reliability in designing for failure.

1 Order service   -> outbox row in the same DB transaction as the order
2 Relay           -> RabbitMQ exchange "orders", key "order.placed"
3 Billing queue   -> charge, ack after INSERT into billing + inbox
4 Failure x20     -> DLX -> orders.dead, alert, manual or scheduled replay

Distributed data ​

Replicas, caches and regions change guarantees. Redis replicas are asynchronous, so a stream failover can lose entries; Kafka's min.insync.replicas plus acks=all trades availability for durability; SQS/SNS and Pub/Sub are regional, with cross-region done by fan-out or Pulsar geo-replication; RabbitMQ moves messages between sites with shovel or federation rather than stretching one cluster. Consumers reading from a cache or replica see lag: see replication and Redis.

Scaling path ​

ScaleSetupWhat changes
1x (about 10 msg/s)Laravel database queueNothing
10x (about 100 msg/s)redis driver + Horizon, or RabbitMQ if services appearPersistence and retries
100x (about 10,000 msg/s)RabbitMQ quorum queues with competing consumers, or Kafka for eventsPartition/consumer count (scaling consumers)
1000xKafka/Pulsar with planned partitions and multi-cluster mirroringCapacity and retention planning, quotas, schema governance

Lab ​

Run the same workload against the three adapters and compare latency and lag. Expected, not run: no broker was started for this page; the numbers are shapes to look for, not results.

Setup (commands; one broker at a time, same machine, same payload):

docker compose up -d rabbitmq            # or kafka, or redis (own compose files)
export BROKER=rabbitmq AMQP_URL=amqp://guest:guest@localhost:5672/
go run ./adapters          # publishes one message and prints "accepted by rabbitmq"
#ExperimentCommand (sketch)Expected, not run
1Publish accepted latency, 1 KB, 10,000 messages, sequentialloop Publish, record p50/p99Redis lowest; RabbitMQ (confirm) low; Kafka (acks=all) higher p50 unless batched
2Batched throughputpublish concurrently, batch 100Kafka highest; RabbitMQ and Redis medium
3Consumer lag under a slow handler (50 ms)1 consumer, publish 1,000/s for 60 sBacklog grows ~950/s on all; lag visible as queue depth, group lag, XLEN - acked
4Scale consumers to 4start 3 moreRabbitMQ and Redis drain faster; Kafka only if partitions are at least 4
5Kill the consumer mid-messagekill -9 the handlerRedelivery on all three (unacked requeue, uncommitted offset, pending entry)
6Kill the broker (replicated setup)stop the leaderRabbitMQ quorum and Kafka continue after election; Redis may lose acked entries

Record per broker: p50/p99 publish latency, end-to-end latency (publish timestamp in a header, subtract at the handler), peak lag, and duplicates seen after experiment 5. Compare against the matrix rows 26, 27 and 28.

# expected, not run: shape of the result table
broker    pub_p50  pub_p99  e2e_p99  peak_lag  duplicates
redis     <1 ms    few ms   low      grows     0..few
rabbitmq  low ms   ~10 ms   low      grows     0..few
kafka     ms       ~10s ms  ms-tens  grows     0..few

Common misconceptions ​

BeliefReality
"Kafka is a faster RabbitMQ"Different models; Kafka wins on log throughput, RabbitMQ on routing and per-message features
"RabbitMQ keeps messages on disk, Kafka in memory" (or the reverse)Both persist; RabbitMQ persists persistent messages in durable queues, Kafka always writes to its log
"Redis Streams is durable because XADD returned"It is on the primary; durability is AOF and replication settings
"Pub/sub and Streams are the same thing in Redis"Pub/sub has no storage and no ack
"Exactly-once exists across systems"Only inside one system (Kafka transactions); elsewhere it is at-least-once plus idempotency
"A confirm means processed"It means accepted
"A committed offset means earlier records succeeded"It means the position moved
"Managed brokers need no ops"Topic design, lag and cost remain yours
"SQS FIFO is unlimited"300 TPS per partition per API unless high-throughput mode
"An abstraction layer makes brokers interchangeable"It covers the intersection only; ordering, retry and replay still differ

Cheat sheet ​

TopicWhat to remember
First choiceThe queue you already run (Laravel database/redis)
Task queue with retry/DLQ/delayRabbitMQ quorum queues
Event bus and replayKafka (or Pulsar, JetStream, RabbitMQ streams)
Light, fast, in-stackRedis Streams, with AOF and WAIT understood
AWS / GCP managedSQS+SNS / Pub/Sub
OrderingPer queue, partition, stream, message group, ordering key
Accepted vs processedConfirm/offset/XADD vs ack/commit/XACK
Dual writeNever; use the outbox
MigrationDual publish via outbox, idempotent consumers, move one group at a time
CoexistenceCommands on a queue broker, events on a log broker
CostMachines, storage x replication, network, people
Anti-decisionsKafka at 100 msg/s; Redis pub/sub for must-not-lose
LaravelBuilt-in: database, sqs, redis, beanstalkd, sync, null; the rest by package or raw client
SeamPublisher/Consumer, handlers idempotent

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A teammate proposes Kafka for 80 jobs/s of image resizing. What do you say, and what do you propose? Must-know ​

Answer

Answer: Kafka has no per-message retry, delay or DLQ and a slow job stalls a partition; run the Laravel database/redis queue or RabbitMQ.

2 — Why can "RabbitMQ can replay" be wrong? Must-know ​

Answer

Answer: Classic and quorum queues delete on ack; replay needs RabbitMQ streams.

3 — What does a returned Kafka offset prove, and what does it not? Important ​

Answer

Answer: The broker accepted the record (with acks=all, the in-sync replicas did). It says nothing about the consumer processing it.

4 — Give the ordering unit for Kafka, SQS FIFO, Pub/Sub and RabbitMQ. Must-know ​

Answer

Answer: Partition, message group, ordering key, queue.

5 — Why is pub/sub unsuitable for a payment event? Must-know ​

Answer

Answer: No subscriber means the message is gone; no ack or replay.

6 — How do you move one consumer group from RabbitMQ to Kafka safely? Important ​

Answer

Answer: Dual publish from the outbox, an idempotent consumer on Kafka in shadow mode, compare, switch the group, drain the old queue.

7 — What is the retention of SQS by default, and the maximum? Good to know ​

Answer

Answer: 4 days default, 60 seconds to 14 days.

8 — Why does the Go Kafka adapter stop at a failing record? Important ​

Answer

Answer: Kafka commits positions, not per-message acks; committing a later record would silently cover the failed one.

9 — When do you add a broker to a Laravel app? Must-know ​

Answer

Answer: When the database/redis queue hits a concrete limit: another language consuming, per-message retry across services, replay, load on the database, or managed cloud needs.

10 — Compute the stored volume for 1,000 msg/s of 1 KB retained 7 days with replication factor 3. Important ​

Answer

Answer: About 1 MB/s x 604,800 s = about 605 GB, times 3 = about 1.8 TB.

Glossary ​

TermMeaning
BrokerThe server that stores and routes messages
QueueDestination where a message is removed after ack
LogAppend-only, retained sequence read by position
TopicNamed channel (Kafka, Pulsar, SNS, Pub/Sub)
PartitionOne ordered shard of a Kafka or Pulsar topic
Consumer groupConsumers sharing a topic's work, with shared positions
OffsetPosition of a record in a partition
AckConsumer tells the broker a message is processed
Publisher confirmRabbitMQ signal that the broker accepted a publish
acks=allKafka produce setting: wait for the in-sync replicas
ISRIn-sync replicas of a Kafka partition
DLX / DLQRabbitMQ dead-letter exchange / dead-letter queue
Delivery limitMaximum redeliveries before dead-lettering (quorum queues)
Quorum queueReplicated RabbitMQ queue type using Raft
Stream (RabbitMQ)Non-destructive append-only queue type
Pending entries listRedis group's list of delivered, un-acked entries
XAUTOCLAIMRedis command to take over idle pending entries
JetStreamPersistence layer of NATS
Share groupKafka queue-style consumption of partitions
Visibility timeoutSQS period a received message is hidden
Redrive policySQS rule moving messages to a DLQ after repeated receives
OutboxTable written with the business data, relayed to the broker
Idempotent consumerHandler safe to run twice for one message
Anti-decisionA choice that fails under its stated workload
KRaftKafka's built-in metadata quorum, replacing ZooKeeper
Geo-replicationReplication of topics across clusters/regions

References ​

Built by Morteza Negahi