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 for | Go to |
|---|---|
| "Which broker for my workload?" in one minute | Everything in one minute, Decision tables |
| The 40-row side-by-side matrix | The comparison matrix |
| NATS, Pulsar, SQS/SNS, Pub/Sub, Laravel database/SQS columns | The other columns |
| Why a comparison is hard to trust | Why comparisons mislead |
| Moving from Redis to RabbitMQ to Kafka, or running two | Migration and coexistence |
| Self-host versus managed cost | Cost model sketch |
| "Do I even need a broker in Laravel?" | The Laravel question |
| What not to do | Anti-decisions |
| One interface, three adapters (Go and Laravel) | Go, Laravel |
| How each broker proves "accepted, delivered, processed" | Broker differences |
| Monolith to multi-region | In architecture |
| A comparison lab (expected, not run) | Lab |
Everything in one minute
Table 1: philosophy. Each broker answers a different question first.
| RabbitMQ | Kafka | Redis Streams | |
|---|---|---|---|
| Core idea | Smart broker routes messages to queues; a message is removed when acked | A partitioned, replicated, append-only log; the consumer owns a position | An append-only log inside Redis with consumer groups |
| Best at | Tasks, commands, routing, retries, delay, request/reply | Event log, replay, many readers, stream processing, high volume | Small, fast, in-stack streams where Redis already runs |
| Weakest at | Long retention and replay of millions of events (use its streams) | Per-message retry, delay, priorities, small low-volume setups | Durability by default, datasets bigger than RAM |
| You operate | A broker cluster | A broker cluster with partitions, retention, rebalances | Redis plus persistence and failover you configure |
Table 2: workload to first pick.
| Workload | First pick | Why |
|---|---|---|
| Background tasks inside one Laravel app | Laravel database or redis driver | No new infrastructure |
| Task queue with retries, priorities, delay, DLQ across services | RabbitMQ (quorum queues) | Built-in DLX, delivery limit, priorities, routing |
| Event bus many teams subscribe to | Kafka (or Pulsar) | Independent consumer groups, retention |
| Event log you replay | Kafka, RabbitMQ streams, NATS JetStream, Pulsar | Non-destructive reads |
| Stream processing (joins, windows) | Kafka | Kafka Streams / Flink ecosystem (stream processing) |
| Request/reply | RabbitMQ or NATS | Reply-to and correlation are first-class (request-reply) |
| IoT / MQTT devices | RabbitMQ (MQTT plugin), NATS, or a managed IoT hub | Protocol support |
| Cross-region fan-out | Pulsar geo-replication, Kafka mirroring, SNS/SQS, Pub/Sub | Replication across regions is a feature, not a script |
| Serverless | SQS/SNS (AWS), Pub/Sub (GCP) | Managed, scale to zero, triggers |
Table 3: five questions that decide most cases.
| Question | If yes | If no |
|---|---|---|
| Must a new consumer read history? | Log: Kafka, Pulsar, JetStream, RabbitMQ streams | Queue: RabbitMQ, SQS |
| Does one slow message have to be retried alone, later? | Queue with per-message ack and DLQ | Log is fine |
| Is peak above roughly 10,000 messages/s sustained? | Log with partitions | Anything works; pick by ops |
| Do you already run it and trust its persistence? | Use it first | Do 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:
| Rule | Consequence |
|---|---|
| Facts (limits, defaults, protocol names) come from the product's own docs and are dated | Cells name the version where it matters |
| Throughput and latency are classes, never numbers | Benchmark 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
| # | Dimension | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|---|
| 1 | Model | Exchanges route to queues; queue types: classic, quorum, stream | Topic of partitions, each an append-only log | Stream key (a log) with consumer groups |
| 2 | Storage structure | Per-queue message store; streams are a log | Segment files per partition | In-memory radix tree, persisted by AOF/RDB |
| 3 | Unit of consumption | One delivery, acked individually | A record at an offset; commit moves a position | One entry, acked individually in the group's pending list |
| 4 | Ordering scope | Per queue (single consumer); competing consumers and requeue can reorder | Per partition | Per stream |
| 5 | Ordering key story | Single active consumer or consistent-hash exchange | Partition key | One stream per key, or one stream |
| 6 | Default delivery guarantee | At-least-once with publisher confirms and manual ack | At-least-once (idempotent producer removes producer-retry duplicates) | At-least-once via group pending list |
| 7 | Exactly-once story | None end to end; idempotent consumers | Transactions give it inside Kafka; external effects need idempotency | None; idempotent consumers (Redis 8.6 adds idempotent production, check your version) |
| 8 | "Accepted" signal | Publisher confirm (plus mandatory return) | Produce callback with partition and offset (acks=all) | XADD reply with entry id |
| 9 | "Processed" signal | basic.ack | Committed offset (position) | XACK |
| 10 | Persistence | Persistent messages in durable queues; quorum and stream queues always replicated | Always on disk; flush policy is OS-driven by default | Off by default unless AOF/RDB configured |
| 11 | Durability knob | Quorum queue (majority), confirms | acks=all, min.insync.replicas, replication factor | AOF appendfsync, WAIT |
| 12 | Replication | Raft-based quorum queues; streams replicated | Leader and follower per partition, ISR | Asynchronous primary/replica |
| 13 | Failover | Quorum leader election | Leader election per partition (KRaft controller) | Sentinel or Cluster promote a replica; can lose acked writes |
| 14 | Consumer model | Push (basic.consume) with prefetch, or pull (basic.get) | Pull with fetch batches | Pull with blocking XREADGROUP |
| 15 | Parallelism limit | Many consumers per queue | Consumers per group up to partition count (share groups lift it) | Many consumers per group |
| 16 | Fan-out | Bind several queues to an exchange | Several consumer groups on one topic | Several groups on one stream |
| 17 | Routing | Direct, topic, fanout, headers exchanges | Topic and key only | Stream name only |
| 18 | Priorities | Classic and quorum queues support them | None | None |
| 19 | Delay / scheduling | Quorum queues since 4.4 (x-opt-delivery-time); TTL + DLX earlier | None built in | None built in (sorted set pattern) |
| 20 | Retry | Requeue, delivery limit (default 20 on quorum queues since 4.0), DLX loops | Client side: retry topics | Client side: XPENDING + XAUTOCLAIM |
| 21 | DLQ | Built in (DLX, at-least-once dead-lettering on quorum) | Convention: a dead-letter topic you produce to | Convention: another stream |
| 22 | Retention | Queues: until acked or TTL; streams: size/age | Time/size, or compaction by key; tiered storage for old segments | Until trimmed (MAXLEN, MINID); bounded by RAM |
| 23 | Replay | Streams only | Yes, seek to any offset | Yes, read from any id |
| 24 | Key compaction | No | Yes (cleanup.policy=compact) | No |
| 25 | Message size | max_message_size default 16 MiB, max 512 MiB (config doc) | max.message.bytes default 1048588 | Entry is a hash of fields; keep small, RAM-bound |
| 26 | Throughput class | Medium (per-message bookkeeping) | High (batched sequential I/O) | Medium to high, memory-bound |
| 27 | Latency class | Low | Low to medium (batching adds latency) | Lowest |
| 28 | Backpressure | Consumer prefetch, publisher flow control, memory alarms | Consumer pulls at its pace; broker quotas | None built in; trim policy and XLEN monitoring |
| 29 | Multi-tenancy | Virtual hosts with per-vhost permissions | Topics, ACLs, client quotas | Key prefixes, ACLs, logical DBs (not in Cluster) |
| 30 | Protocols | AMQP 0-9-1, AMQP 1.0, MQTT 5.0 (plugin), STOMP, streams protocol | Kafka protocol (plus HTTP REST proxies as add-ons) | RESP |
| 31 | Schema support | None built in (content-type header) | Not in Apache Kafka; Confluent Schema Registry or Apicurio | None |
| 32 | Transactions | AMQP tx.select on a channel (slow) | Producer transactions and read_committed (KIP-98) | MULTI/EXEC, Lua scripts |
| 33 | Ops complexity | Medium: cluster, queue types, memory/disk alarms | High: partitions, retention, rebalances, controller quorum | Low if Redis already runs; failover is yours |
| 34 | Scaling out | More queues and nodes; a single queue lives on its replicas | Add partitions and brokers | Cluster shards by key; one stream is on one shard |
| 35 | Hosting options | Self-host, CloudAMQP, Amazon MQ, Kubernetes operator | Self-host, Confluent Cloud, Amazon MSK, Aiven | Self-host, Redis Cloud, ElastiCache, Memorystore |
| 36 | Licensing | Apache 2.0 and MPL 2.0 (open source) | Apache 2.0 | Check the license of your Redis version; Valkey is the BSD fork |
| 37 | Laravel support | Package vladimir-yuldashev/laravel-queue-rabbitmq | Package mateusjunges/laravel-kafka (needs ext-rdkafka) | Redis facade; built-in redis driver uses lists, not streams |
| 38 | Go client maturity | amqp091-go (official RabbitMQ team) | franz-go (pure Go, active), kafka-go | go-redis (mature, typed) |
| 39 | Observability | Management UI, Prometheus plugin, queue depth, unacked | Consumer lag per partition, JMX metrics | XINFO, XPENDING, INFO |
| 40 | Security | TLS, SASL, per-vhost configure/write/read permissions | TLS, SASL (PLAIN, SCRAM, GSSAPI, OAUTHBEARER), ACLs | TLS, 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.
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.
| # | Dimension | NATS JetStream | Pulsar | SQS / SNS | Google Pub/Sub | Laravel database / sqs drivers |
|---|---|---|---|---|---|---|
| 1 | Model | Streams capture subjects; consumers read them | Topics with subscriptions; segment storage | SQS queue; SNS topic fans out to queues | Topic and subscriptions | A jobs table; an SQS queue |
| 2 | Ordering | Per stream | Per partition (Key_Shared per key) | SQS FIFO per message group; Standard best effort | Per ordering key when enabled | Table: by id, not guaranteed; SQS Standard unordered |
| 3 | Delivery | At-least-once with ack; Nats-Msg-Id dedup window | At-least-once; transactions | Standard at-least-once; FIFO dedup | At-least-once; exactly-once delivery option per subscription | At-least-once (lock then delete) |
| 4 | Persistence and replication | File or memory storage; replicated in a cluster | BookKeeper, replicated | Managed, multi-AZ | Managed, regional | Your database; SQS managed |
| 5 | Consumer model | Pull and push consumers; AckExplicit, AckAll, AckNone | Exclusive, Failover, Shared, Key_Shared subscriptions | Poll with visibility timeout (default 30 s, max 12 h) | Pull, push, streaming pull; ack deadline | Worker polls (queue:work) |
| 6 | Routing | Subject wildcards | Topics, topic patterns | SNS filter policies to SQS | Subscription filters | Named queues, priority order |
| 7 | Delay | Not a core feature (check) | Delayed delivery on Shared subscriptions | SQS delay up to 15 min | Not a core feature (check) | Laravel delay(); SQS capped at 15 min |
| 8 | DLQ | MaxDeliver and advisories | Retry letter and dead letter topics | Redrive policy | Dead-letter topic | failed_jobs table |
| 9 | Retention and replay | Limits, work queue or interest policies; replay | Retention plus tiered storage; seek | SQS: 4 days default, 60 s to 14 days, no replay | Default 7 days, up to 31 days; seek needs retained acked messages | Until processed; no replay |
| 10 | Message size | max_payload default 1 MB (config up to 64 MB) | Default 5 MB | 1 MiB (larger via S3 extended client, up to 2 GB) | Check the quotas page | Row size / 1 MiB |
| 11 | Throughput | High, small messages | High | Standard: very high; FIFO: 300 TPS per partition per API (higher with high-throughput mode) | High, autoscaling | Low to medium |
| 12 | Multi-tenancy | Accounts | Tenants and namespaces (first class) | AWS accounts and IAM | Projects and IAM | Application level |
| 13 | Protocols | NATS protocol, MQTT support (check) | Pulsar protocol | HTTPS API | gRPC and REST | n/a |
| 14 | Schema support | None built in | Built-in schema registry | None | Topic schemas (Avro, Protocol Buffers) | None |
| 15 | Transactions | Batch publish, no multi-stream tx (check) | Yes | FIFO dedup only | None across topics | Database transaction (afterCommit) |
| 16 | Ops complexity | Low to medium | High (brokers plus BookKeeper) | None (managed) | None (managed) | Lowest |
| 17 | Hosting | Self-host, Synadia Cloud | Self-host, StreamNative | AWS only | GCP only | Wherever your DB or AWS runs |
| 18 | Licensing | Apache 2.0 | Apache 2.0 | Proprietary service | Proprietary service | MIT (Laravel) |
| 19 | Laravel | No first-party; use a client | No first-party | Built in (sqs driver) | Community packages | Built in |
| 20 | Go client | nats.go (official) | pulsar-client-go (official) | AWS SDK v2 | cloud.google.com/go/pubsub | n/a |
| 21 | Observability | nats CLI, monitoring endpoints | Admin API, Prometheus | CloudWatch | Cloud Monitoring | queue:monitor, Horizon (redis) |
| 22 | Security | TLS, accounts, JWT/NKeys | TLS, JWT, authorization | IAM, KMS | IAM, CMEK | DB 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 startReal 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).
| Need | Queue | Log |
|---|---|---|
| Per-message retry and DLQ | Native | You build it (retry topics) |
| New consumer reads history | No | Yes |
| Many independent readers | Bind more queues | Add a group |
| Storage grows with | Backlog | Retention 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 consumerReal 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.
| Broker | Accepted | Processed |
|---|---|---|
| RabbitMQ | Confirm; quorum queue: majority of replicas | basic.ack |
| Kafka | Produce callback with offset (acks=all) | Committed offset = next offset to read |
| Redis Streams | XADD id on the primary | XACK 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 orderReal 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 outboxReal scenario: rebuilding a search index or a read model after a bug; auditing which events a service saw.
| Broker | Replay | Bound by |
|---|---|---|
| RabbitMQ queues | No | Backlog and TTL |
| RabbitMQ streams | Yes | Size/age |
| Kafka | Yes | Time/size, disk |
| Redis Streams | Yes | MAXLEN/MINID, RAM |
| SQS | No | 14 days max |
| Pub/Sub | With seek | 31 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.
| Broker | Main operational chores |
|---|---|
| RabbitMQ | Memory/disk alarms, queue type choice, quorum membership, shovel/federation across sites |
| Kafka | Partition count, retention, under-replicated partitions, rebalances, controller quorum |
| Redis Streams | maxmemory, persistence, failover, trimming |
| SQS/SNS, Pub/Sub | Quotas, 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
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Task queue (emails, thumbnails) | Laravel database/redis; RabbitMQ when cross-service; SQS on AWS | Idempotent job, backoff (retry) | Per-message retry matters more than throughput |
| Event bus | Kafka, Pulsar; RabbitMQ topic exchange at small scale | Outbox, versioned schema (schema) | Independent subscribers |
| Event log / replay | Kafka, Pulsar, JetStream, RabbitMQ streams | Compacted topics for state | Non-destructive reads |
| Stream processing | Kafka (Kafka Streams, Flink) | Exactly-once inside Kafka | Ecosystem |
| Request/reply | RabbitMQ (reply-to), NATS | Correlation id, timeout | Native pattern |
| IoT / MQTT | RabbitMQ MQTT plugin, NATS, managed IoT | Bridge to Kafka for analytics | Protocol |
| Cross-region | Pulsar geo-replication, SNS+SQS, Pub/Sub; Kafka mirroring; RabbitMQ shovel/federation | Regional ownership of data | Latency and failure domains |
| Serverless | SQS/SNS, Pub/Sub | Redrive, small payloads | Managed triggers |
By team and ops maturity Important
| Team situation | Recommendation | Reason |
|---|---|---|
| 1–3 developers, one app | Database or Redis queue | One thing to run |
| Small team, several services, needs retries/DLQ | RabbitMQ managed | Built-in reliability features |
| Platform team exists, many consumers | Kafka (managed if possible) | Operating it is a job |
| Cloud-native, no ops hire planned | SQS/SNS or Pub/Sub | No servers |
| Already run Redis well | Redis Streams for light cases | Reuse skills |
By scale Important
| Sustained rate | Retention need | Typical fit |
|---|---|---|
| Under 100 msg/s | Hours | Database/Redis queue or any broker; do not add Kafka |
| 100–10,000 msg/s | Hours to days | RabbitMQ, Redis Streams, SQS |
| 10,000–100,000 msg/s | Days to weeks | RabbitMQ streams, Kafka, Pulsar, JetStream |
| Over 100,000 msg/s | Weeks, replay | Kafka 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
| Need | Recommendation | Reason |
|---|---|---|
| No message lost, ever | Outbox plus quorum queue or Kafka acks=all | Confirm then durable replication |
| Loss acceptable (cache invalidation hint) | Redis pub/sub or Redis list | Cheapest |
| Strict per-entity order | Kafka key, SQS FIFO group, single-active-consumer queue | Ordering unit |
| Atomic "DB write and publish" | Transactional outbox + relay or CDC | No broker offers a cross-system transaction |
| Atomic consume-transform-produce | Kafka transactions | Inside Kafka only |
Solutions: migration and coexistence
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| Path | Typical trigger | What changes | Watch for |
|---|---|---|---|
| Laravel database -> Redis | Table polling load | Driver name, QUEUE_CONNECTION | Redis persistence |
| Redis -> RabbitMQ | Need retries, DLQ, routing, durability | Consumers and topology | Prefetch, ack semantics |
| RabbitMQ -> Kafka (events) | Many readers, replay | Keys become partition keys | Per-message retry disappears |
| Kafka -> RabbitMQ | Topic was really a work queue | Offsets are dropped | You lose replay |
| Any -> managed same-protocol | Ops cost | Endpoint and credentials | Quotas, 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.
| Pair | Division of labour |
|---|---|
| RabbitMQ + Kafka | Commands and tasks vs domain events and analytics |
| Redis + Kafka | Cache and light work vs durable event log |
| SQS + Kafka | AWS-native jobs vs cross-team events |
| Laravel database + RabbitMQ | In-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_priceWorked sizing with assumed load of 1,000 messages/s of 1 KB, retained 7 days, replication factor 3:
| Quantity | Calculation | Result |
|---|---|---|
| Messages per month | 1,000 x 86,400 x 30 | 2.592 billion |
| Ingest | 1,000 x 1 KB | about 1 MB/s |
| Retained data | 1 MB/s x 604,800 s | about 605 GB |
| Stored with replication 3 | 605 GB x 3 | about 1.8 TB |
| SQS requests (send, receive, delete, no batching) | 2.592 billion x 3 | about 7.8 billion |
| Cost driver | Self-host | Managed |
|---|---|---|
| Capacity planning | You, ahead of time | Vendor, with quotas |
| Idle cost | Always on | Often scales to zero (SQS, Pub/Sub) |
| Cross-AZ replication traffic | Counted on your bill | In unit price or separate line |
| On-call | Your people | Vendor for the platform, you for consumers |
| Break-even | High steady volume, platform team exists | Spiky or low volume, small team |
Anti-decisions
| Anti-decision | Why it fails | Instead |
|---|---|---|
| Kafka for a 100 msg/s task queue | One slow job stalls a partition, no per-message retry, delay or DLQ; a cluster to run for no volume | Laravel database/redis queue or RabbitMQ (Kafka share groups change this: check your version and client) |
| Redis pub/sub for anything that must not be lost | Pub/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 store | Messages vanish on ack; a new consumer cannot read last month | Streams or Kafka |
| Redis Streams as system of record | RAM-bound; failover can lose acked writes (durability) | A database plus outbox |
Laravel redis driver mistaken for Streams | It uses lists and sorted sets (queue internals) | Redis::xadd for streams |
| A broker to avoid a transaction | No broker commits atomically with your database | Outbox |
| One mega-topic/queue for everything | Cannot tune retention, ordering or ACLs per use | Topic 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:
-- 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:
| Signal | Meaning | Next step |
|---|---|---|
| Jobs table polling dominates DB CPU or row churn hurts | Database is the wrong place | Redis driver, then RabbitMQ |
| Another language/service must consume | Needs a protocol, not a Laravel job payload | RabbitMQ or Kafka with a documented message contract |
| Need retries per message across services, DLQ, routing | Queue features | RabbitMQ |
| Need replay or many independent readers | Log | Kafka |
| Need cloud-managed, no servers | Operations | SQS (built-in driver) |
| Need delay longer than 15 minutes on SQS | SQS 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 commandsRelated: 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.
// 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
}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() }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 }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() }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
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
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
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
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
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
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
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".
// 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
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).
// 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
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.
// 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
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
WAITand 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
databasequeue driver locks rows withFOR UPDATE SKIP LOCKEDon supported engines (Illuminate\Queue\DatabaseQueue).
In architecture: from a single process to a distributed system
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 replayDistributed 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
| Scale | Setup | What changes |
|---|---|---|
| 1x (about 10 msg/s) | Laravel database queue | Nothing |
| 10x (about 100 msg/s) | redis driver + Horizon, or RabbitMQ if services appear | Persistence and retries |
| 100x (about 10,000 msg/s) | RabbitMQ quorum queues with competing consumers, or Kafka for events | Partition/consumer count (scaling consumers) |
| 1000x | Kafka/Pulsar with planned partitions and multi-cluster mirroring | Capacity 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"| # | Experiment | Command (sketch) | Expected, not run |
|---|---|---|---|
| 1 | Publish accepted latency, 1 KB, 10,000 messages, sequential | loop Publish, record p50/p99 | Redis lowest; RabbitMQ (confirm) low; Kafka (acks=all) higher p50 unless batched |
| 2 | Batched throughput | publish concurrently, batch 100 | Kafka highest; RabbitMQ and Redis medium |
| 3 | Consumer lag under a slow handler (50 ms) | 1 consumer, publish 1,000/s for 60 s | Backlog grows ~950/s on all; lag visible as queue depth, group lag, XLEN - acked |
| 4 | Scale consumers to 4 | start 3 more | RabbitMQ and Redis drain faster; Kafka only if partitions are at least 4 |
| 5 | Kill the consumer mid-message | kill -9 the handler | Redelivery on all three (unacked requeue, uncommitted offset, pending entry) |
| 6 | Kill the broker (replicated setup) | stop the leader | RabbitMQ 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..fewCommon misconceptions
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| First choice | The queue you already run (Laravel database/redis) |
| Task queue with retry/DLQ/delay | RabbitMQ quorum queues |
| Event bus and replay | Kafka (or Pulsar, JetStream, RabbitMQ streams) |
| Light, fast, in-stack | Redis Streams, with AOF and WAIT understood |
| AWS / GCP managed | SQS+SNS / Pub/Sub |
| Ordering | Per queue, partition, stream, message group, ordering key |
| Accepted vs processed | Confirm/offset/XADD vs ack/commit/XACK |
| Dual write | Never; use the outbox |
| Migration | Dual publish via outbox, idempotent consumers, move one group at a time |
| Coexistence | Commands on a queue broker, events on a log broker |
| Cost | Machines, storage x replication, network, people |
| Anti-decisions | Kafka at 100 msg/s; Redis pub/sub for must-not-lose |
| Laravel | Built-in: database, sqs, redis, beanstalkd, sync, null; the rest by package or raw client |
| Seam | Publisher/Consumer, handlers idempotent |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Broker | The server that stores and routes messages |
| Queue | Destination where a message is removed after ack |
| Log | Append-only, retained sequence read by position |
| Topic | Named channel (Kafka, Pulsar, SNS, Pub/Sub) |
| Partition | One ordered shard of a Kafka or Pulsar topic |
| Consumer group | Consumers sharing a topic's work, with shared positions |
| Offset | Position of a record in a partition |
| Ack | Consumer tells the broker a message is processed |
| Publisher confirm | RabbitMQ signal that the broker accepted a publish |
acks=all | Kafka produce setting: wait for the in-sync replicas |
| ISR | In-sync replicas of a Kafka partition |
| DLX / DLQ | RabbitMQ dead-letter exchange / dead-letter queue |
| Delivery limit | Maximum redeliveries before dead-lettering (quorum queues) |
| Quorum queue | Replicated RabbitMQ queue type using Raft |
| Stream (RabbitMQ) | Non-destructive append-only queue type |
| Pending entries list | Redis group's list of delivered, un-acked entries |
XAUTOCLAIM | Redis command to take over idle pending entries |
| JetStream | Persistence layer of NATS |
| Share group | Kafka queue-style consumption of partitions |
| Visibility timeout | SQS period a received message is hidden |
| Redrive policy | SQS rule moving messages to a DLQ after repeated receives |
| Outbox | Table written with the business data, relayed to the broker |
| Idempotent consumer | Handler safe to run twice for one message |
| Anti-decision | A choice that fails under its stated workload |
| KRaft | Kafka's built-in metadata quorum, replacing ZooKeeper |
| Geo-replication | Replication of topics across clusters/regions |
References
- Apache Kafka documentation, Design, Producer configs, Topic configs, KRaft
- RabbitMQ, Confirms, Reliability, Dead Letter Exchanges, Quorum Queues, Streams, Priority queues, MQTT, Configuration
- Redis, Streams, XACK, WAIT, Persistence
- NATS, JetStream, Streams, Consumers
- Apache Pulsar, Messaging concepts, Overview
- AWS, SQS quotas, SNS FIFO topics
- Google, Pub/Sub API definition
- Laravel 13, Queues, Redis; DatabaseQueue source
- vladimir-yuldashev/laravel-queue-rabbitmq, php-amqplib, mateusjunges/laravel-kafka, phpredis
- Go clients: amqp091-go, franz-go, go-redis
- Vendor opinion: CloudAMQP, RabbitMQ vs Kafka; Confluent, RabbitMQ vs. Apache Kafka