Skip to content

Routing Topologies: Fan-out, Topic & Content-Based ​

"The purpose of exchanges is to route all messages that flow through them to one or more queues, streams, or other exchanges." — RabbitMQ documentation, Exchanges guide

Summary: Routing topology is the map that decides which consumer receives which message: exchanges and bindings on RabbitMQ, topic and key choice on Kafka, stream keys and consumer groups on Redis Streams. Focus: Every RabbitMQ exchange type and binding feature, Kafka topic design (per event type, per aggregate, per bounded context), Redis stream naming and cluster sharding, content-based routing, fan-out and fan-in, and the worked Sales/Fulfilment/Billing topology on all three brokers. Learning goal: Design and declare a topology in code for a new domain, name its channels so ACLs and tenants fall out naturally, and know where each routing decision should live.

This page is the complete reference for where messages go. It covers RabbitMQ's exchange types (direct, fanout, topic, headers, the default exchange, plugin types such as x-consistent-hash), bindings, exchange-to-exchange bindings, alternate exchanges and the dead-letter exchange pointer; Kafka topic design and naming, compacted topics, topic sprawl and multi-tenant ACLs; Redis Streams key naming, per-tenant prefixes and hash tags; the Enterprise Integration Patterns view of routing (Publish-Subscribe Channel, Content-Based Router, Message Filter); and how Laravel's onQueue, onConnection and Queue::route act as a router inside one application. It does not re-teach its neighbours. Per-key ordering, partition-key hashing and the ordering use of the consistent-hash exchange are in Ordering & Partitioning; consumer-group scaling and rebalancing in Competing Consumers & Scaling; DLQ handling in Dead-Letter Queue; Splitter, Aggregator, Recipient List, Dynamic Router and the full Message Filter in Advanced Routing; vhost and ACL hardening in Messaging Security. The broker internals live in RabbitMQ in Depth, Kafka in Depth and Redis Streams & Pub/Sub.

Page map ​

If you are looking forGo to
The whole topic in three tablesEverything in one minute
Why routing is a design problem at allWhy routing topology exists
AMQP, EIP and Kleppmann's topic ruleWhere it comes from
Routing key vs binding key, bindingsRouting key, binding key and binding
Direct, fanout, topic, headers, default exchangeExchange types
* and #, the key grammarTopic exchange
x-match all/anyHeaders exchange
Exchange-to-exchange, alternate exchange, DLX pointerE2E, AE, DLX
Consistent-hash, modulus-hash, sharding pluginHash exchanges
One topic per event type or per aggregate?Kafka topic design
Topic names, compaction, sprawl, ACLsKafka naming
Stream keys, tenants, hash tagsRedis stream naming
Producer vs broker vs consumer routingContent-based routing
Fan-out and fan-in on each brokerFan-out and fan-in
Knobs, limits, error codes, topology as codeMechanics
Language integration and client caveatsGo, Laravel
Per-broker implementation with codeBroker differences
New consumers, tenants, environments, ordering, securitySolving the classic problems
What not to doAnti-patterns
A decision tableChoosing a topology
Monolith to multi-region, with the Sales/Fulfilment/Billing exampleIn architecture
Runnable programs and broker experimentsLab

Everything in one minute ​

The routing primitive on each broker.

QuestionRabbitMQKafkaRedis Streams
What does a producer write to?An exchange, with a routing keyA topic (and a key that picks the partition)A stream key (XADD)
Who decides which consumers get a copy?The broker, using bindingsThe consumer, by subscribing a consumer groupThe consumer, by creating a consumer group
Can the broker filter on content?Yes: topic patterns, headers exchangeNo (consumers filter)No (consumers filter)
Fan-out mechanismOne queue per subscriber, bound to the exchangeOne consumer group per subscriberOne consumer group per subscriber
Fan-in mechanismMany exchanges or keys bound to one queueRegex subscription or several topics in one groupXREADGROUP over several streams
Unroutable messageDropped, returned (mandatory) or sent to an alternate exchangeImpossible: the topic exists or the write failsImpossible: XADD creates the key
Naming limitsRouting key max 255 bytesTopic name max 249 chars, [a-zA-Z0-9._-]Any binary-safe key

Other brokers sit between these models: NATS routes on hierarchical subjects with wildcards, Pulsar has topics with subscriptions, and Amazon SNS topics fan out to SQS queues. They are surveyed in Other Brokers; the design rules on this page carry over.

RabbitMQ exchange types.

TypeRoutes onTiny exampleTypical use
DirectExact routing key equalitykey invoice.pdf → queue bound with invoice.pdfTask routing by job type
FanoutNothing: every bound queueprice update → every cache nodeBroadcast, audit tap
TopicPattern on dot-separated wordssales.order.*.v1 matches sales.order.placed.v1Domain events, selective subscribers
HeadersHeader values, x-match all/anychannel=sms, tier=vipRouting on several attributes
Default ("")Key = queue namepublish to "" with key emails"Send to this queue"
x-consistent-hash (plugin)Hash of key or header onto a ringspread order_id over 4 queuesPartitioning queues
x-modulus-hash (core)Hash of key mod Nsharding plugin's shardsSharded classic queues
Local random (4.0+)Random local queueRPC serversRequest-reply latency

The design rules this page defends.

RuleWhy
One publishing exchange (or topic family) per domain, owned by the producerOwnership and ACLs follow domain boundaries
One queue per consuming service and purposeEach subscriber gets its own copy, backlog, DLQ and scaling
Routing keys and topic names describe the event, never the consumerAdding a consumer must not change the producer
Events that must stay ordered share a topic and a keyKafka orders only within a partition
Route on metadata (key, headers), not on payload stringsThe broker cannot read your JSON; parsing in the router is fragile
Topology is code or definitions in version control, not clicksReproducible environments and reviews

Why routing topology exists ​

Point-to-point messaging needs no topology: the sender names the queue. The moment a second party wants the same message, or a party wants only some messages, someone has to decide who gets a copy. That decision can live in the producer (it sends to several places), in the broker (rules copy the message), or in the consumer (it reads everything and ignores some). The topology is the explicit, inspectable version of that decision. Done well, a new subscriber is a new queue and a binding, or a new consumer group; the producer never changes.

Routing in the producerRouting in the broker or a declared topology
Producer must know every consumerProducer knows only its own exchange or topic
Adding a subscriber = deploy the producerAdding a subscriber = declare a queue/binding or group
No extra infrastructureTopology to name, version and secure
Easy to reason about locallyEasy to reason about globally (one map)
Couples teamsDecouples teams, needs a naming convention

The analogy we reuse on this page: a company mailroom. Letters (messages) arrive with an internal address label (routing key) and sometimes stickers (headers). The mailroom (exchange) has a rule board (bindings): "everything labelled sales.order.anything goes to the Fulfilment pigeonhole", "everything goes to the archive". Each department has its own pigeonhole (queue) so nobody steals another's letters. A letter whose label matches no rule goes to the "unknown recipient" tray (alternate exchange) or back to the sender (mandatory). Kafka is a different building: there is no rule board, only labelled filing cabinets (topics); each department keeps its own bookmark (consumer group offset) and reads the cabinets it cares about. Redis Streams is a smaller version of the cabinet building.

Three common misunderstandings, up front ​

  1. "Topics are the same thing on every broker." A RabbitMQ topic is an exchange type that pattern-matches routing keys and stores nothing; a Kafka topic is a durable, partitioned log; a Redis stream is one key. Routing on a RabbitMQ topic exchange happens at publish time; on Kafka, "routing" happened when the producer picked the topic.
  2. "Fan-out means one queue with many consumers." Many consumers on one queue compete (each message goes to one of them). Fan-out means one copy per subscriber: one queue per subscriber on RabbitMQ, one consumer group per subscriber on Kafka and Redis.
  3. "Fewer, bigger channels are always simpler." One giant queue mixes priorities and failure domains; one topic per event type breaks ordering across types. The right granularity follows ordering needs, ownership and consumer interest, in that order.

Where it comes from ​

AMQP 0-9-1 separated the publication address (exchange) from the consumer backlog (queue). Bindings connect them; RabbitMQ adds E2E bindings, alternate exchanges, headers options and plugin routing types.

Enterprise Integration Patterns (Hohpe and Woolf, 2003) distinguishes broadcasting to independent subscriptions, selecting a destination from message content, and filtering unwanted messages. A router centralizing changing business rules can become a maintenance bottleneck.

Kafka makes topic choice part of routing. Martin Kleppmann’s 2018 article recommends designing topic boundaries around ordering, ownership and volume before splitting by event type. Kafka’s multi-tenancy guide connects hierarchical names to prefixed ACLs.

Redis Streams offers independent consumer groups, but a stream remains one key. Horizontal storage partitioning requires multiple keys chosen by the application.

The concept catalogue ​

Each block: plain words, the usual wrong belief, the definition, a sequence, real scenarios, what each broker does, and the fix in code (Go first, Laravel second). Badges: Must-know, Important, Good to know.

Routing key, binding key and binding Must-know ​

In plain words: the producer writes an address on the message (routing key); each queue registers the addresses it wants (binding key); the binding is that registration.

Common misunderstanding: "The queue name is the routing key." Only on the default exchange. On every other exchange a queue can be bound with any number of keys, and the key it is bound with has nothing to do with its name.

Definition: a binding records source exchange, destination and its type, binding key and arguments. An exchange starts without application destinations. Binding durability depends on both endpoints; prefer durable sources and destinations for persistent topology.

text
1  Fulfilment starts: queue.declare fulfilment.sales-orders (quorum, durable)
2  Fulfilment:        queue.bind fulfilment.sales-orders -> sales.events key "sales.order.*.v1"
3  Billing starts:    queue.declare billing.sales-orders
4  Billing:           queue.bind billing.sales-orders -> sales.events key "sales.order.placed.v1"
5  Sales publishes:   exchange=sales.events key=sales.order.placed.v1
6  Broker:            matches both bindings -> one copy in each queue
7  Sales publishes:   key=sales.order.cancelled.v1 -> only fulfilment.sales-orders

Real scenario: a new Analytics service wants every Sales event: it declares analytics.sales and binds it with sales.#; Sales is not redeployed. A team renames a queue: the binding must be redeclared, which is why bindings belong in topology code next to the queue.

What each broker does: RabbitMQ stores bindings in its metadata store (Khepri in 4.x) per vhost. Kafka has no bindings: a consumer group subscribes to topic names or a regex. Redis has no bindings: a consumer group is created on one stream key with XGROUP CREATE.

Fix / how to use it: declare bindings with the consumer's queue, in the consumer's deployment. See rabbitmq/topology/main.go in Broker differences and DeclareOrderingTopology.php in Solving the classic problems.

direct: exact key equalityfanout: copy to every bound queuetopic: pattern on dot-separated wordsheaders: match headers, key ignoredkey=placeddirectbind: placedbind: placedbind: cancelledSame key bound twice = both queues get a copykey ignoredfanoutbillingfulfilmentauditBroadcast: N bound queues, N copiessales.order.placed.v1topicsales.order.*.v1sales.#*.payment.#* = exactly one word, # = zero or more wordschannel=smstier=vipheadersx-match=allsms + vipx-match=allemail + vipx-match=anychannel=smsSolid = routed, dashed = no match

Direct exchange Must-know ​

In plain words: exact address match. Key invoice.pdf goes to every queue bound with exactly invoice.pdf.

Common misunderstanding: "Direct means one consumer." Direct describes the matching rule, not the recipient count: multiple queues with the same matching key each receive a copy.

Definition: a binding with key K matches a message with routing key R when K = R, byte for byte. amq.direct is the pre-declared direct exchange in every vhost.

Real scenario: a job router where each job type has a queue with its own worker pool (pdf.render, email.send); log severity routing (error to the pager queue and the archive, info to the archive only).

Fix: use direct when keys are a closed set (job types, severities); switch to topic as soon as subscribers want "all of a family".

Fanout exchange Must-know ​

In plain words: photocopy to everyone. The key is ignored.

Common misunderstanding: "Fanout is the only way to broadcast." A topic exchange with a # binding behaves like fanout for that binding, and many domain exchanges should be topic exchanges from day one so that later subscribers can be selective.

Definition: fanout selects all bound destinations without inspecting the routing key.

Real scenario: cache invalidation to every app node (each node an exclusive, auto-delete queue); the audit tap in the worked example, where audit.all is a fanout exchange fed from domain exchanges by exchange-to-exchange bindings.

Fix: fanout for "everyone, always"; topic with # when you might want to narrow later.

Topic exchange and the routing-key grammar Must-know ​

In plain words: the routing key is a dotted address like sales.order.placed.v1; subscribers bind with patterns where * is one word and # is any number of words.

Common misunderstanding: "* and # are like shell globs inside a word." They match whole words only. sales.ord* is not a pattern; it is a literal word ord*.

Definition: topic routing compares dot-separated words. * matches exactly one word; # matches zero or more. Routing keys are limited to 255 bytes. A # binding accepts all keys; a pattern without wildcards performs an exact match.

text
1  binding Q1: *.orange.*     binding Q2: *.*.rabbit and lazy.#
2  publish quick.orange.rabbit     -> Q1, Q2
3  publish lazy.orange.elephant    -> Q1, Q2
4  publish lazy.pink.rabbit        -> Q2 once (two bindings match, one copy)
5  publish quick.brown.fox         -> nothing: dropped (no AE, not mandatory)
6  publish quick.orange.new.rabbit -> nothing: four words never match *.orange.*
7  publish lazy.orange.new.rabbit  -> Q2 via lazy.#
Routing key = words separated by dots (max 255 bytes). * = exactly one word, # = zero or more.Key grammar used on this page: <domain>.<entity>.<event>.v<N> (our convention, not a broker rule)key \ bindingsales.order.*.v1sales.#*.order.placed.*#.v1sales.order.placed.v1sales.order.placed.v1matchmatchmatchmatchmatchsales.order.cancelled.v1matchmatchnomatchnosales.order.placed.v2nomatchmatchnonosales.order.item.added.v1nomatchnomatchnosalesnomatchnononobilling.order.placed.v1nonomatchmatchnosales.ordernomatchnononosales.# also matches "sales" (# can be zero words); item.added is two words, so * cannot match it.A key with the wrong word count matches nothing: it is dropped unless an AE or mandatory catches it.One queue bound by two matching patterns still receives one copy.

Key grammar (our convention, not a broker rule): <domain>.<entity>.<event>.v<N>, lower case, hyphens inside words (sales.order.item-added.v1). Fixed word count makes * patterns reliable; the domain first makes sales.# and ACL prefixes work; the version last lets consumers bind to #.v1 while v2 rolls out.

Real scenario: Fulfilment binds sales.order.*.v1; Billing binds two exact keys; Analytics binds #.v1; an MQTT-style device feed uses site.<id>.sensor.<kind>.

Fix: the runnable matcher in topicmatch/main.go (in the Lab) reproduces the tutorial cases with go test, so you can check a pattern before you bind it.

Headers exchange and x-match Important ​

In plain words: route on several labels at once (channel=sms, tier=vip) instead of one dotted string.

Common misunderstanding: "Headers exchange is slow and useless." It is the right tool when the attributes are independent and combinatorial; encoding them into one key forces every subscriber to know the word order.

Definition: headers routing compares typed header values and ignores the routing key. x-match=all requires every listed condition; any requires at least one. Their -with-x variants include names starting with x-, which ordinary all/any exclude.

Real scenario: notification routing (channel × tier × locale); document processing where format=pdf and size=large go to a high-memory pool; regulatory routing where region=eu messages must reach an EU-only queue.

What each broker does: RabbitMQ only. On Kafka and Redis the same logic is a consumer-side filter or a router process over headers/fields.

Fix: always set x-match explicitly in the binding (see notifications.route in the topology program) and pair the exchange with an alternate exchange for the "matched nothing" case.

Default exchange Good to know ​

In plain words: the nameless exchange that makes "publish to queue X" work.

Common misunderstanding: "I can bind my own keys to the default exchange." Custom bind/unbind operations and alternate exchanges are unavailable there; use a separate named exchange.

Definition: a pre-declared direct exchange named "" (referred to as amq.default in permissions); every queue is automatically bound to it with its own name as key.

Real scenario: Laravel's RabbitMQ driver without an exchange option publishes this way; RPC replies to a client's exclusive queue.

Fix: fine for commands to one known queue; for events use a named exchange so subscribers can be added.

Exchange-to-exchange bindings Important ​

In plain words: an exchange can be bound to another exchange, so you can build routing in layers: a public entry exchange, then internal exchanges per concern.

Common misunderstanding: "Two paths to one queue give two copies." RabbitMQ deduplicates queue destinations and detects cycles during one routing operation. Republishing a message is a separate operation and can still duplicate it.

Definition: E2E bindings are directional and preserve source exchange/key matching. amqp091-go uses ExchangeBind(destination, key, source, noWait, args); php-amqplib uses exchange_bind($destination, $source, $routing_key). An internal destination rejects direct client publication. E2E is not republication, so destination exchange ingress metrics need not increase; inspect queue metrics.

text
1  sales.events (topic) --#--> audit.all (fanout, internal)
2  billing.events (topic) --#--> audit.all
3  audit.all --> audit.archive (stream queue, 30 days)
4  Sales publishes sales.order.placed.v1
5    -> fulfilment.sales-orders (binding sales.order.*.v1)
6    -> billing.sales-orders    (binding sales.order.placed.v1)
7    -> audit.all -> audit.archive (one copy)

Real scenario: an audit or analytics tap over several domains without touching any domain's bindings; a "public" exchange per tenant bound into a shared internal exchange; migrating a consumer from one exchange to another by binding old to new.

Fix: keep layers shallow (two levels); every hop is a place where a missing binding silently drops messages.

Alternate exchange and unroutable messages Important ​

In plain words: a catch-all for messages that matched no binding, instead of silent loss.

Common misunderstanding: "RabbitMQ errors when a message matches nothing." Without an effective AE or mandatory-return handling, an unroutable publication may disappear silently.

Definition: set alternate-exchange through policy or a declaration argument; a client argument takes precedence. Routing can continue through an AE chain. A successful AE route satisfies mandatory. If no queue is reached, mandatory produces basic.return with code 312 NO_ROUTE.

text
1  notifications.route (headers, AE = notifications.unmatched)
2  publish headers channel=push, tier=basic
3  no binding matches (sms+vip with all; email with any)
4  broker republishes to notifications.unmatched (fanout) -> queue notifications.unmatched
5  publisher's mandatory flag: satisfied (routed via AE), no basic.return

Real scenario: catching typos in routing keys during a rollout; "or else" routing where specific cases go to specialised queues and the rest to a generic handler (the docs' own example).

Gotcha in the worked example: the audit tap binds # on every domain exchange, so every message is "routed". An AE or mandatory on those exchanges can no longer tell you that no business consumer wanted a message. Use per-binding metrics or put the AE where no catch-all exists (here: the notifications headers exchange).

Dead-letter exchange (pointer) Good to know ​

In plain words: where a queue sends messages it gives up on.

Common misunderstanding: "The DLX is a special exchange type." It is an ordinary exchange, named by the queue argument or policy dead-letter-exchange, optionally with dead-letter-routing-key. It is a routing decision, which is why it appears here: a topic DLX lets one dlq.all queue (bound with #) or per-domain DLQs collect dead letters using the original keys.

Definition and handling: see Dead-Letter Queue, which owns x-death, poison messages and parking lots; retry delays are in Retry, Backoff & Delayed Delivery.

Consistent-hash, modulus-hash and sharding Good to know ​

In plain words: exchange types that split one stream of messages across N queues by hashing, so N consumers can work in parallel.

Common misunderstanding: "A topic exchange with # and four queues spreads load." It copies to all four. Spreading needs hashing.

Definition: x-consistent-hash maps routing keys, a configured hash-header, or supported properties to weighted destinations. Binding keys encode numeric weights; equal weights and one binding per queue are a straightforward starting point. x-modulus-hash selects by hash modulo destination count and ignores binding keys. rabbitmq_sharding manages sharded classic queues; it is not for quorum queues.

What it is for here: routing to a fixed set of queues by key. The ordering consequence (one key always lands in one queue) is owned by Ordering & Partitioning.

Kafka topic design: per event type, per aggregate, per bounded context Must-know ​

In plain words: on Kafka you route by choosing the topic. The main question is which events share a topic.

Common misunderstanding: "One topic per event type is the clean design." Independent topics can interleave a customer update before its creation, especially during backlog replay.

Definition (three granularities):

GranularityExampleOrder across event typesConsumer costACL granularityWhen
Per event typesales.order.placed.v1, sales.order.cancelled.v1NoneReads only what it wantsPer eventIndependent, high-volume events (clicks, views)
Per aggregate (entity)sales.order.events.v1, key = order idPer orderSkips unwanted types (cheap)Per entityEvent-driven services, event sourcing
Per bounded contextsales.events.v1, key = aggregate idPer aggregateSkips morePer domainSmall domains, low volume

Design related records around shared ordering and ownership. Separate unrelated teams and independent high-volume feeds. Filtering some records is often cheaper than fragmenting a domain into many topics. Multiple Avro record types may require TopicRecordNameStrategy or RecordNameStrategy; see Schema Evolution.

Producerskey = order idhash(key) mod 4header type=...topic sales.order.events.v1 (4 partitions)P0o-7placedo-7paido-7shippedP1o-42placedo-42paido-9placedP2o-3placedo-3cancelledP3o-11placedo-11paido-11shippedoffsets grow left to right; order holds per partition onlygroup fulfilmentmember A: P0, P1member B: P2, P3members split partitions(competing consumers)group billingone member: P0..P3own offsets = fan-outtopic sales.order.state.v1 (cleanup.policy=compact)before: o-7 v1, o-42 v1, o-7 v2, o-7 v3, o-42 nullafter compaction: o-7 v3 (o-42 tombstone removed later)latest value per key: state, not historyTopic design choicesper aggregate: one topic, allevent types, key = aggregate idper event type: one topic each,no order across typesper bounded context: one topic,many aggregates, coarse ACLs

Real scenario: sales.order.events.v1 keyed by order id carries placed, paid, cancelled; Fulfilment reacts to placed/cancelled and skips paid; sales.cart.item-viewed.v1 gets its own 48-partition topic so the order consumers never wade through clicks.

Partition count and key: pick the key that defines the ordering unit (order id, account id), and a partition count that covers the consumer parallelism you expect, because Kafka cannot reduce the topic’s partition count and adding partitions remaps keys. Details in Ordering & Partitioning.

Kafka topic naming, compacted topics and topic sprawl Important ​

In plain words: topic names are your routing table and your security model, so give them a hierarchy and never encode things that change.

Common misunderstanding: "I can rename a topic later." Kafka requires a new topic and a migration rather than a direct rename.

Definition:

  • Legal names (Kafka Topic.java): at most 249 characters, ASCII letters, digits, dots, underscores and hyphens only; . and .. are rejected. Topics that differ only by . vs _ can collide in metric names, so pick one separator.
  • Hierarchy: the docs suggest <organization>.<team>.<dataset>.<event-name> or <project>.<product>.<event-name> and recommend excluding consumer identity and partition count from names. This page uses <domain>.<entity>.<event>.v<N> (per event type) and <domain>.<entity>.events.v<N> (per aggregate): our convention.
  • Enforcement: prefixed ACLs (KIP-290, --resource-pattern-type prefixed), a CreateTopicPolicy (KIP-108, create.topic.policy.class.name), and auto.create.topics.enable=false on brokers so a typo does not create a topic.
  • Compacted topics for state: cleanup.policy=compact. Compaction retains the most recent value for each key; older records are removed asynchronously. A null value is a tombstone; consumers see delete markers only if they are not lagging more than delete.retention.ms (default 24 hours). Use a separate ...state.v1 topic for latest-state-per-key and keep history topics on cleanup.policy=delete. Compaction's role in event sourcing is in Event Sourcing & CQRS.

Topic sprawl: per-event-type, per-tenant and per-environment naming multiply (events × tenants × environments). Each topic costs partitions, metadata and ACLs; thousands of tiny topics are an operations problem before they are a performance problem. Collapse dimensions into keys and headers wherever ordering and ACLs allow.

Redis stream naming and sharding Important ​

In plain words: a Redis stream is one key on one node; the key name is the route, and the naming scheme decides how you shard.

Common misunderstanding: "Consumer groups partition a stream like Kafka." They divide delivery work within one stream, not storage across nodes.

Definition:

  • One stream per aggregate type is the default: sales.order.events, with the event type in a field.
  • Per-tenant prefix: t:{acme}:sales.order.events. In Redis Cluster the slot is CRC16(key) mod 16384, and "only the substring between { and } is hashed", so all of one tenant's streams share a slot. That is required for multi-key commands and MULTI across those keys; without it Redis Cluster answers with a CROSSSLOT error.
  • Sharding a hot stream: N keys with an explicit suffix (sales.order.events:{3}) and a stable hash of the aggregate id, the logical-partition model described in the Redis documentation.
  • Laravel prepends database.redis.options.prefix to keys; the hash tag still works because only the braces' content is hashed.

Real scenario: a SaaS with 2,000 tenants puts each tenant's order, invoice and notification streams under one tag, so multi-key operations can address those streams in one Cluster slot. That does not provide rollback or exactly-once processing; one very large tenant gets sharded keys of its own.

Content-based routing Must-know ​

In plain words: deciding the destination by looking at the message, rather than by where it was sent.

Common misunderstanding: "Content-based routing means parsing the JSON body in the broker." No broker here parses your body. RabbitMQ routes on the key and headers; Kafka and Redis do not route on content at all. "Content" in practice means metadata you put there on purpose.

Definition: a Content-Based Router chooses an output channel from message data. A Message Filter discards unwanted inputs; a Recipient List computes multiple destinations. Their deeper mechanics belong to Advanced Routing. Four placement choices follow:

1. Producer2. Broker3. Router process4. Consumerpicks topic / key /stream / Laravel queueKafka topic choice,onQueue(), stream keybindings decide copiesdirect, topic, headersRabbitMQ only; Kafka andRedis have no equivalentconsume, inspect,republish elsewhereEIP Content-Based RouterKafka Streams, Go workerreads all, skips someby header or fieldEIP Message Filtercheap on Kafka, wasteful at 99%Trade-offsProducer: simplest, but the producer must know the routes; adding a consumer can force a producer change.Broker: producers stay ignorant of consumers; a new subscriber is a new queue + binding. Needs topology management.Router: works on any broker and can route on the body; adds a hop, a process to run, and a place for bugs.Consumer: zero topology, every consumer pays to read and skip; fine until most messages are unwanted.Rule of thumb: route on metadata (key, headers), never by parsing payload strings in the broker path.
WhereRabbitMQKafkaRedis StreamsCost
ProducerChoose exchange and keyChoose topic and keyChoose stream keyProducer knows routes
BrokerTopic patterns, headers exchange, AENot availableNot availableTopology to manage
Router processConsume, republishKafka Streams app or Go worker: consume, produceXREADGROUP then XADDExtra hop, extra service
ConsumerRarely needed (bind narrower)Skip by type headerSkip by fieldWasted reads
text
1  Sales:    XADD t:{acme}:sales.order.events * type sales.order.placed.v1 channel sms ...
2  Router:   XREADGROUP GROUP notification-router router-1 STREAMS t:{acme}:sales.order.events >
3  Router:   channel == sms -> target t:{acme}:notifications.sms.events
4  Router:   XADD target with source id; on success XACK source
5  crash between append and ack -> duplicate output; deduplicate by source id
5  SMS svc:  XREADGROUP GROUP sms ... STREAMS t:{acme}:notifications.sms.events >

Fix: put the routing attribute in a header (Kafka record header type, AMQP header, Redis field) at publish time, so every option above can read it without deserialising the body.

Fan-out and fan-in Must-know ​

In plain words: fan-out is one message, many independent receivers; fan-in is many senders, one receiver.

Common misunderstanding: "Adding consumers to a queue gives fan-out." That is competing consumers (load sharing). Fan-out needs one subscription per receiver: a queue, a consumer group.

Definition and per-broker mechanics:

RabbitMQKafkaRedis Streams
Fan-out unitOne queue per subscriber bound to a fanout/topic exchangeOne consumer group per subscriberOne consumer group per subscriber (each group has independent delivery state)
Load sharing inside a subscriberSeveral consumers on that queueGroup members split partitionsGroup members split entries
Fan-inBind one queue to several exchanges/keysOne group subscribes to several topics or a regex (ConsumeRegex)XREADGROUP ... STREAMS a b c (same slot in Cluster)
Order under fan-inPer queue, interleaved by arrivalNone across topicsPer stream only
Aggregation of fanned-in resultsAggregatorKafka Streams join/aggregate (Stream Processing)Application code
text
1  Sales publishes OrderPlaced once
2  fan-out: fulfilment queue/group gets a copy; billing gets a copy; audit gets a copy
3  Fulfilment group has 3 members -> exactly one member processes this copy
4  fan-in: Fulfilment also reads billing.payment.captured from Billing's channel
5  Fulfilment's handler joins both by order id before shipping

Real scenario: order placed fans out to stock, invoicing, email and analytics; a reporting service fans in from every domain's events topic with one regex subscription.

Mechanics ​

How RabbitMQ evaluates a publish. Missing exchanges produce 404 and close the channel. For existing exchanges RabbitMQ resolves bindings and E2E paths into queue destinations; it tries alternate routing if none match. A mandatory unroutable message is returned before its confirm. Broker acceptance does not demonstrate business processing.

Knobs and limits.

KnobProductValue / meaning
Routing key lengthRabbitMQUp to 255 bytes
x-matchRabbitMQ headers bindingall, any, all-with-x, any-with-x
alternate-exchangeRabbitMQ exchange argument or policy keyName of the AE; argument overrides policy
internalRabbitMQ exchange declare flagClients cannot publish to it; only E2E bindings feed it
auto-deleteRabbitMQ exchange/queueDeleted when last binding (exchange) or consumer (queue) goes
dead-letter-exchange, dead-letter-routing-keyRabbitMQ queue argument or policyDLX pointer
hash-headerx-consistent-hash exchange argumentHash a header instead of the key
Topic nameKafkaMax 249 chars, [a-zA-Z0-9._-]
auto.create.topics.enableKafka brokerSet false so typos fail
create.topic.policy.class.nameKafka brokerPlug in a CreateTopicPolicy to enforce names
cleanup.policyKafka topicdelete (history) or compact (latest per key)
delete.retention.msKafka topicTombstone lifetime, default 24 hours
--resource-pattern-typeKafka ACL CLIliteral (default) or prefixed
topic.metadata.refresh.interval.mslibrdkafka (laravel-kafka)When a regex subscription sees new topics
Hash slotsRedis Cluster16384; {tag} limits hashing to the tag

Errors you will meet.

ErrorWhereMeaningFix
312 NO_ROUTE (basic.return)RabbitMQ publish with mandatoryNo queue matched and no AEFix key or bindings; add AE
404 NOT_FOUNDRabbitMQ publish/bindExchange or queue missingDeclare topology before use
406 PRECONDITION_FAILEDRabbitMQ declareRedeclared with different type, flags or argumentsDelete and recreate, or use policies for mutable settings
403 ACCESS_REFUSEDRabbitMQNo configure/write/read permission on the resource, or topic authorisation refused the keyGrant per-vhost permissions
Error on exchange.declare (invalid exchange type)RabbitMQPlugin exchange type not enabledrabbitmq-plugins enable rabbitmq_consistent_hash_exchange
InvalidTopicExceptionKafka create/produceIllegal nameFollow the naming rules
TOPIC_ALREADY_EXISTSKafka createIdempotent setup ran twiceTreat as success
UNKNOWN_TOPIC_OR_PARTITIONKafka produceTopic missing and auto-create offCreate it in the pipeline
TOPIC_AUTHORIZATION_FAILEDKafkaACL denies the principalPrefixed ACL for the domain
CROSSSLOTRedis ClusterMulti-key command over different slotsHash tags
BUSYGROUPRedis XGROUP CREATEGroup existsTreat as success

Topology in code vs definitions. RabbitMQ declarations are idempotent: declaring an existing exchange with the same properties is a no-op, with different ones a 406. Three ways to manage them: (1) each service declares what it owns at start-up (the consumer declares its queue and bindings, the producer its exchange); (2) a definitions file exported with rabbitmqctl export_definitions (which "does not require management plugin to be enabled") and imported at boot or by CI; (3) infrastructure-as-code. Settings that may change (DLX, AE, TTL, max-length) belong in policies, which "can be set via policies" and do not require redeclaring. Kafka topics are created by an admin client (franz-go kadm.CreateTopic) or a platform pipeline; Redis streams appear on first XADD and groups with XGROUP CREATE ... MKSTREAM.

SQL view: routing data lives with the outbox. In a monolith or modular monolith the routing decision is usually made when the event is written, in the same transaction as the business change, and a relay publishes it. Concurrent relays require explicit per-aggregate serialization or stable shard ownership; this query alone permits overtaking. Storing the destination explicitly keeps the relay broker-agnostic (Transactional Outbox, ACID & Transactions).

sql
CREATE TABLE outbox (
    id            bigserial PRIMARY KEY,
    aggregate_id  text        NOT NULL,              -- Kafka key / Redis shard input
    event_type    text        NOT NULL,              -- sales.order.placed.v1
    destination   text        NOT NULL,              -- exchange, topic or stream key
    routing_key   text,                              -- RabbitMQ only
    headers       jsonb       NOT NULL DEFAULT '{}', -- type, tenant, traceparent
    payload       jsonb       NOT NULL,
    created_at    timestamptz NOT NULL DEFAULT now(),
    published_at  timestamptz
);

-- Work claiming only: SKIP LOCKED does not preserve per-aggregate order across concurrent relays.
SELECT id, destination, routing_key, aggregate_id, headers, payload
FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT 500
FOR UPDATE SKIP LOCKED;

Go ​

Example ​

The broker-specific examples below share event names, not identical semantics: amqp091-go declares bindings, franz-go selects topics and keys, and go-redis addresses stream keys. Pure matcher and naming examples in the lab can be tested without a broker.

go
// Command naming checks channel names against the rules each broker enforces
// and against our own convention. It needs no broker.
//
//   - Kafka (clients/.../internals/Topic.java): at most 249 chars, only ASCII
//     alphanumerics, '.', '_' and '-'; "." and ".." are invalid; names that
//     differ only by '.' vs '_' collide in metric names.
//   - Redis Cluster (cluster spec): slot = CRC16(key) mod 16384, and only the
//     text inside the first non-empty {...} is hashed (hash tag).
//   - Our convention (not a broker rule): <domain>.<entity>.<event>.v<N>.
package main

import (
	"fmt"
	"regexp"
	"strings"
)

var legalKafka = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)

// ValidKafkaTopic mirrors Topic.detectInvalidTopic.
func ValidKafkaTopic(name string) error {
	switch {
	case name == "":
		return fmt.Errorf("the empty string is not allowed")
	case name == "." || name == "..":
		return fmt.Errorf("%q is not allowed", name)
	case len(name) > 249:
		return fmt.Errorf("longer than 249 characters")
	case !legalKafka.MatchString(name):
		return fmt.Errorf("%q contains characters other than ASCII alphanumerics, '.', '_' and '-'", name)
	}
	return nil
}

// Collides mirrors Topic.hasCollision: '.' and '_' map to the same metric name.
func Collides(a, b string) bool {
	return strings.ReplaceAll(a, ".", "_") == strings.ReplaceAll(b, ".", "_")
}

var convention = regexp.MustCompile(`^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*\.v[0-9]+$`)

// EventTopic builds <domain>.<entity>.<event>.v<N> and checks both rule sets.
func EventTopic(domain, entity, event string, version int) (string, error) {
	name := fmt.Sprintf("%s.%s.%s.v%d", domain, entity, event, version)
	if err := ValidKafkaTopic(name); err != nil {
		return "", err
	}
	if !convention.MatchString(name) {
		return "", fmt.Errorf("%q breaks the <domain>.<entity>.<event>.v<N> convention", name)
	}
	return name, nil
}

// crc16 is CRC-16/XMODEM (poly 0x1021, init 0), the Redis Cluster key hash.
func crc16(b []byte) uint16 {
	var crc uint16
	for _, c := range b {
		crc ^= uint16(c) << 8
		for i := 0; i < 8; i++ {
			if crc&0x8000 != 0 {
				crc = crc<<1 ^ 0x1021
			} else {
				crc <<= 1
			}
		}
	}
	return crc
}

// HashSlot applies the hash-tag rule from the Redis Cluster specification.
func HashSlot(key string) int {
	if s := strings.IndexByte(key, '{'); s >= 0 {
		if e := strings.IndexByte(key[s+1:], '}'); e > 0 {
			key = key[s+1 : s+1+e]
		}
	}
	return int(crc16([]byte(key)) % 16384)
}

// TenantStream is our per-tenant stream naming: the tenant is the hash tag,
// so every stream of one tenant lands in one slot (multi-key reads work).
func TenantStream(tenant, domain, entity string) string {
	return fmt.Sprintf("t:{%s}:%s.%s.events", tenant, domain, entity)
}

func main() {
	for _, n := range []string{"sales.order.placed.v1", "sales_order.placed.v1", "Sales Order Placed", "."} {
		fmt.Printf("kafka %-24q valid=%v\n", n, ValidKafkaTopic(n) == nil)
	}
	fmt.Println("collide sales.order / sales_order:", Collides("sales.order", "sales_order"))
	if _, err := EventTopic("sales", "order", "Placed", 1); err != nil {
		fmt.Println("convention:", err)
	}
	for _, k := range []string{
		TenantStream("acme", "sales", "order"), TenantStream("acme", "billing", "invoice"),
		TenantStream("globex", "sales", "order"), "sales.order.events", "billing.invoice.events",
	} {
		fmt.Printf("slot %5d  %s\n", HashSlot(k), k)
	}
}

The Go angle ​

Stop before committing a Kafka batch if any handler fails. Restart replays its uncommitted records, including earlier successful records, so handlers must be idempotent. RabbitMQ publishers await confirms with a deadline and check mandatory returns; the amqp091-go context does not interrupt an in-flight socket write, so production connection setup also needs an I/O deadline policy; a timeout means an unknown outcome, not proof of failure.

Laravel ​

Example ​

Laravel uses connections for queue backends and queue names for workload destinations. onConnection() and onQueue() select them; queue:work --queue=high,default prioritizes polling. Laravel 13 Queue::route() supplies defaults for classes, interfaces, traits or parent classes, and Queue::forward() redirects named queues. Explicit job settings can take precedence. The documented driver list includes:

"including the database, Amazon SQS, Redis, and Beanstalkd drivers" — Laravel 13, Queues

RabbitMQ and Kafka require packages; synchronous and null drivers serve immediate execution and discard use cases.

php
<?php

namespace App\Providers;

use App\Jobs\GenerateInvoicePdf;
use App\Jobs\ReserveStock;
use App\Jobs\SendOrderConfirmation;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;

/**
 * Central routing table for in-process jobs (Laravel 13 Queue::route and
 * Queue::forward). Jobs stay ignorant of where they run; ops changes routes
 * here. A job's own onQueue()/onConnection() still overrides this.
 */
class QueueRoutingServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Queue::route([
            ReserveStock::class => ['redis', 'fulfilment'],       // connection, queue
            GenerateInvoicePdf::class => ['redis', 'billing-slow'],
            SendOrderConfirmation::class => 'notifications',     // queue only
        ]);

        // Move a whole queue to new infrastructure without touching jobs.
        Queue::forward('billing-slow', 'billing-slow', 'sqs');
    }
}

With vladimir-yuldashev/laravel-queue-rabbitmq, exchange configuration and exchange_routing_key control routing. %s substitutes the selected queue name into the key; consuming queues still need matching bindings. pushRaw uses mandatory publication, which must not be confused with waiting for a confirm. Failed-job routing has separate reroute_failed, failed_exchange and failed_routing_key options.

php
<?php

// config/queue.php (excerpt). A Laravel "connection" picks the broker; with
// vladimir-yuldashev/laravel-queue-rabbitmq an exchange turns the Laravel
// "queue" name into a routing key: exchange_routing_key '%s' is replaced by
// the queue passed to onQueue() (package source: RabbitMQQueue::getRoutingKey).

return [

    'default' => env('QUEUE_CONNECTION', 'redis'),

    'connections' => [

        // In-process jobs of the monolith: queue names are the routing.
        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 90,
            'block_for' => null,
        ],

        // Integration events of the Sales domain, published to a topic exchange.
        'sales-events' => [
            'driver' => 'rabbitmq',
            // Default key if a job forgets onQueue(): no business binding wants it.
            'queue' => 'sales.missing-key',
            'connection' => 'default',
            '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', '/prod'),
                ],
            ],
            'options' => [
                'queue' => [
                    'exchange' => 'sales.events',
                    'exchange_type' => 'topic',
                    'exchange_routing_key' => '%s',
                    'reroute_failed' => true,
                    'failed_exchange' => 'dlx',
                    'failed_routing_key' => 'failed.%s',
                ],
            ],
        ],

        // The consuming side: the worker reads a queue, not a routing key.
        // php artisan queue:work fulfilment-in --queue=fulfilment.sales-orders
        'fulfilment-in' => [
            'driver' => 'rabbitmq',
            'queue' => 'fulfilment.sales-orders',
            'connection' => 'default',
            'hosts' => [
                [
                    'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                    'port' => env('RABBITMQ_PORT', 5672),
                    'user' => env('RABBITMQ_FULFILMENT_USER', 'fulfilment'),
                    'password' => env('RABBITMQ_FULFILMENT_PASSWORD', 'secret'),
                    'vhost' => env('RABBITMQ_VHOST', '/prod'),
                ],
            ],
        ],
    ],
];
php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

/**
 * Laravel-to-Laravel integration event. The payload is a serialised Laravel
 * job, so only a Laravel consumer with this class can run it; for polyglot
 * consumers publish plain JSON with php-amqplib or laravel-kafka instead.
 */
class OrderPlacedIntegrationEvent implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $orderId,
        public string $tenant,
        public int $totalCents,
    ) {
        // Connection = broker, queue = routing key on the sales.events exchange.
        $this->onConnection('sales-events');
        $this->onQueue('sales.order.placed.v1');
    }

    public function handle(): void
    {
        // Runs in the Fulfilment worker that consumes fulfilment.sales-orders.
    }
}

Bindings are not created by the package when an exchange is set, so declare them in a command run by deployment (php-amqplib, the library the package uses):

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Wire\AMQPTable;

/**
 * php artisan messaging:topology
 *
 * Declares the Fulfilment side of the ordering topology with php-amqplib (the
 * library laravel-queue-rabbitmq is built on). Declarations are idempotent;
 * a declare with different arguments fails with 406 PRECONDITION_FAILED.
 * Note php-amqplib defaults auto_delete to true, so pass false explicitly.
 */
class DeclareOrderingTopology extends Command
{
    protected $signature = 'messaging:topology';

    protected $description = 'Declare exchanges, queues and bindings owned by Fulfilment';

    public function handle(): int
    {
        $conn = new AMQPStreamConnection(
            config('services.rabbitmq.host'),
            (int) config('services.rabbitmq.port'),
            config('services.rabbitmq.user'),
            config('services.rabbitmq.password'),
            config('services.rabbitmq.vhost'),
        );
        $ch = $conn->channel();

        // The publisher's exchange (declared here too so start order does not matter).
        // exchange_declare(name, type, passive, durable, auto_delete)
        $ch->exchange_declare('sales.events', 'topic', false, true, false);
        $ch->exchange_declare('dlx', 'topic', false, true, false);

        // One queue per consuming service and purpose.
        // queue_declare(name, passive, durable, exclusive, auto_delete, nowait, arguments)
        $ch->queue_declare('fulfilment.sales-orders', false, true, false, false, false, new AMQPTable([
            'x-queue-type' => 'quorum',
            'x-dead-letter-exchange' => 'dlx',
        ]));

        // Topic binding: every v1 order event, whatever its name.
        $ch->queue_bind('fulfilment.sales-orders', 'sales.events', 'sales.order.*.v1');

        // Headers exchange for notifications: route on content, not on the key.
        // Same arguments as the Go topology, so the declarations can coexist.
        $ch->exchange_declare('notifications.unmatched', 'fanout', false, true, false);
        $ch->exchange_declare('notifications.route', 'headers', false, true, false, false, false, new AMQPTable([
            'alternate-exchange' => 'notifications.unmatched',
        ]));
        $ch->queue_declare('notifications.unmatched', false, true, false, false, false, new AMQPTable([
            'x-queue-type' => 'quorum',
        ]));
        $ch->queue_bind('notifications.unmatched', 'notifications.unmatched');
        $ch->queue_declare('notifications.sms-vip', false, true, false, false, false, new AMQPTable([
            'x-queue-type' => 'quorum',
            'x-dead-letter-exchange' => 'dlx',
        ]));
        $ch->queue_bind('notifications.sms-vip', 'notifications.route', '', false, new AMQPTable([
            'x-match' => 'all',
            'channel' => 'sms',
            'tier' => 'vip',
        ]));

        // Exchange-to-exchange: exchange_bind(destination, source, routing_key).
        $ch->exchange_declare('audit.all', 'fanout', false, true, false, true);
        $ch->exchange_bind('audit.all', 'sales.events', '#');

        $ch->close();
        $conn->close();
        $this->info('Fulfilment topology declared');

        return self::SUCCESS;
    }
}

Redis Streams from Laravel use the Redis facade, because the redis queue driver uses lists and sorted sets, not streams:

php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;

/**
 * Redis Streams has no exchanges: the stream key is the route. Argument order
 * below is phpredis (key, id, fields); predis differs. Laravel's
 * database.redis.options.prefix is prepended to keys, which keeps the
 * {tenant} hash tag intact because only the text inside braces is hashed.
 */
final class RedisStreamRouter
{
    /** Trusted application identifiers only. Our convention: t:{tenant}:<domain>.<entity>.events */
    public static function stream(string $tenant, string $domain, string $entity): string
    {
        return "t:{{$tenant}}:{$domain}.{$entity}.events";
    }

    /** Fan-out: one consumer group per subscribing service. */
    public static function setupGroups(string $tenant): void
    {
        $orders = self::stream($tenant, 'sales', 'order');
        foreach (['fulfilment', 'billing', 'notification-router'] as $group) {
            try {
                Redis::xgroup('CREATE', $orders, $group, '$', true); // MKSTREAM
            } catch (\Throwable $e) {
                if (! str_contains($e->getMessage(), 'BUSYGROUP')) {
                    throw $e;
                }
            }
        }
    }

    public static function publish(string $tenant, array $fields): string
    {
        return Redis::xadd(self::stream($tenant, 'sales', 'order'), '*', $fields, 1000000, true);
    }

    /** Content-based router: read one stream, append to the matching one, ack. */
    public static function routeOnce(string $tenant): void
    {
        $orders = self::stream($tenant, 'sales', 'order');
        $batch = Redis::xreadgroup('notification-router', 'router-1', [$orders => '>'], 100, 2000) ?: [];

        foreach ($batch as $entries) {
            foreach ($entries as $id => $fields) {
                $target = ($fields['channel'] ?? '') === 'sms'
                    ? self::stream($tenant, 'notifications', 'sms')
                    : self::stream($tenant, 'notifications', 'email');

                $fields['_source_stream'] = $orders;
                $fields['_source_id'] = $id;
                // Publish before ack; deduplicate retries using the source identity.
                if (Redis::xadd($target, '*', $fields) === false) {
                    throw new \RuntimeException('Destination XADD failed; source remains pending');
                }
                Redis::xack($orders, 'notification-router', [$id]);
            }
        }
    }
}

The Laravel angle ​

The Redis facade delegates to phpredis here: iterate the response values because returned stream names may include the configured prefix. Only ignore BUSYGROUP when provisioning groups; network and authorization failures must propagate. The one-shot router has no pending-entry recovery loop; add reclaim and idempotency for a long-running worker. Its naming helpers accept trusted application identifiers only, and the configured prefix must not contain an earlier hash tag.

Broker differences ​

RabbitMQ ​

RabbitMQ is the only one of the three with broker-side routing. The topology below is the whole ordering domain: one topic exchange per domain, one quorum queue per consuming service with a DLX pointer, an internal fanout audit exchange fed by exchange-to-exchange bindings into a stream queue, and a headers exchange with an alternate exchange for notifications. Without AMQP_URL it prints the plan, so it runs on a laptop.

go
// Command topology declares the ordering domain (Sales, Fulfilment, Billing)
// on RabbitMQ. Without AMQP_URL it only prints the plan, so it runs anywhere.
//
// Rules it follows: one topic exchange per domain (the publisher's), one
// queue per consuming service and purpose, keys <domain>.<entity>.<event>.v<N>,
// a DLX pointer per queue, an audit fan-out built from exchange-to-exchange
// bindings, and a headers exchange for content-based routing of notifications
// whose alternate exchange is the "or else" branch.
//
// Gotcha: the audit binding uses "#", so every domain event is "routed". An
// alternate exchange (or the mandatory flag) on the domain exchanges could no
// longer tell you that no business consumer wanted a message.
package main

import (
	"fmt"
	"log"
	"os"

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

type exchange struct {
	name, kind string
	internal   bool
	args       amqp.Table
}

type queue struct {
	name string
	args amqp.Table
}

type binding struct {
	dest, key, source string
	toExchange        bool
	args              amqp.Table
}

// quorum returns queue arguments: replicated quorum queue plus a DLX pointer.
// Prefer policies for DLX in production; see the Dead-Letter Queue chapter.
func quorum(dlx string) amqp.Table {
	return amqp.Table{"x-queue-type": "quorum", "x-dead-letter-exchange": dlx}
}

var exchanges = []exchange{
	// One publishing exchange per domain, owned by that domain.
	{name: "sales.events", kind: "topic"},
	{name: "fulfilment.events", kind: "topic"},
	{name: "billing.events", kind: "topic"},
	{name: "dlx", kind: "topic"},
	// Internal: only other exchanges may publish into it (exchange.bind).
	{name: "audit.all", kind: "fanout", internal: true},
	// Content-based routing on headers, not on the key. Messages no binding
	// matches go to the alternate exchange (policy preferred in production).
	{name: "notifications.route", kind: "headers", args: amqp.Table{"alternate-exchange": "notifications.unmatched"}},
	{name: "notifications.unmatched", kind: "fanout"},
}

var queues = []queue{
	{"fulfilment.sales-orders", quorum("dlx")},
	{"billing.sales-orders", quorum("dlx")},
	{"billing.fulfilment-shipments", quorum("dlx")},
	{"fulfilment.billing-payments", quorum("dlx")},
	{"notifications.unmatched", amqp.Table{"x-queue-type": "quorum"}},
	{"dlq.all", amqp.Table{"x-queue-type": "quorum"}},
	// A stream keeps history for replay; audit readers do not delete it.
	{"audit.archive", amqp.Table{"x-queue-type": "stream", "x-max-age": "30D"}},
	{"notifications.sms-vip", quorum("dlx")},
	{"notifications.email", quorum("dlx")},
}

var bindings = []binding{
	// Fulfilment needs every order lifecycle event of version 1.
	{dest: "fulfilment.sales-orders", key: "sales.order.*.v1", source: "sales.events"},
	// Billing needs only two event types: two exact bindings, same queue.
	{dest: "billing.sales-orders", key: "sales.order.placed.v1", source: "sales.events"},
	{dest: "billing.sales-orders", key: "sales.order.cancelled.v1", source: "sales.events"},
	{dest: "billing.fulfilment-shipments", key: "fulfilment.shipment.dispatched.v1", source: "fulfilment.events"},
	{dest: "fulfilment.billing-payments", key: "billing.payment.captured.v1", source: "billing.events"},
	{dest: "notifications.unmatched", source: "notifications.unmatched"},
	{dest: "dlq.all", key: "#", source: "dlx"},
	// Exchange-to-exchange: every domain exchange feeds the audit fan-out.
	{dest: "audit.all", key: "#", source: "sales.events", toExchange: true},
	{dest: "audit.all", key: "#", source: "fulfilment.events", toExchange: true},
	{dest: "audit.all", key: "#", source: "billing.events", toExchange: true},
	{dest: "audit.archive", source: "audit.all"},
	// Headers exchange: x-match all = every listed header must match.
	{dest: "notifications.sms-vip", source: "notifications.route",
		args: amqp.Table{"x-match": "all", "channel": "sms", "tier": "vip"}},
	// x-match any = one matching header is enough.
	{dest: "notifications.email", source: "notifications.route",
		args: amqp.Table{"x-match": "any", "channel": "email", "fallback": "email"}},
}

func plan() {
	for _, e := range exchanges {
		fmt.Printf("exchange %-22s %-8s internal=%v args=%v\n", e.name, e.kind, e.internal, e.args)
	}
	for _, q := range queues {
		fmt.Printf("queue    %-30s args=%v\n", q.name, q.args)
	}
	for _, b := range bindings {
		kind := "queue"
		if b.toExchange {
			kind = "exchange"
		}
		fmt.Printf("bind     %-20s -[%s]-> %s %s %v\n", b.source, b.key, kind, b.dest, b.args)
	}
}

func apply(ch *amqp.Channel) error {
	for _, e := range exchanges {
		// durable=true, autoDelete=false, noWait=false
		if err := ch.ExchangeDeclare(e.name, e.kind, true, false, e.internal, false, e.args); err != nil {
			return fmt.Errorf("exchange %s: %w", e.name, err)
		}
	}
	for _, q := range queues {
		// durable=true, autoDelete=false, exclusive=false, noWait=false
		if _, err := ch.QueueDeclare(q.name, true, false, false, false, q.args); err != nil {
			return fmt.Errorf("queue %s: %w", q.name, err)
		}
	}
	for _, b := range bindings {
		var err error
		if b.toExchange {
			// ExchangeBind(destination, key, source, ...): messages flow source -> destination.
			err = ch.ExchangeBind(b.dest, b.key, b.source, false, b.args)
		} else {
			err = ch.QueueBind(b.dest, b.key, b.source, false, b.args)
		}
		if err != nil {
			return fmt.Errorf("bind %s -> %s: %w", b.source, b.dest, err)
		}
	}
	return nil
}

func main() {
	url := os.Getenv("AMQP_URL")
	if url == "" {
		plan()
		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)
	}
	// A failed declare (e.g. 406 PRECONDITION_FAILED for changed arguments)
	// closes the channel; topology code must stop, not continue.
	if err := apply(ch); err != nil {
		log.Fatal(err)
	}
	log.Println("topology declared")
}

The producer side: the key is the event name, headers carry content for the headers exchange, mandatory plus NotifyReturn surfaces messages that reached no queue.

go
// Command publish shows the producer side of RabbitMQ routing: the routing
// key carries the event name, headers carry content for a headers exchange,
// and mandatory=true plus NotifyReturn surfaces messages no queue accepted.
package main

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

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

func main() {
	url := os.Getenv("AMQP_URL")
	if url == "" {
		log.Println("AMQP_URL 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)
	}
	if err := ch.Confirm(false); err != nil {
		log.Fatal(err)
	}
	returns := ch.NotifyReturn(make(chan amqp.Return, 16))

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

	// 1. Topic routing: the key is the event name, never the consumer name.
	order := amqp.Publishing{
		ContentType:  "application/json",
		DeliveryMode: amqp.Persistent,
		Type:         "sales.order.placed.v1",
		MessageId:    "evt-01J9Z",
		Body:         []byte(`{"order_id":"o-42","tenant":"acme","total":1990}`),
	}
	if err := publish(ctx, ch, returns, "sales.events", "sales.order.placed.v1", true, false, order); err != nil {
		log.Fatal(err)
	}

	// 2. A typo in the key: no business binding matches. With the audit "#"
	// binding it still counts as routed, which is why that binding hides typos.
	if err := publish(ctx, ch, returns, "sales.events", "sales.oder.placed.v1", true, false, order); err != nil {
		log.Fatal(err)
	}

	// 3. Headers routing: the key is ignored; x-match decides.
	sms := amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		Headers:      amqp.Table{"channel": "sms", "tier": "vip"},
		Body:         []byte(`{"to":"+31...","text":"Your order shipped"}`),
	}
	if err := publish(ctx, ch, returns, "notifications.route", "", true, false, sms); err != nil {
		log.Fatal(err)
	}
}

func publish(ctx context.Context, ch *amqp.Channel, returns <-chan amqp.Return, exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error {
	dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, exchange, key, mandatory, immediate, msg)
	if err != nil {
		return err
	}
	ack, err := dc.WaitContext(ctx)
	if err != nil {
		return err
	}
	if !ack {
		return fmt.Errorf("broker rejected publish")
	}
	// amqp091-go dispatches basic.return before completing the matching confirm.
	select {
	case r, ok := <-returns:
		if ok {
			return fmt.Errorf("returned %d %s exchange=%s key=%s", r.ReplyCode, r.ReplyText, r.Exchange, r.RoutingKey)
		}
	default:
	}
	return nil
}

What breaks: a declare with different arguments returns 406 and closes the channel; a consumer that starts before its producer must declare the exchange too; a missing binding is silent loss unless mandatory, an AE or "unroutable" metrics are watched.

Kafka ​

Kafka has no exchanges and no bindings. Routing is topic choice plus key choice at the producer and group subscription plus filtering at the consumer. The program creates the ordering domain's topics (per-aggregate history topics, a compacted state topic, a separate high-volume topic):

go
// Command topics creates the ordering domain's Kafka topics. Without
// KAFKA_BROKERS it prints the plan. Topic design rules used here:
//
//   - one topic per aggregate stream when order matters across event types
//     (sales.order.events.v1, key = order id), Kleppmann's rule;
//   - one topic per event type only for independent, high-volume events;
//   - a compacted topic for "latest state per key" (sales.order.state.v1);
//   - names <domain>.<entity>.<stream>.v<N>: our convention, enforced with
//     prefixed ACLs on "sales." and auto.create.topics.enable=false.
package main

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

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

type topic struct {
	name       string
	partitions int32
	configs    map[string]*string
}

func ptr(s string) *string { return &s }

var plan = []topic{
	// All order lifecycle events, keyed by order id: placed, paid, cancelled.
	{"sales.order.events.v1", 12, map[string]*string{
		"cleanup.policy": ptr("delete"),
		"retention.ms":   ptr("604800000"), // 7 days
	}},
	// Latest order snapshot per key; a null value (tombstone) deletes it.
	{"sales.order.state.v1", 12, map[string]*string{
		"cleanup.policy":        ptr("compact"),
		"min.compaction.lag.ms": ptr("3600000"),
	}},
	{"fulfilment.shipment.events.v1", 6, nil},
	{"billing.invoice.events.v1", 6, nil},
	// High-volume, independent: its own topic so others need not skip it.
	{"sales.cart.item-viewed.v1", 48, map[string]*string{"retention.ms": ptr("86400000")}},
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		for _, t := range plan {
			fmt.Printf("%-32s partitions=%-3d configs=%s\n", t.name, t.partitions, show(t.configs))
		}
		return
	}
	cl, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...))
	if err != nil {
		log.Fatal(err)
	}
	defer cl.Close()
	adm := kadm.NewClient(cl)
	for _, t := range plan {
		// Replication factor 3; partitions can grow later but never shrink,
		// and growing them remaps keys (see Ordering & Partitioning).
		resp, err := adm.CreateTopic(context.Background(), t.partitions, 3, t.configs, t.name)
		if err != nil {
			log.Fatal(err)
		}
		if resp.Err != nil {
			log.Printf("%s: %v", t.name, resp.Err) // e.g. TOPIC_ALREADY_EXISTS
			continue
		}
		log.Printf("created %s", t.name)
	}
}

func show(m map[string]*string) string {
	var parts []string
	for k, v := range m {
		parts = append(parts, k+"="+*v)
	}
	sort.Strings(parts)
	return strings.Join(parts, " ")
}

The consumer shows fan-in with a regex subscription (franz-go ConsumeTopics + ConsumeRegex) and a consumer-side content-based router on the type header. Each consumer group is an independent subscriber, which is Kafka's fan-out.

go
// Command consume shows the two consumer-side routing tools Kafka has:
// fan-in through a regex subscription, and content-based dispatch on a
// header because the broker cannot filter. Each consumer group gets its own
// copy of every record (fan-out); members of one group split partitions.
package main

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

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

type handler func(context.Context, *kgo.Record) error

// Fulfilment handles three of the order events; it ignores the rest cheaply.
var routes = map[string]handler{
	"sales.order.placed.v1":    reserveStock,
	"sales.order.cancelled.v1": releaseStock,
	"billing.payment.captured.v1": func(ctx context.Context, r *kgo.Record) error {
		log.Printf("ship order %s", r.Key)
		return nil
	},
}

func reserveStock(_ context.Context, r *kgo.Record) error {
	log.Printf("reserve stock for %s", r.Key)
	return nil
}

func releaseStock(_ context.Context, r *kgo.Record) error {
	log.Printf("release stock for %s", r.Key)
	return nil
}

func header(r *kgo.Record, key string) string {
	for _, h := range r.Headers {
		if h.Key == key {
			return string(h.Value)
		}
	}
	return ""
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		log.Println("KAFKA_BROKERS not set; nothing to do")
		return
	}
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(strings.Split(brokers, ",")...),
		// The group id is the subscriber identity: one group per service.
		kgo.ConsumerGroup("fulfilment.order-handler"),
		// Fan-in: every <domain>.<entity>.events.v1 topic of sales and billing.
		// New matching topics are picked up on the next metadata refresh.
		kgo.ConsumeTopics(`^(sales|billing)\.[a-z-]+\.events\.v1$`),
		kgo.ConsumeRegex(),
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer cl.Close()

	ctx := context.Background()
	for {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() {
			return
		}
		fetches.EachError(func(t string, p int32, err error) { log.Printf("fetch %s/%d: %v", t, p, err) })
		if err := dispatchBatch(ctx, fetches.Records(), routes); err != nil {
			log.Printf("%v; stop without committing this batch", err)
			return // Restart replays the batch; handlers must be idempotent.
		}
		if err := cl.CommitUncommittedOffsets(ctx); err != nil {
			log.Printf("commit: %v", err)
		}
	}
}

// A failure stops the whole batch: the caller must not commit past a gap.
func dispatchBatch(ctx context.Context, records []*kgo.Record, handlers map[string]handler) error {
	for _, r := range records {
		h, ok := handlers[header(r, "type")]
		if !ok {
			continue
		} // Intentional Message Filter: safe to commit ignored types.
		if err := h(ctx, r); err != nil {
			return fmt.Errorf("handler %s at %s/%d/%d: %w", header(r, "type"), r.Topic, r.Partition, r.Offset, err)
		}
	}
	return nil
}

What breaks: a typo creates a topic if auto.create.topics.enable is on; splitting one aggregate's events over several topics loses their order; a regex subscription silently starts reading any new matching topic.

Redis Streams ​

Redis has no routing layer: the stream key is the address and a consumer group is the subscription. The program uses the per-tenant hash-tag naming, one group per service for fan-out, and a router group that XADDs to target streams before acknowledging the source. A crash between these operations can duplicate output, so _source_stream and _source_id are retained for downstream deduplication. MULTI does not roll back runtime command errors: a failed XADD must not be followed by an unconditional XACK.

go
// Command streams shows routing on Redis Streams, which has no exchanges:
// the stream key IS the route. It uses one stream per aggregate type,
// a per-tenant hash tag so one tenant's streams share a cluster slot, one
// consumer group per subscribing service (fan-out), and a small router
// process that reads one stream and XADDs to others (content-based router).
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

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

// Inputs here are trusted application constants, not user-supplied tenant IDs.
// Stream is our naming convention, not a Redis rule:
// t:{<tenant>}:<domain>.<entity>.events
func Stream(tenant, domain, entity string) string {
	return fmt.Sprintf("t:{%s}:%s.%s.events", tenant, domain, entity)
}

func ensureGroup(ctx context.Context, rdb *redis.Client, stream, group string) error {
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "$").Err()
	// BUSYGROUP means the group exists already: fine for idempotent setup.
	if err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
		return err
	}
	return nil
}

func main() {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		fmt.Println(Stream("acme", "sales", "order"))
		fmt.Println(Stream("acme", "notifications", "sms"))
		return
	}
	ctx := context.Background()
	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()

	orders := Stream("acme", "sales", "order")
	// Fan-out: each service has its own group, so each sees every entry.
	for _, g := range []string{"fulfilment", "billing", "analytics", "notification-router"} {
		if err := ensureGroup(ctx, rdb, orders, g); err != nil {
			log.Fatal(err)
		}
	}
	// Producer: the event type is a field; MAXLEN ~ bounds memory.
	if err := rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: orders,
		MaxLen: 1_000_000,
		Approx: true,
		Values: map[string]any{"type": "sales.order.placed.v1", "order_id": "o-42", "channel": "sms"},
	}).Err(); err != nil {
		log.Fatal(err)
	}

	// Router: a consumer group of its own that forwards by content.
	if err := ensureGroup(ctx, rdb, orders, "notification-router"); err != nil {
		log.Fatal(err)
	}
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: "notification-router", Consumer: "router-1",
		Streams: []string{orders, ">"}, Count: 100, Block: 2 * time.Second,
	}).Result()
	if err != nil && !errors.Is(err, redis.Nil) {
		log.Fatal(err)
	}
	for _, s := range res {
		for _, m := range s.Messages {
			target := Stream("acme", "notifications", "email")
			if m.Values["channel"] == "sms" {
				target = Stream("acme", "notifications", "sms")
			}
			// Publish first, then ack. A crash between them can duplicate output.
			// MULTI does not roll back command errors; do not ack a failed XADD.
			fields := make(map[string]any, len(m.Values)+2)
			for k, v := range m.Values {
				fields[k] = v
			}
			fields["_source_stream"], fields["_source_id"] = orders, m.ID
			if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: target, Values: fields}).Err(); err != nil {
				log.Fatal(err)
			}
			if err := rdb.XAck(ctx, orders, "notification-router", m.ID).Err(); err != nil {
				log.Fatal(err)
			}
		}
	}
}

What breaks: one stream is one node, so a hot aggregate type needs sharded keys; untagged keys in a multi-key command fail with CROSSSLOT; nothing stops a producer from writing to a misspelled key.

In production systems ​

  • RabbitMQ evaluates exchange bindings as routing metadata; topology durability depends on both endpoints.
  • Kafka applies ACLs to topics and groups, not to arbitrary tenant headers.
  • Redis Cluster places each stream key in one slot; group membership does not repartition storage.
  • Laravel route/forward choose application job destinations; external exchange bindings remain a deployment concern.

Solving the classic problems ​

Adding a subscriber without touching the producer ​

SolutionHowAdvantageCost
RabbitMQ: new queue + bindingqueue.bind analytics.sales sales.events "sales.#"Zero producer change, own backlogBindings to manage
Kafka: new consumer groupgroup.id=analytics on existing topicsCan replay historyMust read and skip unwanted types
Redis: new consumer groupXGROUP CREATE <stream> analytics $ MKSTREAMTrivialOnly entries still in the stream (MAXLEN trims)
Laravel in-processNew listener on the domain eventSame deployNot cross-service

One consumer needs only a subset ​

Bind narrower on RabbitMQ (sales.order.placed.v1 instead of sales.#) or use a headers binding; on Kafka and Redis filter on the type header or field, and split the topic only when the consumer would skip almost everything. With laravel-kafka the producer sets the partition key with withKafkaKey() and the event type with withHeaders(), and the consumer routes in its handler:

php
<?php

namespace App\Messaging;

use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Facades\Kafka;

/**
 * Kafka routing with mateusjunges/laravel-kafka: the topic is the channel,
 * the key picks the partition (and so the order), the "type" header lets
 * consumers route or skip without decoding the body.
 */
final class KafkaOrderEvents
{
    public const TOPIC = 'sales.order.events.v1';

    public static function publishPlaced(string $orderId, string $tenant, int $totalCents): void
    {
        Kafka::publish()
            ->onTopic(self::TOPIC)
            ->withKafkaKey($orderId)
            ->withHeaders([
                'type' => 'sales.order.placed.v1',
                'tenant' => $tenant,
            ])
            ->withBodyKey('order_id', $orderId)
            ->withBodyKey('total_cents', $totalCents)
            ->send();
    }

    /**
     * Fulfilment's consumer group. Regex subscription (topics prefixed with ^)
     * is fan-in from every matching topic; the handler is a content-based router.
     */
    public static function consumeForFulfilment(): void
    {
        $routes = [
            'sales.order.placed.v1' => fn (ConsumerMessage $m) => logger()->info('reserve', $m->getBody()),
            'sales.order.cancelled.v1' => fn (ConsumerMessage $m) => logger()->info('release', $m->getBody()),
        ];

        Kafka::consumer()
            ->subscribe('^sales\..*\.events\.v1$')
            ->withConsumerGroupId('fulfilment.order-handler')
            ->withHandler(function (ConsumerMessage $message) use ($routes): void {
                $type = $message->getHeaders()['type'] ?? null;
                if (! isset($routes[$type])) {
                    return; // not for Fulfilment: skip cheaply
                }
                $routes[$type]($message);
            })
            ->build()
            ->consume();
    }
}

Multi-tenancy ​

OptionRabbitMQKafkaRedis StreamsIsolationCost
Shared channel, tenant in header/keyHeader tenant, or key word acmeHeader tenant, key = tenant + aggregateField tenantLogical onlyCheapest; noisy neighbours
Prefix per tenantExchange acme.sales.eventsTopic acme.sales.order.events.v1 + prefixed ACLt:{acme}:...ACL-levelSprawl grows with tenants
Space per tenantOne vhost per tenant ("logical groups of entities")Cluster per tenantInstance or cluster per tenant (Cluster has database 0 only)StrongOperations multiply

The Kafka multi-tenancy guide combines hierarchical names, prefixed ACLs and quotas to isolate tenants sharing a cluster. Start shared with tenant in the key and headers, promote large or regulated tenants to their own prefix or space.

Environments ​

Do not route environments through one broker by prefix if you can avoid it: a staging consumer bound with # on a shared exchange reads production. Use a vhost per environment on RabbitMQ (permissions are per vhost), a cluster per environment on Kafka (or at least a prefix with ACLs and auto.create.topics.enable=false), and a separate Redis instance or database. The topology code is the same; only connection settings differ.

Routing and ordering ​

Every fan-out copy is ordered independently; fan-in interleaves. On RabbitMQ, one queue preserves publish order from one channel, but two exchanges feeding one queue interleave. On Kafka, order exists only within one partition of one topic, which is why topic granularity and key choice are routing decisions. On Redis, order is per stream key, so sharded keys keep per-key order only if the shard is a stable function of the aggregate id. Deep dive: Ordering & Partitioning.

Routing and security ​

Routing boundaries are where permissions attach. RabbitMQ permissions are configure/write/read regexes per vhost, and topic authorisation can additionally check "the routing key of a message published to a topic exchange" against a regex; Kafka uses literal or prefixed ACLs on topic and group names; Redis ACLs can restrict key patterns (~t:{acme}:*). A naming convention with the domain first makes all three one rule per team. Hardening lives in Messaging Security.

Anti-patterns ​

Anti-patternSymptomBetter
One giant queue or topic for everythingSlow jobs block fast ones, one DLQ for all failures, no per-consumer scalingQueue per consumer and purpose; topic per aggregate
Routing logic in payload stringsRouter parses JSON and regexes on "status":"VIP"; breaks on schema changePut routing attributes in key or headers at publish
Consumer names in keys or topics (sales.to-billing)Every new consumer changes the producerName the event, let consumers bind
Per-request queues for replies or sessionsThousands of queues, churn, memoryDirect reply-to or one reply queue per instance (Request-Reply)
Too many exchanges (one per event type)Hundreds of exchanges with one binding eachOne topic exchange per domain; types are keys
Topic per tenant per event type per envTopic sprawl, controller load, ACL explosionTenant and type in key/headers; prefix only where isolation demands
Catch-all # binding plus AE for "unroutable" alarmsAE never firesWatch per-binding queue rates or move the AE
Events of one aggregate split across topicsConsumers see updates before createsOne topic per aggregate, key = aggregate id
Producer declares consumer queuesProducer must know consumersConsumers declare their own queues and bindings
Clicking topology in the management UIEnvironments driftCode or definitions in Git

Choosing a topology ​

SituationRecommendationExtra techniqueReason
Background jobs inside one Laravel appLaravel queues by name; Queue::route--queue=high,defaultNo broker topology needed
Domain events to a few services, rich selectionRabbitMQ topic exchange per domain, queue per consumerAE on selective exchanges, policies for DLXBroker does the selection
Routing on several independent attributesRabbitMQ headers exchangex-match explicit, AE for the restAvoids encoding attributes in key order
Event log, replay, many consumers, high volumeKafka topic per aggregate, key = aggregate idCompacted state topic beside itOrder per entity, cheap skipping
Independent firehose eventsKafka topic per event typeShort retentionKeeps volume away from others
Latest state per entityKafka compacted topicTombstones for deletesRebuild caches from the log
Small team, Redis already thereRedis stream per aggregate type, group per serviceHash-tagged tenant keys, MAXLENFewest moving parts
SaaS with many small tenantsShared channels, tenant in key/headerPromote big tenants to prefix/spaceAvoid sprawl
Regulated tenant or regionVhost / cluster / prefix with ACLsTopic authorisation, prefixed ACLsIsolation is a requirement
Spread one queue's load by keyx-consistent-hash or Kafka partitionsEqual weightsParallelism with per-key affinity
Audit everythingE2E bindings into an internal fanout → stream queue; Kafka group auditSeparate retentionNo domain changes

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

Monolith (one process, one database) ​

Routing is method calls and Laravel's queue names. An order placed in a controller dispatches ReserveStock to the fulfilment queue and SendOrderConfirmation to notifications, and Queue::route() keeps those decisions in one service provider. Workers are started per queue (queue:work redis --queue=fulfilment), which is the monolith's fan-out to worker pools. Integration events, if any, are written to an outbox table with their destination, so introducing a broker later changes only the relay.

Modular monolith ​

Modules (Sales, Fulfilment, Billing) publish domain events in-process and the boundary becomes visible: each module owns its event names, and other modules subscribe. Use stable versioned names on integration contracts that cross module boundaries; internal domain events need not adopt the external wire vocabulary. A module must not read another module's queue; it gets its own subscription, just as it will after the split.

Microservices ​

The worked topology: Sales publishes sales.order.placed.v1 and sales.order.cancelled.v1; Fulfilment consumes order events and Billing's billing.payment.captured.v1, and publishes fulfilment.shipment.dispatched.v1; Billing consumes placed/cancelled and shipments, and publishes billing.invoice.issued.v1 and billing.payment.captured.v1. The same contract on three brokers:

RabbitMQSalesexchange sales.eventstype topickey sales.order.placed.v1fulfilment.sales-ordersbind sales.order.*.v1Fulfilmentbilling.sales-ordersbind placed + cancelledBillingaudit.all -> audit.archivee2e bind #, stream queueAuditBroker routes: bindings decide copiesKafkaSalestopic sales.order.events.v112 partitionskey = order id, header typegroup fulfilment.order-handlerfilters on type headerFulfilmentgroup billing.order-handlerfilters on type headerBillinggroup analyticsreads everythingAnalyticsTopic choice routes; consumers filterRedis StreamsSalest:{acme}:sales.order.eventsone key per tenant+typeXADD fields type=...group fulfilmentXREADGROUP >Fulfilmentgroup billingXREADGROUP >Billinggroup notification-routerXADD to sms/email streamsRouterKey is the route; router code forwards
FlowRabbitMQKafkaRedis Streams
Sales → Fulfilmentsales.events → fulfilment.sales-orders (sales.order.*.v1)sales.order.events.v1, group fulfilment.order-handlert:{acme}:sales.order.events, group fulfilment
Sales → Billingsales.events → billing.sales-orders (two exact keys)same topic, group billing.order-handler, skip paidsame stream, group billing
Fulfilment → Billingfulfilment.events → billing.fulfilment-shipmentsfulfilment.shipment.events.v1t:{acme}:fulfilment.shipment.events
Billing → Fulfilmentbilling.events → fulfilment.billing-paymentsbilling.invoice.events.v1 (payments as type)t:{acme}:billing.invoice.events
AuditE2E # → audit.all → audit.archive streamgroup audit on all topics (regex)group audit on each stream
Notificationsnotifications.route headers + AErouter service filters on channel headerrouter group XADDs to sms/email streams
text
1  Sales: BEGIN; insert order; insert outbox(destination=sales.events, key=sales.order.placed.v1); COMMIT
2  Relay: publish with confirms; mark outbox row published
3  Broker: copies to fulfilment.sales-orders and billing.sales-orders (+ audit)
4  Billing: captures payment on placed; publishes billing.payment.captured.v1
5  Fulfilment: reserves stock and observes payment; dispatches and publishes fulfilment.shipment.dispatched.v1
6  Billing: observes dispatched for reconciliation (no circular prerequisite)

What survives the service boundary is the contract: event names, keys, headers and the ownership rule (publisher owns the exchange/topic, consumer owns its queue/group). Reliable configurations use at-least-once processing and recovery; storage loss and retention remain separate limits. Consumers therefore should be idempotent; publishing goes through the outbox; the difference between domain and integration events is in Domain Events vs Integration Events, and failure design in Designing for Failure. The sync alternative is in Service Communication.

Distributed data and multi-region ​

Routing across clusters is a different mechanism from routing inside one. RabbitMQ links separate clusters with Federation or Shovel, which forward from an exchange or queue in one cluster to another (see RabbitMQ in Depth); topology must exist on both ends. Kafka mirrors topics between clusters (geo-replication); keep names identical or prefix by source region so consumers know what they read, and remember that keys keep order only within one cluster's partition. Redis replication is per instance; streams in Redis Cluster are sharded by slot, so per-tenant hash tags also decide which node a tenant lives on. Database replicas and their lag affect routing only when a relay reads the outbox from a replica, which it should not (Replication & Failover).

Scaling path ​

LoadRabbitMQKafkaRedis Streams
1×One topic exchange per domain, a queue per consumerTopic per aggregate, 6–12 partitionsOne stream per aggregate type
10×More consumers per queue; split a queue by purpose; quorum queuesRaise partitions early (keys remap); split firehose topicsShard hot streams into N keys by aggregate hash
100×x-consistent-hash over N queues; streams/super streams; separate vhosts or clusters per domainMore partitions, per-domain clusters, mirroringRedis Cluster with tenant hash tags; move the biggest tenants out

Lab (expected, not run) ​

All commands and outputs below are expected, not run. Compile/lint/unit-test checks are separate from these experiments; no Docker or broker labs were started.

  1. Topic wildcard matcher (expected, not run). From docs/snippets/messaging/routing-topologies/go:
go
// Command topicmatch is a pure-Go model of RabbitMQ topic-exchange matching:
// keys are dot-separated words, "*" matches exactly one word and "#" matches
// zero or more words. It needs no broker, so you can run it in the lab.
package main

import (
	"fmt"
	"strings"
)

// Match reports whether a routing key matches a binding pattern.
func Match(pattern, key string) bool {
	return match(strings.Split(pattern, "."), strings.Split(key, "."))
}

func match(p, k []string) bool {
	if len(p) == 0 {
		return len(k) == 0
	}
	switch p[0] {
	case "#":
		// "#" may swallow zero words, or one word and try again.
		if match(p[1:], k) {
			return true
		}
		return len(k) > 0 && match(p, k[1:])
	case "*":
		return len(k) > 0 && match(p[1:], k[1:])
	default:
		return len(k) > 0 && p[0] == k[0] && match(p[1:], k[1:])
	}
}

func main() {
	bindings := []string{"*.orange.*", "*.*.rabbit", "lazy.#", "sales.order.*.v1", "sales.#", "#"}
	keys := []string{
		"quick.orange.rabbit", "lazy.orange.elephant", "quick.orange.fox",
		"lazy.brown.fox", "quick.brown.fox", "orange", "quick.orange.new.rabbit",
		"lazy.orange.new.rabbit", "lazy", "sales.order.placed.v1", "sales.order.placed.v2",
	}
	for _, k := range keys {
		var hits []string
		for _, b := range bindings {
			if Match(b, k) {
				hits = append(hits, b)
			}
		}
		fmt.Printf("%-26s -> %s\n", k, strings.Join(hits, ", "))
	}
}
text
$ go test ./topicmatch/ && go run ./topicmatch/
ok  	academy/routing-topologies/topicmatch
quick.orange.rabbit        -> *.orange.*, *.*.rabbit, #
lazy.orange.elephant       -> *.orange.*, lazy.#, #
quick.orange.fox           -> *.orange.*, #
lazy.brown.fox             -> lazy.#, #
quick.brown.fox            -> #
orange                     -> #
quick.orange.new.rabbit    -> #
lazy.orange.new.rabbit     -> lazy.#, #
lazy                       -> lazy.#, #
sales.order.placed.v1      -> sales.order.*.v1, sales.#, #
sales.order.placed.v2      -> sales.#, #
  1. Names and hash slots (expected, not run): go test ./naming/ && go run ./naming/.
text
kafka "sales.order.placed.v1"  valid=true
kafka "Sales Order Placed"     valid=false
collide sales.order / sales_order: true
convention: "sales.order.Placed.v1" breaks the <domain>.<entity>.<event>.v<N> convention
slot 11304  t:{acme}:sales.order.events
slot 11304  t:{acme}:billing.invoice.events
slot 14041  t:{globex}:sales.order.events
slot 14303  sales.order.events
slot  4073  billing.invoice.events

Both acme streams share slot 11304, so a MULTI over them works in Redis Cluster; the untagged pair lands on different slots.

  1. Topology plan (expected, not run): go run ./rabbitmq/topology/ prints every exchange, queue and binding of the ordering domain (first lines):
text
exchange sales.events           topic    internal=false args=map[]
exchange audit.all              fanout   internal=true args=map[]
queue    fulfilment.sales-orders        args=map[x-dead-letter-exchange:dlx x-queue-type:quorum]
bind     sales.events         -[sales.order.*.v1]-> queue fulfilment.sales-orders map[]
bind     sales.events         -[#]-> exchange audit.all map[]
  1. RabbitMQ routing (expected, not run). With a local broker: AMQP_URL=amqp://guest:guest@localhost:5672/ go run ./rabbitmq/topology/, then go run ./rabbitmq/publish/, then rabbitmqctl list_queues name messages.
text
# expected, not run
fulfilment.sales-orders      1   # placed (key ok) + nothing for the typo
billing.sales-orders         1
audit.archive                2   # the typo is "routed" here: the # binding hides it
notifications.sms-vip        1
# no "returned 312 NO_ROUTE" line: every publish matched at least the audit binding

Remove the three audit.all bindings and publish again: the typo now prints returned 312 NO_ROUTE exchange=sales.events key=sales.oder.placed.v1.

  1. Kafka topics and fan-in (expected, not run). KAFKA_BROKERS=localhost:9092 go run ./kafka/topics/, then kafka-topics.sh --describe --topic sales.order.state.v1 shows cleanup.policy=compact; run go run ./kafka/consume/ and produce a record with header type=sales.order.placed.v1 to sales.order.events.v1: the log prints reserve stock for o-42; a record with type=sales.order.paid.v1 prints nothing (filtered). Create billing.refund.events.v1 while it runs: after the next metadata refresh the consumer reads it too (regex fan-in).

  2. Redis fan-out and router (expected, not run). REDIS_ADDR=localhost:6379 go run ./redis/streams/ then:

text
# expected, not run
> XINFO GROUPS t:{acme}:sales.order.events
fulfilment, billing, analytics, notification-router  (4 groups)
> XLEN t:{acme}:notifications.sms.events
(integer) 1
> XPENDING t:{acme}:sales.order.events notification-router
0   # successful publish followed by ack; interruption can leave pending work

Common misconceptions ​

BeliefReality
A RabbitMQ topic is like a Kafka topicOne is an exchange type that stores nothing; the other is a partitioned log
More consumers on a queue = fan-outThat is competing consumers; fan-out needs a queue or group per subscriber
Direct exchanges deliver to one queueEvery queue bound with the same key gets a copy
* matches any charactersIt matches exactly one dot-separated word; # matches zero or more words
Unroutable messages raise an errorThey are dropped unless mandatory or an alternate exchange is set
Publisher confirm = someone got itConfirms also ack unroutable messages
Two bindings to one queue = two copiesOne copy per queue, even through E2E paths
One topic per event type is cleanest on KafkaIt loses ordering between an entity's events
Kafka can filter messages for a consumerConsumers filter; the broker serves whole partitions
A Redis consumer group partitions a streamPartitions are logical; one stream is one key on one node
Kafka topics can be renamed or shrunkNo rename; partition count can only grow
Laravel onQueue with RabbitMQ names the queue that consumers readWith an exchange configured it is the routing key; consumers read the queue they bound

Cheat sheet ​

TopicRemember
Fan-outOne queue (RabbitMQ) or consumer group (Kafka, Redis) per subscriber
Load sharingMany consumers on one queue / members of one group
Topic key grammarDot-separated words, max 255 bytes; * one word, # zero or more
Our naming<domain>.<entity>.<event>.v<N>; consumer names never appear
Headers exchangex-match all/any (+ -with-x); key ignored
Default exchangeKey = queue name; no custom bindings, no AE
E2E bindingsexchange.bind, one copy per queue, use internal for inner exchanges
Unroutablemandatory → 312 NO_ROUTE return; AE catches; # bindings hide both
DLXQueue argument/policy pointer; details on the DLQ page
Kafka topic granularitySame-order events share a topic and key; per type only for independent firehoses
Kafka names≤ 249 chars, [a-zA-Z0-9._-], no rename, no ./_ mix, auto-create off
Kafka statecleanup.policy=compact, tombstone = null value
Kafka multi-tenancyHierarchical prefix + prefixed ACLs (KIP-290) + quotas
Redis namingStream per aggregate type; t:{tenant}:... hash tag; shard into N keys when hot
LaravelonConnection = broker, onQueue = queue (or routing key), Queue::route/forward centralise
Topology managementConsumers declare their queues/bindings; policies for mutable settings; definitions in Git

Self-check: questions & answers ​

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

1 — A queue is bound to a topic exchange with sales.order.* and sales.#. A message with key sales.order.placed arrives. How many copies does the queue get? Must-know ​

Answer

Answer: One. Both bindings match, but RabbitMQ delivers one copy per queue.

2 — Which keys does audit.events.# match among audit.events, audit.events.orders.placed, audit.users? Must-know ​

Answer

Answer: The first two. # can be zero words; audit.users fails on the second word.

3 — Why does an alternate exchange on sales.events never fire in the worked example? Good to know ​

Answer

Answer: The audit exchange-to-exchange binding uses #, so every message is routed at least to audit.all. AE (and mandatory) only trigger when nothing matches.

4 — You need SMS for VIP customers and email for everyone else, chosen by two attributes. Which exchange type and which x-match? Important ​

Answer

Answer: A headers exchange: bind the SMS queue with x-match=all, channel=sms, tier=vip; use an alternate exchange for the remainder. any is OR over its listed conditions, not the logical complement of SMS-and-VIP.

5 — Why should customer.created and customer.address-changed share a Kafka topic? Must-know ​

Answer

Answer: Order is only kept within a partition of one topic. Separate topics let a consumer see the address change before the creation, especially after downtime (Kleppmann).

6 — Your Kafka topic sales.order.events.v1 has 6 partitions and you need 24 consumers in one group. What happens if you raise partitions to 24? Important ​

Answer

Answer: It works for parallelism, but keys are rehashed to different partitions, so per-key order is broken across the change. Kafka cannot reduce partitions later.

7 — Name three ways to stop a typo from creating a Kafka topic or reaching the wrong tenant. Important ​

Answer

Answer: auto.create.topics.enable=false, a CreateTopicPolicy that enforces the naming pattern, and prefixed ACLs so a principal can only create or write under its prefix.

8 — Two streams t:{acme}:sales.order.events and t:{acme}:notifications.sms.events: can a Redis Cluster MULTI touch both? And sales.order.events with billing.invoice.events? Important ​

Answer

Answer: Yes for the first pair: the hash tag acme puts both in one slot. Probably not for the second: different slots give CROSSSLOT.

9 — In Laravel with laravel-queue-rabbitmq and exchange => 'sales.events', what does onQueue('sales.order.placed.v1') mean, and which queue does Fulfilment's worker read? Important ​

Answer

Answer: It becomes the routing key (via exchange_routing_key %s). Fulfilment's worker reads its own bound queue, for example queue:work fulfilment-in --queue=fulfilment.sales-orders.

10 — When is a consumer-side filter on Kafka acceptable, and when should you split the topic? Must-know ​

Answer

Answer: Acceptable when the consumer skips a moderate share; Kleppmann suggests splitting only when nearly all messages (around 99.9%) are unwanted or one type's volume overwhelms others.

Glossary ​

TermMeaning
ExchangeRabbitMQ routing entity that copies messages to queues, streams or exchanges
BindingRule linking an exchange to a destination, with a key and optional arguments
Routing keyAddress set by the publisher on a message
Binding keyKey or pattern a binding uses to match routing keys
Direct exchangeRoutes on exact key equality
Fanout exchangeCopies to every bound destination, ignores the key
Topic exchangeMatches dot-separated keys with * and #
Headers exchangeMatches header values with x-match
x-matchHeaders binding argument: all, any, all-with-x, any-with-x
Default exchangeNameless direct exchange; every queue bound by its name
amq.direct, amq.topic, amq.fanout, amq.headersPre-declared exchanges in every vhost
Exchange-to-exchange bindingexchange.bind: one exchange feeds another
Internal exchangeCannot be published to by clients
Alternate exchange (AE), alternate-exchangeReceives messages an exchange could not route
mandatoryPublish flag: return unroutable messages (312 NO_ROUTE)
Dead-letter exchange (DLX), dead-letter-exchangeExchange a queue republishes rejected or expired messages to
x-consistent-hashPlugin exchange hashing key or header onto a weighted ring
x-modulus-hashCore exchange: hash mod number of bound queues
rabbitmq_shardingPlugin creating sharded classic queues per node
Local random exchangeRabbitMQ 4.0 type delivering to a random local queue for RPC
VhostRabbitMQ namespace for exchanges, queues, bindings, permissions
Topic authorisationRabbitMQ check of the routing key against a permission regex
DefinitionsExported/imported JSON of RabbitMQ topology (export_definitions)
PolicyServer-side rule applying arguments (AE, DLX, TTL) to matching entities
Kafka topicNamed, partitioned, replicated log
Consumer groupSet of consumers sharing a subscription and offsets; one per subscriber
Topic per aggregateAll event types of an aggregate type in one topic, keyed by entity id
Compacted topiccleanup.policy=compact: keeps the latest value per key
TombstoneRecord with a null value that deletes a key in a compacted topic
Prefixed ACLKafka ACL on all resources starting with a prefix (KIP-290)
CreateTopicPolicyKafka broker plug-in that validates topic creation (KIP-108)
Topic sprawlUncontrolled growth in topic count from encoding dimensions in names
Redis streamAppend-only log stored in one key
Hash tag{...} part of a Redis key that alone decides the cluster slot
Hash slotOne of 16384 Redis Cluster shards, CRC16(key) mod 16384
CROSSSLOTRedis Cluster error for multi-key commands spanning slots
Publish-Subscribe ChannelEIP: each subscriber receives a copy
Content-Based RouterEIP: chooses the output channel from message content
Message FilterEIP: one-output router that drops unwanted messages
Recipient ListEIP: sends to a computed list of channels
Fan-outOne message to many independent subscribers
Fan-inMany sources into one consumer or channel
onQueue / onConnectionLaravel job methods choosing queue and connection
Queue::route / Queue::forwardLaravel 13 central job routing and queue forwarding
exchange_routing_keylaravel-queue-rabbitmq option; %s becomes the queue name
Multi-tenant topologyChannel layout separating tenants by key, prefix or space
PRECONDITION_FAILEDRabbitMQ 406 channel error when an existing declaration differs
Quorum queueRabbitMQ replicated queue type, independent of its exchange routing rule
Topic per event type / per aggregateSeparate type channels versus a shared aggregate-type history keyed by entity id
Bounded contextModel and ownership boundary used to group related event channels
auto.create.topics.enableKafka broker control for automatic topic creation
Kafka name limitAt most 249 legal characters; no arbitrary consumer identity in names
ConsumeRegexfranz-go subscription to topics whose names match the supplied regex
XREADGROUP, XADD, XACKRedis group read, append, and acknowledgement operations
laravel-kafka, withKafkaKeyKafka integration package and its record-key selector
auto-deleteRabbitMQ lifecycle setting; conditions differ for queues and exchanges

References ​

Built by Morteza Negahi