Skip to content

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 forGo to
The vocabulary in tables you can memoriseEverything in one minute
Why asynchronous at all, and what it costsWhy messaging exists
MQ in the 1990s, JMS, AMQP, Kafka 2011, Redis Streams 2018Where the vocabulary comes from
One concept with a timeline and a fixThe concepts, one by one
Message vs event vs command vs documentMessage kinds
RabbitMQ queue vs Kafka log vs Redis streamQueue, log, stream
Point-to-point vs publish/subscribeTwo channel semantics
Push vs pull consumptionPush and pull
What "durable" really requiresDurability basics
Who owns which guaranteeThe producer, broker, consumer triangle
Messaging vs RPC vs a shared databaseMessaging, RPC or shared database
Which of Hohpe and Woolf's 65 patterns lives whereEIP coverage map
One line about each of the 33 chaptersThe path: all chapters
How a message really travels, knobs and error namesMechanics
The problems everyone hits firstSolving the first problems
Which style for which problemChoosing a style
First Go and Laravel codeGo, Laravel, Broker differences
Monolith to distributed systemIn architecture
Reproduce itLab
Wrong beliefs, cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts.

WordIn plain wordsTiny exampleWhere it is taught
MessageOne unit of data handed to a broker, with headers and a body{"order_id": 42} plus an id and a timestampMessage kinds, Message Design
Command"Please do this", addressed to one receiver, may be refusedChargeCardMessage kinds, Event-Driven Architecture
Event"This already happened", no single owner of the reactionOrderPlacedMessage kinds, Event-Driven Architecture
DocumentData handed over; the receiver decides what to doA price list, a customer recordMessage kinds
Producer / publisherThe code that sendsThe checkout serviceTriangle
BrokerThe server that stores, routes and tracks messagesRabbitMQ, Kafka, RedisTriangle
Consumer / subscriberThe code that receives and worksThe email workerTriangle
QueueA buffer where each message goes to one consumerRabbitMQ queue, Laravel default queueQueue, log, stream
TopicA named stream of events many readers can followKafka orders topic, RabbitMQ topic exchangeTwo channel semantics
Log / streamAn append-only sequence readers walk with their own positionKafka partition, Redis StreamQueue, log, stream
AckThe consumer telling the broker "done"basic.ack, XACK, offset commitMessage Acknowledgment
Offset / IDA reader's position in a logKafka offset 17, Redis ID 1700000000000-0Queue, log, stream

The three brokers in one table.

QuestionRabbitMQKafkaRedis Streams
Core objectQueue behind an exchangePartitioned append-only log (topic)Append-only stream under one key
After a message is readRemoved once acknowledgedStays until retention removes itStays until trimmed (XTRIM, MAXLEN)
Who remembers the positionBroker, per messageCluster, per group and partition (offset)Server, per group (last-delivered ID + pending list)
Delivery to the consumerBroker pushesConsumer pullsConsumer pulls (blocking read)
Replay old dataNo (stream queues aside)Yes, move the offsetYes, read from an older ID
Typical useWork distribution, routingEvent streaming, pipelines, replayLight queue or stream next to existing Redis

The five questions to ask of any messaging design.

QuestionWhy it decides the designChapter
What happens if the consumer crashes after taking the message?Decides ack timing and whether duplicates appearMessage Acknowledgment
What happens if the producer retries?Duplicates; needs an idempotent consumerIdempotent Consumers & Inbox
What order must be kept, and per what key?Decides partitioning and parallelismOrdering & Partitioning
Is the database write and the publish atomic?If not, you lose or invent eventsTransactional Outbox
What happens when the consumer cannot keep up, or never succeeds?Lag, backpressure, poison messagesBackpressure, 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 gainYou 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 redeliveryDuplicates and reordering; every consumer must cope
Teams deploy independentlyA 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.

  1. "Async makes it faster." It makes the caller return sooner; the work still happens, and end-to-end latency usually goes up.
  2. "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.
  3. "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.

WhenWhatWhy it matters hereSource type
1993IBM MQSeries (later WebSphere MQ, now IBM MQ) launchedThe first widely deployed message-oriented middleware for heterogeneous systems; the origin of "queue manager" thinkingSecondary (Wikipedia)
1998 to 2002JMS 1.0.1 (October 1998) to JMS 1.1 (April 2002), now Jakarta MessagingA Java API, not a wire protocol: queues and topics as the two modelsSecondary (Wikipedia); Jakarta Messaging page: "create, send, and receive messages via loosely coupled, reliable asynchronous communication services"
2003Enterprise Integration Patterns publishedThe pattern language: channel, router, translator, endpointPrimary (EIP site)
2003 to 2008AMQP born at JPMorgan Chase (2003); RabbitMQ started 2007; AMQP 0-9-1 published November 2008A wire protocol so different vendors interoperate; exchanges, bindings and queuesSecondary (Wikipedia); AMQP 1.0 overview document is primary
2011Kafka (LinkedIn), NetDB 2011 paperThe log as the central abstraction, pull consumption, replayPrimary: the paper says it "has been open sourced and used successfully in production at LinkedIn for more than 6 months"
2012AMQP 1.0 approved as an OASIS standard (October); ISO/IEC 19464 in 2014A protocol significantly different from 0-9-1Secondary (Wikipedia)
2018Redis 5.0 introduces the Stream data type (RC1, 29 May 2018)A log with consumer groups inside a server many teams already runPrimary: 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.

BrokerHow the wait is bounded
RabbitMQQueue length limits, per-message or per-queue TTL; see Message Acknowledgment
KafkaTopic retention (retention.ms, retention.bytes); the group's position is kept
Redis StreamsXTRIM, MAXLEN on XADD; unacknowledged entries stay in the pending list
Laravel queueJob 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 forms

Real scenario: Black Friday order intake, end-of-month batch imports, a mobile push campaign, a webhook storm from a payment provider.

BrokerSignal that the backlog is growing
RabbitMQQueue depth (messages ready and unacknowledged) in the management UI or metrics
KafkaConsumer lag per partition (log end offset minus committed offset)
Redis StreamsXLEN, XPENDING, group lag in XINFO GROUPS
Laravel queuequeue: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 changes

Real scenario: order lifecycle events, user-signup hooks, cache invalidation across instances, audit trails, search-index updates.

BrokerHow fan-out is built
RabbitMQFanout or topic exchange binds one queue per subscriber; see Routing Topologies
KafkaOne topic, one consumer group per subscriber
RedisStreams: one consumer group per subscriber; classic Pub/Sub: SUBSCRIBE (no history)
LaravelAn 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 draining

Real 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 charge

Real scenario: double charges, double emails, two shipments, a counter incremented twice, "status = shipped" overwritten by an older "status = packed".

BrokerDuplicate sources
RabbitMQConsumer crash before ack; requeue; publisher retry after missing confirm
KafkaProducer retry without idempotence; offset committed after processing then crash; rebalance
Redis StreamsEntry delivered but not acknowledged is reclaimed (XCLAIM, XAUTOCLAIM)
Laravel queueJob 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:

KindIntentNamingReceiversMay be refused?EIP pattern
CommandAsk one party to do somethingImperative: ChargeCardExactly one ownerYesCommand Message
EventAnnounce a fact that already happenedPast tense: OrderPlacedAny number, unknown to the senderNo (it already happened)Event Message
DocumentHand over data; the receiver decides what to doNoun: CustomerSnapshotOne or manyThe receiver decidesDocument Message
Query / requestAsk for data and wait for the answerGetPriceOneYesRequest-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.

ProductCommandsEvents
RabbitMQA queue named for the receiver, default exchangeA topic or fanout exchange, one queue per subscriber
KafkaRare; a topic with one consuming groupThe natural fit: topic per event type or aggregate
Redis StreamsA stream with one consumer groupA stream with one group per subscriber
LaravelA queued job (ShouldQueue)An event with queued listeners

Queue, log, stream: three mental models ​

RabbitMQ: queueKafka: partitioned logRedis Streams: stream + groupProducerexchangem3m2m1queue: head is m1C1C2Each message goes to ONE consumerBroker tracks per-message delivery stateack = message removed from the queuenack / crash = message goes backBroker PUSHES to a registered consumerTopics = exchange + bindings + queuesAfter the ack there is no replayProducerP0P101234012newnewgroup A: P0 offset 2group B: P0 offset 1Reading never deletes anythingPosition (offset) per group lives in the clusterSame key goes to the same partition: orderedConsumer PULLS; group members split partitionsReplay = move the offset backEvents leave only by retention or compactionOne partition is read by one member per groupProducerid1id2id3id4XADD appends one entryconsumer grouplast-delivered-id = id3PEL (pending): id2 owned by c1Log with queue-like group stateXREADGROUP delivers, XACK clears the PELCrashed consumer: XAUTOCLAIM takes overA single key; entries trimmed by XTRIMClassic Pub/Sub is separate: no historyPersistence = AOF / RDB of the Redis serverConsumer PULLS with a blocking read

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 history

Stream (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 over

Per-broker summary:

AspectRabbitMQ queueKafka partitionRedis stream
Storage after readDeleted on ackKept until retentionKept until trimmed
Position trackingPer message, in the brokerOffset per group, in the clusterLast-delivered ID plus PEL per group
Multiple independent readersOne queue per reader (via exchange)One group per readerOne group per reader
OrderFIFO per queue; requeue and parallel consumers can reorderPer partitionPer stream
ReplayNoYesYes
Where bytes liveBroker disk and memoryBroker disk, replicatedRedis 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-pointPublish/subscribe
Receivers per messageOne of NAll N
PurposeDistribute workAnnounce facts
Scaling by adding consumersYes (competing consumers)Adds a new reaction, not capacity
RabbitMQOne queue, many consumersExchange with one queue per subscriber
KafkaMany members in one groupMany groups
RedisLPUSH/BRPOP list or one stream groupOne stream group per subscriber, or Pub/Sub
LaravelJob on a queueEvent with several listeners
ChapterCompeting ConsumersRouting 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)
BrokerModelPace control
RabbitMQPush (basic.consume), pull available (basic.get)prefetch_count (QoS)
KafkaPull (poll/fetch)max.poll.records, fetch sizes
Redis StreamsPull (XREAD/XREADGROUP with BLOCK)COUNT per read
Laravel queueWorker pulls from the driver in a loopqueue: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
LayerRabbitMQKafkaRedis Streams
Container is durableDurable queueTopic partitions on diskStream key in AOF/RDB
Message is durablePersistent delivery modeWritten to the logWritten to AOF with the chosen fsync
Producer knows it is safePublisher confirmsacks (0, 1, all), min.insync.replicasReply to XADD; replica ack via WAIT is separate
Survives node lossQuorum queues replicateReplication factor and in-sync replicasReplication 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 ​

Produceryour service: builds themessage, picks key / route,sends it, waits for the confirmBrokerstores the message, keepsorder, routes it, tracks whohas taken itConsumeryour service: receives,does the work, then tellsthe broker it is done1 publish2 confirm / ack3 deliver4 ack / commitGuarantees owned hereRetry when no confirm arrives(a retry can create a duplicate)RabbitMQ: publisher confirmsKafka: acks, idempotent producerRedis: XADD reply = acceptedMessage id / key chosen hereSchema and size limitsDB write + publish: not atomicGuarantees owned hereDurability: disk, replicasRabbitMQ: durable queue +persistent messageKafka: replication, acks=allRedis: AOF fsync policyOrder inside a queue / partitionRouting and retentionRedelivery of unacked messagesGuarantees owned hereWhen to ack: after the work(ack early = may lose,ack late = may repeat)Idempotent handler / inboxPrefetch / max.poll.recordsPoison message handlingSide effects (email, payment)must tolerate a second run

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:

HopWhat can go wrongWho protects youProtection
1 publishMessage lost before the broker has it; duplicate on retryProducerWait for confirm; retry; idempotent producer; attach an id
2 confirmConfirm lost, producer retries an accepted messageProducer and consumerDedup downstream
StorageBroker crash, disk loss, failoverBrokerPersistence, replication, quorum
3 deliverMessage sent twice, or in a different orderBroker, consumerRedelivery rules; ordering keys
4 ack/commitAcked before work (lost) or after work (duplicate if crash)ConsumerAck after the work; idempotent handler
Database + publishRow saved, message never sent (or the reverse)ProducerTransactional 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 databaseMessaging
AvailabilityCallee must be up nowBoth depend on one databaseCallee may be down; message waits
ResultIn the same callRead the rowSeparate message, or none (Request-Reply)
FailureCaller sees the errorLocks and schema couplingRetries, redelivery, duplicates
DebuggingOne stack traceQuery logsTrace across hops
ConsistencyCan sit in one transactionStrong, inside one databaseEventual; needs Outbox and Saga
CouplingContract plus availabilitySchema (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.

ChapterEIP patterns it ownsCount
Messaging Fundamentals (this page)Message, Command Message, Document Message, Event Message, Point-to-Point Channel, Publish-Subscribe Channel, Pipes and Filters7
Integration Styles & ChannelsFile 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 Indicator14
Message TransformationMessage Translator, Envelope Wrapper, Content Enricher, Content Filter, Normalizer, Canonical Data Model, Messaging Mapper7
Message Design & Schema EvolutionClaim Check1
Routing TopologiesMessage Router, Content-Based Router2
Advanced RoutingMessage Filter, Dynamic Router, Recipient List, Splitter, Aggregator, Resequencer, Composed Message Processor, Scatter-Gather, Routing Slip, Process Manager, Message Broker11
Consumer & Endpoint PatternsMessage Endpoint, Messaging Gateway, Transactional Client, Polling Consumer, Event-Driven Consumer, Message Dispatcher, Selective Consumer, Durable Subscriber, Service Activator9
Competing Consumers & ScalingCompeting Consumers1
Idempotent Consumers & InboxIdempotent Receiver1
Request-ReplyRequest-Reply, Return Address, Correlation Identifier3
Dead-Letter QueueDead Letter Channel1
System ManagementControl Bus, Detour, Wire Tap, Message History, Message Store, Smart Proxy, Test Message, Channel Purger8
Total65

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 ​

MSG 01 Fundamentals1. Messaging Fundamentals2. Integration Styles3. Delivery Guarantees4. Message Acknowledgment5. Ordering & Partitioning6. Idempotent Consumers7. Message Design & Schema8. Message TransformationMSG 02 Brokers9. RabbitMQ10. Kafka11. Redis Streams & Pub/Sub12. Broker Comparison13. Other BrokersMSG 03 Routing14. Routing Topologies15. Advanced Routing16. Consumer Endpoints17. Competing Consumers18. Request-ReplyMSG 04 Reliability19. Transactional Outbox20. Saga21. Dead-Letter Queue22. Retry & Backoff23. Durable WorkflowsMSG 05 Event-Driven24. Event-Driven Arch.25. Event Sourcing & CQRS26. Change Data Capture27. Stream ProcessingMSG 06 Operations28. Backpressure29. Observability30. System Management31. Laravel Queue Internals32. Testing Messaging33. Messaging SecurityRead left to right: vocabulary, then the brokers, then patterns on top of them, then running them in production

Read top to bottom the first time. The order is the learning order: vocabulary, brokers, patterns built on them, then running them in production.

#ChapterOne line
MSG 01 · Fundamentals
1Messaging FundamentalsThis page: why async, queue vs log vs stream, the map of the path
2Integration Styles & ChannelsFile, shared database, RPC and messaging compared; channel patterns such as Guaranteed Delivery and Message Bus
3Delivery GuaranteesAt-most, at-least and exactly-once; why end-to-end exactly-once needs idempotency
4Message AcknowledgmentAck, nack, reject, prefetch, offset commit, XACK and redelivery
5Ordering & PartitioningPer-key order, partition keys, head-of-line blocking
6Idempotent Consumers & InboxDedup keys and the inbox table so a duplicate does no harm
7Message Design & Schema EvolutionEnvelope, versioning, Avro/Protobuf/JSON Schema, registry, claim check
8Message TransformationTranslator, Enricher, Normalizer, Canonical Data Model
MSG 02 · Brokers
9RabbitMQ in DepthExchanges, bindings, queue types, confirms, clustering
10Kafka in DepthTopics, partitions, groups, replication, transactions
11Redis Streams & Pub/SubXADD, consumer groups, the pending list, Pub/Sub limits
12Broker ComparisonSide-by-side table and decision guide, delivery and ack verified
13Other BrokersNATS JetStream, Pulsar, SQS/SNS, Google Pub/Sub
MSG 03 · Routing & Consumers
14Routing TopologiesExchange types, topic design, content-based routing
15Advanced RoutingSplitter, Aggregator, Resequencer, Scatter-Gather, Routing Slip, Process Manager
16Consumer & Endpoint PatternsPolling vs event-driven consumer, gateway, selective consumer, durable subscriber
17Competing Consumers & ScalingWorker pools, consumer groups, rebalancing, graceful shutdown
18Request-Reply & REST vs AMQPCorrelation ids, reply queues, sync-over-async trap
MSG 04 · Reliability Patterns
19Transactional OutboxWrite the event with the data, publish it after
20SagaDistributed workflows with compensation
21Dead-Letter QueuePoison messages, parking lots, failed_jobs
22Retry, Backoff & Delayed DeliveryExponential backoff with jitter, delayed messages per broker
23Durable Workflows & JobsTemporal model, Laravel batches and chains, reconciliation
MSG 05 · Event-Driven & Streams
24Event-Driven ArchitectureEvents vs commands, notification vs state transfer
25Event Sourcing & CQRSEvent store, replay, projections, when not to
26Change Data CaptureLog-based CDC, Debezium, logical decoding
27Stream ProcessingEvent time, windows, watermarks, state
MSG 06 · Operations
28Backpressure & Flow ControlPrefetch, lag, bounded buffers, load shedding
29Messaging Observability & TracingTrace context in headers, lag and DLQ metrics
30System Management PatternsControl Bus, Wire Tap, Detour, Message Store, Test Message
31Laravel Queue InternalsDrivers, Redis lists and sorted sets, uniqueness, batches, Horizon
32Testing Messaging SystemsQueue::fake, testcontainers, contract tests
33Messaging SecurityTLS, SASL, ACLs, payload encryption, erasure in logs

Three reading routes for people in a hurry:

You areRead in this order
A Laravel developer with queues in production1, 3, 4, 6, 31, 21, 22, 19, 17
Choosing a broker for a new system1, 9, 10, 11, 12, 13, 3, 5
Splitting a monolith into services1, 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 blockEIP definition in shortIn RabbitMQ / Kafka / Redis / LaravelOwned 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 queueIntegration Styles & Channels
MessageA data record with a header (for the messaging system) and a body (the data)AMQP properties + body / record key, value, headers / entry fields / job payloadThis page
Pipes and FiltersChain independent processing steps, each reading from one channel and writing to the nextQueue chains / topic-to-topic pipelines / stream-to-stream / Bus::chainThis page
Message RouterConsume from one channel and republish to a different one depending on conditionsExchange bindings / topic choice in code / consumer republishing / event listenersRouting Topologies
Message TranslatorConvert one application's data model into another'sConsumer-side mapper in all fourMessage Transformation
Message EndpointThe client code an application uses to send or receiveamqp091-go channel, kgo.Client, redis.Client, Laravel dispatch()/workerConsumer & 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.

StepWhat happensRabbitMQ knobKafka knobRedis Streams knobLaravel knob
1 SerializeTurn the object into bytes plus headersProperties and headers (content_type, correlation_id)Record key, value, headers; serializerField-value pairs in the entryJob payload (JSON with a serialized command)
2 Send and confirmHand to the broker and waitPublisher confirms (confirm.select)acks (0, 1, all), enable.idempotenceReply to XADDdispatch(), after_commit
3 StoreMake it durableDurable queue + persistent message; quorum queueReplication factor, min.insync.replicas, retentionAOF (appendonly, appendfsync), replicationTable row or Redis list item
4 DeliverMove it to a consumerbasic.consume, prefetch_countgroup.id, max.poll.records, partition assignmentXREADGROUP, COUNT, BLOCKqueue:work, block_for, --sleep
5 AcknowledgeTell the broker it is donebasic.ack, nack, rejectCommit offset (enable.auto.commit or manual)XACKJob 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.

ProductErrorMeaningRetry?
RabbitMQ406 PRECONDITION_FAILEDQueue or exchange redeclared with different attributes; also an ack for an unknown delivery tagNo: fix the declaration or the double ack
RabbitMQ404 NOT_FOUNDQueue or exchange does not existNo until it is declared
KafkaUNKNOWN_TOPIC_OR_PARTITIONTopic missing (or metadata stale)Yes after metadata refresh, or create the topic
KafkaNOT_LEADER_OR_FOLLOWERThe partition leader movedYes, the client refreshes metadata
KafkaNOT_ENOUGH_REPLICASacks=all but in-sync replicas are below min.insync.replicasYes later; it is a durability signal, not a bug
RedisBUSYGROUPConsumer group already existsIgnore on startup
RedisNOGROUPThe stream or group does not existCreate the group
LaravelMaxAttemptsExceededExceptionJob was attempted more times than allowedNo: it goes to failed_jobs

Solving the first problems ​

ProblemSolutionHowAdvantageCost or limit
Job runs before the transaction that created its data has committedDispatch after commitafterCommit() or after_commit => true; or an outboxWorker never sees missing rowsDispatch is lost if the process dies right after commit: use the Outbox for must-not-lose
The same message arrives twiceIdempotent consumerUnique message id checked in the same database transaction as the effectSafe retriesAn extra table and a key discipline (Inbox)
A burst overloads the systemQueue plus workersPut the work on a queue and scale workersSpike becomes latencyBacklog must be watched (Backpressure)
One message always failsDead-letter queueCap attempts, then park the messageThe queue keeps flowingSomeone must look at the parking lot (DLQ)
Caller needs the resultRequest-reply, or just RESTCorrelation id and reply queueStays asyncMore moving parts than a call (Request-Reply)
Order mattersPartition by keySame key, same partition or queuePer-entity orderParallelism limited per key (Ordering)
Several services must change togetherSagaLocal transactions plus compensationsNo distributed transactionComplex (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.

sql
-- 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;
sql
-- 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 effect

Retry and failure handling ​

FailureRetry?Rule
Network blip while publishingYesRetry with the same message id, so a duplicate can be recognised
Broker refused (full, memory alarm, no leader)Yes, with backoffSlow the producer; see Backpressure
Consumer exception from a flaky dependencyYes, with backoff and a capRetry & Backoff
Consumer exception from bad dataNoPark it in the DLQ; retrying cannot help
Consumer crash mid-workAutomatic redeliveryHandler must be idempotent

Choosing a style ​

ProblemStyleProduct to reach for firstReason
Send an email, resize an image, generate a PDF after a requestWork queue (point-to-point)Laravel queue on Redis or database; SQS in AWSSimple, one consumer per job
Spread heavy tasks over many workersCompeting consumersRabbitMQ or a Laravel Redis queueFair dispatch, prefetch
Tell several services that an order was placedPublish/subscribe eventsRabbitMQ topic exchange, or Kafka topic with groupsOne publish, many reactions
Keep an immutable history that new services can replayLog / event streamKafka, or Redis Streams at small scaleReplay by moving the offset
Very high throughput data pipelinePartitioned logKafkaSequential I/O, partitions, batching
A small app that already runs Redis and needs light queuesRedis list queue or StreamLaravel Redis driver or StreamsNo new infrastructure
Per-customer ordering of eventsKeyed partitions or single-active consumerKafka keys, RabbitMQ consistent-hash exchangeOrder per key, parallel across keys
The caller needs the answer in the same requestRPC (REST/gRPC)HTTPMessaging adds only delay
Move changes from a database to othersCDC plus logDebezium into KafkaChange Data Capture
Long multi-step business processSaga or durable workflowOrchestrator service, Temporal, Laravel chainsSaga, Durable Workflows
Fire-and-forget notifications where loss is acceptableRedis Pub/Sub or plain eventsRedis Pub/SubAt-most-once is fine, no storage
A monolith needs background work todayQueue in the same appLaravel database or redis driverThe cheapest first step
Must not lose an event when the database commitsOutbox plus relayOutbox table with polling or CDCOutbox
Very different clouds, protocols or IoT devicesProtocol bridgeMQTT/AMQP 1.0 brokers, NATSOther 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.

go
// 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
<?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:

DriverWhat it isNeedsNotes
syncRuns the job immediately in the current processNothingDevelopment and tests; hides ordering and serialization bugs
databaseA jobs table in your databasephp artisan make:queue-tableThe default QUEUE_CONNECTION in a fresh app
redisRedis lists and sorted setspredis/predis or phpredisblock_for blocks instead of polling; in a Redis Cluster queue names need a hash tag such as {default}
sqsAmazon SQSaws/aws-sdk-phpFIFO and fair queues are documented separately
beanstalkdBeanstalkdpda/pheanstalkSmall dedicated queue server
nullDiscards queued jobsNothingDisable queued work
deferredRuns after the HTTP response, in the same processNothingAlso the default failover target
backgroundRuns after the response in a separately spawned PHP processNothingFrees the PHP-FPM worker
failoverTries the next listed connection if pushing failsA list of connectionsNeeds a worker for each real connection
MongoDBA MongoDB-backed queuemongodb/laravel-mongodbPackage, documented in the driver prerequisites
php
<?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
<?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,default

Laravel 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
<?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
<?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.

go
// 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
<?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 rabbitmq

Kafka ​

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().

go
// 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
<?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.

go
// 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
<?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 sync driver and dispatch inside transactions. sync runs 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 provide after_commit for 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 dashboard

Modular 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 ​

LoadDesignWhat changes
1x (tens of messages per second)Laravel database or redis queue, one workerNothing special; monitor failed_jobs
10xRedis or SQS queue, several workers, named queues for priorityPrefetch / worker count, retry_after above job time, Horizon
100xRabbitMQ or Kafka; keyed partitions; one consumer group per servicePartition count, consumer lag alarms, schema registry
BeyondMultiple clusters or regions, stream processing, CDC feeding the logIdempotency 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".

  1. Queue versus topic, in-process (run). From docs/snippets/messaging/messaging-fundamentals/go:
bash
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)
  1. First Laravel queue (expected, not run).
bash
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)
  1. RabbitMQ hello (expected, not run). A broker such as rabbitmq:4-management must be reachable.
bash
RABBITMQ_URL=amqp://guest:guest@localhost:5672/ go run ./rabbitmq
# received "hello"
# (the queue "hello" is now empty; rabbitmqctl list_queues shows messages 0)
  1. Kafka hello (expected, not run).
bash
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)
  1. Redis Streams, with a crash (expected, not run). Remove the XAck line, run once, then inspect:
bash
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 recovered

Common misconceptions ​

BeliefReality
"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 ​

TopicWhat to remember
Why asyncTemporal decoupling, load levelling, fan-out, failure isolation; cost: eventual consistency, duplicates, hard debugging
Message vs event vs command vs documentIntent differs, envelope is the same: do this / it happened / here is data
QueueOne consumer per message; ack removes it; RabbitMQ and Laravel
LogAppend-only, offsets per group, replay, retention; Kafka
StreamLog in one Redis key with group state (last-delivered ID, PEL)
Point-to-point vs pub/subOne of N versus all N
Push vs pullRabbitMQ pushes with prefetch; Kafka and Redis pull
DurableDurable container, persistent message, confirmed publish, replicated or fsynced
TriangleProducer owns retries and ids, broker owns storage and order, consumer owns ack timing and idempotency
First ruleAssume every message can arrive twice
Second ruleThe database commit and the publish are not atomic: outbox
LaravelShouldQueue, dispatch(), queue:work, afterCommit(), drivers: sync, database, redis, sqs, beanstalkd, null, deferred, background, failover
Pick a brokerLight work: Laravel queue; routing and work distribution: RabbitMQ; replay and throughput: Kafka; already on Redis: Streams
Where to goGuarantees (3), ack (4), order (5), inbox (6), brokers (9 to 11), outbox (19)

Self-check: questions & answers ​

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

1 — 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 ​

TermMeaning
Acknowledgment (ack)The consumer telling the broker a message was handled so it can be removed or the offset advanced
Nack / rejectThe consumer telling the broker it could not handle the message; requeue or dead-letter
AggregatorEIP: collects related messages and combines them into one
AMQPAdvanced Message Queuing Protocol; RabbitMQ speaks 0-9-1, a separate 1.0 is an OASIS and ISO standard
AOFRedis Append Only File; logs every write; its fsync policy decides Redis durability
At-least-onceNever lost, may be delivered more than once
At-most-onceMay be lost, never redelivered
Exactly-onceProcessed once and only once; end to end it needs idempotency
BackpressureSlowing the producer or limiting the consumer so a queue does not grow without bound
BindingRabbitMQ rule that routes messages from an exchange to a queue
BrokerThe server that stores, routes and tracks messages
Canonical Data ModelEIP: 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 AdapterEIP: connects an application to a messaging channel
Channel PurgerEIP: removes unwanted messages from a channel
Claim CheckEIP: store a large payload elsewhere and send only a reference
CommandA message asking one receiver to do something
Competing consumersSeveral consumers reading one queue so each message is handled once
Composed Message ProcessorEIP: processes a composite message by routing parts and re-aggregating
ConsumerThe code that receives and processes messages
Consumer groupKafka and Redis Streams name for a set of consumers sharing one position and splitting the work
Consumer lagHow far a consumer's position is behind the end of the log
Content-Based RouterEIP: routes a message by what is inside it
Content EnricherEIP: adds missing data to a message from another source
Content FilterEIP: removes unwanted fields from a message
Control BusEIP: a channel to manage and monitor the messaging system itself
Correlation idAn identifier that ties a reply or a trace to its original message
Datatype ChannelEIP: one channel per kind of message
Dead-letter queue (DLQ)A queue where messages that could not be processed are parked
Delivery modeAMQP property marking a message transient or persistent
DetourEIP: routes messages through extra steps such as validation, switchable at runtime
Document messageA message that carries data; the receiver decides what to do
Durable SubscriberEIP: a subscriber whose messages are kept while it is offline
Durable queueA RabbitMQ queue whose definition survives a restart
Envelope WrapperEIP: wraps a message in the format a messaging system needs, then unwraps it
EventA message announcing something that already happened
Event-Driven ConsumerEIP: a consumer the broker calls when a message arrives (push)
Event notificationAn event carrying little data; the receiver asks for details if it needs them
Eventual consistencyState converges after a delay rather than immediately
ExchangeRabbitMQ entity that receives published messages and routes them to queues by bindings
Fan-outOne message delivered to many receivers
Format IndicatorEIP: a field telling the receiver which format or version the message uses
Guaranteed DeliveryEIP: persist messages so they survive a broker crash
Idempotent consumer / receiverA consumer for which processing the same message twice has the same effect as once
InboxA table of processed message ids used to drop duplicates
Invalid Message ChannelEIP: where a receiver puts messages it cannot understand
JMS / Jakarta MessagingJava API for message-oriented middleware with queues and topics
Kafka partitionOne ordered, append-only log of a topic
KRaftKafka's built-in consensus mode that replaces ZooKeeper
Load levellingLetting a queue absorb a burst so consumers work at their own pace
MessageOne unit of data with a header and a body
Message BusEIP: shared infrastructure that lets applications communicate
Message DispatcherEIP: distributes messages among performers within one consumer
Message EndpointEIP: the client code an application uses to send or receive messages
Message ExpirationEIP: a time after which a message is no longer useful
Message FilterEIP: drops messages that do not match a condition
Message HistoryEIP: a record of the components a message has passed through
Message RouterEIP: sends a message to one of several channels based on conditions
Message SequenceEIP: numbering parts of a large message so they can be reassembled
Message StoreEIP: a database that keeps copies of messages for analysis
Message TranslatorEIP: converts one data format into another
Messaging BridgeEIP: connects two messaging systems
Messaging GatewayEIP: wraps messaging code behind a plain interface
Messaging MapperEIP: maps between domain objects and messages
NormalizerEIP: converts different formats of the same meaning into one
OffsetA record's position in a Kafka partition
OutboxA 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 messageA message the broker writes to disk
Pipes and FiltersEIP: a chain of independent processing steps joined by channels
Point-to-pointEach message goes to exactly one receiver
Polling ConsumerEIP: a consumer that asks the channel for the next message
PrefetchLimit on delivered but unacknowledged messages per consumer (RabbitMQ prefetch_count)
Process ManagerEIP: a central unit that keeps the state of a multi-step process
Producer / publisherThe code that sends messages
Pub/SubPublish/subscribe: each subscriber gets a copy
Publisher confirmRabbitMQ acknowledgment from the broker to the publisher
Quorum queueRabbitMQ replicated queue type based on consensus
QueueA buffer where each message goes to one consumer
Recipient ListEIP: sends a message to a list of receivers computed per message
ReplayReading old messages again from a log
Request-ReplyA pair of messages: a request and its correlated response
ResequencerEIP: restores order to out-of-order messages
RetentionHow long a log keeps messages (Kafka retention.ms)
Return AddressEIP: where the reply to a request should be sent
Routing keyRabbitMQ message attribute used by bindings to route
SagaA sequence of local transactions with compensations instead of one distributed transaction
Scatter-GatherEIP: sends a request to several recipients and combines the replies
Selective ConsumerEIP: a consumer that only takes messages matching a filter
Service ActivatorEIP: connects a messaging channel to a service call
Smart ProxyEIP: tracks the reply of a request to a service with unknown reply address
SplitterEIP: breaks one message into several
Stream (Redis)An append-only data structure under one key with consumer groups
SubscriptionThe registration through which a consumer receives messages
Temporal decouplingSender and receiver need not run at the same time
Test MessageEIP: a message injected to check a component is healthy
TopicA named channel for publish/subscribe, or a Kafka log
Transactional ClientEIP: a client that makes sending and receiving part of a transaction
Wire TapEIP: 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/.

Built by Morteza Negahi