Skip to content

Integration Styles & Channels: File, Shared DB, RPC, Messaging ​

"Use Messaging to transfer packets of data frequently, immediately, reliably, and asynchronously, using customizable formats." — Gregor Hohpe & Bobby Woolf, Enterprise Integration Patterns, "Messaging" (Integration Styles), enterpriseintegrationpatterns.com/patterns/messaging/Messaging.html

Summary: There are four ways to make separate applications share data (files, one database, remote calls, messages), and once you pick messages you still have to design the channels: which kinds exist, how they are named, what happens to bad messages, and how two brokers are joined. Focus: The four integration styles and their trade-offs, then every channel pattern in the Enterprise Integration Patterns catalogue (Message Channel, Point-to-Point, Publish-Subscribe, Datatype, Invalid Message, Dead Letter, Guaranteed Delivery, Channel Adapter, Messaging Bridge, Message Bus, Message Expiration, Message Sequence, Format Indicator) mapped onto RabbitMQ, Kafka, Redis Streams and Laravel. Learning goal: Given a new integration, choose the style on purpose, draw the channel layout (one type per channel, one queue or group per consumer), say where invalid, expired and undeliverable messages go, and connect a legacy system or a second broker with an adapter or a bridge.

This page is the vocabulary chapter of the messaging section. Messaging Fundamentals draws the map, and this page is where the map's first two regions are surveyed in full: the choice between File Transfer, Shared Database, Remote Procedure Invocation and Messaging, and the patterns that describe a channel (the pipe between a sender and a receiver). It does not re-teach the neighbours. Delivery semantics live in Delivery Guarantees, ack mechanics in Message Acknowledgment, ordering in Ordering & Partitioning, exchange types in Routing Topologies, the Dead Letter Channel in Dead-Letter Queue, transformation in Message Transformation, and the broker internals in RabbitMQ, Kafka and Redis Streams & Pub/Sub.

Page map ​

If you are looking forGo to
The four styles and the channel patterns in two tablesEverything in one minute
Why a channel layout is a design decision, not plumbingWhy it exists
Where the vocabulary comes from (Hohpe and Woolf, 2003)Where it comes from
File Transfer, Shared Database, RPC, Messaging and when each is fineThe four integration styles
RPC against messaging, point by pointRPC vs messaging
Message Channel, Point-to-Point, Publish-Subscribe, DatatypeThe channel patterns
Invalid Message Channel vs Dead Letter ChannelInvalid Message Channel and Dead Letter Channel
Guaranteed Delivery per brokerGuaranteed Delivery
Channel Adapter, Messaging Bridge (Shovel, Federation, MirrorMaker 2, Kafka Connect)Channel Adapter and Messaging Bridge
Message Bus vs Message Broker vs ESBMessage Bus and Bus, broker, ESB
Message Expiration, Message Sequence, Format IndicatorThe three header patterns
Channel naming and channel-per-type vs channel-per-consumerNaming and granularity
The invalid-message flow step by stepMechanics
Go and Laravel codeGo, Laravel
What each broker does for each patternBroker differences
Which style and channel layout for which situationChoosing
Monolith to distributed, with one worked exampleIn architecture
Reproduce the topology (expected, not run)Lab
Wrong beliefs, cheat sheet, glossaryMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The four integration styles. Each row is unpacked in the styles section.

StyleHow applications shareCoupling in timeTypical shape todayMain weakness
File TransferOne writes a file, another reads it laterHours to daysNightly CSV, SFTP drop, S3 object, data lake exportStale data, whole-file failures, format drift
Shared DatabaseEveryone reads and writes the same schemaNone (same rows)One PostgreSQL or MySQL shared by several apps, reporting viewsOne schema and one lock domain for all teams
Remote Procedure InvocationA calls B and waits for the answerZero (both must be up now)REST, gRPC, GraphQL, SOAPAvailability multiplies, tight temporal coupling
MessagingA hands a message to a channel and carries onMinutes (decoupled)RabbitMQ, Kafka, Redis Streams, SQS, NATSEventual consistency, a broker to run

The channel patterns. Every row has its own block under the channel patterns.

PatternThe problem in one lineThe solution in one lineBroker primitive (RabbitMQ / Kafka / Redis Streams)
Message ChannelHow does one application talk to another by messaging?A named channel; one writes, the other readsQueue or exchange / topic / stream key
Point-to-Point ChannelHow do I make sure exactly one receiver gets it?Many receivers may compete, one wins per messageQueue with competing consumers / one consumer group / one group on a stream
Publish-Subscribe ChannelHow do I broadcast an event to all interested receivers?One input, one output copy per subscriberFanout or topic exchange with a queue per subscriber / one group per subscriber / one group per subscriber
Datatype ChannelHow does the receiver know how to process it?One channel per message typeOne queue per type / one topic per type / one stream per type
Invalid Message ChannelWhat do I do with a message that makes no sense?Move it to a special channel with the reasonDLX or explicit republish / invalid topic / invalid stream
Dead Letter ChannelWhat does the system do with a message it cannot deliver?The messaging system parks itDLX, dead-letter queue / consumer-side retry and DLQ topics / XPENDING, XCLAIM, parking stream
Guaranteed DeliveryWhat if the broker crashes?Persist at every hop until acknowledgedDurable queue, persistent message, confirms / acks=all, ISR, min.insync.replicas / AOF fsync, WAIT
Channel AdapterHow does a non-messaging application join?A messaging client that wraps the application's API or dataYour worker, Kafka Connect source or sink, Laravel queue:work
Messaging BridgeHow do two messaging systems exchange messages?A set of adapters, one pair per corresponding channelShovel, Federation / MirrorMaker 2, Connect / none native
Message BusHow do many applications cooperate in a decoupled way?Common infrastructure, common commands, common data modelA broker plus conventions, not a product
Message ExpirationWhen is a message too old to matter?A time limit on viabilityQueue or per-message TTL / retention only, header check / MINID trim, header check
Message SequenceHow do I send more data than fits in one message?Chunks with sequence id, position, size or end markerHeaders, plus ordering per queue / key / stream
Format IndicatorHow can the format change later?The message names its own formatProperties and headers; schema registry on Kafka

The three things to do.

SituationDo this
Designing a new integrationStart from "does the caller need the answer now?" If not, prefer messaging; if yes, RPC; keep files and shared databases for the cases in Choosing
Laying out channelsOne channel per message type, one queue (or consumer group) per consumer, names that state owner, type and version
Connecting something that does not speak the broker's protocolWrite or deploy a Channel Adapter; connect two brokers channel by channel with a Messaging Bridge, never by sharing one client

Why it exists ​

The problem. Applications are built independently, "with different languages and platforms", and still "need to share data and processes in a responsive way". That sentence is the shared problem statement of all four styles in the book. Every style answers one question: where does the data (or the call) live while it travels between two applications that are not the same program?

ChoiceGainsPays with
Share a fileAlmost no shared runtime; any language can write a CSVLatency in hours, no per-record failure handling, nobody owns the format
Share a databaseInstant consistency, real transactions across applicationsOne schema every team must agree on; every application depends on every other one's migrations
Call remotelyThe answer arrives immediately; the owner keeps its data privateBoth sides must be up; failures and latency of the callee become the caller's
Send a messageThe sender does not wait; the broker absorbs bursts and outagesEventual consistency, duplicates, ordering questions, one more system to operate

An everyday picture. The four styles are four ways to hand a colleague information. A printed report left in their tray (File Transfer). A whiteboard in a shared office that everybody writes on and reads from (Shared Database). A phone call where you wait until they pick up (Remote Procedure Invocation). A message in their inbox that they answer when they can (Messaging). A channel is the inbox: the thing you address, not the person. Channel patterns are the office rules about inboxes: one inbox per kind of request, a separate tray for mail nobody can read, a rule that says what happens to a letter that stays unopened too long.

Three common misunderstandings, up front.

  1. "Messaging replaces the other three." It does not. Real organisations run all four at once, and the right answer for a nightly accounting export is still a file.
  2. "A channel is just a queue." A queue is one implementation. A channel is the contract: which type of data flows through it, who may read it, what happens to failures. Kafka has no queue and still has channels.
  3. "Pub/sub and point-to-point are two kinds of broker." They are two delivery rules on a channel, and every serious broker can do both, as the Publish-Subscribe block shows.

Where it comes from ​

Hohpe and Woolf published Enterprise Integration Patterns in 2003. The book starts with a catalogue of four integration styles and then spends most of its pages on messaging. The patterns are named on the website enterpriseintegrationpatterns.com, which publishes the problem and solution statements of each pattern under a Creative Commons licence and the rest of the text by purchase. This page quotes only those published problem and solution statements. The wording of everything that follows, including the mapping to brokers, is this site's own work.

The vocabulary outlived the era of JMS and MQSeries that it was written for. The names are still the working language of integration work, and cloud brokers describe themselves in them: the pattern site itself now carries a note that Google Cloud Pub/Sub offers "both Competing Consumers and Publish-Subscribe Channel semantics, managed through topics (Publish-Subscribe) and subscriptions (Competing Consumers)". That sentence is the whole of this chapter in miniature: the two delivery rules are properties of how a channel is read.

YearEventWhy it matters here
2003Enterprise Integration Patterns (Hohpe, Woolf)Fixes the names: Message Channel, Datatype Channel, Messaging Bridge and the rest
2011Kafka's first public description (the NetDB paper)A log with consumer-controlled offsets: Publish-Subscribe by default, queue behaviour through groups
2010sMicroservices (this row is this site's summary, not a quote)Moves the debate from a central ESB hub to channels owned by services
TodayBrokers ship adapters (Kafka Connect) and bridges (Shovel, Federation, MirrorMaker 2) as productsThe patterns became configuration

The four integration styles ​

All four blocks share the same opening problem statement from the book: "An enterprise has multiple applications that are being built independently, with different languages and platforms. The enterprise needs to share data and processes in a responsive way." The question is the same each time: "How can I integrate multiple applications so that they work together and can exchange information?"

File Transfer Good to know ​

In plain words: One application writes a file; another application picks it up later and reads it. The file is the whole interface.

Common misunderstanding: "Files are legacy, nobody does that any more." Bank statements, payroll runs, data-lake exports, logistics manifests and every ETL job to a warehouse are files today. The pattern is alive; only the transport changed from FTP to SFTP and S3.

Definition (EIP): "Have each application produce files containing information that other applications need to consume. Integrators take the responsibility of transforming files into different formats. Produce the files at regular intervals according to the nature of the business." (File Transfer)

  Legacy ERP                         Reporting app
  1  22:00  write orders-2026-11-25.csv (50 000 rows)
  2  22:05  upload to SFTP /inbox
  3                                  02:00  poll /inbox, find the file
  4                                  02:01  parse row 1 ... row 31 244: malformed price
  5                                  02:01  whole job fails (or: skip row, log, continue)
  6  06:30  business reads yesterday's numbers; today's are not there yet

Real scenarios: nightly bank statement import; payroll export to an accountant; marketing feed (CSV or XML) to a price-comparison site; data-warehouse load; a partner who can only drop files. Staleness is the cost: the receiver sees the world as it was at the last export.

When it is fine: the data is naturally batch (a daily statement), the partner cannot do anything else, the volume is large and a bulk format (Parquet, CSV) is cheaper than a million messages, or the latency requirement is measured in hours. When it is not: anything a user waits on, anything where a half-processed file is hard to recover (use a per-row sequence number, see Message Sequence).

AspectFile Transfer
Failure unitThe whole file, unless rows are checkpointed
Format ownerWhoever writes the file; EIP says integrators transform it
AtomicityWrite to a temp name and rename, otherwise the reader sees half a file
Typical adapterA Channel Adapter that turns each row into a message

Shared Database Good to know ​

In plain words: Several applications read and write the same tables, so they always see the same data.

Common misunderstanding: "One database means one source of truth, so it is the safest integration." It is the most consistent style and the most coupled one. A column rename needs every application's release in lockstep, and one team's slow report query can lock another team's checkout.

Definition (EIP): "Integrate applications by having them store their data in a single Shared Database." The pattern's own warning: "One of the biggest difficulties with Shared Database is coming up with a suitable design for the shared database. Coming up with a unified schema that can meet the needs of multiple applications is a very difficult exercise." (Shared Database)

  Billing app                              Inventory app                  DBA
  1  UPDATE orders SET status='paid' ...
  2                                        SELECT ... WHERE status='paid'   -- sees it at once
  3                                        UPDATE stock SET qty = qty - 1
  4                                                                       ALTER TABLE orders RENAME COLUMN status TO state
  5  ERROR: column "status" does not exist                                -- both apps are down
sql
-- Shared Database in its most honest form: a view that is the contract.
-- Other applications read orders_for_inventory, never the orders table itself,
-- so the owner can change the table without breaking them.
CREATE VIEW orders_for_inventory AS
SELECT id AS order_id, sku, quantity, placed_at
FROM   orders
WHERE  status = 'paid';

-- The reader gets a role that can only see the view.
CREATE ROLE inventory_reader LOGIN;
GRANT SELECT ON orders_for_inventory TO inventory_reader;

Real scenarios: a modular monolith whose modules share one PostgreSQL; a reporting database that analysts read; two internal tools that grew on the same MySQL; a database-per-service system that cheats with a "read replica for the other team". Transactions across applications are a real advantage (ACID & Transactions); the price is the lock domain.

When it is fine: one team owns every application, the schema changes rarely, the applications are really modules of one product. When it is not: different teams with different release cadences, or any case where one application's load must not affect another's. The way out is rarely a rewrite: put the contract behind a view, then replace the view with a message or an API (see Outbox and Change Data Capture).

AspectShared Database
Failure unitThe database: if it is down, everything is down
CouplingSchema, data types, locks, connection limits (Connection Pooling)
ConsistencyImmediate, transactional
Escape hatchViews as contracts, then events from the owner

Remote Procedure Invocation Must-know ​

In plain words: One application calls a function on another across the network and waits for the result, as if it were a local call.

Common misunderstanding: "A remote call is a local call with a longer wire." It is a call that can time out, arrive twice, arrive never, and succeed while the answer is lost. The book says the same: "People often design the integration the way they would design a single application, unaware that the rules change."

Definition (EIP): "Develop each application as a large-scale object or component with encapsulated data. Provide an interface to allow other applications to interact with the running application." The pattern notes the consequence: "the applications are still fairly tightly coupled together. The remote calls each system supports tends to tie the different systems into a growing knot." (Remote Procedure Invocation)

  Checkout                 Payments                 Tax service
  1  POST /charge ------------>
  2                           GET /rate ------------------->
  3                                                         (slow: 8 s)
  4                           <-------------------------- 200
  5  <------------------ 200 charge ok
  -- if Tax is down at step 2, Checkout's request fails although Payments is healthy
  -- availability of the chain = product of the three availabilities

Real scenarios: a REST call to look up a price while the user waits; gRPC between services in one data centre; GraphQL resolvers calling backends; payment authorisation where the user must see "approved" or "declined" now. See Service Communication for the REST, gRPC and GraphQL mechanics.

When it is right: the caller cannot proceed without the answer, the operation is a query, the callee is in the same trust and availability domain. When it hurts: long chains, fan-out to many callees, anything that should survive a callee outage.

AspectRPC
Failure unitThe call; failures propagate along the chain
RetriesCaller's problem; needs idempotency keys (Idempotent Consumers)
CouplingInterface, availability, and often call order ("sequencing")
MitigationsTimeouts, circuit breakers, bulkheads, or convert to messaging

Messaging Must-know ​

In plain words: The sender hands a self-contained message to a channel and moves on. The receiver takes it from the channel when it is ready.

Common misunderstanding: "Messaging is RPC with a queue in the middle." If the sender sits and waits for the reply, it is RPC with extra steps (see Request-Reply). Messaging earns its keep when the sender does not wait and the design accepts that the effect happens later.

Definition (EIP): "Use Messaging to transfer packets of data frequently, immediately, reliably, and asynchronously, using customizable formats." The book's reasoning: "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." And: "Messages can be transformed in transit without either the sender or receiver knowing about the transformation." (Messaging)

  Orders service                  Broker (channel)                 Billing service
  1  INSERT order, COMMIT
  2  publish order.placed ------->  persist, confirm
  3  <------------ confirm
  4  respond 201 to the user
  5                                                          (Billing was down for 20 minutes)
  6                                                          comes back, consumes order.placed
  7                                  <------------- ack

Real scenarios: order placed fans out to billing, inventory and e-mail; a video upload triggers thumbnails; a payment webhook is queued and processed at the system's pace; a data change is streamed to a search index. The rest of the section is the detail of this one style: Messaging Fundamentals for the map, Event-Driven Architecture for the design style built on it.

AspectMessaging
Failure unitThe message; failures are retried, parked or expired individually
CouplingThe message format and the channel name, not the other side's availability
ConsistencyEventual; see Delivery Guarantees for what "once" means
CostA broker to run, a duplicate to tolerate, an ordering question to answer

RPC vs messaging: the trade-offs, point by point ​

The following comparison is this page's own synthesis, not a quote from the book.

QuestionRPC (REST, gRPC)Messaging (RabbitMQ, Kafka, Redis Streams, SQS, NATS)
Does the caller need the answer now?Yes, that is the pointNo; if yes, use Request-Reply or RPC
What if the callee is down?The call fails; retry or circuit-breakThe message waits in the channel
Who absorbs a traffic spike?The callee, or it sheds loadThe channel; the consumer drains at its own pace (Backpressure)
How many receivers?One per callOne (Point-to-Point) or many (Publish-Subscribe)
Can I add a receiver without touching the sender?NoYes, bind a new queue or start a new consumer group
What does the sender know about the receiver?Address and interfaceOnly the channel name and message format
OrderingWhatever the caller sequencesPer queue, per partition or per key; see Ordering & Partitioning
DuplicatesPossible on retryPossible by design (at-least-once)
DebuggingA stack trace across servicesA trace id in headers across channels (Observability)
TestingStub the HTTP clientFake the queue (Testing Messaging)
Best atQueries, commands that need an immediate verdictNotifications, work distribution, integration across teams

The four styles side by side ​

1. File TransferApp AApp Borders.csvwritten nightly, read later+ trivial, no shared runtime- stale, whole-file failures2. Shared DatabaseApp AApp Bone schemasame rows, same transactions+ always consistent- one schema, one lock domain3. Remote Procedure InvocationApp AApp BHTTP, gRPC: call and waitA is blocked while B works+ immediate answer- both must be up, tight coupling4. MessagingApp AApp Bchannel (broker)send, then carry on+ decoupled in time- eventual, needs a brokerCoupling in time: File = days, Shared DB = none (same rows), RPC = zero (both up now), Messaging = minutesReal systems mix all four: a nightly file, a shared reporting database, a REST call, and events on a broker

The channel patterns ​

Messaging as a style is only the start. The book's "Messaging Channels" chapter lists the patterns that decide what the channel is. The table below names every pattern this page owns and where its block is; the blocks follow in the order a design meets them.

PatternBlockOwner of the deep detail
Message ChannelMessage ChannelThis page
Point-to-Point ChannelPoint-to-PointThis page; scaling in Competing Consumers
Publish-Subscribe ChannelPublish-SubscribeThis page; exchange types in Routing Topologies
Datatype ChannelDatatype ChannelThis page
Invalid Message ChannelInvalid Message ChannelThis page
Dead Letter ChannelDead Letter ChannelPointer only; Dead-Letter Queue
Guaranteed DeliveryGuaranteed DeliveryThis page; semantics in Delivery Guarantees
Channel AdapterChannel AdapterThis page
Messaging BridgeMessaging BridgeThis page
Message BusMessage BusThis page
Message Expiration, Message Sequence, Format IndicatorThree header patternsThis page; versioning in Message Design

Message Channel Must-know ​

In plain words: A channel is a named place where one application drops messages and another picks them up. You do not send "to the broker"; you send to a specific channel.

Common misunderstanding: "A channel is a queue." A channel is whatever the messaging system gives you as an addressable pipe: a RabbitMQ exchange plus its queues, a Kafka topic, a Redis stream key. The sender may not know the queue at all; it knows the exchange and routing key.

Definition (EIP): Problem: "How does one application communicate with another using messaging?" Solution: "Connect the applications using a Message Channel, where one application writes information to the channel and the other one reads that information from the channel." And: "the messaging system has different Message Channels for different types of information the applications want to communicate." (Message Channel)

  Sender                      Messaging system                       Receiver
  1  open connection ----------> (authenticated, vhost / cluster)
  2  address a channel by name:  orders.events  /  orders.order-placed.v1  /  orders:order-placed:v1
  3  send(message) ------------> channel accepts it, stores it
  4                                                         <------ receiver reads from ITS end
  -- the two ends never talk to each other directly
ProductWhat a Message Channel isAddressed by
RabbitMQAn exchange (where you publish) with queues bound to it (where you read); with the default exchange the queue name is the routing keyExchange name plus routing key, or queue name
KafkaA topic, split into partitionsTopic name (plus key to choose the partition)
Redis StreamsA stream, one Redis key holding an append-only logKey name
Redis Pub/SubA channel name; no storage, "at-most-once"Channel name
LaravelA connection (the transport) and a queue inside it, per the docsonConnection('rabbitmq')->onQueue('billing.order-placed')
SQS, NATS, PulsarA queue, a subject, a topic (see Other Brokers)URL, subject string, topic name

Laravel's own documentation draws the same line: "it is important to understand the distinction between 'connections' and 'queues'". A connection is a broker; a queue is a channel inside it. If a job is dispatched without naming either, it "is sent to the default connection's default queue" (Laravel 13 queues).

Point-to-Point Channel Must-know ​

In plain words: Many workers may listen to the channel, but each message goes to exactly one of them. This is how you share work.

Common misunderstanding: "Point-to-point means one consumer." It means one consumer per message. Ten workers on one queue is still Point-to-Point; that is the Competing Consumers pattern in its own page.

Definition (EIP): Problem: "How can the caller be sure that exactly one receiver will receive the document or perform the call?" Solution: "Send the message on a Point-to-Point Channel, which ensures that only one receiver will receive a particular message." The channel "ensures that only one receiver consumes any given message. If the channel has multiple receivers, only one of them can successfully consume a particular message." (Point-to-Point Channel)

  Producer        Channel billing.commands        Worker A      Worker B
  1  send m1 ---->  [m1]
  2  send m2 ---->  [m1][m2]
  3                  m1 ---------------------------> A
  4                  m2 ----------------------------------------> B
  5                                                  A acks m1
  6                                                              B crashes before ack
  7                  m2 redelivered ----------------> A
  -- each message is processed by one worker at a time, but may be redelivered after a failure
ProductHow Point-to-Point is builtThe catch
RabbitMQA queue with several consumers; the broker dispatches each message to one consumer (round robin, bounded by prefetch)Order across consumers is not preserved; use single active consumer if order matters (Ordering)
KafkaA consumer group: each partition is assigned to one member, so each record reaches one member of the groupParallelism is capped by the partition count
Redis StreamsA consumer group on a stream; XREADGROUP hands each entry to one consumer, which must XACKPending entries need claiming when a consumer dies (XAUTOCLAIM)
LaravelSeveral queue:work processes on one connection and queue; the driver reserves each job for one workerretry_after must exceed the longest job or the job runs twice

Publish-Subscribe Channel Must-know ​

In plain words: One announcement, many listeners, each gets their own copy.

Common misunderstanding: "Pub/sub means the fire-and-forget Redis PUBLISH." That is one implementation with at-most-once delivery. Publish-Subscribe as a pattern only says each subscriber gets a copy; whether the copy is stored for a subscriber who is offline is a separate property (see Durable Subscriber in Consumer & Endpoint Patterns).

Definition (EIP): Problem: "How can the sender broadcast an event to all interested receivers?" Solution: "Send the event on a Publish-Subscribe Channel, which delivers a copy of a particular event to each receiver." The channel "has one input channel that splits into multiple output channels, one for each subscriber. [...] Each output channel has only one subscriber, which is only allowed to consume a message once." (Publish-Subscribe Channel)

  Orders       Exchange orders.events (topic)      billing queue    inventory queue    email queue
  1  publish order.placed.v1 -->
  2                 copy ------------------------>  [m]
  3                 copy ---------------------------------------->  [m]
  4                 copy ---------------------------------------------------------->  [m]
  5                                                  Billing acks   Inventory acks     Email is down: [m] waits
  -- each subscriber has its own queue, so a slow or dead subscriber cannot take messages from the others
ProductHow Publish-Subscribe is builtStored for offline subscribers?
RabbitMQA fanout or topic exchange; one queue per subscriber bound to it. A queue is "the output channel with one subscriber" in EIP termsYes, as long as the queue exists and is durable
KafkaOne topic; each consumer group has its own committed offsets, so every group sees every recordYes, until retention deletes the log
Redis StreamsOne stream; one consumer group per subscriber, each with its own last-delivered IDYes, until the entry is trimmed
Redis Pub/SubPUBLISH to a channel; connected subscribers receive itNo: "the message is forever lost" if the subscriber cannot handle it (Redis Pub/Sub)
LaravelAn event with several queued listeners: Laravel pushes one job per listener, each to its own queueAs durable as the queue connection

Because EIP says each output channel has exactly one subscriber, Publish-Subscribe is built from Point-to-Point channels: a fan-out in front, one queue (or one group) per subscriber behind it. That is the single most useful sentence in this chapter, because it tells you how to add a subscriber: add one more queue, binding or group, never a second consumer on someone else's queue.

The pattern site's own "Publish-Subscribe Channel" page also names the debugging use: "using a Publish-Subscribe Channel allows you to eavesdrop on a message channel without disturbing the existing message flow." A bound extra queue that only logs is the broker-level version of that; the full pattern is the Wire Tap in Messaging System Management.

Datatype Channel Important ​

In plain words: One channel carries one kind of message. If you can read the channel name, you know what to deserialise.

Common misunderstanding: "One events topic is simpler." It is simpler to create and harder to consume: every consumer must open every envelope, decide whether it cares, and fail on types it has never seen. A Datatype Channel moves that decision into the broker's addressing.

Definition (EIP): Problem: "How can the application send a data item such that the receiver will know how to process it?" Solution: "Use a separate Datatype Channel for each data type, so that all data on a particular channel is of the same type." The sender "will need to select the appropriate channel to send it on. The receiver, knowing what channel the data was received on, will know what its type is." (Datatype Channel)

ProductDatatype Channel asExample name
RabbitMQOne queue per type per consumer, bound by routing keybilling.order-placed, bound to orders.events with key orders.order-placed.v1
KafkaOne topic per event type (or per aggregate with a type header; see Routing Topologies)orders.order-placed.v1
Redis StreamsOne stream per typeorders:order-placed:v1
LaravelOne queue name per job or listener typeonQueue('billing.order-placed')

Trade-off. The more types, the more channels to create, secure and monitor, and the fewer chances of a consumer being surprised. A middle road is one channel per aggregate with a type header; its cost is that consumers must filter. Channel-per-type vs channel-per-consumer discusses it with a table.

Invalid Message Channel Must-know ​

In plain words: When a receiver opens a message and it makes no sense (wrong format, missing field, impossible value), the receiver moves it to a special channel and gets on with its work.

Common misunderstanding: "Invalid messages should be retried like any failed message." A malformed JSON stays malformed. Retrying it N times only delays the next message and fills the logs. Retry is for transient problems; an invalid message is a permanent one.

Definition (EIP): Problem: "How can a messaging receiver gracefully handle receiving a message that makes no sense?" Solution: "The receiver should move the improper message to an Invalid Message Channel, a special channel for messages that could not be processed by their receivers." (Invalid Message Channel) The channel "will not be used for normal, successful communication, so its being cluttered with improper messages will not cause a problem. An error handler that wants to diagnose improper messages can use a receiver on the invalid channel."

  Channel billing.order-placed     Billing consumer                      billing.order-placed.invalid
  1  m17 {"order_id":"abc"} ---->
  2                               parse: order_id is not an integer
  3                               DO NOT retry: the content will not change
  4                               publish m17 + reason + source -------->  [m17 + headers]
  5                               ack m17 (only after step 4 succeeded)
  6                                                                       operator or fixer reads, repairs, replays
ProductHow to build the Invalid Message ChannelWhat to attach
RabbitMQThe consumer publishes to an orders.invalid exchange, then acks. Or basic.reject with requeue=false so a configured dead-letter exchange takes it (the DLX path, which records x-death)reason, original queue, the original body unchanged
KafkaThe consumer produces to orders.order-placed.v1.invalid, then commits the offsetHeaders reason, source-topic, source-partition, source-offset
Redis StreamsXADD to an invalid stream, then XACK the originalFields reason, source, body
Laravel$this->fail($exception) sends the job to failed_jobs; for a "do not retry, keep the evidence" flow insert into an invalid_messages table and delete() the jobValidator errors as JSON

Dead Letter Channel Important ​

In plain words: Where the messaging system puts a message it could not deliver. Not the same as the invalid channel, though they often share a queue.

Common misunderstanding: "Invalid and dead letter are the same queue under two names." They differ in who decides. The receiver reads the content and declares it invalid. The messaging system declares a message dead because of a delivery rule: it expired, it hit a delivery limit, the queue was full, a consumer rejected it without requeue.

Definition (EIP): Problem: "What will the messaging system do with a message it cannot deliver?" Solution: "When a messaging system determines that it cannot or should not deliver a message, it may elect to move the message to a Dead Letter Channel." (Dead Letter Channel) The detail (DLX, x-death, retry topics, Redis parking, Laravel failed_jobs and queue:retry) is owned by Dead-Letter Queue; here only the contrast matters.

Invalid Message ChannelDead Letter Channel
Who decidesThe receiver, after reading the contentThe messaging system, by a rule
WhyThe content makes no senseExpired, rejected, delivery limit, queue overflow
Would a retry helpNoSometimes (the next attempt may succeed)
In RabbitMQAn explicit republish, or basic.reject with a DLXThe DLX for the four dead-letter events in the docs: basic.reject or basic.nack with requeue=false, per-message TTL expiry, queue length limit, quorum-queue delivery limit
In KafkaAn invalid topic written by the consumerA retry or DLQ topic written by the consumer framework (Kafka itself has none); Kafka Connect sinks have errors.deadletterqueue.topic.name
In Redis StreamsAn invalid streamA parking stream plus XPENDING and XAUTOCLAIM
In LaravelA table or custom queue plus delete()failed_jobs after tries are used up

In practice many teams point both at one dead-letter queue and distinguish by a reason header. That is fine as long as the reason is recorded; what you must not do is retry invalid messages.

Guaranteed Delivery Must-know ​

In plain words: Once the sender is told "accepted", the message must survive a broker crash. It is on disk somewhere until the receiver has it.

Common misunderstanding: "Persistent messages are guaranteed." A persistent flag alone does not protect you; the queue must be durable, the write must have reached disk (or enough replicas), and the sender must wait for the confirmation. RabbitMQ's own documentation says "A RabbitMQ node can lose persistent messages if it fails before said messages are written to disk" and recommends publisher confirms.

Definition (EIP): Problem: "How can the sender make sure that a message will be delivered, even if the messaging system fails?" Solution: "Use Guaranteed Delivery to make messages persistent so that they are not lost even if the messaging system crashes." The book describes the chain: "the send operation does not complete successfully until the message is safely stored in the sender's data store. Subsequently, the message is not deleted from one data store until it is successfully forwarded to and stored in the next data store." (Guaranteed Delivery)

  Sender        Broker disk A         Broker disk B (replica)       Receiver
  1  send ---->  write
  2              replicate ---------->  write
  3  <-- confirm only after step 1 (and 2 where replicated)
  4              deliver ---------------------------------------------->  process
  5              <------------------------------------------------------- ack
  6              delete from A and B only now
  -- crash between 1 and 3: the sender got no confirm, so it re-sends (duplicate risk, see delivery-guarantees)
Link of the chainRabbitMQKafkaRedis StreamsLaravel
Storage durableDurable queue; "applications must use durable queues and make sure that publishers mark published messages as persisted"The log on disk, replicatedAOF and RDB; "AOF must be used with a strong fsync policy"Database table or Redis; depends on the driver
ReplicatedQuorum queue (Raft)Replication factor; a record is committed when every in-sync replica has itAsynchronous to replicas; WAIT forces propagation, best effort on failoverSame as the backing store
Sender waitsPublisher confirms (Confirm, NotifyPublish, or deferred confirm)acks=all plus min.insync.replicas; idempotent producer retries safelyThe reply to XADD; add WAIT if replicas matterdispatch() returns after the driver's write; use afterCommit so the job never precedes the data
Receiver acksManual ackCommit the offset after processingXACKThe worker deletes the job on success

The semantics (at-most-once, at-least-once, exactly-once) are the subject of Delivery Guarantees; ack modes and prefetch are in Message Acknowledgment; the database-side durability a broker relies on is described in Durability, WAL & Crash Recovery.

Channel Adapter Must-know ​

In plain words: A small piece of code (or a product) that lets an application that does not speak messaging take part anyway. It reads the application's data and publishes messages, and it takes incoming messages and calls the application.

Common misunderstanding: "An adapter is the same as a transformer." An adapter connects transport and API; a Message Translator changes content. The book's adapter "acts as a messaging client to the messaging system and invokes applications functions via an application-supplied interface". Content mapping lives in Message Transformation.

Definition (EIP): Problem: "How can you connect an application to the messaging system so that it can send and receive messages?" Solution: "Use a Channel Adapter that can access the application's API or data and publish messages on a channel based on this data, and that likewise can receive messages and invoke functionality inside the application." The adapter "can connect to different layers of the application's architecture, depending on that architecture and the data the messaging system needs to access." (Channel Adapter)

  Legacy ERP (writes files)     Adapter process                    Broker
  1  drop orders-2026-11-25.csv
  2                             list inbox, open file
  3                             row 1 -> {"order_id":1001,...} --->  publish orders.order-placed.v1
  4                             row 2 -> ...                    --->  publish
  5                             all rows confirmed -> move file to /done
  6                             crash after row 1? on restart re-read file: rows 1.. published again (duplicate)
  -- so the adapter attaches file name and row number (Message Sequence) and the consumer dedups
Layer the adapter attaches toExampleNotes
FileCSV drop folder, SFTP, S3 prefixSee the Go and Laravel adapters below
DatabasePoll a table with SELECT ... FOR UPDATE SKIP LOCKED, or capture changes from the logPrefer the Transactional Outbox or CDC over polling the business tables
Business logic APICall a SOAP or REST endpoint of the legacy systemThe adapter is the only caller
User interfaceScreen scraping, last resortFragile
Messaging-to-messagingAnother brokerThat is a Messaging Bridge

Where adapters come as products: Kafka Connect — "a tool for scalably and reliably streaming data between Apache Kafka and other systems", with source connectors that import into Kafka and sink connectors that export out of it (Kafka Connect overview); the Kafka introduction says the Connect API is for "reusable data import/export connectors". RabbitMQ has no connector framework; adapters are the plugins for other protocols (MQTT, STOMP, AMQP 1.0) and your own consumers. Redis Streams has none built in. Laravel: the queue:work process is the adapter between the queue connection and your PHP code: it reserves a job, calls handle(), and deletes or releases it. That mapping is this page's own framing, not Laravel's terminology.

Messaging Bridge Important ​

In plain words: A bridge copies messages from a channel on one broker to a channel on another, so applications on each side see the messages they care about.

Common misunderstanding: "A bridge connects the two brokers as a whole." The book is explicit that this is not practical: "Typically, there is no practical way to connect two complete messaging systems, so instead we connect individual, corresponding channels between the messaging systems." You bridge channel by channel.

Definition (EIP): Problem: "How can multiple messaging systems be connected so that messages available on one are also available on the others?" Solution: "Use a Messaging Bridge, a connection between messaging systems, to replicate messages between systems." It "is a set of Channel Adapters, where the non-messaging client is a actually another messaging system, and where each pair of adapters connects a pair of corresponding channels. The bridge acts as map from one set of channels to the other, and also transforms the message format of one system to the other." (Messaging Bridge)

  RabbitMQ queue billing.order-placed      Bridge process                       Kafka topic orders.order-placed.v1
  1  [m1]  --- consume (prefetch 100) --->
  2                                        header x-bridged-by? no -> continue
  3                                        produce m1 (acks=all) ------------->  [m1]
  4                                        <------------------------ produce ack
  5  <---- ack m1 (only now)
  6  -- crash between 4 and 5: m1 stays unacked, is redelivered, produced again: duplicate, never a loss
ProductBuilt-in bridgeWhat it doesLimits
RabbitMQShovel plugin: "a shovel behaves like a well-written client application, which connects to its source and destination, consumes and republishes messages, and uses acknowledgements on both ends to cope with failures"; AMQP 0.9.1 and AMQP 1.0 on either end; dynamic shovels are set with rabbitmqctl set_parameter shovel (src-uri, src-queue, dest-uri, dest-queue)Moves messages one way between queues or exchanges, in one cluster or across clustersUnidirectional; you configure each direction
RabbitMQFederation plugin: "replicate or move messages between brokers that have the plugin enabled but do not belong to the same cluster"; asynchronous, "assumes that connections between clusters will fail from time to time"; federated exchanges and federated queues, applied by policy (federation-upstream-set)Loose coupling over a WAN; downstream pulls from upstreamRabbitMQ to RabbitMQ only
KafkaMirrorMaker 2: replicates topics, built on Kafka Connect; "the names of replicated topics in the target cluster will be prefixed with the name of the source cluster" (us-west.foo); also replicates consumer groups' offsets; exactly-once from version 3.5.0 for dedicated clustersCluster to cluster (geo-replication, disaster recovery, cloud migration, aggregation)Kafka to Kafka; the prefix means consumers must subscribe to the renamed topic
KafkaKafka Connect with a RabbitMQ, JMS or other connectorA source connector reads the other system and writes to Kafka; a sink connector does the oppositeConnectors are third-party packages; read their delivery guarantees
Redis StreamsNone nativeWrite a consumer that XREADGROUPs, produces to the target, then XACKsYou own retries, ordering and loop prevention
Cross-broker, any pairYour own bridge (see bridge/main.go)Consume, produce, ack after the produce is confirmedDuplicates on a crash; add a loop guard header and idempotent consumers

Three rules for any bridge. (1) Ack the source only after the target confirmed, so a crash duplicates rather than loses. (2) Prevent loops: when two bridges mirror in both directions, a message ping-pongs forever unless a header marks it as already bridged (MirrorMaker 2's documentation says that flows defined in the same configuration file need no explicit topics.exclude to avoid replication "loops"). (3) Preserve what the other side needs: keys for ordering, headers for trace ids, the format indicator, and a stable message id for deduplication (Idempotent Consumers).

Bridge and adapter topology ​

Legacy CSV dropFile TransferShared databaselegacy tablesOrders servicenative clientChannel Adapterreads filesChannel Adapterpoll or CDCBroker 1: RabbitMQexchange orders.eventsqueues per consumer+ DLX orders.invalidMessaging Bridgeconsume, produce, ackBroker 2: Kafkatopic orders.order-placed.v1group per consumer+ invalid topicChannel AdapterKafka Connect sinkWarehousenon-messaging appShovel, Federation, MM2, or custom codeA bridge is a pair of adapters whose non-messaging side is another messaging system; it also maps names and formats.Redis Streams has no native bridge: use a consumer plus a producer.

Message Bus Good to know ​

In plain words: An architecture, not a product: a set of rules so that many applications can plug into one messaging infrastructure and be added or removed without the others noticing.

Common misunderstanding: "A message bus is a broker you install." A broker is the infrastructure; the bus is the broker plus the agreement. The book lists the parts: a "common data model, a common command set, and a messaging infrastructure."

Definition (EIP): Problem: "What is an architecture that enables separate applications to work together, but in a decoupled fashion such that applications can be easily added or removed without affecting the others?" Solution: "Structure the connecting middleware between these applications as a Message Bus that enables them to work together using messaging." (Message Bus) The three ingredients: a common communication infrastructure (a messaging system, often with Publish-Subscribe Channels), adapters (Channel Adapters and Service Activators, plus a Canonical Data Model), and a common command structure (Command Messages or Datatype Channels).

IngredientIn a modern systemOwner
Common infrastructureOne or two brokers, with naming and security conventionsPlatform team
AdaptersClient libraries, Connect connectors, outbox relays, queue:work workersEach service team
Common data modelEvent schemas in a registry; see Message Design and the Canonical Data Model in Message TransformationA shared contract, owned by the event's publisher
Common command setA few verbs everyone understands; see Command, Document and Event Message in Messaging FundamentalsArchitecture guild

Message Bus, Message Broker and ESB ​

These three words are used for overlapping things, so keep them apart.

TermWhat it isCentral?Lives where
Message Broker (the server)The process that stores and delivers messages: RabbitMQ, a Kafka cluster, RedisA deploymentInfrastructure
Message Broker (the EIP pattern)"a central Message Broker that can receive messages from multiple destinations, determine the correct destination and route the message", the hub-and-spoke architectureYes, a hubArchitecture; detail in Advanced Routing
Message BusConventions for decoupled cooperation: common model, commands, infrastructureNo, shared agreementArchitecture
ESB (Enterprise Service Bus)A product that bundles a broker with routing, transformation, orchestration and protocol adapters in one central runtimeYesAn integration platform; see Service-Oriented Architecture

The EIP page on the Message Broker names the cost of the hub itself: "The advantage of central maintenance of a Message Broker can also turn into a disadvantage" because routing everything through one place makes it a bottleneck. Modern microservice systems usually choose the first and third rows (dumb broker, smart endpoints, published schemas) and avoid the fourth; Service Communication discusses the same choice from the service side.

The three header patterns: Message Expiration, Message Sequence, Format Indicator ​

These three patterns do not need a new channel. They are fields on the message that every hop agrees to read. The Go file envelope/main.go models all three.

Message Expiration Important ​

In plain words: A "use by" date on a message. After it, the message is worthless and must not be processed.

Common misunderstanding: "TTL on the queue is Message Expiration." The queue TTL is one mechanism. The pattern is the meaning: a price quote valid for ten seconds, a "payment pending" prompt valid for thirty minutes. Without it, a consumer coming back after an outage processes yesterday's request as if it were fresh.

Definition (EIP): Problem: "How can a sender indicate when a message should be considered stale and thus shouldn't be processed?" Solution: "Set the Message Expiration to specify a time limit how long the message is viable." "Most messaging system implementations reroute expired messages to the Dead Letter Channel, while others simply discard expired messages; this may be configurable." (Message Expiration)

  Producer          Queue (TTL 30 s)           Consumer
  1  12:00:00 send quote m1 ---> [m1 exp 12:00:30]
  2                 consumer offline until 12:01:10
  3  12:00:30       m1 expires: dead-lettered or dropped
  4                                      12:01:10 consumer returns, m1 is NOT delivered
  -- without expiry the consumer would act on a 70-second-old price
ProductMechanismDetail
RabbitMQQueue argument x-message-ttl, or the per-message expiration property (string of milliseconds); an expired message is dead-lettered if a DLX is setThe docs say the server "guarantees that expired messages will not be delivered"; they are dead-lettered or removed only when they reach the head of the queue; when both TTLs are set the lower value is used
KafkaNone per message. Topic retention.ms deletes old log segments ("an SLA on how soon consumers must read their data")Put expires-at in a header and check it in the consumer
Redis StreamsNone per entry. XTRIM ... MINID removes entries older than an ID; IDs begin with a millisecond timestampSame: check a header
LaravelretryUntil() on a job (the job is no longer attempted after that time) or the RetryFor attribute; "If both retryUntil and tries are defined, Laravel gives precedence to the retryUntil method"It bounds retries, not the first attempt: a late first attempt still runs, so check expires_at in handle()

Message Sequence Good to know ​

In plain words: When data is too big for one message, cut it into numbered pieces so the receiver can put it back together.

Common misunderstanding: "The broker will keep the pieces in order." Only within one queue, partition or stream, and only with one consumer; competing consumers, redelivery and retries can reorder. The receiver needs the numbers.

Definition (EIP): Problem: "How can messaging transmit an arbitrarily large amount of data?" Solution: "Whenever a large set of data may need to be broken into message-size chunks, send the data as a Message Sequence and mark each message with sequence identification fields." The fields: a sequence identifier, a position identifier, and a size or end indicator. (Message Sequence)

  Sender                      Channel                    Receiver (Reassembler)
  1  seq=export-7 pos=2 of 3 -->
  2  seq=export-7 pos=1 of 3 -->
  3  seq=export-7 pos=1 of 3 -->  (redelivered duplicate)
  4  seq=export-7 pos=3 of 3 -->
  5                                                       parts {1,2,3} complete -> concatenate -> process
  -- positions make the order, the count makes completeness, overwriting the same position makes duplicates harmless

For large payloads the usual alternative is the claim-check (store the body elsewhere, send a pointer), owned by Message Design & Schema Evolution. For re-ordering across partitions see Ordering & Partitioning and the Resequencer in Advanced Routing.

Format Indicator Important ​

In plain words: The message says what format it is in, so a receiver that knows several versions can pick the right parser.

Common misunderstanding: "We will version the topic when the format changes." That works for breaking changes, and costs you a new channel plus a migration. A format indicator lets two versions flow in the same channel during the migration.

Definition (EIP): Problem: "How can a message's data format be designed to allow for possible future changes?" Solution: "Design a data format that includes a Format Indicator, so that the message specifies what format it is using." Three ways: a version number, a foreign key to a format document, or an embedded format document (a schema). (Format Indicator)

Style (EIP)ExampleWhere it lives
Version numberorder.placed/1 in a format header or the AMQP type propertyHeaders or properties; cheap, needs a convention
Foreign keyA schema id looked up in a schema registryHeader or message prefix; see Message Design
Embedded format documentAn Avro file with its schema in the headerLarge; rarely used per message

The file envelope/main.go carries Format in an envelope; the compatibility rules (backward, forward, full) belong to Message Design & Schema Evolution.

The channel types on one map ​

Orders servicesender endpointconfirmPublish-Subscribe ChannelDatatype Channel: order.placed v1topic exchange / topic / streamcopycopycopybilling.order-placedPoint-to-Point: one of N workersinventory.order-placedPoint-to-Point: one of N workersemail.order-placedPoint-to-Point: one of N workersBillingInventoryEmailreceiver says: this makes no sense (reason attached)Invalid Message Channelexpired, rejected, limit hitDead Letter ChannelGuaranteed Deliverydisk at every hop, confirm to sender,ack from receiver

Channel naming conventions and granularity ​

Naming. The following conventions are this page's recommendation, not a standard. The aim is that a channel name answers three questions: who owns it, what flows through it, which version.

RuleExampleWhy
Start with the owner (the publishing bounded context)orders.The owner decides the format and the retention; consumers cannot rename it
Name the fact or command in past or imperative tenseorder-placed, charge-cardEvents are facts, commands are requests (Event-Driven Architecture)
Include the major version.v1A breaking format change gets a new channel, see Format Indicator
Consumer queues add the consumer firstbilling.order-placedThe consumer owns its queue, its DLX and its backlog alarms
Invalid and dead-letter channels use a suffix.invalid, .dlqAlarms and runbooks can match the suffix
Use one separator per brokerRabbitMQ and Kafka: dot; Redis keys: colon; Laravel: dot or hyphenMatches each tool's conventions; pick one separator per system and keep it
Environment lives in the vhost, cluster or prefix, not in the namevhost /prodThe same code can be pointed at another environment

Channel-per-type vs channel-per-consumer. These are two different axes and a real design uses both.

AxisOption AOption BPrefer
By message typeOne channel per type (Datatype Channel)One shared events channel with a type headerA for a handful of well-known types; B only when the number of types is large and every consumer takes most of them
By consumerOne queue (or consumer group, or stream group) per consumer, bound to the type's channelSeveral consumers share one queueOne per consumer for Publish-Subscribe; share a queue only when the consumers are copies of the same worker (Competing Consumers)
By tenant or prioritySeparate channelsHeader or key inside oneSeparate channels when priorities or tenants need different capacity; a header otherwise
MistakeSymptomFix
Two different consumers on one queueEach sees half of the messagesOne queue per consumer, bound to the exchange
One topic for all events, a type headerEvery consumer deserialises everything; one new type breaks old consumersOne topic per type (or per aggregate with an explicit contract)
Hundreds of channels per tenantMetadata and file handles grow; Kafka partition counts explodeKey by tenant inside shared channels
Channel name carries the consumer's name on the producer sideProducer must know its consumersProducer names the type; consumers name their queues

Mechanics ​

The invalid-message flow, step by step ​

The flow below is the one the Go test in invalid/main_test.go checks. It is the rule that keeps a poison message from blocking a channel.

StepReceiver doesWhy
1Read the message and check the format indicatorAn unknown format is invalid, not an error to retry
2Parse the body (JSON, Protobuf, Avro)A parse failure is permanent for this message
3Validate fields and business rules (positive id, known currency)A rule violation will not fix itself
4If anything above failed: publish the original body unchanged plus reason, source channel and, where the broker gives it, partition and offset, to the invalid channelThe operator needs the evidence; do not "fix" the message in place
5Only after step 4 is confirmed: ack the source (commit the offset, XACK, basic.ack, delete the job)Otherwise a crash between 4 and 5 loses the message; duplicates in the invalid channel are harmless
6If the content is valid but processing failed transiently: do not park it, let retry apply (Retry & Backoff)Retry and invalid handling answer different questions
7After the retries (or the broker's delivery limit): the messaging system dead-letters it (Dead-Letter Queue)The Dead Letter Channel is the safety net, not the first resort
8Alarm on invalid-channel depth and on its arrival rateA sudden stream of invalid messages means a producer shipped a breaking change
9Provide a replay path: a tool that reads the invalid channel and republishes the repaired message to the original channelOtherwise the channel is a graveyard
  decision tree at the consumer

  received m
    |-- format unknown / body unparsable / rule broken ---> INVALID channel (reason) ---> ack source
    |-- valid, processing succeeds ------------------------> ack source
    |-- valid, processing fails transiently ---------------> nack / release / no ack  --> retry
                                                              |-- limit reached ------> DEAD LETTER channel (by the broker)

Guaranteed Delivery: the knobs ​

BrokerSettingMeaningSource
RabbitMQQueue durable=trueQueue metadata and persistent messages survive a node restartQueues
RabbitMQMessage delivery_mode=2 (amqp.Persistent)The message is written to disk, not only kept in memoryPublishers, via Reliability guide
RabbitMQx-queue-type: quorumA replicated, Raft-based queue; the recommended type for data that must survive node lossQuorum Queues
RabbitMQPublisher confirms (ch.Confirm, NotifyPublish)The broker acks after the message is persisted (and replicated for quorum queues)Confirms
RabbitMQmandatory flagAn unroutable message is returned with basic.return instead of silently droppedConfirms
Kafkaacks=allThe leader waits for all in-sync replicasProducer configs
Kafkamin.insync.replicasWith acks=all, the minimum ISR size for a write to succeed (commonly 2 with replication factor 3)Topic configs
Kafkareplication.factorCopies per partitionDesign
Kafkaenable.idempotenceRetries cannot duplicate within a partition; on by default in current clientsProducer configs
Redis Streamsappendonly yes, appendfsync always or everysecHow much the AOF can lose on a crashStreams, persistence section
Redis StreamsWAIT numreplicas timeoutBlock until replicas have the write; best effort across failoverStreams

Timeline: a crash at each point of the chain ​

  Sender            Broker                    Receiver
  1  send m ------->  write to disk
  2   (crash here)    ---                      Sender has no confirm: it must re-send. Broker may now hold m twice.
  3  send m ------->  write, confirm -------->
  4  got confirm
  5                   deliver m ------------->  process
  6                   (crash here)             Receiver has done the work but not acked: m is redelivered.
  7                   deliver m again ------->  process again   <- the receiver must tolerate this (idempotent consumer)
  8                   <------------------------ ack
  -- Guaranteed Delivery means "not lost", never "exactly once"

Bridge: failure matrix ​

FailureWhat the bridge seesResultMitigation
Target broker downProduceSync returns an errorNack with requeue (or stop consuming)Backoff; alarm on source backlog
Bridge crashes after produce, before ackSource redelivers on restartDuplicate on the targetStable message id; idempotent consumer on the target
Source broker downConsume loop endsNothing flowsReconnect with backoff; Shovel and Federation do this by themselves
Target slower than the sourceUnacked messages pile up at the bridgeMemory growthPrefetch limit (Qos(100, ...)); flow control (Backpressure)
Bridge in both directionsA message returns to where it startedInfinite loopHeader such as x-bridged-by; MirrorMaker 2 flows in one config
Format differsTarget consumers cannot parseThey publish to the invalid channelThe bridge applies a Message Translator (Transformation)
OrderingParallel produce reordersPer-key order lostProduce synchronously per key, or keep the Kafka key equal to the entity id

Solving the classic problems ​

ProblemSolutionHowCost
A legacy system exports files onlyChannel Adapter over File TransferPoll a folder, publish one message per row, record file and rowAt-least-once; duplicates on restart
Two teams share a database and block each otherReplace the shared table with eventsOwner publishes changes (Outbox); consumers keep their own copyEventual consistency; see Distributed data
A burst of orders overloads the payments serviceReplace RPC by a Point-to-Point channelQueue the work, drain at a safe rateResult arrives later; need a status endpoint
Everyone wants to know about "order placed"Publish-Subscribe ChannelFanout or topic; one queue or group per subscriberMore channels to monitor
Consumers crash on unknown message shapesDatatype Channel plus Format IndicatorOne type per channel; version in the name or headerMore channel names
A bad message blocks the queueInvalid Message ChannelPark with reason, ack, continueA replay tool and an alarm are required
Messages must survive a broker crashGuaranteed DeliveryDurable, replicated storage; confirms; manual ackLatency (fsync, replicas)
Stale requests act on old dataMessage ExpirationHeader expires-at; TTL where the broker supports itThe consumer must check, not just the broker
Data too large for one messageMessage Sequence or claim-checkChunk with id, position, totalReassembly state
Two brokers in a company (merger, migration, edge to core)Messaging BridgeShovel, Federation, MirrorMaker 2, or a small consumer-producerDuplicates, loop prevention, double monitoring
One application cannot be changedChannel AdapterWrap its API, database or filesThe adapter is a new thing to run

Go ​

The Go snippets use the three clients named in the section rules (amqp091-go, franz-go, go-redis) and stdlib for the logic that is independent of a broker. Every program exits quietly when its broker URL is not set, so go vet ./... and go test ./... run without any broker. The module is academy/integration-styles-channels.

The three programs that need no broker ​

A Channel Adapter for File Transfer. The only thing it knows about messaging is a Publisher interface, so the same function works for RabbitMQ, Kafka or Redis.

go
// Package main is a Channel Adapter for a File Transfer source: it reads a CSV drop file that a
// legacy system writes nightly and turns every row into one message on a channel.
// The adapter knows the file format; the rest of the system only knows the message.
package main

import (
	"context"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// Publisher is the only thing the adapter knows about the messaging system.
// A RabbitMQ, Kafka or Redis Streams client satisfies it behind a thin wrapper.
type Publisher interface {
	Publish(ctx context.Context, channel, key string, body []byte, headers map[string]string) error
}

type orderPlaced struct {
	OrderID string `json:"order_id"`
	Total   string `json:"total"`
}

// AdaptFile reads "order_id,total" rows and publishes one order.placed message per row.
// A row that cannot be read is skipped with an error; the caller decides what happens to the file.
func AdaptFile(ctx context.Context, r io.Reader, pub Publisher, source string) (published int, err error) {
	cr := csv.NewReader(r)
	cr.FieldsPerRecord = 2
	for line := 1; ; line++ {
		row, rerr := cr.Read()
		if rerr == io.EOF {
			return published, nil
		}
		if rerr != nil {
			return published, fmt.Errorf("%s line %d: %w", source, line, rerr)
		}
		body, _ := json.Marshal(orderPlaced{OrderID: row[0], Total: row[1]})
		headers := map[string]string{
			"format": "order.placed/1",
			// Message Sequence fields: position inside the file lets a consumer detect gaps.
			"sequence-id": filepath.Base(source),
			"position":    fmt.Sprint(line),
		}
		if err := pub.Publish(ctx, "orders.order-placed.v1", row[0], body, headers); err != nil {
			return published, err
		}
		published++
	}
}

// stdoutPublisher stands in for a broker so the program runs anywhere.
type stdoutPublisher struct{}

func (stdoutPublisher) Publish(_ context.Context, channel, key string, body []byte, h map[string]string) error {
	fmt.Printf("-> %s key=%s headers=%v body=%s\n", channel, key, h, body)
	return nil
}

func main() {
	n, err := AdaptFile(context.Background(), strings.NewReader("1001,1999\n1002,450\n"), stdoutPublisher{}, os.Args[0])
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("published", n)
}

The invalid-message flow as code and test: the three invalid cases are parked with a reason and consumed; a transient error is returned so the broker redelivers it.

go
// Package main separates an Invalid Message Channel from a Dead Letter Channel.
// Invalid: the receiver looked at the message and says "this makes no sense". It is parked at once,
// with the reason, because retrying cannot help. Dead letter: the message was fine but could not be
// delivered or processed within the broker's rules (expired, rejected, delivery limit reached).
package main

import (
	"encoding/json"
	"errors"
	"fmt"
)

type Message struct {
	Channel string
	Format  string
	Body    []byte
	Headers map[string]string
}

// Router sends a message to the next hop; here it only records where messages go.
type Router struct{ Sent []Message }

func (r *Router) Send(m Message) { r.Sent = append(r.Sent, m) }

var ErrTransient = errors.New("transient failure")

type orderPlaced struct {
	OrderID int `json:"order_id"`
	Total   int `json:"total"`
}

// Handle returns nil when the message is done with (processed or parked) and an error
// only when the broker should redeliver it, which is the dead-letter path after N attempts.
func Handle(r *Router, m Message, process func(orderPlaced) error) error {
	if m.Format != "order.placed/1" {
		r.Send(invalid(m, "unknown format "+m.Format))
		return nil
	}
	var ev orderPlaced
	if err := json.Unmarshal(m.Body, &ev); err != nil {
		r.Send(invalid(m, "malformed JSON: "+err.Error()))
		return nil
	}
	if ev.OrderID <= 0 || ev.Total < 0 {
		r.Send(invalid(m, "business rule: order_id must be positive and total non-negative"))
		return nil
	}
	return process(ev) // an ErrTransient here is retried and may end up dead-lettered
}

func invalid(m Message, reason string) Message {
	h := map[string]string{"invalid-reason": reason, "original-channel": m.Channel}
	return Message{Channel: m.Channel + ".invalid", Format: m.Format, Body: m.Body, Headers: h}
}

func main() {
	r := &Router{}
	ok := func(orderPlaced) error { return nil }
	_ = Handle(r, Message{Channel: "billing.order-placed", Format: "order.placed/1", Body: []byte(`{"order_id":1,"total":5}`)}, ok)
	_ = Handle(r, Message{Channel: "billing.order-placed", Format: "order.placed/1", Body: []byte(`{oops`)}, ok)
	fmt.Println("parked:", len(r.Sent))
}

The envelope with Format Indicator, Message Expiration and Message Sequence, including a Reassembler that survives out-of-order and duplicate parts.

go
// Package main models three small EIP ideas on top of any broker: Format Indicator,
// Message Expiration and Message Sequence. The broker carries the fields as headers;
// the application enforces them, because only some brokers expire or order for you.
package main

import (
	"fmt"
	"sort"
	"time"
)

// Envelope is the header set an application agrees on, whatever the transport is.
type Envelope struct {
	Format    string    // Format Indicator: "order.placed/1" is a version number style indicator
	ExpiresAt time.Time // Message Expiration: absolute time, so every hop agrees on it
	SeqID     string    // Message Sequence: identifies the cluster of messages
	Position  int       // Message Sequence: 1-based position inside the cluster
	Total     int       // Message Sequence: size of the cluster (0 = unknown, use the end marker)
	Body      []byte
}

// Expired reports whether a receiver must throw the message away without processing it.
func (e Envelope) Expired(now time.Time) bool {
	return !e.ExpiresAt.IsZero() && !now.Before(e.ExpiresAt)
}

// Reassembler collects a Message Sequence that may arrive out of order and duplicated.
type Reassembler struct {
	parts map[string]map[int]Envelope
}

func NewReassembler() *Reassembler { return &Reassembler{parts: map[string]map[int]Envelope{}} }

// Add stores a part and returns the whole body in order once every part has arrived.
func (r *Reassembler) Add(e Envelope) ([]byte, bool) {
	m := r.parts[e.SeqID]
	if m == nil {
		m = map[int]Envelope{}
		r.parts[e.SeqID] = m
	}
	m[e.Position] = e // a redelivered part overwrites itself: idempotent
	if e.Total == 0 || len(m) < e.Total {
		return nil, false
	}
	order := make([]int, 0, len(m))
	for p := range m {
		order = append(order, p)
	}
	sort.Ints(order)
	var out []byte
	for _, p := range order {
		out = append(out, m[p].Body...)
	}
	delete(r.parts, e.SeqID)
	return out, true
}

func main() {
	r := NewReassembler()
	for _, p := range []Envelope{
		{SeqID: "export-7", Position: 2, Total: 3, Body: []byte("B")},
		{SeqID: "export-7", Position: 1, Total: 3, Body: []byte("A")},
		{SeqID: "export-7", Position: 1, Total: 3, Body: []byte("A")}, // duplicate delivery
		{SeqID: "export-7", Position: 3, Total: 3, Body: []byte("C")},
	} {
		if whole, done := r.Add(p); done {
			fmt.Printf("reassembled %q\n", whole)
		}
	}
}

The bridge ​

A Messaging Bridge from a RabbitMQ queue to a Kafka topic: consume with a prefetch limit, produce with acks=all, ack the source only after Kafka confirmed, skip messages already marked as bridged.

go
// Package main is a Messaging Bridge: it consumes one RabbitMQ queue and republishes every
// message to one Kafka topic, acking the source only after Kafka has confirmed the write.
// It exits quietly unless both RABBITMQ_URL and KAFKA_BROKERS are set.
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

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

const (
	sourceQueue = "billing.order-placed"
	targetTopic = "orders.order-placed.v1"
	bridgeName  = "rabbit-to-kafka"
)

func main() {
	url, brokers := os.Getenv("RABBITMQ_URL"), os.Getenv("KAFKA_BROKERS")
	if url == "" || brokers == "" {
		fmt.Println("RABBITMQ_URL and KAFKA_BROKERS must be 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)
	}
	// Prefetch bounds how many unacked messages the bridge holds if Kafka is slow.
	if err := ch.Qos(100, 0, false); err != nil {
		log.Fatal(err)
	}
	deliveries, err := ch.Consume(sourceQueue, bridgeName, false, false, false, false, nil)
	if err != nil {
		log.Fatal(err)
	}

	kc, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...), kgo.RequiredAcks(kgo.AllISRAcks()))
	if err != nil {
		log.Fatal(err)
	}
	defer kc.Close()

	ctx := context.Background()
	for d := range deliveries {
		// Loop guard: never re-bridge something that already crossed this bridge.
		if h, ok := d.Headers["x-bridged-by"]; ok && fmt.Sprint(h) == bridgeName {
			_ = d.Ack(false)
			continue
		}
		rec := &kgo.Record{
			Topic: targetTopic,
			Key:   []byte(d.MessageId), // keep per-entity ordering on the Kafka side
			Value: d.Body,
			Headers: []kgo.RecordHeader{
				{Key: "x-bridged-by", Value: []byte(bridgeName)},
				{Key: "content-type", Value: []byte(d.ContentType)},
			},
		}
		if err := kc.ProduceSync(ctx, rec).FirstErr(); err != nil {
			_ = d.Nack(false, true) // requeue: the source keeps the message
			log.Println("kafka write failed, requeued:", err)
			continue
		}
		_ = d.Ack(false) // crash between produce and ack means a duplicate, never a loss
	}
}

The Go angle ​

Go has no integration framework in the standard library; the pieces are small and explicit. database/sql is the right client for a polling adapter. encoding/csv and bufio read files. context carries the deadline of a confirm. A channel (chan) in Go is an in-process Message Channel with bounded capacity, and the same vocabulary applies in miniature: an unbuffered channel is a rendezvous, a buffered one is a queue, select with a timeout is Message Expiration, and closing a channel is an end marker. For bounded buffering and shutdown see Backpressure & Flow Control and Competing Consumers.

Laravel ​

Laravel's built-in drivers are, per the 13.x queue documentation, "the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver", plus a null driver that discards jobs. RabbitMQ and Kafka are not built in: RabbitMQ comes from the vladimir-yuldashev/laravel-queue-rabbitmq package, and Kafka from mateusjunges/laravel-kafka (which is a producer and consumer API, not a queue driver). Laravel's Redis queue driver uses lists and sorted sets, so Redis Streams go through the Redis facade.

How the vocabulary maps. A connection in config/queue.php is the transport. A queue is the Message Channel inside it. A queued listener is a subscriber with its own queue. queue:work is the Channel Adapter between the channel and your code (this mapping is this page's framing).

EIP patternLaravel construct
Message Channelconfig/queue.php connection plus queue name; onConnection(), onQueue()
Point-to-Point ChannelSeveral php artisan queue:work --queue=... workers on one queue
Publish-Subscribe ChannelAn event with several queued listeners (each gets a job on its own queue)
Datatype ChannelOne queue name per job or listener type
Invalid Message Channel$this->fail() (to failed_jobs) or an explicit table, then $this->delete()
Dead Letter Channelfailed_jobs, queue:failed, queue:retry; RabbitMQ package failed_exchange
Guaranteed DeliveryA durable driver; after_commit or ->afterCommit() so a job never precedes its data
Channel Adapterqueue:work, an Artisan command that polls a folder, Kafka consumer commands
Messaging BridgeNot in the framework; a command that consumes one connection and dispatches to another
Message ExpirationretryUntil(), RetryFor; check expires_at in handle()

The event and the queued listeners ​

An event is dispatched only after the transaction commits, so a rolled-back order never reaches a channel. The Laravel 13 documentation describes it: "you may want to instruct Laravel to only dispatch an event after the active database transaction has committed", by implementing ShouldDispatchAfterCommit.

php
<?php

namespace App\Events;

use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

// An Event Message: a fact that already happened. ShouldDispatchAfterCommit holds the event back
// until the surrounding database transaction commits, so a rolled-back order is never announced.
class OrderPlaced implements ShouldDispatchAfterCommit
{
    use Dispatchable, SerializesModels;

    public function __construct(
        public int $orderId,
        public int $totalCents,
    ) {}
}
php
<?php

namespace App\Orders;

use App\Events\OrderPlaced;
use Illuminate\Support\Facades\DB;

// Monolith: the "channel" is the in-process event dispatcher plus the queue connection.
// The same code later publishes to RabbitMQ or Kafka by changing config, not call sites.
class PlaceOrder
{
    public function handle(int $customerId, int $totalCents): int
    {
        return DB::transaction(function () use ($customerId, $totalCents): int {
            $orderId = DB::table('orders')->insertGetId([
                'customer_id' => $customerId,
                'total_cents' => $totalCents,
                'created_at' => now(),
            ]);

            OrderPlaced::dispatch($orderId, $totalCents); // delivered only after COMMIT

            return $orderId;
        });
    }
}

Each queued listener names its own connection and queue with the Connection and Queue attributes shown in the Laravel 13 documentation, which makes the layout channel-per-consumer:

php
<?php

namespace App\Listeners;

use App\Events\OrderPlaced;
use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Attributes\Connection;
use Illuminate\Queue\Attributes\Queue;
use Illuminate\Queue\InteractsWithQueue;

// One queued listener = one subscriber with its own channel (channel-per-consumer).
// Dispatching OrderPlaced pushes one job per queued listener, which is Publish-Subscribe
// built from several Point-to-Point queues.
#[Connection('rabbitmq')]
#[Queue('inventory.order-placed')]
class ReserveStock implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(OrderPlaced $event): void
    {
        // reserve stock for $event->orderId
    }

    // Message Expiration: after this instant the job is no longer attempted.
    public function retryUntil(): DateTime
    {
        return now()->plus(hours: 24);
    }
}
php
<?php

namespace App\Listeners;

use App\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Attributes\Connection;
use Illuminate\Queue\Attributes\Queue;
use Illuminate\Queue\InteractsWithQueue;

#[Connection('rabbitmq')]
#[Queue('email.order-placed')]
class SendConfirmation implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(OrderPlaced $event): void
    {
        // send the e-mail for $event->orderId
    }
}

The connections ​

php
<?php

// config/queue.php (excerpt). A Laravel "connection" is the transport (a broker);
// a "queue" inside it is the Message Channel. Pick both per job with onConnection / onQueue.
return [
    'default' => env('QUEUE_CONNECTION', 'database'),

    'connections' => [
        // Built into Laravel: the database, Redis (lists and sorted sets, not Streams), SQS, Beanstalkd.
        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'retry_after' => 90,
            'after_commit' => true, // do not hand the job over before the transaction commits
        ],

        // From the vladimir-yuldashev/laravel-queue-rabbitmq package, not from the framework.
        'rabbitmq' => [
            'driver' => 'rabbitmq',
            'hosts' => [[
                'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                'port' => env('RABBITMQ_PORT', 5672),
                'user' => env('RABBITMQ_USER', 'guest'),
                'password' => env('RABBITMQ_PASSWORD', 'guest'),
                'vhost' => env('RABBITMQ_VHOST', '/'),
            ]],
            'options' => [
                'queue' => [
                    'exchange' => 'orders.events',
                    'exchange_type' => 'topic',
                    'exchange_routing_key' => 'orders.order-placed.v1',
                    'failed_exchange' => 'orders.invalid', // where rejected jobs are rerouted
                ],
            ],
        ],
    ],
];

The adapter command and the invalid message job ​

php
<?php

namespace App\Console\Commands;

use App\Jobs\InvalidMessageJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

// Channel Adapter for File Transfer: the legacy system drops CSV files, this command turns every
// row into one message and moves the file away. Only the adapter knows the file format.
class LegacyFileAdapter extends Command
{
    protected $signature = 'orders:adapt-legacy-files';
    protected $description = 'Turn legacy CSV drop files into queue messages';

    public function handle(): int
    {
        foreach (Storage::disk('legacy')->files('inbox') as $path) {
            $handle = fopen(Storage::disk('legacy')->path($path), 'r');

            for ($position = 1; ($row = fgetcsv($handle)) !== false; $position++) {
                InvalidMessageJob::dispatch([
                    'format' => 'order.placed/1',
                    'order_id' => (int) ($row[0] ?? 0),
                    'total_cents' => (int) ($row[1] ?? -1),
                    'sequence_id' => basename($path), // Message Sequence fields
                    'position' => $position,
                ])->onConnection('rabbitmq')->onQueue('billing.order-placed');
            }

            fclose($handle);
            Storage::disk('legacy')->move($path, 'done/'.basename($path)); // at-least-once: crash = reprocess
        }

        return self::SUCCESS;
    }
}
php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Throwable;

// A consumer for a payload it did not create (a Channel Adapter hands it over).
// Invalid content is parked at once with a reason; a retry cannot fix a malformed message.
class InvalidMessageJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public function __construct(public array $payload) {}

    public function handle(): void
    {
        $validator = Validator::make($this->payload, [
            'format' => ['required', 'in:order.placed/1'],
            'order_id' => ['required', 'integer', 'min:1'],
            'total_cents' => ['required', 'integer', 'min:0'],
        ]);

        if ($validator->fails()) {
            // Invalid Message Channel as a table: nothing is lost, an operator can inspect and replay.
            DB::table('invalid_messages')->insert([
                'channel' => $this->job->getQueue(),
                'reason' => $validator->errors()->toJson(),
                'payload' => json_encode($this->payload),
                'created_at' => now(),
            ]);

            $this->delete(); // consumed on purpose: do not let it go through retries to failed_jobs

            return;
        }

        // process the valid message
    }

    // Reached for TRANSIENT failures after the retries are used up: Laravel's dead-letter path.
    public function failed(Throwable $e): void
    {
        logger()->error('order message failed after retries', ['error' => $e->getMessage()]);
    }
}

The Laravel angle ​

Three details matter. First, after_commit and afterCommit(): if a job is dispatched inside a transaction and the worker runs before COMMIT, it will not find the row. Second, retry_after on the connection must be larger than the longest job, or the driver hands the same job to a second worker (see Laravel Queue Internals). Third, fail() and the failed() method are for jobs that failed; an invalid message is a decision, so insert it into a table or send it to a named queue, then delete() the job. Details of failed_jobs and queue:retry are in Dead-Letter Queue.

Broker differences ​

RabbitMQ ​

RabbitMQ separates the entry point (an exchange) from the channel you read (a queue) and joins them with bindings. That makes it the most literal implementation of the EIP vocabulary. Publish-Subscribe is a fanout or topic exchange with one queue per subscriber; Point-to-Point is a queue with several consumers; the Datatype Channel is a queue per type bound with a routing key; the Invalid Message Channel is a second exchange you republish to, or a dead-letter exchange (DLX) attached to the queue; Guaranteed Delivery is durable queue plus persistent messages plus publisher confirms; Message Expiration is x-message-ttl or the per-message expiration property; the Messaging Bridge is the Shovel plugin (one way, queue to queue) or Federation (WAN friendly, exchange or queue level).

go
// Package main declares the order-placed channels on RabbitMQ and publishes with publisher confirms.
// One topic exchange is the entry point, one durable quorum queue per consumer is a channel,
// and a dead-letter exchange (DLX) is the broker-side half of an Invalid Message Channel.
// 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"
)

const (
	eventsExchange  = "orders.events"  // publish-subscribe entry point
	invalidExchange = "orders.invalid" // dead-letter exchange for rejected messages
	invalidQueue    = "orders.invalid.parking"
)

// consumers maps each consumer to its own queue: channel-per-consumer.
var consumers = []string{"billing", "inventory", "email"}

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

	// Invalid Message Channel: rejected messages are republished here by the broker.
	must(ch.ExchangeDeclare(invalidExchange, "fanout", true, false, false, false, nil))
	_, err = ch.QueueDeclare(invalidQueue, true, false, false, false, amqp.Table{"x-queue-type": "quorum"})
	must(err)
	must(ch.QueueBind(invalidQueue, "", invalidExchange, false, nil))

	// Publish-Subscribe Channel: a topic exchange copies each message to every bound queue.
	must(ch.ExchangeDeclare(eventsExchange, "topic", true, false, false, false, nil))
	for _, c := range consumers {
		q := c + ".order-placed" // Datatype Channel: one message type per queue
		_, err := ch.QueueDeclare(q, true, false, false, false, amqp.Table{
			"x-queue-type":              "quorum",
			"x-dead-letter-exchange":    invalidExchange,
			"x-delivery-limit":          int32(5),
			"x-message-ttl":             int32(24 * 60 * 60 * 1000), // Message Expiration: 24 h
			"x-dead-letter-strategy":    "at-least-once",
			"x-overflow":                "reject-publish",
			"x-dead-letter-routing-key": q,
		})
		must(err)
		must(ch.QueueBind(q, "orders.order-placed.v1", eventsExchange, false, nil))
	}

	// Guaranteed Delivery, sender side: wait for the broker's confirm before moving on.
	must(ch.Confirm(false))
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, eventsExchange, "orders.order-placed.v1",
		true, false, // mandatory: unroutable messages come back instead of vanishing
		amqp.Publishing{
			ContentType:  "application/json",
			DeliveryMode: amqp.Persistent,
			Type:         "order.placed", // Format Indicator lives in message properties and headers
			Headers:      amqp.Table{"format": "order.placed/1"},
			Body:         []byte(`{"order_id":42,"total":1999}`),
		})
	must(err)
	acked, err := dc.WaitContext(ctx)
	must(err)
	fmt.Println("broker confirmed:", acked)
}

func must(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

What breaks: an unbound queue silently receives nothing; a message published with mandatory unset and no matching binding is dropped; non-persistent messages in a non-replicated queue are lost on a crash; and Federation and Shovel have to be enabled as plugins on both ends. Laravel with the package declares its exchange and failed_exchange in the connection options (shown above); the exchange_routing_key option applies when a job is dispatched.

Kafka ​

Kafka has one primitive, the partitioned log, and every pattern is a way of reading it. Publish-Subscribe is a consumer group per subscriber; Point-to-Point is the members of one group; the Datatype Channel is a topic per type; there is no queue to bind and no broker-side dead-lettering, so the Invalid Message Channel and the Dead Letter Channel are topics that the consumer (or the framework) writes. Guaranteed Delivery is acks=all with min.insync.replicas and a replication factor of at least three. Message Expiration is only topic-level retention, so a per-message deadline is a header the consumer checks. The Messaging Bridge is MirrorMaker 2 (cluster to cluster, topics renamed with the source cluster as prefix) or a Kafka Connect connector (any system to Kafka and back), and the Channel Adapter is also Connect.

go
// Package main shows the order-placed channel on Kafka: one topic per message type,
// one consumer group per consumer, acks=all on the producer, and an invalid-message topic.
// It exits quietly when KAFKA_BROKERS is not set, so it compiles and runs without a broker.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

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

const (
	orderPlacedTopic = "orders.order-placed.v1" // Datatype Channel
	invalidTopic     = "orders.order-placed.v1.invalid"
)

type orderPlaced struct {
	OrderID int `json:"order_id"`
	Total   int `json:"total"`
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS") // e.g. localhost:9092
	if brokers == "" {
		fmt.Println("KAFKA_BROKERS is not set; nothing to do")
		return
	}
	seeds := strings.Split(brokers, ",")

	// Guaranteed Delivery, sender side: acks=all waits for the in-sync replicas.
	// franz-go enables the idempotent producer by default with this setting.
	producer, err := kgo.NewClient(
		kgo.SeedBrokers(seeds...),
		kgo.RequiredAcks(kgo.AllISRAcks()),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer producer.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	rec := &kgo.Record{
		Topic:   orderPlacedTopic,
		Key:     []byte("order-42"), // same key -> same partition -> per-order ordering
		Value:   []byte(`{"order_id":42,"total":1999}`),
		Headers: []kgo.RecordHeader{{Key: "format", Value: []byte("order.placed/1")}},
	}
	if err := producer.ProduceSync(ctx, rec).FirstErr(); err != nil {
		log.Fatal(err)
	}

	// Publish-Subscribe: every consumer group has its own cursor over the same topic.
	// Point-to-Point: members of one group share the partitions, so a record reaches one of them.
	consumer, err := kgo.NewClient(
		kgo.SeedBrokers(seeds...),
		kgo.ConsumerGroup("billing"),
		kgo.ConsumeTopics(orderPlacedTopic),
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer consumer.Close()

	fetches := consumer.PollFetches(ctx)
	fetches.EachRecord(func(r *kgo.Record) {
		var ev orderPlaced
		if err := json.Unmarshal(r.Value, &ev); err != nil {
			// Invalid Message Channel: park it with the reason, then move on.
			bad := &kgo.Record{Topic: invalidTopic, Key: r.Key, Value: r.Value, Headers: []kgo.RecordHeader{
				{Key: "reason", Value: []byte(err.Error())},
				{Key: "source", Value: []byte(fmt.Sprintf("%s/%d/%d", r.Topic, r.Partition, r.Offset))},
			}}
			if perr := producer.ProduceSync(ctx, bad).FirstErr(); perr != nil {
				log.Fatal(perr) // do not commit if parking failed
			}
			return
		}
		fmt.Printf("order %d handled at offset %d\n", ev.OrderID, r.Offset)
	})
	// Commit only after the batch is handled: at-least-once.
	if err := consumer.CommitUncommittedOffsets(ctx); err != nil {
		log.Fatal(err)
	}
}

The PHP side, through mateusjunges/laravel-kafka (the Kafka::publish() and Kafka::consumer() calls come from its documentation):

php
<?php

namespace App\Messaging;

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).
// Kafka is not a Laravel queue driver, so this is a plain adapter around the package.
class KafkaChannel
{
    public function publishOrderPlaced(int $orderId, int $totalCents): void
    {
        Kafka::publish('broker')
            ->onTopic('orders.order-placed.v1') // Datatype Channel: one topic per message type
            ->withKafkaKey('order-'.$orderId)   // same key, same partition, per-order ordering
            ->withHeaders(['format' => 'order.placed/1'])
            ->withBodyKey('order_id', $orderId)
            ->withBodyKey('total_cents', $totalCents)
            ->send();
    }

    public function consumeForBilling(): void
    {
        // The group id is the subscription: channel-per-consumer on a shared topic.
        $consumer = Kafka::consumer(['orders.order-placed.v1'], 'billing', 'broker')
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) {
                logger()->info('billing got order', ['body' => $message->getBody()]);
            })
            ->build();

        $consumer->consume();
    }
}

What breaks: a consumer that commits before it parks an invalid record loses it; too few partitions cap Point-to-Point parallelism; a topic per tenant explodes metadata; Kafka does not delay or expire a single message.

Redis Streams ​

A Redis stream "acts like an append-only log" with consumer groups, so the mapping is close to Kafka's with one key as the whole channel. Publish-Subscribe is one group per subscriber on the same stream; Point-to-Point is the consumers of one group; Datatype Channel is a stream per type; Guaranteed Delivery depends on AOF with a strong fsync policy and, if replicas matter, WAIT, because replication is asynchronous by default. Message Expiration is approximated with XTRIM ... MINID. There is no native bridge, no dead-lettering and no invalid channel; they are streams and code you write, with XPENDING and XAUTOCLAIM for stuck entries. Redis Pub/Sub, in contrast, is "at-most-once" and has no storage, so it is not a Guaranteed Delivery channel at all.

go
// Package main shows the order-placed channel on Redis Streams: one stream per message type,
// one consumer group per consumer, MINID trimming as expiration, and an invalid stream.
// It exits quietly when REDIS_ADDR is not set, so it compiles and runs without a server.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

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

const (
	orderPlacedStream = "orders:order-placed:v1" // Datatype Channel
	invalidStream     = "orders:order-placed:v1:invalid"
)

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(), 10*time.Second)
	defer cancel()

	// Publish-Subscribe: each group keeps its own last-delivered ID over the same stream.
	for _, group := range []string{"billing", "inventory", "email"} {
		err := rdb.XGroupCreateMkStream(ctx, orderPlacedStream, group, "0").Err()
		if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
			log.Fatal(err)
		}
	}

	// Publish. Appending is not confirmed by a consumer; it is confirmed by the server reply.
	id, err := rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: orderPlacedStream,
		Values: map[string]any{"format": "order.placed/1", "body": `{"order_id":42,"total":1999}`},
	}).Result()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("appended", id)

	// Message Expiration, approximated: entries older than 24 h are trimmed away.
	// Stream IDs begin with a millisecond timestamp, so MINID acts as an age limit.
	cutoff := strconv.FormatInt(time.Now().Add(-24*time.Hour).UnixMilli(), 10)
	if err := rdb.XTrimMinID(ctx, orderPlacedStream, cutoff).Err(); err != nil {
		log.Fatal(err)
	}

	// Competing consumers of ONE group form a Point-to-Point Channel.
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: "billing", Consumer: "worker-1",
		Streams: []string{orderPlacedStream, ">"}, Count: 10, Block: time.Second,
	}).Result()
	if err != nil && err != redis.Nil {
		log.Fatal(err)
	}
	for _, s := range res {
		for _, m := range s.Messages {
			var ev struct {
				OrderID int `json:"order_id"`
			}
			if jerr := json.Unmarshal([]byte(fmt.Sprint(m.Values["body"])), &ev); jerr != nil {
				// Invalid Message Channel: copy to the invalid stream with the reason, then ack.
				if aerr := rdb.XAdd(ctx, &redis.XAddArgs{Stream: invalidStream, Values: map[string]any{
					"reason": jerr.Error(), "source": orderPlacedStream + "/" + m.ID, "body": m.Values["body"],
				}}).Err(); aerr != nil {
					log.Fatal(aerr) // do not ack if parking failed
				}
			}
			rdb.XAck(ctx, orderPlacedStream, "billing", m.ID)
		}
	}
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;

// Laravel's redis queue driver uses lists and sorted sets, not Streams, so Streams go through the
// Redis facade. Command signatures follow phpredis (Predis differs); written against the client, not run here.
class RedisStreamsChannel
{
    private const STREAM = 'orders:order-placed:v1'; // Datatype Channel

    public function publish(int $orderId, int $totalCents): void
    {
        Redis::xadd(self::STREAM, '*', [
            'format' => 'order.placed/1',
            'body' => json_encode(['order_id' => $orderId, 'total_cents' => $totalCents]),
        ]);
    }

    public function expireOlderThan(int $hours): void
    {
        // Message Expiration, approximated: the ID starts with a millisecond timestamp.
        $cutoffMs = (int) ((microtime(true) - $hours * 3600) * 1000);
        Redis::xtrim(self::STREAM, 'MINID', (string) $cutoffMs);
    }

    public function consume(string $group, string $consumer): void
    {
        $batch = Redis::xreadgroup($group, $consumer, [self::STREAM => '>'], 10, 2000);

        foreach ($batch[self::STREAM] ?? [] as $id => $fields) {
            // handle $fields['body']
            Redis::xack(self::STREAM, $group, [$id]);
        }
    }
}

What breaks: a single stream is not partitioned across Redis Cluster nodes (the docs say partitioning needs multiple keys); XACK without first parking a bad entry loses it; trimming by MINID can delete entries that a slow group has not read; the Laravel redis queue driver is a different mechanism.

The three brokers side by side.

PatternRabbitMQKafkaRedis StreamsLaravel
Message ChannelExchange and queueTopicStream keyConnection and queue
Point-to-PointQueue with competing consumersMembers of one consumer groupConsumers of one groupSeveral queue:work
Publish-SubscribeFanout or topic exchange, queue per subscriberConsumer group per subscriberGroup per subscriberEvent with queued listeners
Datatype ChannelQueue per typeTopic per typeStream per typeQueue name per type
Invalid Message ChannelRepublish to an invalid exchange, or reject to DLXInvalid topicInvalid streamTable or named queue
Dead Letter ChannelDLX (reject, TTL, length, delivery limit)Retry and DLQ topics by the consumer; Connect sink DLQXPENDING, XAUTOCLAIM, parking streamfailed_jobs
Guaranteed DeliveryDurable, persistent, quorum, confirmsacks=all, ISR, replicationAOF fsync, WAITDriver-dependent, afterCommit
Channel AdapterPlugins, own consumersKafka Connect source and sinkOwn codequeue:work, commands
Messaging BridgeShovel, FederationMirrorMaker 2, ConnectNone nativeNone native
Message Expirationx-message-ttl, expirationRetention onlyMINID trimretryUntil()
Message SequenceHeaders; order per queueHeaders; order per partitionHeaders; order per streamHeaders in the payload
Format Indicatortype, content-type, headersHeaders, schema registryFieldsPayload field

For the full side-by-side decision guide see Broker Comparison, and for NATS, Pulsar, SQS/SNS and Google Pub/Sub see Other Brokers.

In production systems ​

  • RabbitMQ Shovel and Federation are documented core plugins. The Shovel guide describes a shovel as behaving "like a well-written client application" with acknowledgements on both ends, and the Federation guide lists loose coupling, WAN friendliness and "specificity" (federated and local-only components in the same broker) as its goals. Both are the Messaging Bridge pattern as a plugin. (Shovel, Federation)
  • Kafka MirrorMaker 2 is the documented geo-replication tool, built on Kafka Connect; its docs list geo-replication, disaster recovery, edge-to-central aggregation, cloud migration and compliance as use cases. (Geo-Replication)
  • Kafka Connect is the documented Channel Adapter framework with source and sink connectors, and sinks have an error-handling dead letter queue topic option, errors.deadletterqueue.topic.name. (Connect overview, Connect configs)
  • Google Cloud Pub/Sub is described on the pattern site as combining Publish-Subscribe on topics with Competing Consumers on subscriptions. (Publish-Subscribe Channel)
  • Laravel: dispatching to named connections and queues, ShouldDispatchAfterCommit on events, after_commit on connections and retryUntil() on jobs are documented behaviour. (Queues, Events)

Choosing ​

Choosing a style ​

SituationStyleExtra techniqueReason
User waits for the answer (price lookup, login, payment verdict)RPCTimeouts, circuit breaker, idempotency keyThe caller cannot proceed without it
Something happened and others may careMessaging, Publish-SubscribeOutbox, schema in a registryThe sender must not know the receivers
Work to do later at a controlled rateMessaging, Point-to-PointRetry with backoff, DLQThe queue absorbs the burst
Partner can only exchange filesFile TransferAdapter per row, file and row idThe constraint is theirs
Bulk data for analytics, dailyFile Transfer or a Connect sinkParquet, partitioned foldersCheaper than one message per row
One team, one product, modules in one processShared Database inside a modular monolithViews as contracts per moduleTransactions are free; split later
Different teams with independent releasesMessaging or RPC, never a shared databasePublished contractsEach owner changes its schema alone
Reporting over many systemsShared read-only database fed by events or CDCRead replica, viewsAnalysts get SQL without coupling producers

Choosing a channel layout ​

QuestionIf yesIf no
Does the message have several independent receivers?Publish-Subscribe: queue or group per receiverPoint-to-Point
Do receivers need to be added without changing the sender?Publish-SubscribePoint-to-Point may do
Can the receiver tolerate any message type on the channel?Shared channel with a type headerOne channel per type
Must the message survive a broker crash?Guaranteed Delivery chain; see the knobsIn-memory or Pub/Sub is enough
Is old data harmful?Message Expiration header plus TTLNo expiry
Is the payload large?Message Sequence or claim-checkSingle message
Does the format change over time?Format Indicator plus compatibility rulesVersion the channel name
Do two brokers exist?Messaging Bridge channel by channelNothing
Does something not speak the protocol?Channel AdapterNative client

Choosing a broker for these patterns ​

PriorityPickWhy
Rich routing, per-message TTL, DLX, work queuesRabbitMQThe exchange, binding and DLX model maps one-to-one to the patterns
Replay, many independent subscribers, huge volume, connectorsKafkaConsumer groups over a retained log; Connect and MirrorMaker 2 are the adapter and the bridge
Already running Redis, modest volume, simple groupsRedis StreamsOne key, consumer groups, no new system; accept weaker replication guarantees
Laravel only, one appThe database or redis queue driverNo extra broker; add one only when a second consumer language appears

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

Monolith (one process, one database) ​

How it shows up. A monolith integrates its own modules by function calls, which is the degenerate RPC. The first useful step is an in-process event, then a queued listener on the database driver. The "channel" is the jobs table, the "Publish-Subscribe Channel" is one event with several listeners, and the "adapter" is queue:work.

Simplest correct usage. Dispatch the event after commit. Use the database connection with after_commit => true, one queue per consumer (inventory.order-placed, email.order-placed), and an invalid_messages table.

Example. PlaceOrder inserts the order and dispatches OrderPlaced inside the same transaction; the event waits for COMMIT; two queued listeners each get a job on their own queue; a nightly Artisan command ingests a CSV from the legacy ERP as messages. Nothing in this design needs RabbitMQ yet, and nothing in it prevents adding it later, because call sites do not name the broker.

Modular monolith / multiple databases ​

How it shows up. Modules own their tables. The Shared Database style survives inside the monolith, protected by views and database roles (the SQL block above). Cross-module reads go through those views; cross-module writes go through events.

Example. Billing may SELECT from orders_for_billing and nothing else; Orders publishes OrderPlaced to the redis or rabbitmq connection with a queue per module. The day Billing moves out as a service, only the connection changes: the channel name, the message format and the consumer queue are already independent. Rule: no module reads another's table, and every cross-module event has a name, a version and an owner.

Microservices ​

What survives across the boundary. Only messages and published API contracts. Transactions do not: the order row and the OrderPlaced message must be tied by the Transactional Outbox; consumers must be idempotent (Idempotent Consumers); cross-service business flows become Sagas.

Example, step by step. Checkout calls Orders by REST (RPC: the user waits). Orders commits the order and an outbox row; the relay publishes order.placed v1 to orders.events. Billing, Inventory and Email each own a queue, a DLX and an invalid queue. Email goes down for a day: its queue grows, nobody else notices, and when it returns it drains the backlog, skipping messages that carry an expired expires-at header. Domain-event design and the integration-event distinction are in Domain Events vs Integration Events and Designing for Failure: Reliable Messaging.

Worked example: order placed to three channels and a second broker ​

The scenario: an online shop runs RabbitMQ for operations. The analytics team has Kafka and wants the same events, without making Orders know about Kafka.

StepWhat happensPattern
1The legacy ERP drops orders-2026-11-25.csv; an adapter turns each row into order.placed/1 messages with file name and row numberFile Transfer, Channel Adapter, Message Sequence
2Orders (modern path) writes the order and an outbox row in one transactionOutbox; Outbox Pattern
3The relay publishes with mandatory, persistent delivery mode and a publisher confirm to the topic exchange orders.events with key orders.order-placed.v1Guaranteed Delivery, Datatype Channel
4Three queues are bound: billing.order-placed, inventory.order-placed, email.order-placed; each is a quorum queue with a DLX orders.invalid and x-message-ttl of 24 hoursPublish-Subscribe, Point-to-Point, Message Expiration
5Billing finds {"order_id":"abc"}, publishes it with the reason to orders.invalid, and acksInvalid Message Channel
6Inventory rejects a message five times; the quorum queue's delivery limit dead-letters it to orders.invalid with x-death historyDead Letter Channel
7A bridge consumes a fourth queue (analytics.bridge, also bound to the exchange) and produces to Kafka topic orders.order-placed.v1, acking after the Kafka produce is confirmed, with x-bridged-by setMessaging Bridge
8Kafka consumers in the analytics group read the topic; a Connect sink writes it to the warehouseChannel Adapter (sink)
9Dashboards alarm on queue depth, on the invalid and dead-letter queues, and on bridge lagObservability

The Go and Laravel code for every step is on this page: steps 1 (adapter, LegacyFileAdapter.php), 3 to 6 (rabbitmq, invalid, queue-connections.php, InvalidMessageJob.php), 7 (bridge).

Distributed data (replicas, caches, multi-region) ​

Where the concept breaks. A bridge across regions adds latency and, because replication is asynchronous, a window in which the two sides differ. MirrorMaker 2 documents active/passive and active/active layouts; in the active/active one a topic exists under two names (us-west.foo and foo) and consumers must decide which to read. RabbitMQ Federation is designed for connections that "fail from time to time". Read replicas lag behind the primary, so a consumer that reads the database after receiving an event may not yet see the change (Replication, Read Replicas & Failover); cache consumers may serve stale data until invalidated (Redis). Consensus-based brokers (quorum queues, KRaft Kafka) trade availability for consistency under partition (Distributed SQL & Consensus).

Rules. Put a stable message id on every message; design consumers for duplicates; pick one region as the owner of each channel; never bridge both ways without a loop guard; accept that "exactly once across regions" costs an idempotency record, not a configuration flag.

Scaling path ​

LoadLayoutWhat changes
1x: hundreds of messages a minutedatabase or redis Laravel queue, a queue per consumer, invalid_messages tableNothing special; add alarms on queue depth
10x: thousands a minuteRabbitMQ with quorum queues, one queue per consumer, confirms onAdd Guaranteed Delivery and an invalid queue; more workers per queue (Competing Consumers)
100x: tens of thousands a secondKafka for the high-volume types, partitions keyed by entityDatatype topics, partition count planning (Ordering & Partitioning); Connect sinks for the warehouse
Multi-team, multi-regionBoth brokers plus bridges, a schema registry, naming and ownership rulesMessage Bus conventions; MirrorMaker 2 or Shovel and Federation; governance

Lab ​

This lab is labelled "expected, not run": no broker was started while writing this page. The Go and PHP programs were only compiled, vetted and unit-tested; the commands below show what you would see.

Setup (any machine with Docker; the images are the official ones):

bash
docker run -d --name rmq -p 5672:5672 -p 15672:15672 rabbitmq:4-management
docker run -d --name kafka -p 9092:9092 apache/kafka:latest
export RABBITMQ_URL=amqp://guest:guest@localhost:5672/
export KAFKA_BROKERS=localhost:9092
cd docs/snippets/messaging/integration-styles-channels/go
  1. Declare the channels and publish with a confirm.
    bash
    go run ./rabbitmq
    # expected, not run: broker confirmed: true
    docker exec rmq rabbitmqctl list_queues name messages
    # expected, not run:
    # billing.order-placed    1
    # inventory.order-placed  1
    # email.order-placed      1
    # orders.invalid.parking  0
  2. Show that each subscriber has its own copy. In the management UI at localhost:15672, get one message from billing.order-placed; the other two queues still show 1 message.
  3. Test the invalid path. Publish {oops to orders.events with the same routing key through the management UI and let a consumer reject it with requeue=false (or run your consumer with the invalid logic). Expect orders.invalid.parking to show 1 message whose x-death header names the source queue.
    bash
    docker exec rmq rabbitmqctl list_queues name messages | grep invalid
    # expected, not run: orders.invalid.parking  1
  4. Bridge to Kafka. Create the target topic, bind a fourth queue and run the bridge.
    bash
    docker exec kafka /opt/kafka/bin/kafka-topics.sh --create --topic orders.order-placed.v1 --bootstrap-server localhost:9092
    go run ./bridge &
    go run ./rabbitmq
    docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh --topic orders.order-placed.v1 --from-beginning --bootstrap-server localhost:9092 --max-messages 1
    # expected, not run: {"order_id":42,"total":1999}
  5. Kill the bridge between produce and ack (add time.Sleep before d.Ack and kill the process). Restart: the same message appears twice in Kafka, which is the "duplicate, never a loss" behaviour. A consumer with a dedup table (Idempotent Consumers) makes it harmless.
  6. Run the broker-free checks, which were run.
    bash
    gofmt -l . && go vet ./... && go test ./...
    # actual: ok for academy/integration-styles-channels/invalid and /envelope

Common misconceptions ​

BeliefReality
Messaging replaces files, shared databases and RPCThe four styles coexist; each is right somewhere
A shared database is the safest integrationIt is the most consistent and the most coupled; one schema, one lock domain
A message channel is a queueA channel is the addressable pipe: exchange plus queues, topic, stream key
Publish-Subscribe and Point-to-Point are different brokersThey are two delivery rules; Publish-Subscribe is built from one Point-to-Point channel per subscriber
Several consumers on one queue means every consumer sees every messageThey compete: each message reaches one of them
One events topic is simplerSimpler to create, harder to consume and evolve; a Datatype Channel is addressing
Invalid messages should be retried like failuresThey are permanent failures; park them with a reason
Invalid Message Channel and Dead Letter Channel are the same thingThe receiver decides one; the messaging system decides the other
Persistent means guaranteedDurable queue, disk or replicas, a confirm, and a manual ack are all required
Guaranteed Delivery means exactly onceIt means not lost; duplicates are expected, see Delivery Guarantees
A queue TTL is Message ExpirationA TTL is one mechanism; the pattern is "this message is useless after T", and on Kafka and Redis you check a header
A bridge joins two brokers entirelyIt joins corresponding channels, one pair at a time
Mirroring both ways is harmlessWithout a loop guard a message circulates forever
A message bus is a productIt is an architecture: common infrastructure, commands and data model
Redis Pub/Sub is a message channel with delivery guaranteesIt is at-most-once with no storage

Cheat sheet ​

TopicWhat to remember
Four stylesFile Transfer (stale, simple), Shared Database (consistent, coupled), RPC (immediate, coupled in time), Messaging (decoupled, eventual)
Message ChannelThe addressable pipe; Laravel calls the transport a connection and the channel a queue
Point-to-PointOne receiver per message; many consumers may compete
Publish-SubscribeA copy per subscriber; build it as a fan-out plus one queue or group per subscriber
Datatype ChannelOne message type per channel; name it owner.type.version
Invalid Message ChannelThe receiver parks a message that makes no sense, with the reason, then acks; never retry it
Dead Letter ChannelThe messaging system parks what it cannot deliver; link Dead-Letter Queue
Guaranteed DeliveryDurable storage at every hop, confirm to the sender, ack from the receiver
RabbitMQDurable queue, persistent message, publisher confirm, quorum queue, DLX
Kafkaacks=all, min.insync.replicas, replication factor 3, commit after processing
Redis StreamsAOF with a strong fsync policy, WAIT, XACK, XAUTOCLAIM
Channel AdapterWraps an application's files, database or API as a messaging client; Kafka Connect is the product form
Messaging BridgeChannel-by-channel replication between brokers; Shovel, Federation, MirrorMaker 2; ack after the target confirms
Message BusCommon infrastructure, common commands, common data model
Expiration, Sequence, FormatHeader-level patterns: expires-at, sequence-id and position, format
Namingowner.type.version, consumer-first for queues, .invalid and .dlq suffixes

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 — What are the four integration styles and the main weakness of each? Must-know ​

Answer

Answer: File Transfer (stale data, whole-file failure), Shared Database (one schema and one lock domain for all applications), Remote Procedure Invocation (both sides must be up, tight coupling in time), Messaging (eventual consistency and a broker to run).

2 — Why is Publish-Subscribe described as built from Point-to-Point channels? Important ​

Answer

Answer: EIP says each output channel has exactly one subscriber. The fan-out in front copies the message into one channel per subscriber, and each of those channels delivers to one receiver (or to a pool of competing copies of one receiver). In RabbitMQ that is a queue per subscriber; in Kafka a consumer group per subscriber.

3 — When should you choose one channel per message type over a shared channel with a type header? Important ​

Answer

Answer: When there are a handful of well-known types and consumers care about only some of them. The Datatype Channel lets the receiver know the type from the channel; a shared channel forces every consumer to open and filter every envelope and to survive new types.

4 — How does an Invalid Message Channel differ from a Dead Letter Channel? Important ​

Answer

Answer: The receiver decides a message is invalid after reading it, and a retry cannot fix it. The messaging system decides a message is dead because of a delivery rule (expired, rejected, delivery limit, queue overflow), and a retry may sometimes succeed.

5 — Which settings together give Guaranteed Delivery on RabbitMQ, on Kafka and on Redis Streams? Important ​

Answer

Answer: RabbitMQ: a durable (preferably quorum) queue, persistent messages, publisher confirms, manual consumer acks. Kafka: acks=all with min.insync.replicas and replication factor 3, offsets committed after processing. Redis Streams: AOF with a strong fsync policy, WAIT for replicas if needed, XACK after processing.

6 — Why does a bridge ack the source only after the target confirmed? Important ​

Answer

Answer: If the bridge crashes between the two, the source redelivers and the target gets a duplicate; the opposite order would lose the message. Duplicates are handled by idempotent consumers.

7 — How do you stop two mirrored brokers from passing a message back and forth? Good to know ​

Answer

Answer: Mark bridged messages with a header such as x-bridged-by and skip them, or use a bridge that does it by design (MirrorMaker 2 renames replicated topics with the source cluster as prefix and handles flows defined in one configuration file).

8 — Kafka has no per-message TTL. How do you implement Message Expiration there? Important ​

Answer

Answer: Put an absolute expires-at in a header and check it in the consumer; use topic retention.ms only as a coarse upper bound. The same holds for Redis Streams, where XTRIM MINID is a coarse age limit.

9 — What are the three fields of a Message Sequence, and how does the receiver cope with duplicates? Good to know ​

Answer

Answer: Sequence identifier, position identifier, and a size or end indicator. The receiver stores parts by position, so a redelivered part overwrites itself, and reassembles when all positions are present.

10 — What is the difference between a Message Bus, a Message Broker and an ESB? Must-know ​

Answer

Answer: A broker is the server that stores and routes messages. The EIP Message Broker pattern is a central hub that routes by content. A Message Bus is an architecture of common infrastructure, commands and data model. An ESB is a product bundling broker, routing, transformation and orchestration in one central runtime.

11 — Why dispatch the event after the transaction commits in Laravel? Must-know ​

Answer

Answer: So a rolled-back transaction never announces a fact that did not happen, and so a fast consumer never looks for a row that is not committed yet. Laravel offers ShouldDispatchAfterCommit on events, after_commit on connections and afterCommit() on jobs.

Glossary ​

TermMeaning
Integration styleOne of File Transfer, Shared Database, Remote Procedure Invocation, Messaging
File TransferOne application writes a file that another reads later
Shared DatabaseSeveral applications read and write the same schema
Remote Procedure Invocation (RPC)A synchronous call to another application over the network
MessagingAsynchronous transfer of self-contained messages through channels
Message ChannelThe addressable pipe messages travel through
Point-to-Point ChannelA channel where each message is consumed by exactly one receiver
Publish-Subscribe ChannelA channel that delivers a copy of each message to every subscriber
Datatype ChannelA channel that carries only one message type
Invalid Message ChannelA channel where receivers park messages that make no sense
Dead Letter ChannelA channel where the messaging system parks messages it cannot deliver
Guaranteed DeliveryPersistence at every hop so messages survive a broker crash
Channel AdapterA messaging client that connects a non-messaging application
Messaging BridgeA set of adapters that replicates channels between messaging systems
Message BusAn architecture of common infrastructure, commands and data model
Message Broker (pattern)A central hub that routes messages to the correct channel
ESBEnterprise Service Bus: a central integration product with routing and transformation
Message ExpirationA time after which a message is stale and must not be processed
Message SequenceA set of chunks marked with sequence id, position and size
Format IndicatorA field naming the message's format or version
ExchangeRabbitMQ entry point that routes published messages to queues by bindings
BindingA rule connecting an exchange to a queue
DLX (dead letter exchange)A RabbitMQ exchange that receives dead-lettered messages
Publisher confirmA RabbitMQ acknowledgement from the broker to the publisher
ShovelRabbitMQ plugin that moves messages between brokers one way
FederationRabbitMQ plugin that replicates exchanges or queues between brokers
Quorum queueRabbitMQ replicated queue type based on Raft
TopicKafka's named, partitioned log
Consumer groupKafka consumers sharing a group id; each partition goes to one member
acks=allKafka producer setting that waits for all in-sync replicas
ISRIn-sync replicas of a Kafka partition
MirrorMaker 2Kafka's cross-cluster replication tool, built on Kafka Connect
Kafka ConnectFramework of source and sink connectors between Kafka and other systems
Stream (Redis)An append-only log data structure under one Redis key
XADD, XREADGROUP, XACKRedis commands to append, read as a group member, acknowledge
MINIDXTRIM strategy that removes entries older than an ID
AOFRedis append-only file used for persistence
Connection (Laravel)A configured queue transport in config/queue.php
queue:workThe Laravel worker process that reserves and runs jobs
ShouldDispatchAfterCommitLaravel interface that holds an event until the transaction commits
Idempotent consumerA consumer that tolerates duplicates by recognising a message id
Poison messageA message that always fails when processed
Loop guardA header or rule that stops a bridged message from being bridged again

References ​

Enterprise Integration Patterns (Hohpe and Woolf): Messaging, File Transfer, Shared Database, Remote Procedure Invocation, Message Channel, Point-to-Point Channel, Publish-Subscribe Channel, Datatype Channel, Invalid Message Channel, Dead Letter Channel, Guaranteed Delivery, Channel Adapter, Messaging Bridge, Message Bus, Message Broker, Message Expiration, Message Sequence, Format Indicator.

RabbitMQ: Shovel, Dynamic Shovels, Federation, Federation reference, Consumer Acknowledgements and Publisher Confirms, Dead Letter Exchanges, Time-to-Live and Expiration, Quorum Queues, Queues, Reliability; client amqp091-go; Laravel package laravel-queue-rabbitmq.

Kafka: Design, Geo-Replication, Kafka Connect overview, Producer configs, Topic configs, Connect configs, Introduction; client franz-go; Laravel package laravel-kafka.

Redis: Streams, Pub/Sub; client go-redis.

Laravel 13: Queues, Events.

Related pages: Messaging Fundamentals, Delivery Guarantees, Message Acknowledgment, Ordering & Partitioning, Routing Topologies, Dead-Letter Queue, Message Transformation, Message Design & Schema Evolution, Service Communication, Service-Oriented Architecture, Domain Events vs Integration Events, Designing for Failure: Reliable Messaging.

Built by Morteza Negahi