Messaging Fundamentals: Queues, Topics & Async
"Asynchronous messaging is fundamentally a pragmatic reaction to the problems of distributed systems. Sending a message does not require both systems to be up and ready at the same time." — Gregor Hohpe & Bobby Woolf, Enterprise Integration Patterns, "Messaging" (Integration Styles)
Summary: Messaging replaces "call and wait" with "hand it to a broker and move on": the sender and the receiver stop needing each other at the same moment, and in exchange you accept duplicates, eventual consistency and a new piece of infrastructure. Focus: Why asynchronous, what a message is, queue versus topic versus log versus stream, push versus pull, durability, who owns which guarantee, the Laravel queue as the first messaging a monolith meets, and a map of the 33 chapters of this path. Learning goal: Read the rest of the messaging path with a correct mental model of each broker, pick the right style for a problem, and know which chapter owns every question you will meet next.
This is the entry page and the map of the Messaging path. It teaches the shared vocabulary completely (so the other 32 chapters can build on it) and points to the chapter that owns each deep topic: Integration Styles & Channels for the four styles of integration, Delivery Guarantees, Message Acknowledgment, Ordering & Partitioning and Idempotent Consumers & Inbox for the hard guarantees, RabbitMQ, Kafka and Redis Streams & Pub/Sub for each broker, and the rest through the chapter map. It covers RabbitMQ, Kafka, Redis Streams and the Laravel queue side by side, and names NATS, Pulsar, Amazon SQS/SNS and Google Pub/Sub only to place them (Other Brokers).
Page map
| If you are looking for | Go to |
|---|---|
| The vocabulary in tables you can memorise | Everything in one minute |
| Why asynchronous at all, and what it costs | Why messaging exists |
| MQ in the 1990s, JMS, AMQP, Kafka 2011, Redis Streams 2018 | Where the vocabulary comes from |
| One concept with a timeline and a fix | The concepts, one by one |
| Message vs event vs command vs document | Message kinds |
| RabbitMQ queue vs Kafka log vs Redis stream | Queue, log, stream |
| Point-to-point vs publish/subscribe | Two channel semantics |
| Push vs pull consumption | Push and pull |
| What "durable" really requires | Durability basics |
| Who owns which guarantee | The producer, broker, consumer triangle |
| Messaging vs RPC vs a shared database | Messaging, RPC or shared database |
| Which of Hohpe and Woolf's 65 patterns lives where | EIP coverage map |
| One line about each of the 33 chapters | The path: all chapters |
| How a message really travels, knobs and error names | Mechanics |
| The problems everyone hits first | Solving the first problems |
| Which style for which problem | Choosing a style |
| First Go and Laravel code | Go, Laravel, Broker differences |
| Monolith to distributed system | In architecture |
| Reproduce it | Lab |
| Wrong beliefs, cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts.
| Word | In plain words | Tiny example | Where it is taught |
|---|---|---|---|
| Message | One unit of data handed to a broker, with headers and a body | {"order_id": 42} plus an id and a timestamp | Message kinds, Message Design |
| Command | "Please do this", addressed to one receiver, may be refused | ChargeCard | Message kinds, Event-Driven Architecture |
| Event | "This already happened", no single owner of the reaction | OrderPlaced | Message kinds, Event-Driven Architecture |
| Document | Data handed over; the receiver decides what to do | A price list, a customer record | Message kinds |
| Producer / publisher | The code that sends | The checkout service | Triangle |
| Broker | The server that stores, routes and tracks messages | RabbitMQ, Kafka, Redis | Triangle |
| Consumer / subscriber | The code that receives and works | The email worker | Triangle |
| Queue | A buffer where each message goes to one consumer | RabbitMQ queue, Laravel default queue | Queue, log, stream |
| Topic | A named stream of events many readers can follow | Kafka orders topic, RabbitMQ topic exchange | Two channel semantics |
| Log / stream | An append-only sequence readers walk with their own position | Kafka partition, Redis Stream | Queue, log, stream |
| Ack | The consumer telling the broker "done" | basic.ack, XACK, offset commit | Message Acknowledgment |
| Offset / ID | A reader's position in a log | Kafka offset 17, Redis ID 1700000000000-0 | Queue, log, stream |
The three brokers in one table.
| Question | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| Core object | Queue behind an exchange | Partitioned append-only log (topic) | Append-only stream under one key |
| After a message is read | Removed once acknowledged | Stays until retention removes it | Stays until trimmed (XTRIM, MAXLEN) |
| Who remembers the position | Broker, per message | Cluster, per group and partition (offset) | Server, per group (last-delivered ID + pending list) |
| Delivery to the consumer | Broker pushes | Consumer pulls | Consumer pulls (blocking read) |
| Replay old data | No (stream queues aside) | Yes, move the offset | Yes, read from an older ID |
| Typical use | Work distribution, routing | Event streaming, pipelines, replay | Light queue or stream next to existing Redis |
The five questions to ask of any messaging design.
| Question | Why it decides the design | Chapter |
|---|---|---|
| What happens if the consumer crashes after taking the message? | Decides ack timing and whether duplicates appear | Message Acknowledgment |
| What happens if the producer retries? | Duplicates; needs an idempotent consumer | Idempotent Consumers & Inbox |
| What order must be kept, and per what key? | Decides partitioning and parallelism | Ordering & Partitioning |
| Is the database write and the publish atomic? | If not, you lose or invent events | Transactional Outbox |
| What happens when the consumer cannot keep up, or never succeeds? | Lag, backpressure, poison messages | Backpressure, Dead-Letter Queue |
Why messaging exists
Two services that call each other directly must be up at the same time, must agree on speed, and fail together. Messaging puts a broker in the middle. The fundamental trade-off is a swap, not a free gain.
| You gain | You pay |
|---|---|
| The sender returns before the work is done (temporal decoupling) | The result is not available now: eventual consistency |
| A burst becomes a backlog instead of an outage (load levelling) | Latency grows under load; a backlog can hide a stuck consumer |
| One announcement reaches many readers (fan-out) | The sender no longer knows what runs because of it |
| A downed receiver does not break the sender (resilience) | The broker is a new shared dependency that can fail or fill up |
| Retries come for free from redelivery | Duplicates and reordering; every consumer must cope |
| Teams deploy independently | A shared message contract that must evolve compatibly |
The everyday picture. A post office. You drop a letter in a box and walk away; the recipient need not be home. One mailbox read by one person is a queue. A magazine printed once and delivered as a copy to every subscriber is a topic. Nobody speaks to the recipient directly, which is both the benefit and the reason a lost letter is hard to trace.
Three common misunderstandings, up front.
- "Async makes it faster." It makes the caller return sooner; the work still happens, and end-to-end latency usually goes up.
- "A queue and a topic are different products." They are channel semantics. RabbitMQ builds topics out of exchanges, bindings and queues; Kafka builds queue-like behaviour out of consumer groups; Redis offers both.
- "Messaging decouples everything." It decouples availability and timing. Message shape, delivery semantics and the broker itself stay shared contracts.
Where the vocabulary comes from
Hohpe and Woolf's Enterprise Integration Patterns (2003) fixed the words almost every broker uses today. Their question was integration: applications "built independently, with different languages and platforms" that must share data. Their answer, Messaging, is to "transfer packets of data frequently, immediately, reliably, and asynchronously, using customizable formats". A Message Channel conveys messages from sender to receiver; a Message has a header (for the messaging system) and a body (the data); a Message Endpoint is the client of the messaging system an application uses to send or receive.
The technology has its own timeline. Only the rows with a primary source are quoted; the rest are marked as secondary.
| When | What | Why it matters here | Source type |
|---|---|---|---|
| 1993 | IBM MQSeries (later WebSphere MQ, now IBM MQ) launched | The first widely deployed message-oriented middleware for heterogeneous systems; the origin of "queue manager" thinking | Secondary (Wikipedia) |
| 1998 to 2002 | JMS 1.0.1 (October 1998) to JMS 1.1 (April 2002), now Jakarta Messaging | A Java API, not a wire protocol: queues and topics as the two models | Secondary (Wikipedia); Jakarta Messaging page: "create, send, and receive messages via loosely coupled, reliable asynchronous communication services" |
| 2003 | Enterprise Integration Patterns published | The pattern language: channel, router, translator, endpoint | Primary (EIP site) |
| 2003 to 2008 | AMQP born at JPMorgan Chase (2003); RabbitMQ started 2007; AMQP 0-9-1 published November 2008 | A wire protocol so different vendors interoperate; exchanges, bindings and queues | Secondary (Wikipedia); AMQP 1.0 overview document is primary |
| 2011 | Kafka (LinkedIn), NetDB 2011 paper | The log as the central abstraction, pull consumption, replay | Primary: the paper says it "has been open sourced and used successfully in production at LinkedIn for more than 6 months" |
| 2012 | AMQP 1.0 approved as an OASIS standard (October); ISO/IEC 19464 in 2014 | A protocol significantly different from 0-9-1 | Secondary (Wikipedia) |
| 2018 | Redis 5.0 introduces the Stream data type (RC1, 29 May 2018) | A log with consumer groups inside a server many teams already run | Primary: Redis 5.0 release notes, "1. The new Stream data type." |
The two channel flavours come from the same book. A Point-to-Point Channel "ensures that only one receiver consumes any given message". A Publish-Subscribe Channel "delivers a copy of a particular event to each receiver". Everything that follows is an implementation of one of those ideas or a blend.
The concepts, one by one
Temporal decoupling Must-know
In plain words: The sender and the receiver do not have to be running at the same moment; the broker holds the message in between.
Common misunderstanding: "If the receiver is down the message is lost." With a durable queue or a log it waits; what you must decide is how long (TTL, retention) and who notices the wait.
Definition: Sending completes when the broker has accepted the message, not when the receiver has processed it. The two sides have independent availability and independent speed.
1 t=00:00 checkout service -> broker: publish OrderPlaced (broker accepts, checkout returns 201)
2 t=00:01 email worker is down for a deploy
3 t=00:05 broker holds OrderPlaced on a durable queue
4 t=00:09 email worker starts, takes OrderPlaced (customer gets the mail 8 minutes late)
5 t=00:09 email worker -> broker: ack (message removed)Real scenario: welcome emails, invoice PDFs, search indexing, webhook delivery, image thumbnails: anything the user does not wait for.
| Broker | How the wait is bounded |
|---|---|
| RabbitMQ | Queue length limits, per-message or per-queue TTL; see Message Acknowledgment |
| Kafka | Topic retention (retention.ms, retention.bytes); the group's position is kept |
| Redis Streams | XTRIM, MAXLEN on XADD; unacknowledged entries stay in the pending list |
| Laravel queue | Job retry_after and $tries; failed_jobs table |
Fix / how to use it: Return 202 Accepted from the HTTP request and enqueue the work; see Laravel and the lab.
Load levelling Must-know
In plain words: A queue is a shock absorber: a traffic spike becomes a longer line, not a crash.
Common misunderstanding: "The queue makes the system scale." It only moves the problem in time. If consumers are slower than producers on average, the queue grows forever.
Definition: The arrival rate may exceed the service rate for a while because the backlog (queue depth, consumer lag) absorbs the difference. Controlling the drain speed is Backpressure & Flow Control; adding drains is Competing Consumers.
1 arrival rate 500 msg/s for 60 s (a flash sale), then 50 msg/s
2 one worker handles 100 msg/s
3 backlog grows by 400/s for 60 s = 24 000 messages
4 after the spike backlog shrinks by 50/s -> 480 s to drain (customers see delay, not errors)
5 with 5 workers service rate 500 msg/s: backlog never formsReal scenario: Black Friday order intake, end-of-month batch imports, a mobile push campaign, a webhook storm from a payment provider.
| Broker | Signal that the backlog is growing |
|---|---|
| RabbitMQ | Queue depth (messages ready and unacknowledged) in the management UI or metrics |
| Kafka | Consumer lag per partition (log end offset minus committed offset) |
| Redis Streams | XLEN, XPENDING, group lag in XINFO GROUPS |
| Laravel queue | queue:monitor, Horizon wait times |
Fan-out Must-know
In plain words: One announcement, many independent reactions, and the announcer does not know who listens.
Common misunderstanding: "Fan-out is just calling three services in a loop." In a loop the producer owns every receiver, fails when one fails and must be redeployed to add one. With a topic a new receiver subscribes without touching the producer.
Definition: A publish/subscribe channel delivers a copy of each message to every subscriber; each subscriber consumes its copy independently.
1 OrderPlaced published once to topic "orders"
2 billing subscription -> copy 1 -> invoice created
3 shipping subscription -> copy 2 -> pick list created
4 analytics subscription -> copy 3 -> counter incremented
5 loyalty added next month -> subscribes, nobody else changesReal scenario: order lifecycle events, user-signup hooks, cache invalidation across instances, audit trails, search-index updates.
| Broker | How fan-out is built |
|---|---|
| RabbitMQ | Fanout or topic exchange binds one queue per subscriber; see Routing Topologies |
| Kafka | One topic, one consumer group per subscriber |
| Redis | Streams: one consumer group per subscriber; classic Pub/Sub: SUBSCRIBE (no history) |
| Laravel | An event with several listeners; queued listeners implement ShouldQueue |
Resilience and failure isolation Important
In plain words: If the email service is on fire, checkout still works.
Common misunderstanding: "Messaging removes failure." It moves failure from the request into the consumer, where it becomes retries, a dead-letter queue and a lag alarm.
Definition: A failing consumer does not fail the producer; the broker redelivers the message (Retry & Backoff), and a message that can never succeed is parked (Dead-Letter Queue).
1 worker takes message m7, throws an exception
2 no ack arrives -> broker marks m7 for redelivery
3 attempt 2, 3 ... fail -> backoff between tries
4 attempt 5 fails -> m7 moved to the dead-letter queue, alarm raised
5 the queue behind m7 keeps drainingReal scenario: a third-party API outage during email sending; a bad deploy of one consumer; a malformed message from an old producer.
The cost: eventual consistency Important
In plain words: After you hand the message over, the world is briefly inconsistent: the order exists but the invoice does not yet.
Common misunderstanding: "I can read my own result right after publishing." The consumer may not have run yet; design the screen to say "processing".
Definition: State changed by a consumer becomes visible some time after the producer's write, with no upper bound unless you set one. There is no transaction across the database and the broker (ACID & Transactions); the answers are the Transactional Outbox and the Saga.
Real scenario: the user pays, the page says "thank you", the order list still shows "pending" for two seconds; a stock count in search lags behind the database.
The cost: duplicates and reordering Important
In plain words: The same message can arrive twice, and two messages can arrive out of order.
Common misunderstanding: "My broker gives exactly-once." Exactly-once end to end needs an idempotent consumer; brokers offer at-least-once by default (Delivery Guarantees).
Definition: Redelivery after a missing ack, a producer retry after a lost confirm, and a rebalance can each create a duplicate. Parallel consumers and retries can break order.
1 consumer takes m1, charges the card
2 consumer crashes before sending the ack
3 broker redelivers m1 to another consumer
4 second consumer charges the card again (duplicate side effect)
5 fix: an idempotency key checked in the same DB transaction as the chargeReal scenario: double charges, double emails, two shipments, a counter incremented twice, "status = shipped" overwritten by an older "status = packed".
| Broker | Duplicate sources |
|---|---|
| RabbitMQ | Consumer crash before ack; requeue; publisher retry after missing confirm |
| Kafka | Producer retry without idempotence; offset committed after processing then crash; rebalance |
| Redis Streams | Entry delivered but not acknowledged is reclaimed (XCLAIM, XAUTOCLAIM) |
| Laravel queue | Job exceeds retry_after while still running and is handed to a second worker |
The cost: debugging across hops Important
In plain words: There is no single stack trace any more; one business action leaves clues in four services.
Common misunderstanding: "Logs from each service are enough." Without a correlation id carried in the message headers you cannot join them (Messaging Observability & Tracing).
Real scenario: "the customer paid but got no invoice": which hop dropped it, the producer, the broker, the consumer or the dead-letter queue?
Message kinds: message, event, command, document
One envelope, four intents Must-know
In plain words: A message is just an envelope; the intent in it is what differs: do this (command), this happened (event), here is some data (document).
Common misunderstanding: "Commands and events are different broker features." No. Hohpe and Woolf say "there is no specific message type for commands; a Command Message is simply a regular message that happens to contain a command". Intent is a naming and ownership convention, not a protocol field.
Definition:
| Kind | Intent | Naming | Receivers | May be refused? | EIP pattern |
|---|---|---|---|---|---|
| Command | Ask one party to do something | Imperative: ChargeCard | Exactly one owner | Yes | Command Message |
| Event | Announce a fact that already happened | Past tense: OrderPlaced | Any number, unknown to the sender | No (it already happened) | Event Message |
| Document | Hand over data; the receiver decides what to do | Noun: CustomerSnapshot | One or many | The receiver decides | Document Message |
| Query / request | Ask for data and wait for the answer | GetPrice | One | Yes | Request-Reply |
1 command checkout -> payments : ChargeCard{order 42} (one receiver, may answer "declined")
2 event payments -> topic : PaymentCaptured{order 42} (facts; billing, shipping, analytics react)
3 document catalog -> search : ProductSnapshot{sku 7, full state}The EIP site separates event and document by "timing and content": an event's "contents is typically less important", its "timing is very important"; for a document "the important part ... is its content". Event-Driven Architecture develops event notification versus event-carried state transfer, and Message Design & Schema Evolution the envelope and versioning. This site's earlier chapter on domain versus integration events is DDD: Domain Events & Integration Events.
Real scenario: SendInvoice as a command on a work queue (one worker must do it); InvoiceSent as an event on a topic (CRM, analytics and audit react); a nightly PriceList document.
| Product | Commands | Events |
|---|---|---|
| RabbitMQ | A queue named for the receiver, default exchange | A topic or fanout exchange, one queue per subscriber |
| Kafka | Rare; a topic with one consuming group | The natural fit: topic per event type or aggregate |
| Redis Streams | A stream with one consumer group | A stream with one group per subscriber |
| Laravel | A queued job (ShouldQueue) | An event with queued listeners |
Queue, log, stream: three mental models
Queue (RabbitMQ) Must-know
In plain words: A line at a counter: the broker hands the first message to a free consumer, and once that consumer says "done" the message is gone.
Common misunderstanding: "A queue keeps messages forever." A queue holds them until consumed and acknowledged; after the ack nothing remains, so there is no replay.
Definition: A broker-side buffer, usually first-in first-out, that tracks delivery state per message. Publishers send to an exchange; bindings route copies into queues; the broker pushes messages to consumers registered on the queue. The AMQP 0-9-1 guide: exchanges "distribute message copies to queues using rules called bindings". RabbitMQ also offers queue types beyond the classic one (quorum queues, and streams, "an immutable append-only log" with offsets), so "RabbitMQ" does not always mean "queue that deletes on ack".
1 producer -> exchange "" (default), routing key "emails"
2 exchange -> queue "emails": [m3, m2, m1]
3 consumer C1 (prefetch 1) receives m1 (m1 is unacked: invisible to others)
4 C1 -> ack(m1) (m1 deleted)
5 consumer C2 receives m2 ...Log (Kafka) Must-know
In plain words: A ledger that only grows. Readers keep a bookmark; reading does not erase.
Common misunderstanding: "A Kafka topic is a big queue." Reads do not consume: two groups read the same events independently, and an old event can be read again.
Definition: A topic is split into partitions; each partition is an ordered, append-only log with a numeric offset. Kafka's own introduction: "unlike traditional messaging systems, events are not deleted after consumption. Instead, you define for how long Kafka should retain your events through a per-topic configuration setting." Events with the same key go to the same partition and "any consumer of a given topic-partition will always read that partition's events in exactly the same order as they were written". The "subscription" is a consumer group: members of one group split the partitions, and a second group reads everything again.
1 producer -> topic orders, key "customer-7" -> partition 1, offset 41
2 group billing reads partition 1 up to offset 41, commits 42
3 group analytics is still at offset 12 (slow); nothing is lost
4 a new group "search" starts at offset 0 (retention allowing) and replays historyStream (Redis) Must-know
In plain words: A log like Kafka's, but living in one Redis key, with a built-in "who has taken what" bookkeeping for each consumer group.
Common misunderstanding: "Redis Pub/Sub and Redis Streams are the same thing." Pub/Sub keeps nothing: the Redis docs say it "exhibits at-most-once message delivery semantics" and a missed message "is forever lost". Streams are persisted entries with groups.
Definition: The Redis docs: "A Redis stream is a data structure that acts like an append-only log but also implements several operations to overcome some of the limits of a typical append-only log. These include random access in O(1) time and complex consumption strategies, such as consumer groups." XADD appends an entry; XREADGROUP delivers entries to group members; the group stores a last-delivered ID and a pending entries list (PEL) until XACK.
1 XADD orders * body "..." -> id 1700000000000-0
2 XGROUP CREATE orders billing 0 MKSTREAM (first time only)
3 XREADGROUP GROUP billing c1 COUNT 1 STREAMS orders > -> entry delivered, now in the PEL
4 XACK orders billing 1700000000000-0 -> removed from the PEL
5 c1 dies before step 4 -> another consumer runs XAUTOCLAIM and takes the entry overPer-broker summary:
| Aspect | RabbitMQ queue | Kafka partition | Redis stream |
|---|---|---|---|
| Storage after read | Deleted on ack | Kept until retention | Kept until trimmed |
| Position tracking | Per message, in the broker | Offset per group, in the cluster | Last-delivered ID plus PEL per group |
| Multiple independent readers | One queue per reader (via exchange) | One group per reader | One group per reader |
| Order | FIFO per queue; requeue and parallel consumers can reorder | Per partition | Per stream |
| Replay | No | Yes | Yes |
| Where bytes live | Broker disk and memory | Broker disk, replicated | Redis memory, AOF/RDB |
Two channel semantics: point-to-point and publish/subscribe
Point-to-point versus publish/subscribe Must-know
In plain words: Point-to-point: many workers, each message handled once. Publish/subscribe: many listeners, each message handled once per listener.
Common misunderstanding: "A broker supports one or the other." Real brokers blend them: a Kafka topic read by two groups is publish/subscribe between groups and point-to-point inside each group.
Definition: Hohpe and Woolf: a Point-to-Point Channel "ensures that only one receiver consumes any given message"; if several receivers compete, "the channel ensures that only one of them succeeds, so the receivers do not have to coordinate with each other". A Publish-Subscribe Channel "has one input channel that splits into multiple output channels, one for each subscriber" and "consumed copies disappear from their channels".
| Point-to-point | Publish/subscribe | |
|---|---|---|
| Receivers per message | One of N | All N |
| Purpose | Distribute work | Announce facts |
| Scaling by adding consumers | Yes (competing consumers) | Adds a new reaction, not capacity |
| RabbitMQ | One queue, many consumers | Exchange with one queue per subscriber |
| Kafka | Many members in one group | Many groups |
| Redis | LPUSH/BRPOP list or one stream group | One stream group per subscriber, or Pub/Sub |
| Laravel | Job on a queue | Event with several listeners |
| Chapter | Competing Consumers | Routing Topologies |
1 point-to-point queue [j1 j2 j3 j4] workers {A,B} -> A:j1 B:j2 A:j3 B:j4 (4 handled)
2 publish/sub topic [e1 e2] subscribers {X,Y} -> X:e1 X:e2 Y:e1 Y:e2 (4 deliveries)The Go program in the Go section runs exactly this comparison in-process with channels.
Push and pull
Push versus pull consumption Important
In plain words: Push: the broker hands you messages when they arrive. Pull: you ask for the next batch when you are ready.
Common misunderstanding: "Push is real-time, pull is slow." A long poll or a blocking read returns the instant data exists; the real difference is who controls the pace.
Definition: RabbitMQ lets applications "subscribe to have RabbitMQ push enqueued messages (deliveries) to them" and documents basic.get polling as something to avoid: "Use long-lived consumers instead of polling". Kafka's design page explains the opposite choice: "a push-based system has difficulty dealing with diverse consumers as the broker controls the rate at which data is transferred ... A pull-based system has the nicer property that the consumer simply falls behind and catches up when it can", and pull "lends itself to aggressive batching". Its drawback, busy waiting, is solved with long polling parameters on the fetch request.
1 push (RabbitMQ) broker -> consumer : delivery m1, m2, m3 ... up to prefetch unacked
2 push, slow cons. prefetch limit reached -> broker stops sending until acks arrive
3 pull (Kafka) consumer -> broker : fetch from offset 42 (wait up to N ms)
4 pull broker -> consumer : records 42..61 (a batch)| Broker | Model | Pace control |
|---|---|---|
| RabbitMQ | Push (basic.consume), pull available (basic.get) | prefetch_count (QoS) |
| Kafka | Pull (poll/fetch) | max.poll.records, fetch sizes |
| Redis Streams | Pull (XREAD/XREADGROUP with BLOCK) | COUNT per read |
| Laravel queue | Worker pulls from the driver in a loop | queue:work --sleep, Redis block_for |
Pace control is the subject of Backpressure & Flow Control.
Durability basics
What "durable" actually requires Must-know
In plain words: A message survives a broker restart only if every link in the chain wrote it to disk (or to enough replicas) before you were told "accepted".
Common misunderstanding: "I declared a durable queue, so messages are safe." RabbitMQ says applications "must use durable queues and make sure that publishers mark published messages as persisted"; messages published as transient "will be discarded during recovery, even if they were stored in durable queues".
Definition: Durability is a chain: the producer waits for the broker's confirmation, the broker persists (disk, replicas), and the consumer acknowledges only after its own work is stored. EIP calls the idea Guaranteed Delivery: "the send operation does not complete successfully until the message is safely stored".
1 producer -> broker : publish (persistent)
2 broker writes to disk / replicas, THEN confirms (RabbitMQ: publisher confirm; Kafka: acks)
3 producer receives confirm; only now treat it as sent
4 broker restarts; durable queue + persistent message is recovered
5 consumer works, stores its result, THEN acks| Layer | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| Container is durable | Durable queue | Topic partitions on disk | Stream key in AOF/RDB |
| Message is durable | Persistent delivery mode | Written to the log | Written to AOF with the chosen fsync |
| Producer knows it is safe | Publisher confirms | acks (0, 1, all), min.insync.replicas | Reply to XADD; replica ack via WAIT is separate |
| Survives node loss | Quorum queues replicate | Replication factor and in-sync replicas | Replication is asynchronous by default |
The Redis docs warn: "AOF must be used with a strong fsync policy if persistence of messages is important". Kafka notes that "acknowledgement by all replicas" means all in-sync replicas by default. Details: Delivery Guarantees and, for the storage side, Durability, WAL & Crash Recovery and Replication, Read Replicas & Failover.
The producer, broker and consumer triangle
Who owns which guarantee Must-know
In plain words: Three parties, four hops. Each party can fail, and each owns a different promise.
Common misunderstanding: "The broker guarantees delivery." The broker guarantees what it stored. Whether the message was produced once, processed once, and acknowledged at the right time is decided by your two programs.
Definition:
| Hop | What can go wrong | Who protects you | Protection |
|---|---|---|---|
| 1 publish | Message lost before the broker has it; duplicate on retry | Producer | Wait for confirm; retry; idempotent producer; attach an id |
| 2 confirm | Confirm lost, producer retries an accepted message | Producer and consumer | Dedup downstream |
| Storage | Broker crash, disk loss, failover | Broker | Persistence, replication, quorum |
| 3 deliver | Message sent twice, or in a different order | Broker, consumer | Redelivery rules; ordering keys |
| 4 ack/commit | Acked before work (lost) or after work (duplicate if crash) | Consumer | Ack after the work; idempotent handler |
| Database + publish | Row saved, message never sent (or the reverse) | Producer | Transactional Outbox |
The vocabulary of the guarantees (the Kafka design page: "At most once - Messages may be lost but are never redelivered. At least once - Messages are never lost but may be redelivered. Exactly once - Each message is processed once and only once") is the subject of Delivery Guarantees.
Messaging, RPC or a shared database?
Choosing how two systems talk Important
In plain words: You can call the other system (RPC), read its tables (shared database), drop a file, or send it a message. Each trades simplicity against independence.
Common misunderstanding: "REST between microservices is already decoupled." It is decoupled in language and deployment, not in time: the callee must be up now.
Definition: The four classic integration styles are File Transfer, Shared Database, Remote Procedure Invocation and Messaging; Integration Styles & Channels owns them in depth. The comparison below is this page's own synthesis, not a quote.
| Request/response (REST, gRPC) | Shared database | Messaging | |
|---|---|---|---|
| Availability | Callee must be up now | Both depend on one database | Callee may be down; message waits |
| Result | In the same call | Read the row | Separate message, or none (Request-Reply) |
| Failure | Caller sees the error | Locks and schema coupling | Retries, redelivery, duplicates |
| Debugging | One stack trace | Query logs | Trace across hops |
| Consistency | Can sit in one transaction | Strong, inside one database | Eventual; needs Outbox and Saga |
| Coupling | Contract plus availability | Schema (worst) | Contract plus broker |
When the caller needs the answer now, plain REST is simply right. See also Service Communication.
EIP coverage map: Hohpe and Woolf's 65 patterns
The book's table of contents lists 65 patterns: four integration styles plus 61 messaging patterns in seven groups (systems, channels, construction, routing, transformation, endpoints, system management). Every pattern is owned by exactly one chapter of this path; this table is the index.
| Chapter | EIP patterns it owns | Count |
|---|---|---|
| Messaging Fundamentals (this page) | Message, Command Message, Document Message, Event Message, Point-to-Point Channel, Publish-Subscribe Channel, Pipes and Filters | 7 |
| Integration Styles & Channels | File Transfer, Shared Database, Remote Procedure Invocation, Messaging, Message Channel, Datatype Channel, Invalid Message Channel, Guaranteed Delivery, Channel Adapter, Messaging Bridge, Message Bus, Message Sequence, Message Expiration, Format Indicator | 14 |
| Message Transformation | Message Translator, Envelope Wrapper, Content Enricher, Content Filter, Normalizer, Canonical Data Model, Messaging Mapper | 7 |
| Message Design & Schema Evolution | Claim Check | 1 |
| Routing Topologies | Message Router, Content-Based Router | 2 |
| Advanced Routing | Message Filter, Dynamic Router, Recipient List, Splitter, Aggregator, Resequencer, Composed Message Processor, Scatter-Gather, Routing Slip, Process Manager, Message Broker | 11 |
| Consumer & Endpoint Patterns | Message Endpoint, Messaging Gateway, Transactional Client, Polling Consumer, Event-Driven Consumer, Message Dispatcher, Selective Consumer, Durable Subscriber, Service Activator | 9 |
| Competing Consumers & Scaling | Competing Consumers | 1 |
| Idempotent Consumers & Inbox | Idempotent Receiver | 1 |
| Request-Reply | Request-Reply, Return Address, Correlation Identifier | 3 |
| Dead-Letter Queue | Dead Letter Channel | 1 |
| System Management | Control Bus, Detour, Wire Tap, Message History, Message Store, Smart Proxy, Test Message, Channel Purger | 8 |
| Total | 65 |
Chapters that are not in the table implement patterns rather than own them: the Saga, Transactional Outbox, Event Sourcing & CQRS, Change Data Capture, Stream Processing and Retry & Backoff chapters cover patterns from other catalogues (Richardson's microservices.io, Fowler, Kleppmann) that sit on top of the EIP vocabulary.
The path: all 33 chapters
Read top to bottom the first time. The order is the learning order: vocabulary, brokers, patterns built on them, then running them in production.
| # | Chapter | One line |
|---|---|---|
| MSG 01 · Fundamentals | ||
| 1 | Messaging Fundamentals | This page: why async, queue vs log vs stream, the map of the path |
| 2 | Integration Styles & Channels | File, shared database, RPC and messaging compared; channel patterns such as Guaranteed Delivery and Message Bus |
| 3 | Delivery Guarantees | At-most, at-least and exactly-once; why end-to-end exactly-once needs idempotency |
| 4 | Message Acknowledgment | Ack, nack, reject, prefetch, offset commit, XACK and redelivery |
| 5 | Ordering & Partitioning | Per-key order, partition keys, head-of-line blocking |
| 6 | Idempotent Consumers & Inbox | Dedup keys and the inbox table so a duplicate does no harm |
| 7 | Message Design & Schema Evolution | Envelope, versioning, Avro/Protobuf/JSON Schema, registry, claim check |
| 8 | Message Transformation | Translator, Enricher, Normalizer, Canonical Data Model |
| MSG 02 · Brokers | ||
| 9 | RabbitMQ in Depth | Exchanges, bindings, queue types, confirms, clustering |
| 10 | Kafka in Depth | Topics, partitions, groups, replication, transactions |
| 11 | Redis Streams & Pub/Sub | XADD, consumer groups, the pending list, Pub/Sub limits |
| 12 | Broker Comparison | Side-by-side table and decision guide, delivery and ack verified |
| 13 | Other Brokers | NATS JetStream, Pulsar, SQS/SNS, Google Pub/Sub |
| MSG 03 · Routing & Consumers | ||
| 14 | Routing Topologies | Exchange types, topic design, content-based routing |
| 15 | Advanced Routing | Splitter, Aggregator, Resequencer, Scatter-Gather, Routing Slip, Process Manager |
| 16 | Consumer & Endpoint Patterns | Polling vs event-driven consumer, gateway, selective consumer, durable subscriber |
| 17 | Competing Consumers & Scaling | Worker pools, consumer groups, rebalancing, graceful shutdown |
| 18 | Request-Reply & REST vs AMQP | Correlation ids, reply queues, sync-over-async trap |
| MSG 04 · Reliability Patterns | ||
| 19 | Transactional Outbox | Write the event with the data, publish it after |
| 20 | Saga | Distributed workflows with compensation |
| 21 | Dead-Letter Queue | Poison messages, parking lots, failed_jobs |
| 22 | Retry, Backoff & Delayed Delivery | Exponential backoff with jitter, delayed messages per broker |
| 23 | Durable Workflows & Jobs | Temporal model, Laravel batches and chains, reconciliation |
| MSG 05 · Event-Driven & Streams | ||
| 24 | Event-Driven Architecture | Events vs commands, notification vs state transfer |
| 25 | Event Sourcing & CQRS | Event store, replay, projections, when not to |
| 26 | Change Data Capture | Log-based CDC, Debezium, logical decoding |
| 27 | Stream Processing | Event time, windows, watermarks, state |
| MSG 06 · Operations | ||
| 28 | Backpressure & Flow Control | Prefetch, lag, bounded buffers, load shedding |
| 29 | Messaging Observability & Tracing | Trace context in headers, lag and DLQ metrics |
| 30 | System Management Patterns | Control Bus, Wire Tap, Detour, Message Store, Test Message |
| 31 | Laravel Queue Internals | Drivers, Redis lists and sorted sets, uniqueness, batches, Horizon |
| 32 | Testing Messaging Systems | Queue::fake, testcontainers, contract tests |
| 33 | Messaging Security | TLS, SASL, ACLs, payload encryption, erasure in logs |
Three reading routes for people in a hurry:
| You are | Read in this order |
|---|---|
| A Laravel developer with queues in production | 1, 3, 4, 6, 31, 21, 22, 19, 17 |
| Choosing a broker for a new system | 1, 9, 10, 11, 12, 13, 3, 5 |
| Splitting a monolith into services | 1, 2, 19, 20, 6, 24, 18, 29 |
Mechanics: how a message really travels
The six building blocks of a messaging system
The EIP "Messaging Systems" group names the parts every broker is made of. This page teaches the first two and the last; the rest are owned by later chapters.
| Building block | EIP definition in short | In RabbitMQ / Kafka / Redis / Laravel | Owned by |
|---|---|---|---|
| Message Channel | "the structure in a messaging system that conveys messages from the sender to the receiver" | Queue or exchange / topic / stream key / named queue | Integration Styles & Channels |
| Message | A data record with a header (for the messaging system) and a body (the data) | AMQP properties + body / record key, value, headers / entry fields / job payload | This page |
| Pipes and Filters | Chain independent processing steps, each reading from one channel and writing to the next | Queue chains / topic-to-topic pipelines / stream-to-stream / Bus::chain | This page |
| Message Router | Consume from one channel and republish to a different one depending on conditions | Exchange bindings / topic choice in code / consumer republishing / event listeners | Routing Topologies |
| Message Translator | Convert one application's data model into another's | Consumer-side mapper in all four | Message Transformation |
| Message Endpoint | The client code an application uses to send or receive | amqp091-go channel, kgo.Client, redis.Client, Laravel dispatch()/worker | Consumer & Endpoint Patterns |
Pipes and Filters in practice: the output of one consumer is the input of the next, so each step can be scaled and replaced alone. A Laravel Bus::chain([...]) and a Kafka topic-to-topic processor are both pipelines; the cost is one more hop (and one more place to lose or duplicate a message) per filter.
The five steps of a message's journey
Every messaging system, whatever its brand, runs the same five steps. The table names the step and the knob that controls it on each product.
| Step | What happens | RabbitMQ knob | Kafka knob | Redis Streams knob | Laravel knob |
|---|---|---|---|---|---|
| 1 Serialize | Turn the object into bytes plus headers | Properties and headers (content_type, correlation_id) | Record key, value, headers; serializer | Field-value pairs in the entry | Job payload (JSON with a serialized command) |
| 2 Send and confirm | Hand to the broker and wait | Publisher confirms (confirm.select) | acks (0, 1, all), enable.idempotence | Reply to XADD | dispatch(), after_commit |
| 3 Store | Make it durable | Durable queue + persistent message; quorum queue | Replication factor, min.insync.replicas, retention | AOF (appendonly, appendfsync), replication | Table row or Redis list item |
| 4 Deliver | Move it to a consumer | basic.consume, prefetch_count | group.id, max.poll.records, partition assignment | XREADGROUP, COUNT, BLOCK | queue:work, block_for, --sleep |
| 5 Acknowledge | Tell the broker it is done | basic.ack, nack, reject | Commit offset (enable.auto.commit or manual) | XACK | Job finishes without exception, row deleted |
Declaring things. A RabbitMQ queue must be declared before use; declaring again with the same attributes is a no-op, and with different attributes the broker raises a channel-level exception with code 406 (PRECONDITION_FAILED). Kafka topics have num.partitions and a replication factor fixed at creation (partitions can be added later, which changes key placement). A Redis consumer group is created once with XGROUP CREATE ... MKSTREAM; creating it again answers BUSYGROUP.
Error names you will meet first.
| Product | Error | Meaning | Retry? |
|---|---|---|---|
| RabbitMQ | 406 PRECONDITION_FAILED | Queue or exchange redeclared with different attributes; also an ack for an unknown delivery tag | No: fix the declaration or the double ack |
| RabbitMQ | 404 NOT_FOUND | Queue or exchange does not exist | No until it is declared |
| Kafka | UNKNOWN_TOPIC_OR_PARTITION | Topic missing (or metadata stale) | Yes after metadata refresh, or create the topic |
| Kafka | NOT_LEADER_OR_FOLLOWER | The partition leader moved | Yes, the client refreshes metadata |
| Kafka | NOT_ENOUGH_REPLICAS | acks=all but in-sync replicas are below min.insync.replicas | Yes later; it is a durability signal, not a bug |
| Redis | BUSYGROUP | Consumer group already exists | Ignore on startup |
| Redis | NOGROUP | The stream or group does not exist | Create the group |
| Laravel | MaxAttemptsExceededException | Job was attempted more times than allowed | No: it goes to failed_jobs |
Solving the first problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Job runs before the transaction that created its data has committed | Dispatch after commit | afterCommit() or after_commit => true; or an outbox | Worker never sees missing rows | Dispatch is lost if the process dies right after commit: use the Outbox for must-not-lose |
| The same message arrives twice | Idempotent consumer | Unique message id checked in the same database transaction as the effect | Safe retries | An extra table and a key discipline (Inbox) |
| A burst overloads the system | Queue plus workers | Put the work on a queue and scale workers | Spike becomes latency | Backlog must be watched (Backpressure) |
| One message always fails | Dead-letter queue | Cap attempts, then park the message | The queue keeps flowing | Someone must look at the parking lot (DLQ) |
| Caller needs the result | Request-reply, or just REST | Correlation id and reply queue | Stays async | More moving parts than a call (Request-Reply) |
| Order matters | Partition by key | Same key, same partition or queue | Per-entity order | Parallelism limited per key (Ordering) |
| Several services must change together | Saga | Local transactions plus compensations | No distributed transaction | Complex (Saga) |
Dispatching before the commit Important
In plain words: A fast worker can pick the job up before the web request has committed the row the job needs.
Common misunderstanding: "Dispatch inside the transaction is safe because it is inside the transaction." The queue is not part of the database transaction. Laravel's docs: "it is possible that the job will be processed by a worker before the parent transaction has committed".
1 T-web BEGIN
2 T-web INSERT INTO orders (id=42, ...)
3 T-web dispatch(SendInvoice{42}) -> Redis / SQS accepts it immediately
4 worker takes SendInvoice{42}, runs SELECT * FROM orders WHERE id = 42 -> 0 rows
5 T-web COMMIT (too late; the job fails or finds nothing)The fix is to hold the dispatch until the commit. Laravel waits for the commit when after_commit is true or afterCommit() is called, and discards the job if the transaction rolls back. The database queue driver avoids the race because the job row lives in the same database, but then it also shares its fate and load.
-- PostgreSQL rendition of Laravel's `jobs` table (the database queue driver; see database/migrations/0001_01_01_000002_create_jobs_table.php)
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
queue varchar(255) NOT NULL,
payload text NOT NULL,
attempts smallint NOT NULL,
reserved_at integer,
available_at integer NOT NULL,
created_at integer NOT NULL
);
CREATE INDEX jobs_queue_index ON jobs (queue);
-- How many workers take rows without waiting on each other.
-- PostgreSQL docs: SKIP LOCKED "can be used to avoid lock contention with multiple consumers accessing a queue-like table".
-- Laravel's DatabaseQueue::getLockForPopping() chooses FOR UPDATE SKIP LOCKED on PostgreSQL 9.5+, MySQL 8.0.1+ and
-- MariaDB 10.6+ (read in the 13.x source); this sketch is the idea, not Laravel's literal statement
-- (the reservation logic is in Laravel Queue Internals).
BEGIN;
SELECT id, payload FROM jobs
WHERE queue = 'default' AND reserved_at IS NULL AND available_at <= extract(epoch FROM now())
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 1;
-- ... mark reserved, commit, run the job, delete the row when done ...
COMMIT;-- Idempotent consumer: the unique key makes the second delivery a no-op (details in Idempotent Consumers & Inbox)
CREATE TABLE processed_messages (
message_id uuid PRIMARY KEY,
processed_at timestamptz NOT NULL DEFAULT now()
);
-- inside the same transaction as the business effect:
INSERT INTO processed_messages (message_id) VALUES ($1) ON CONFLICT DO NOTHING;
-- 0 rows affected => duplicate, skip the effectRetry and failure handling
| Failure | Retry? | Rule |
|---|---|---|
| Network blip while publishing | Yes | Retry with the same message id, so a duplicate can be recognised |
| Broker refused (full, memory alarm, no leader) | Yes, with backoff | Slow the producer; see Backpressure |
| Consumer exception from a flaky dependency | Yes, with backoff and a cap | Retry & Backoff |
| Consumer exception from bad data | No | Park it in the DLQ; retrying cannot help |
| Consumer crash mid-work | Automatic redelivery | Handler must be idempotent |
Choosing a style
| Problem | Style | Product to reach for first | Reason |
|---|---|---|---|
| Send an email, resize an image, generate a PDF after a request | Work queue (point-to-point) | Laravel queue on Redis or database; SQS in AWS | Simple, one consumer per job |
| Spread heavy tasks over many workers | Competing consumers | RabbitMQ or a Laravel Redis queue | Fair dispatch, prefetch |
| Tell several services that an order was placed | Publish/subscribe events | RabbitMQ topic exchange, or Kafka topic with groups | One publish, many reactions |
| Keep an immutable history that new services can replay | Log / event stream | Kafka, or Redis Streams at small scale | Replay by moving the offset |
| Very high throughput data pipeline | Partitioned log | Kafka | Sequential I/O, partitions, batching |
| A small app that already runs Redis and needs light queues | Redis list queue or Stream | Laravel Redis driver or Streams | No new infrastructure |
| Per-customer ordering of events | Keyed partitions or single-active consumer | Kafka keys, RabbitMQ consistent-hash exchange | Order per key, parallel across keys |
| The caller needs the answer in the same request | RPC (REST/gRPC) | HTTP | Messaging adds only delay |
| Move changes from a database to others | CDC plus log | Debezium into Kafka | Change Data Capture |
| Long multi-step business process | Saga or durable workflow | Orchestrator service, Temporal, Laravel chains | Saga, Durable Workflows |
| Fire-and-forget notifications where loss is acceptable | Redis Pub/Sub or plain events | Redis Pub/Sub | At-most-once is fine, no storage |
| A monolith needs background work today | Queue in the same app | Laravel database or redis driver | The cheapest first step |
| Must not lose an event when the database commits | Outbox plus relay | Outbox table with polling or CDC | Outbox |
| Very different clouds, protocols or IoT devices | Protocol bridge | MQTT/AMQP 1.0 brokers, NATS | Other Brokers |
The side-by-side of the three brokers, with delivery and ack behaviour verified, is Redis vs RabbitMQ vs Kafka.
Go
Example
Go has no standard messaging API, but its channels are the same idea in one process: a send blocks or is buffered until a receiver is ready. The program below shows both channel semantics with no broker: three workers sharing one channel (point-to-point: 6 messages, 6 handled) and a tiny topic that copies each message to three subscribers (publish/subscribe: 6 messages, 18 deliveries). It runs in milliseconds and prints only totals, so the output is deterministic.
// Package main shows the two channel semantics inside one process, with no broker at all:
// a work queue (point-to-point: each message goes to exactly one worker) and a topic
// (publish/subscribe: each subscriber gets its own copy). Go channels are the in-process
// "queue"; the output is deterministic because only totals are printed.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// Topic is a minimal publish/subscribe channel: Publish copies the message to every subscriber.
type Topic struct {
mu sync.Mutex
subs []chan string
}
// Subscribe registers a new subscriber with its own buffered inbox.
func (t *Topic) Subscribe(buf int) <-chan string {
ch := make(chan string, buf)
t.mu.Lock()
t.subs = append(t.subs, ch)
t.mu.Unlock()
return ch
}
// Publish delivers a copy to each subscriber; a full inbox blocks the publisher (backpressure).
func (t *Topic) Publish(msg string) {
t.mu.Lock()
defer t.mu.Unlock()
for _, ch := range t.subs {
ch <- msg
}
}
// Close ends every subscription so the readers can finish.
func (t *Topic) Close() {
t.mu.Lock()
defer t.mu.Unlock()
for _, ch := range t.subs {
close(ch)
}
}
func main() {
const messages = 6
// Point-to-point: one buffered channel, three competing workers.
queue := make(chan string, messages)
var handled atomic.Int64
var wg sync.WaitGroup
for range 3 {
wg.Add(1)
go func() {
defer wg.Done()
for range queue { // each message is received by exactly one worker
handled.Add(1)
}
}()
}
for i := range messages {
queue <- fmt.Sprintf("job-%d", i)
}
close(queue)
wg.Wait()
fmt.Printf("queue: %d messages sent, %d handled in total (each by one worker)\n", messages, handled.Load())
// Publish/subscribe: every subscriber sees every message.
var topic Topic
var delivered atomic.Int64
for range 3 {
inbox := topic.Subscribe(messages)
wg.Add(1)
go func() {
defer wg.Done()
for range inbox {
delivered.Add(1)
}
}()
}
for i := range messages {
topic.Publish(fmt.Sprintf("event-%d", i))
}
topic.Close()
wg.Wait()
fmt.Printf("topic: %d messages published, %d deliveries in total (3 subscribers x %d)\n", messages, delivered.Load(), messages)
}The Go angle
Across processes you need a client library per broker (shown under Broker differences): github.com/rabbitmq/amqp091-go, github.com/twmb/franz-go/pkg/kgo and github.com/redis/go-redis/v9. Their shapes differ because the brokers differ. A good Go design keeps the broker behind a small interface owned by the business package (see DIP), so "publish this event" is not an AMQP call in the middle of domain code, and a fake can replace it in tests (Testing Messaging Systems). A buffered channel is a bounded queue: when it is full the sender blocks, which is the in-process form of backpressure (Backpressure & Flow Control). The snippets exit quietly when no broker address is configured, so they compile and go vet anywhere.
Laravel
Example
Laravel's queue component is point-to-point messaging with a job as the message, and it is the first messaging most PHP teams meet. The documentation says: "Laravel queues provide a unified queueing API across a variety of different queue backends, such as Amazon SQS, Redis, or even a relational database." and, about the configuration, "you will find connection configurations for each of the queue drivers that are included with the framework, including the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver that will execute jobs immediately (for use during development or testing). A null queue driver is also included which discards queued jobs."
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// A job is a serialized command; the worker deserializes it and calls handle().
class SendWelcomeEmail implements ShouldQueue
{
use Queueable;
public function __construct(public int $userId) {}
public function handle(): void
{
// ...send the email...
}
}
// Dispatching puts the job on the default queue of the default connection
// (QUEUE_CONNECTION in .env). Run it with: php artisan queue:work
//
// SendWelcomeEmail::dispatch($user->id);The 13.x drivers, with the config keys from a fresh application's config/queue.php:
| Driver | What it is | Needs | Notes |
|---|---|---|---|
sync | Runs the job immediately in the current process | Nothing | Development and tests; hides ordering and serialization bugs |
database | A jobs table in your database | php artisan make:queue-table | The default QUEUE_CONNECTION in a fresh app |
redis | Redis lists and sorted sets | predis/predis or phpredis | block_for blocks instead of polling; in a Redis Cluster queue names need a hash tag such as {default} |
sqs | Amazon SQS | aws/aws-sdk-php | FIFO and fair queues are documented separately |
beanstalkd | Beanstalkd | pda/pheanstalk | Small dedicated queue server |
null | Discards queued jobs | Nothing | Disable queued work |
deferred | Runs after the HTTP response, in the same process | Nothing | Also the default failover target |
background | Runs after the response in a separately spawned PHP process | Nothing | Frees the PHP-FPM worker |
failover | Tries the next listed connection if pushing fails | A list of connections | Needs a worker for each real connection |
| MongoDB | A MongoDB-backed queue | mongodb/laravel-mongodb | Package, documented in the driver prerequisites |
<?php
// Excerpt of config/queue.php in a fresh Laravel 13 application: one entry per built-in driver.
// QUEUE_CONNECTION picks the default; the worker is `php artisan queue:work {connection}`.
return [
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
// Runs the job immediately, inside the current process (development, tests).
'sync' => ['driver' => 'sync'],
// A `jobs` table in your own database (created by `php artisan make:queue-table`).
'database' => [
'driver' => 'database',
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
// Redis lists and sorted sets (not Redis Streams).
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
// Amazon SQS and Beanstalkd need aws/aws-sdk-php and pda/pheanstalk respectively.
'sqs' => [
'driver' => 'sqs',
'queue' => env('SQS_QUEUE', 'default'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'after_commit' => false,
],
// Run after the HTTP response is sent: in this process (deferred) or a spawned one (background).
'deferred' => ['driver' => 'deferred'],
'background' => ['driver' => 'background'],
// Try the next connection when pushing to the first one fails.
'failover' => [
'driver' => 'failover',
'connections' => ['database', 'deferred'],
],
],
];The Laravel angle
dispatch() serializes the job onto the queue and php artisan queue:work runs it. The connection and the queue name are chosen per job, so the same job can move between backends by configuration. The distinction the docs stress is "connections versus queues": a connection is a backend, a queue is one of several named piles inside it, and queue:work --queue=high,default serves them in priority order.
<?php
namespace App\Examples;
use App\Jobs\SendWelcomeEmail;
use App\Models\User;
// Every line below is one way to put the SAME job on a queue (or not).
final class DispatchExamples
{
public function register(User $user): void
{
// Default connection, default queue.
SendWelcomeEmail::dispatch($user->id);
// A named queue on the default connection: workers can serve `emails` first.
SendWelcomeEmail::dispatch($user->id)->onQueue('emails');
// A different backend for this one job.
SendWelcomeEmail::dispatch($user->id)->onConnection('redis')->onQueue('emails');
// Temporal decoupling in its simplest form: not before ten minutes from now.
SendWelcomeEmail::dispatch($user->id)->delay(now()->plus(minutes: 10));
// Do not hand the job to the broker until the surrounding DB transaction commits.
SendWelcomeEmail::dispatch($user->id)->afterCommit();
// Not queued at all: run now, in this process (what the `sync` driver does for every job).
SendWelcomeEmail::dispatchSync($user->id);
}
}
// Workers (long-lived processes, restart them on deploy with `php artisan queue:restart`):
// php artisan queue:work redis --queue=emails,defaultLaravel also gives you publish/subscribe in the same process: an event with several listeners, any of which can implement ShouldQueue to become a queued job. That is the monolith's version of "announce a fact, let others react".
<?php
namespace App\Events;
// An event is a fact in the past tense: it names something that already happened.
// Any number of listeners may react; the publisher does not know them.
final class OrderPlaced
{
public function __construct(public int $orderId) {}
}
// Publishing it (from the code that completed the order):
//
// event(new \App\Events\OrderPlaced($order->id));<?php
namespace App\Listeners;
use App\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Attributes\Queue;
// Implementing ShouldQueue turns an in-process event listener into a queued job:
// the event is the "topic" side (many listeners), each queued listener is a "queue" side
// (one worker runs it). This is publish/subscribe and point-to-point in one framework.
// The Queue attribute names the queue (Laravel 13 queued-listener docs).
#[Queue('notifications')]
final class SendShipmentNotification implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
// ...notify the customer about order $event->orderId...
}
}RabbitMQ and Kafka are not built in; they come from packages (below). Laravel's redis queue driver uses lists and sorted sets (the framework's RedisQueue and LuaScripts source uses rpush, lpop and zadd on queue, queue:delayed and queue:reserved keys), not Redis Streams. How the built-in drivers work inside is Laravel Queue Internals; testing them is Testing Messaging Systems.
Broker differences
The words "queue", "topic" and "subscription" mean different things on each broker. The snippets are the smallest producer and consumer on each; the Go programs exit quietly if the broker address is not set.
RabbitMQ
A queue is a broker-side buffer that stores messages until a consumer acknowledges them. Publishers send to an exchange; bindings route copies into queues; a subscription is a consumer registered on a queue, to which the broker pushes messages. Publishing to the default exchange (the empty name) routes by queue name, which is why the first example needs no exchange. What is missing compared with Kafka: replay after the ack (except RabbitMQ streams) and a per-consumer position. What breaks first: redeclaring a queue with different arguments (406), and a durable queue with transient messages that disappear on restart. In Laravel, vladimir-yuldashev/laravel-queue-rabbitmq adds a rabbitmq connection driver.
// Package main publishes one "hello" message to a RabbitMQ queue and reads it back.
// It exits quietly when RABBITMQ_URL is not set, so it compiles and runs without a broker.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
url := os.Getenv("RABBITMQ_URL") // e.g. amqp://guest:guest@localhost:5672/
if url == "" {
fmt.Println("RABBITMQ_URL is not set; nothing to do")
return
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
defer ch.Close()
// A queue is a named buffer inside the broker. Declaring it is idempotent.
q, err := ch.QueueDeclare("hello", true, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Publishing to the default exchange ("") routes by queue name.
err = ch.PublishWithContext(ctx, "", q.Name, false, false, amqp.Publishing{
ContentType: "text/plain",
Body: []byte("hello"),
})
if err != nil {
log.Fatal(err)
}
// Consuming registers a subscription on the queue; the broker pushes messages to it.
deliveries, err := ch.Consume(q.Name, "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
select {
case d := <-deliveries:
fmt.Printf("received %q\n", d.Body)
_ = d.Ack(false) // remove the message from the queue
case <-ctx.Done():
log.Fatal("timed out waiting for a message")
}
}<?php
namespace App\Examples;
use App\Jobs\SendWelcomeEmail;
// Needs: composer require vladimir-yuldashev/laravel-queue-rabbitmq
// and a 'rabbitmq' connection (driver => 'rabbitmq') in config/queue.php.
//
// The same job now becomes an AMQP message in the RabbitMQ queue named
// 'default' (the package's default queue name).
SendWelcomeEmail::dispatch(42)->onConnection('rabbitmq');
// Worker: php artisan queue:work rabbitmqKafka
There is no queue. A topic is a partitioned, append-only log; events "are not deleted after consumption" but kept for a configured retention. A subscription is a consumer group: a name under which the cluster stores the committed offset per partition, and the group's members split the partitions between them. A second group reads the same topic independently. What is missing: per-message acknowledgment and per-message delay (offsets are cumulative). What breaks first: a slow consumer that gets its partitions rebalanced away, and a key choice that makes one partition hot. Kafka is not built into Laravel; mateusjunges/laravel-kafka provides Kafka::publish() and Kafka::consumer().
// Package main produces one "hello" record to a Kafka topic and reads it back.
// It exits quietly when KAFKA_BROKERS is not set, so it compiles and runs without a broker.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
brokers := os.Getenv("KAFKA_BROKERS") // e.g. localhost:9092
if brokers == "" {
fmt.Println("KAFKA_BROKERS is not set; nothing to do")
return
}
// A "subscription" in Kafka is a consumer group: a shared name under which
// the cluster stores the committed offset for each partition of the topic.
client, err := kgo.NewClient(
kgo.SeedBrokers(strings.Split(brokers, ",")...),
kgo.ConsumerGroup("hello-group"),
kgo.ConsumeTopics("hello"),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// A topic is an append-only log; producing appends a record to it.
rec := &kgo.Record{Topic: "hello", Value: []byte("hello")}
if err := client.ProduceSync(ctx, rec).FirstErr(); err != nil {
log.Fatal(err)
}
// Records stay in the log after being read; the group only moves its offset.
fetches := client.PollFetches(ctx)
if err := fetches.Err(); err != nil {
log.Fatal(err)
}
fetches.EachRecord(func(r *kgo.Record) {
fmt.Printf("received %q from partition %d at offset %d\n", r.Value, r.Partition, r.Offset)
})
}<?php
namespace App\Examples;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
// Needs: composer require mateusjunges/laravel-kafka (and the PHP rdkafka extension).
// Publish: append a record to the 'hello' topic; the key picks the partition.
Kafka::publish('broker')
->onTopic('hello')
->withKafkaKey('user-42')
->withBodyKey('greeting', 'hello')
->send();
// Consume: a group id is the "subscription"; the handler runs per record.
$consumer = Kafka::consumer(['hello'], 'hello-group', 'broker')
->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) {
logger()->info('received', ['body' => $message->getBody()]);
})
->build();
$consumer->consume();Redis Streams
A stream is "a data structure that acts like an append-only log" under one Redis key; there is no separate queue object. A subscription is a consumer group: server-side state that remembers the last delivered ID and a pending list of entries delivered but not yet acknowledged. Redis also has classic Pub/Sub, which has no group and no persistence (Redis Streams & Pub/Sub). What is missing compared with a full broker: built-in dead-lettering, delayed delivery and rich routing; you build them with the pending list and sorted sets. What breaks first: memory growth when nobody trims, and message safety that depends on the AOF fsync policy. Laravel reaches Streams through the Redis facade, which passes commands to the client. Redis itself is in Redis: Data Structures, Commands & Patterns.
// Package main adds one "hello" entry to a Redis Stream and reads it back through a consumer group.
// It exits quietly when REDIS_ADDR is not set, so it compiles and runs without a server.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
addr := os.Getenv("REDIS_ADDR") // e.g. localhost:6379
if addr == "" {
fmt.Println("REDIS_ADDR is not set; nothing to do")
return
}
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// A "subscription" is a consumer group: server-side state on the stream that
// tracks the last delivered ID and the entries still pending acknowledgment.
err := rdb.XGroupCreateMkStream(ctx, "hello", "hello-group", "0").Err()
if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
log.Fatal(err)
}
// A stream is a data structure under one key; XADD appends an entry to it.
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "hello",
Values: map[string]any{"body": "hello"},
}).Err(); err != nil {
log.Fatal(err)
}
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "hello-group",
Consumer: "worker-1",
Streams: []string{"hello", ">"}, // ">" means entries never delivered to this group
Count: 1,
Block: 2 * time.Second,
}).Result()
if err != nil {
log.Fatal(err)
}
for _, stream := range res {
for _, msg := range stream.Messages {
fmt.Printf("received %v (id %s)\n", msg.Values["body"], msg.ID)
rdb.XAck(ctx, "hello", "hello-group", msg.ID) // clear it from the pending list
}
}
}<?php
namespace App\Examples;
use Illuminate\Support\Facades\Redis;
// Laravel's built-in redis queue driver uses lists and sorted sets, not streams,
// so Redis Streams are used through the Redis facade, which forwards commands to the
// client. The calls follow the phpredis signatures (not run here; Predis differs).
// Publish: XADD appends an entry with an auto-generated ID.
Redis::xadd('hello', '*', ['body' => 'hello']);
// Create the consumer group once (MKSTREAM creates the stream if missing).
try {
Redis::xgroup('CREATE', 'hello', 'hello-group', '0', true);
} catch (\Throwable $e) {
// BUSYGROUP: the group already exists.
}
// Consume: '>' asks for entries never delivered to this group.
$batch = Redis::xreadgroup('hello-group', 'worker-1', ['hello' => '>'], 1, 2000);
foreach ($batch['hello'] ?? [] as $id => $fields) {
logger()->info('received', ['id' => $id, 'body' => $fields['body']]);
Redis::xack('hello', 'hello-group', [$id]);
}The three brokers in one paragraph each. RabbitMQ speaks AMQP 0-9-1 and is usually called a smart broker: it routes through exchanges and bindings, tracks per-message delivery state and removes a message once acknowledged. Kafka is a distributed log, usually called dumb broker, smart consumer: the broker appends and serves bytes, and each consumer group tracks its own position, so history can be replayed. Redis Streams is a data structure inside a server you may already run, lightweight and fast, with consumer groups but fewer operational features. "Smart/dumb" is common shorthand in the industry, not wording from the three vendors' docs. Choosing between them is Redis vs RabbitMQ vs Kafka; NATS, Pulsar, SQS/SNS and Google Pub/Sub are in Other Brokers.
In production systems
- Kafka retention, not deletion. Kafka's introduction states that events "can be read as often as needed" and are discarded only after a per-topic retention setting, which is why replay is possible there and not on an acknowledged RabbitMQ queue.
- RabbitMQ durability needs two settings. The queues guide says applications "must use durable queues and make sure that publishers mark published messages as persisted", and that transient messages "will be discarded during recovery, even if they were stored in durable queues". A "durable" queue alone is not enough.
- Redis Pub/Sub is at-most-once. The Redis Pub/Sub page says it "exhibits at-most-once message delivery semantics" and that a missed message "is forever lost"; for stronger guarantees it points to Streams.
- Laravel's
syncdriver and dispatch inside transactions.syncruns jobs immediately in the request, so a test that passes with it can hide ordering and serialization bugs. The Laravel docs warn that a job dispatched inside a transaction "may be processed by a worker before the parent transaction has committed" and provideafter_commitfor it.
In architecture: from a single process to a distributed system
Monolith (one process, one database)
The simplest correct usage is the framework queue. A Laravel app sets QUEUE_CONNECTION=database, dispatches SendWelcomeEmail, and runs one queue:work under Supervisor. Fan-out is an in-process event with queued listeners. In a Go service the same role is a buffered channel feeding a worker pool (the Go example). Everything lives in one failure domain, so the new risks are small: a lost job if the process dies between commit and dispatch, and a worker that needs restarting after a deploy (queue:restart).
1 HTTP POST /orders -> controller writes order row, COMMIT
2 controller -> dispatch(SendInvoice)->afterCommit() (jobs table / Redis list)
3 queue:work -> takes SendInvoice, renders PDF, sends mail
4 failure after 3 tries -> row in failed_jobs, visible in the dashboardModular monolith (modules, perhaps several schemas)
Modules (Billing, Shipping, Catalog) talk through events instead of calling each other's classes, so a module can later be extracted. OrderPlaced is published in process, and Billing's and Shipping's listeners are queued so a slow listener does not block checkout. Each module owns its tables; no module reads another's. When "must not lose" matters the event is written to an outbox table in the same transaction (Transactional Outbox). The event contract is already a public API: version it (Message Design & Schema Evolution).
Microservices (each service owns its data)
Now the broker is real infrastructure and the database transaction no longer covers the whole business action. A concrete flow: Checkout publishes OrderPlaced via an outbox; Payments consumes it, charges the card idempotently and publishes PaymentCaptured or PaymentFailed; Shipping reacts to PaymentCaptured. If shipping fails, a compensating command refunds: a Saga. Every consumer deduplicates by message id (Idempotent Consumers & Inbox); every message carries a correlation id (Observability); poison messages go to a DLQ.
1 Checkout tx{ INSERT orders; INSERT outbox(OrderPlaced) } COMMIT
2 relay outbox -> broker topic "orders.v1" (at-least-once)
3 Payments consumes OrderPlaced (inbox: unseen) -> charge -> outbox(PaymentCaptured)
4 Shipping consumes PaymentCaptured (inbox: unseen) -> create shipment
5 Shipping fails after retries -> DLQ; saga sends RefundPayment (compensation)What survives a service boundary: contracts, ids, idempotency, eventual consistency. What does not: transactions, joins, and the guarantee that everything happens or nothing does.
Distributed data (replicas, caches, multi-region)
Messaging is how derived data stays roughly in sync with its source: cache invalidation events, search-index updates, read-model projections. Because consumers lag, a reader on a replica or a projection can see stale data; show "processing" states and read from the primary for read-your-writes (Replication, Read Replicas & Failover). Across regions, asynchronous replication of the broker (Kafka replication across clusters, RabbitMQ shovel or federation) means a failover can lose or repeat the tail of the log, so consumers must be idempotent. Consensus-based brokers (Kafka KRaft, RabbitMQ quorum queues) rely on the same ideas as Distributed SQL, Consensus & 2PC. For the reliability angle see also DDD: Designing for Failure and Reliable Messaging and DDD: Domain Events & Integration Events.
Scaling path
| Load | Design | What changes |
|---|---|---|
| 1x (tens of messages per second) | Laravel database or redis queue, one worker | Nothing special; monitor failed_jobs |
| 10x | Redis or SQS queue, several workers, named queues for priority | Prefetch / worker count, retry_after above job time, Horizon |
| 100x | RabbitMQ or Kafka; keyed partitions; one consumer group per service | Partition count, consumer lag alarms, schema registry |
| Beyond | Multiple clusters or regions, stream processing, CDC feeding the log | Idempotency everywhere, retention and compaction planning, cost of replay |
Lab
Cost rule: no Docker or Compose brokers are started here. Experiment 1 was actually run; the others are commands with the output you should see, labelled "expected, not run".
- Queue versus topic, in-process (run). From
docs/snippets/messaging/messaging-fundamentals/go:
go run ./inprocess
# observed:
# queue: 6 messages sent, 6 handled in total (each by one worker)
# topic: 6 messages published, 18 deliveries in total (3 subscribers x 6)- First Laravel queue (expected, not run).
php artisan make:queue-table && php artisan migrate # creates the jobs table
php artisan tinker --execute='App\Jobs\SendWelcomeEmail::dispatch(1);'
# SELECT count(*) FROM jobs; -> 1
php artisan queue:work --once
# INFO Processing jobs ... App\Jobs\SendWelcomeEmail ... DONE
# SELECT count(*) FROM jobs; -> 0 (acknowledged: row deleted)- RabbitMQ hello (expected, not run). A broker such as
rabbitmq:4-managementmust be reachable.
RABBITMQ_URL=amqp://guest:guest@localhost:5672/ go run ./rabbitmq
# received "hello"
# (the queue "hello" is now empty; rabbitmqctl list_queues shows messages 0)- Kafka hello (expected, not run).
KAFKA_BROKERS=localhost:9092 go run ./kafka
# received "hello" from partition 0 at offset 0
KAFKA_BROKERS=localhost:9092 go run ./kafka
# received "hello" from partition 0 at offset 1 (the log kept offset 0; the group continued after it)- Redis Streams, with a crash (expected, not run). Remove the
XAckline, run once, then inspect:
REDIS_ADDR=localhost:6379 go run ./redis
# received hello (id 1760000000000-0)
redis-cli XPENDING hello hello-group
# 1) (integer) 1 <- one entry delivered but never acknowledged
redis-cli XAUTOCLAIM hello hello-group worker-2 0 0-0
# the entry moves to worker-2: this is how a crashed consumer's work is recoveredCommon misconceptions
| Belief | Reality |
|---|---|
| "Async makes the system faster" | The caller returns sooner; end-to-end latency usually rises and the work is unchanged |
| "A queue and a topic are different products" | They are channel semantics; every broker here can build both |
| "Messaging decouples everything" | It decouples time and availability; the message contract and the broker stay shared |
| "A Kafka topic is a queue" | Reads do not delete; groups read independently; replay is possible |
| "Redis Pub/Sub is a lightweight Kafka" | It keeps nothing and is at-most-once; Streams are the durable structure |
| "A durable queue keeps my messages" | Only persistent messages in a durable queue survive a restart (RabbitMQ) |
| "The broker guarantees delivery" | It guarantees what it stored; produce-once and process-once are your code's job |
| "Exactly-once means no duplicate handling needed" | End-to-end exactly-once needs an idempotent consumer |
| "Dispatching inside a transaction is safe" | A worker can run before the commit; use afterCommit or an outbox |
| "Messages arrive in the order sent" | Only within one queue or partition, and parallel consumers or retries can reorder |
| "More consumers always drain faster" | Not for one ordered key or one partition, and not when the database is the bottleneck |
| "Laravel's Redis queue uses Redis Streams" | It uses lists and sorted sets; use the Redis facade for Streams |
| "RabbitMQ can never replay" | Classic and quorum queues cannot after an ack, but RabbitMQ streams are an append-only log with offsets |
Cheat sheet
| Topic | What to remember |
|---|---|
| Why async | Temporal decoupling, load levelling, fan-out, failure isolation; cost: eventual consistency, duplicates, hard debugging |
| Message vs event vs command vs document | Intent differs, envelope is the same: do this / it happened / here is data |
| Queue | One consumer per message; ack removes it; RabbitMQ and Laravel |
| Log | Append-only, offsets per group, replay, retention; Kafka |
| Stream | Log in one Redis key with group state (last-delivered ID, PEL) |
| Point-to-point vs pub/sub | One of N versus all N |
| Push vs pull | RabbitMQ pushes with prefetch; Kafka and Redis pull |
| Durable | Durable container, persistent message, confirmed publish, replicated or fsynced |
| Triangle | Producer owns retries and ids, broker owns storage and order, consumer owns ack timing and idempotency |
| First rule | Assume every message can arrive twice |
| Second rule | The database commit and the publish are not atomic: outbox |
| Laravel | ShouldQueue, dispatch(), queue:work, afterCommit(), drivers: sync, database, redis, sqs, beanstalkd, null, deferred, background, failover |
| Pick a broker | Light work: Laravel queue; routing and work distribution: RabbitMQ; replay and throughput: Kafka; already on Redis: Streams |
| Where to go | Guarantees (3), ack (4), order (5), inbox (6), brokers (9 to 11), outbox (19) |
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 — Name the four benefits of asynchronous messaging and the three costs it brings. Must-know
Answer
Answer: Temporal decoupling, load levelling, fan-out and failure isolation. Costs: eventual consistency, duplicates and reordering, and harder debugging across hops (plus a new shared dependency, the broker).
2 — What is the difference between a command and an event, and is it a broker feature? Must-know
Answer
Answer: A command asks one receiver to do something and can be refused; an event announces a fact that already happened and has no single owner of the reaction. It is a naming and ownership convention: "a Command Message is simply a regular message that happens to contain a command".
3 — What happens to a message in a RabbitMQ queue, a Kafka topic and a Redis stream after a consumer reads it? Must-know
Answer
Answer: RabbitMQ removes it after the ack. Kafka keeps it until retention removes it; the group only moves its offset. Redis keeps the entry until it is trimmed; the group moves its last-delivered ID and clears the pending list on XACK.
4 — How can a Kafka topic be both publish/subscribe and point-to-point? Must-know
Answer
Answer: Each consumer group gets every event (publish/subscribe between groups); inside one group each partition is read by one member, so each record goes to one member (point-to-point inside the group).
5 — Why is a RabbitMQ durable queue not enough to survive a restart? Must-know
Answer
Answer: Messages must also be published as persistent; transient messages are discarded on recovery even from a durable queue. The publisher should also wait for a publisher confirm.
6 — Who pushes and who pulls? Must-know
Answer
Answer: RabbitMQ pushes to registered consumers, limited by prefetch (it also offers basic.get polling, discouraged). Kafka and Redis Streams are pull-based with long polling or blocking reads. A Laravel worker pulls from its driver in a loop.
7 — Which party owns "ack after the work" and which owns "wait for the confirm"? Important
Answer
Answer: The consumer owns when to acknowledge; the producer owns waiting for and retrying on the broker's confirm. The broker owns storage, order and redelivery.
8 — Why can a Laravel job dispatched inside a database transaction fail, and how do you prevent it? Must-know
Answer
Answer: A worker can take it before the transaction commits and not find the rows. Use afterCommit() or after_commit => true, or write the event to an outbox table in the same transaction.
9 — Which drivers does Laravel 13 ship for queues? Important
Answer
Answer: sync, database, redis, sqs, beanstalkd and null, plus deferred, background and failover; MongoDB through the mongodb/laravel-mongodb package. RabbitMQ and Kafka need packages.
10 — How many EIP patterns are there, and which chapter owns Pipes and Filters? Good to know
Answer
Answer: Sixty-five (four integration styles and 61 messaging patterns). Pipes and Filters is on this page; the rest are distributed as listed in the EIP coverage map.
11 — For a flash sale, would you choose a queue, a topic or RPC to take the orders, and what must you watch? Must-know
Answer
Answer: A queue (load levelling) behind an HTTP endpoint that returns 202; watch queue depth or lag, and size the workers so the backlog drains.
Glossary
| Term | Meaning |
|---|---|
| Acknowledgment (ack) | The consumer telling the broker a message was handled so it can be removed or the offset advanced |
| Nack / reject | The consumer telling the broker it could not handle the message; requeue or dead-letter |
| Aggregator | EIP: collects related messages and combines them into one |
| AMQP | Advanced Message Queuing Protocol; RabbitMQ speaks 0-9-1, a separate 1.0 is an OASIS and ISO standard |
| AOF | Redis Append Only File; logs every write; its fsync policy decides Redis durability |
| At-least-once | Never lost, may be delivered more than once |
| At-most-once | May be lost, never redelivered |
| Exactly-once | Processed once and only once; end to end it needs idempotency |
| Backpressure | Slowing the producer or limiting the consumer so a queue does not grow without bound |
| Binding | RabbitMQ rule that routes messages from an exchange to a queue |
| Broker | The server that stores, routes and tracks messages |
| Canonical Data Model | EIP: one shared message format that every application translates to and from |
| CDC (change data capture) | Reading a database's change log and publishing the changes as events |
| Channel Adapter | EIP: connects an application to a messaging channel |
| Channel Purger | EIP: removes unwanted messages from a channel |
| Claim Check | EIP: store a large payload elsewhere and send only a reference |
| Command | A message asking one receiver to do something |
| Competing consumers | Several consumers reading one queue so each message is handled once |
| Composed Message Processor | EIP: processes a composite message by routing parts and re-aggregating |
| Consumer | The code that receives and processes messages |
| Consumer group | Kafka and Redis Streams name for a set of consumers sharing one position and splitting the work |
| Consumer lag | How far a consumer's position is behind the end of the log |
| Content-Based Router | EIP: routes a message by what is inside it |
| Content Enricher | EIP: adds missing data to a message from another source |
| Content Filter | EIP: removes unwanted fields from a message |
| Control Bus | EIP: a channel to manage and monitor the messaging system itself |
| Correlation id | An identifier that ties a reply or a trace to its original message |
| Datatype Channel | EIP: one channel per kind of message |
| Dead-letter queue (DLQ) | A queue where messages that could not be processed are parked |
| Delivery mode | AMQP property marking a message transient or persistent |
| Detour | EIP: routes messages through extra steps such as validation, switchable at runtime |
| Document message | A message that carries data; the receiver decides what to do |
| Durable Subscriber | EIP: a subscriber whose messages are kept while it is offline |
| Durable queue | A RabbitMQ queue whose definition survives a restart |
| Envelope Wrapper | EIP: wraps a message in the format a messaging system needs, then unwraps it |
| Event | A message announcing something that already happened |
| Event-Driven Consumer | EIP: a consumer the broker calls when a message arrives (push) |
| Event notification | An event carrying little data; the receiver asks for details if it needs them |
| Eventual consistency | State converges after a delay rather than immediately |
| Exchange | RabbitMQ entity that receives published messages and routes them to queues by bindings |
| Fan-out | One message delivered to many receivers |
| Format Indicator | EIP: a field telling the receiver which format or version the message uses |
| Guaranteed Delivery | EIP: persist messages so they survive a broker crash |
| Idempotent consumer / receiver | A consumer for which processing the same message twice has the same effect as once |
| Inbox | A table of processed message ids used to drop duplicates |
| Invalid Message Channel | EIP: where a receiver puts messages it cannot understand |
| JMS / Jakarta Messaging | Java API for message-oriented middleware with queues and topics |
| Kafka partition | One ordered, append-only log of a topic |
| KRaft | Kafka's built-in consensus mode that replaces ZooKeeper |
| Load levelling | Letting a queue absorb a burst so consumers work at their own pace |
| Message | One unit of data with a header and a body |
| Message Bus | EIP: shared infrastructure that lets applications communicate |
| Message Dispatcher | EIP: distributes messages among performers within one consumer |
| Message Endpoint | EIP: the client code an application uses to send or receive messages |
| Message Expiration | EIP: a time after which a message is no longer useful |
| Message Filter | EIP: drops messages that do not match a condition |
| Message History | EIP: a record of the components a message has passed through |
| Message Router | EIP: sends a message to one of several channels based on conditions |
| Message Sequence | EIP: numbering parts of a large message so they can be reassembled |
| Message Store | EIP: a database that keeps copies of messages for analysis |
| Message Translator | EIP: converts one data format into another |
| Messaging Bridge | EIP: connects two messaging systems |
| Messaging Gateway | EIP: wraps messaging code behind a plain interface |
| Messaging Mapper | EIP: maps between domain objects and messages |
| Normalizer | EIP: converts different formats of the same meaning into one |
| Offset | A record's position in a Kafka partition |
| Outbox | A table written in the same transaction as the data, relayed to the broker later |
| Pending entries list (PEL) | Redis Streams list of entries delivered to a group member but not yet acknowledged |
| Persistent message | A message the broker writes to disk |
| Pipes and Filters | EIP: a chain of independent processing steps joined by channels |
| Point-to-point | Each message goes to exactly one receiver |
| Polling Consumer | EIP: a consumer that asks the channel for the next message |
| Prefetch | Limit on delivered but unacknowledged messages per consumer (RabbitMQ prefetch_count) |
| Process Manager | EIP: a central unit that keeps the state of a multi-step process |
| Producer / publisher | The code that sends messages |
| Pub/Sub | Publish/subscribe: each subscriber gets a copy |
| Publisher confirm | RabbitMQ acknowledgment from the broker to the publisher |
| Quorum queue | RabbitMQ replicated queue type based on consensus |
| Queue | A buffer where each message goes to one consumer |
| Recipient List | EIP: sends a message to a list of receivers computed per message |
| Replay | Reading old messages again from a log |
| Request-Reply | A pair of messages: a request and its correlated response |
| Resequencer | EIP: restores order to out-of-order messages |
| Retention | How long a log keeps messages (Kafka retention.ms) |
| Return Address | EIP: where the reply to a request should be sent |
| Routing key | RabbitMQ message attribute used by bindings to route |
| Saga | A sequence of local transactions with compensations instead of one distributed transaction |
| Scatter-Gather | EIP: sends a request to several recipients and combines the replies |
| Selective Consumer | EIP: a consumer that only takes messages matching a filter |
| Service Activator | EIP: connects a messaging channel to a service call |
| Smart Proxy | EIP: tracks the reply of a request to a service with unknown reply address |
| Splitter | EIP: breaks one message into several |
| Stream (Redis) | An append-only data structure under one key with consumer groups |
| Subscription | The registration through which a consumer receives messages |
| Temporal decoupling | Sender and receiver need not run at the same time |
| Test Message | EIP: a message injected to check a component is healthy |
| Topic | A named channel for publish/subscribe, or a Kafka log |
| Transactional Client | EIP: a client that makes sending and receiving part of a transaction |
| Wire Tap | EIP: copies messages passing a channel to a second channel for inspection |
References
Every URL below was fetched and read; the saved copies are under scratchpad/sources/messaging-fundamentals/.
- Hohpe & Woolf, Enterprise Integration Patterns: Introduction and table of contents, Messaging, Message Channel, Message, Point-to-Point Channel, Publish-Subscribe Channel, Message Router, Message Translator, Message Endpoint, Command Message, Document Message, Event Message, Guaranteed Delivery
- RabbitMQ (docs repository, raw markdown): Queues, Consumers, Consumer Acknowledgements and Publisher Confirms, Reliability Guide; AMQP 0-9-1 Model Explained
- Apache Kafka: Introduction, Design; Kreps, Narkhede, Rao, Kafka: a Distributed Messaging System for Log Processing (NetDB 2011)
- Redis: Streams, Pub/Sub, Persistence, XGROUP CREATE, Redis 5.0 release notes
- Laravel 13: Queues, Events, Redis; framework source RedisQueue.php, LuaScripts.php, DatabaseQueue.php; application skeleton config/queue.php and the jobs migration
- PostgreSQL: SELECT, locking clause
- History: AMQP 1.0 overview (OASIS), Jakarta Messaging; secondary sources (Wikipedia): IBM MQ, Jakarta Messaging, AMQP, RabbitMQ, Apache Kafka
- Packages: laravel-queue-rabbitmq, Laravel Kafka, phpredis
- Go clients: amqp091-go, franz-go kgo, go-redis