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 for | Go to |
|---|---|
| The whole topic in three tables | Everything in one minute |
| Why routing is a design problem at all | Why routing topology exists |
| AMQP, EIP and Kleppmann's topic rule | Where it comes from |
| Routing key vs binding key, bindings | Routing key, binding key and binding |
| Direct, fanout, topic, headers, default exchange | Exchange types |
* and #, the key grammar | Topic exchange |
x-match all/any | Headers exchange |
| Exchange-to-exchange, alternate exchange, DLX pointer | E2E, AE, DLX |
| Consistent-hash, modulus-hash, sharding plugin | Hash exchanges |
| One topic per event type or per aggregate? | Kafka topic design |
| Topic names, compaction, sprawl, ACLs | Kafka naming |
| Stream keys, tenants, hash tags | Redis stream naming |
| Producer vs broker vs consumer routing | Content-based routing |
| Fan-out and fan-in on each broker | Fan-out and fan-in |
| Knobs, limits, error codes, topology as code | Mechanics |
| Language integration and client caveats | Go, Laravel |
| Per-broker implementation with code | Broker differences |
| New consumers, tenants, environments, ordering, security | Solving the classic problems |
| What not to do | Anti-patterns |
| A decision table | Choosing a topology |
| Monolith to multi-region, with the Sales/Fulfilment/Billing example | In architecture |
| Runnable programs and broker experiments | Lab |
Everything in one minute
The routing primitive on each broker.
| Question | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| What does a producer write to? | An exchange, with a routing key | A topic (and a key that picks the partition) | A stream key (XADD) |
| Who decides which consumers get a copy? | The broker, using bindings | The consumer, by subscribing a consumer group | The consumer, by creating a consumer group |
| Can the broker filter on content? | Yes: topic patterns, headers exchange | No (consumers filter) | No (consumers filter) |
| Fan-out mechanism | One queue per subscriber, bound to the exchange | One consumer group per subscriber | One consumer group per subscriber |
| Fan-in mechanism | Many exchanges or keys bound to one queue | Regex subscription or several topics in one group | XREADGROUP over several streams |
| Unroutable message | Dropped, returned (mandatory) or sent to an alternate exchange | Impossible: the topic exists or the write fails | Impossible: XADD creates the key |
| Naming limits | Routing key max 255 bytes | Topic 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.
| Type | Routes on | Tiny example | Typical use |
|---|---|---|---|
| Direct | Exact routing key equality | key invoice.pdf → queue bound with invoice.pdf | Task routing by job type |
| Fanout | Nothing: every bound queue | price update → every cache node | Broadcast, audit tap |
| Topic | Pattern on dot-separated words | sales.order.*.v1 matches sales.order.placed.v1 | Domain events, selective subscribers |
| Headers | Header values, x-match all/any | channel=sms, tier=vip | Routing on several attributes |
Default ("") | Key = queue name | publish to "" with key emails | "Send to this queue" |
x-consistent-hash (plugin) | Hash of key or header onto a ring | spread order_id over 4 queues | Partitioning queues |
x-modulus-hash (core) | Hash of key mod N | sharding plugin's shards | Sharded classic queues |
| Local random (4.0+) | Random local queue | RPC servers | Request-reply latency |
The design rules this page defends.
| Rule | Why |
|---|---|
| One publishing exchange (or topic family) per domain, owned by the producer | Ownership and ACLs follow domain boundaries |
| One queue per consuming service and purpose | Each subscriber gets its own copy, backlog, DLQ and scaling |
| Routing keys and topic names describe the event, never the consumer | Adding a consumer must not change the producer |
| Events that must stay ordered share a topic and a key | Kafka orders only within a partition |
| Route on metadata (key, headers), not on payload strings | The broker cannot read your JSON; parsing in the router is fragile |
| Topology is code or definitions in version control, not clicks | Reproducible 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 producer | Routing in the broker or a declared topology |
|---|---|
| Producer must know every consumer | Producer knows only its own exchange or topic |
| Adding a subscriber = deploy the producer | Adding a subscriber = declare a queue/binding or group |
| No extra infrastructure | Topology to name, version and secure |
| Easy to reason about locally | Easy to reason about globally (one map) |
| Couples teams | Decouples 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
- "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.
- "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.
- "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.
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-ordersReal 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 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.
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.#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.
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.
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.returnReal 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):
| Granularity | Example | Order across event types | Consumer cost | ACL granularity | When |
|---|---|---|---|---|---|
| Per event type | sales.order.placed.v1, sales.order.cancelled.v1 | None | Reads only what it wants | Per event | Independent, high-volume events (clicks, views) |
| Per aggregate (entity) | sales.order.events.v1, key = order id | Per order | Skips unwanted types (cheap) | Per entity | Event-driven services, event sourcing |
| Per bounded context | sales.events.v1, key = aggregate id | Per aggregate | Skips more | Per domain | Small 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.
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), aCreateTopicPolicy(KIP-108,create.topic.policy.class.name), andauto.create.topics.enable=falseon 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 thandelete.retention.ms(default 24 hours). Use a separate...state.v1topic for latest-state-per-key and keep history topics oncleanup.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 isCRC16(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 andMULTIacross those keys; without it Redis Cluster answers with aCROSSSLOTerror. - 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.prefixto 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:
| Where | RabbitMQ | Kafka | Redis Streams | Cost |
|---|---|---|---|---|
| Producer | Choose exchange and key | Choose topic and key | Choose stream key | Producer knows routes |
| Broker | Topic patterns, headers exchange, AE | Not available | Not available | Topology to manage |
| Router process | Consume, republish | Kafka Streams app or Go worker: consume, produce | XREADGROUP then XADD | Extra hop, extra service |
| Consumer | Rarely needed (bind narrower) | Skip by type header | Skip by field | Wasted reads |
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:
| RabbitMQ | Kafka | Redis Streams | |
|---|---|---|---|
| Fan-out unit | One queue per subscriber bound to a fanout/topic exchange | One consumer group per subscriber | One consumer group per subscriber (each group has independent delivery state) |
| Load sharing inside a subscriber | Several consumers on that queue | Group members split partitions | Group members split entries |
| Fan-in | Bind one queue to several exchanges/keys | One group subscribes to several topics or a regex (ConsumeRegex) | XREADGROUP ... STREAMS a b c (same slot in Cluster) |
| Order under fan-in | Per queue, interleaved by arrival | None across topics | Per stream only |
| Aggregation of fanned-in results | Aggregator | Kafka Streams join/aggregate (Stream Processing) | Application code |
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 shippingReal 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.
| Knob | Product | Value / meaning |
|---|---|---|
| Routing key length | RabbitMQ | Up to 255 bytes |
x-match | RabbitMQ headers binding | all, any, all-with-x, any-with-x |
alternate-exchange | RabbitMQ exchange argument or policy key | Name of the AE; argument overrides policy |
internal | RabbitMQ exchange declare flag | Clients cannot publish to it; only E2E bindings feed it |
auto-delete | RabbitMQ exchange/queue | Deleted when last binding (exchange) or consumer (queue) goes |
dead-letter-exchange, dead-letter-routing-key | RabbitMQ queue argument or policy | DLX pointer |
hash-header | x-consistent-hash exchange argument | Hash a header instead of the key |
| Topic name | Kafka | Max 249 chars, [a-zA-Z0-9._-] |
auto.create.topics.enable | Kafka broker | Set false so typos fail |
create.topic.policy.class.name | Kafka broker | Plug in a CreateTopicPolicy to enforce names |
cleanup.policy | Kafka topic | delete (history) or compact (latest per key) |
delete.retention.ms | Kafka topic | Tombstone lifetime, default 24 hours |
--resource-pattern-type | Kafka ACL CLI | literal (default) or prefixed |
topic.metadata.refresh.interval.ms | librdkafka (laravel-kafka) | When a regex subscription sees new topics |
| Hash slots | Redis Cluster | 16384; {tag} limits hashing to the tag |
Errors you will meet.
| Error | Where | Meaning | Fix |
|---|---|---|---|
312 NO_ROUTE (basic.return) | RabbitMQ publish with mandatory | No queue matched and no AE | Fix key or bindings; add AE |
404 NOT_FOUND | RabbitMQ publish/bind | Exchange or queue missing | Declare topology before use |
406 PRECONDITION_FAILED | RabbitMQ declare | Redeclared with different type, flags or arguments | Delete and recreate, or use policies for mutable settings |
403 ACCESS_REFUSED | RabbitMQ | No configure/write/read permission on the resource, or topic authorisation refused the key | Grant per-vhost permissions |
Error on exchange.declare (invalid exchange type) | RabbitMQ | Plugin exchange type not enabled | rabbitmq-plugins enable rabbitmq_consistent_hash_exchange |
InvalidTopicException | Kafka create/produce | Illegal name | Follow the naming rules |
TOPIC_ALREADY_EXISTS | Kafka create | Idempotent setup ran twice | Treat as success |
UNKNOWN_TOPIC_OR_PARTITION | Kafka produce | Topic missing and auto-create off | Create it in the pipeline |
TOPIC_AUTHORIZATION_FAILED | Kafka | ACL denies the principal | Prefixed ACL for the domain |
CROSSSLOT | Redis Cluster | Multi-key command over different slots | Hash tags |
BUSYGROUP | Redis XGROUP CREATE | Group exists | Treat 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).
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.
// 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
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
// 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
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
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
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.
// 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.
// 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):
// 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.
// 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.
// 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| RabbitMQ: new queue + binding | queue.bind analytics.sales sales.events "sales.#" | Zero producer change, own backlog | Bindings to manage |
| Kafka: new consumer group | group.id=analytics on existing topics | Can replay history | Must read and skip unwanted types |
| Redis: new consumer group | XGROUP CREATE <stream> analytics $ MKSTREAM | Trivial | Only entries still in the stream (MAXLEN trims) |
| Laravel in-process | New listener on the domain event | Same deploy | Not 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
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
| Option | RabbitMQ | Kafka | Redis Streams | Isolation | Cost |
|---|---|---|---|---|---|
| Shared channel, tenant in header/key | Header tenant, or key word acme | Header tenant, key = tenant + aggregate | Field tenant | Logical only | Cheapest; noisy neighbours |
| Prefix per tenant | Exchange acme.sales.events | Topic acme.sales.order.events.v1 + prefixed ACL | t:{acme}:... | ACL-level | Sprawl grows with tenants |
| Space per tenant | One vhost per tenant ("logical groups of entities") | Cluster per tenant | Instance or cluster per tenant (Cluster has database 0 only) | Strong | Operations 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-pattern | Symptom | Better |
|---|---|---|
| One giant queue or topic for everything | Slow jobs block fast ones, one DLQ for all failures, no per-consumer scaling | Queue per consumer and purpose; topic per aggregate |
| Routing logic in payload strings | Router parses JSON and regexes on "status":"VIP"; breaks on schema change | Put routing attributes in key or headers at publish |
Consumer names in keys or topics (sales.to-billing) | Every new consumer changes the producer | Name the event, let consumers bind |
| Per-request queues for replies or sessions | Thousands of queues, churn, memory | Direct reply-to or one reply queue per instance (Request-Reply) |
| Too many exchanges (one per event type) | Hundreds of exchanges with one binding each | One topic exchange per domain; types are keys |
| Topic per tenant per event type per env | Topic sprawl, controller load, ACL explosion | Tenant and type in key/headers; prefix only where isolation demands |
Catch-all # binding plus AE for "unroutable" alarms | AE never fires | Watch per-binding queue rates or move the AE |
| Events of one aggregate split across topics | Consumers see updates before creates | One topic per aggregate, key = aggregate id |
| Producer declares consumer queues | Producer must know consumers | Consumers declare their own queues and bindings |
| Clicking topology in the management UI | Environments drift | Code or definitions in Git |
Choosing a topology
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Background jobs inside one Laravel app | Laravel queues by name; Queue::route | --queue=high,default | No broker topology needed |
| Domain events to a few services, rich selection | RabbitMQ topic exchange per domain, queue per consumer | AE on selective exchanges, policies for DLX | Broker does the selection |
| Routing on several independent attributes | RabbitMQ headers exchange | x-match explicit, AE for the rest | Avoids encoding attributes in key order |
| Event log, replay, many consumers, high volume | Kafka topic per aggregate, key = aggregate id | Compacted state topic beside it | Order per entity, cheap skipping |
| Independent firehose events | Kafka topic per event type | Short retention | Keeps volume away from others |
| Latest state per entity | Kafka compacted topic | Tombstones for deletes | Rebuild caches from the log |
| Small team, Redis already there | Redis stream per aggregate type, group per service | Hash-tagged tenant keys, MAXLEN | Fewest moving parts |
| SaaS with many small tenants | Shared channels, tenant in key/header | Promote big tenants to prefix/space | Avoid sprawl |
| Regulated tenant or region | Vhost / cluster / prefix with ACLs | Topic authorisation, prefixed ACLs | Isolation is a requirement |
| Spread one queue's load by key | x-consistent-hash or Kafka partitions | Equal weights | Parallelism with per-key affinity |
| Audit everything | E2E bindings into an internal fanout → stream queue; Kafka group audit | Separate retention | No 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:
| Flow | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| Sales → Fulfilment | sales.events → fulfilment.sales-orders (sales.order.*.v1) | sales.order.events.v1, group fulfilment.order-handler | t:{acme}:sales.order.events, group fulfilment |
| Sales → Billing | sales.events → billing.sales-orders (two exact keys) | same topic, group billing.order-handler, skip paid | same stream, group billing |
| Fulfilment → Billing | fulfilment.events → billing.fulfilment-shipments | fulfilment.shipment.events.v1 | t:{acme}:fulfilment.shipment.events |
| Billing → Fulfilment | billing.events → fulfilment.billing-payments | billing.invoice.events.v1 (payments as type) | t:{acme}:billing.invoice.events |
| Audit | E2E # → audit.all → audit.archive stream | group audit on all topics (regex) | group audit on each stream |
| Notifications | notifications.route headers + AE | router service filters on channel header | router group XADDs to sms/email streams |
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
| Load | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| 1× | One topic exchange per domain, a queue per consumer | Topic per aggregate, 6–12 partitions | One stream per aggregate type |
| 10× | More consumers per queue; split a queue by purpose; quorum queues | Raise partitions early (keys remap); split firehose topics | Shard hot streams into N keys by aggregate hash |
| 100× | x-consistent-hash over N queues; streams/super streams; separate vhosts or clusters per domain | More partitions, per-domain clusters, mirroring | Redis 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.
- Topic wildcard matcher (expected, not run). From
docs/snippets/messaging/routing-topologies/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, ", "))
}
}$ 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.#, #- Names and hash slots (expected, not run):
go test ./naming/ && go run ./naming/.
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.eventsBoth acme streams share slot 11304, so a MULTI over them works in Redis Cluster; the untagged pair lands on different slots.
- Topology plan (expected, not run):
go run ./rabbitmq/topology/prints every exchange, queue and binding of the ordering domain (first lines):
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[]- RabbitMQ routing (expected, not run). With a local broker:
AMQP_URL=amqp://guest:guest@localhost:5672/ go run ./rabbitmq/topology/, thengo run ./rabbitmq/publish/, thenrabbitmqctl list_queues name messages.
# 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 bindingRemove the three audit.all bindings and publish again: the typo now prints returned 312 NO_ROUTE exchange=sales.events key=sales.oder.placed.v1.
Kafka topics and fan-in (expected, not run).
KAFKA_BROKERS=localhost:9092 go run ./kafka/topics/, thenkafka-topics.sh --describe --topic sales.order.state.v1showscleanup.policy=compact; rungo run ./kafka/consume/and produce a record with headertype=sales.order.placed.v1tosales.order.events.v1: the log printsreserve stock for o-42; a record withtype=sales.order.paid.v1prints nothing (filtered). Createbilling.refund.events.v1while it runs: after the next metadata refresh the consumer reads it too (regex fan-in).Redis fan-out and router (expected, not run).
REDIS_ADDR=localhost:6379 go run ./redis/streams/then:
# 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 workCommon misconceptions
| Belief | Reality |
|---|---|
| A RabbitMQ topic is like a Kafka topic | One is an exchange type that stores nothing; the other is a partitioned log |
| More consumers on a queue = fan-out | That is competing consumers; fan-out needs a queue or group per subscriber |
| Direct exchanges deliver to one queue | Every queue bound with the same key gets a copy |
* matches any characters | It matches exactly one dot-separated word; # matches zero or more words |
| Unroutable messages raise an error | They are dropped unless mandatory or an alternate exchange is set |
| Publisher confirm = someone got it | Confirms also ack unroutable messages |
| Two bindings to one queue = two copies | One copy per queue, even through E2E paths |
| One topic per event type is cleanest on Kafka | It loses ordering between an entity's events |
| Kafka can filter messages for a consumer | Consumers filter; the broker serves whole partitions |
| A Redis consumer group partitions a stream | Partitions are logical; one stream is one key on one node |
| Kafka topics can be renamed or shrunk | No rename; partition count can only grow |
Laravel onQueue with RabbitMQ names the queue that consumers read | With an exchange configured it is the routing key; consumers read the queue they bound |
Cheat sheet
| Topic | Remember |
|---|---|
| Fan-out | One queue (RabbitMQ) or consumer group (Kafka, Redis) per subscriber |
| Load sharing | Many consumers on one queue / members of one group |
| Topic key grammar | Dot-separated words, max 255 bytes; * one word, # zero or more |
| Our naming | <domain>.<entity>.<event>.v<N>; consumer names never appear |
| Headers exchange | x-match all/any (+ -with-x); key ignored |
| Default exchange | Key = queue name; no custom bindings, no AE |
| E2E bindings | exchange.bind, one copy per queue, use internal for inner exchanges |
| Unroutable | mandatory → 312 NO_ROUTE return; AE catches; # bindings hide both |
| DLX | Queue argument/policy pointer; details on the DLQ page |
| Kafka topic granularity | Same-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 state | cleanup.policy=compact, tombstone = null value |
| Kafka multi-tenancy | Hierarchical prefix + prefixed ACLs (KIP-290) + quotas |
| Redis naming | Stream per aggregate type; t:{tenant}:... hash tag; shard into N keys when hot |
| Laravel | onConnection = broker, onQueue = queue (or routing key), Queue::route/forward centralise |
| Topology management | Consumers declare their queues/bindings; policies for mutable settings; definitions in Git |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A 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
| Term | Meaning |
|---|---|
| Exchange | RabbitMQ routing entity that copies messages to queues, streams or exchanges |
| Binding | Rule linking an exchange to a destination, with a key and optional arguments |
| Routing key | Address set by the publisher on a message |
| Binding key | Key or pattern a binding uses to match routing keys |
| Direct exchange | Routes on exact key equality |
| Fanout exchange | Copies to every bound destination, ignores the key |
| Topic exchange | Matches dot-separated keys with * and # |
| Headers exchange | Matches header values with x-match |
x-match | Headers binding argument: all, any, all-with-x, any-with-x |
| Default exchange | Nameless direct exchange; every queue bound by its name |
amq.direct, amq.topic, amq.fanout, amq.headers | Pre-declared exchanges in every vhost |
| Exchange-to-exchange binding | exchange.bind: one exchange feeds another |
| Internal exchange | Cannot be published to by clients |
Alternate exchange (AE), alternate-exchange | Receives messages an exchange could not route |
mandatory | Publish flag: return unroutable messages (312 NO_ROUTE) |
Dead-letter exchange (DLX), dead-letter-exchange | Exchange a queue republishes rejected or expired messages to |
x-consistent-hash | Plugin exchange hashing key or header onto a weighted ring |
x-modulus-hash | Core exchange: hash mod number of bound queues |
rabbitmq_sharding | Plugin creating sharded classic queues per node |
| Local random exchange | RabbitMQ 4.0 type delivering to a random local queue for RPC |
| Vhost | RabbitMQ namespace for exchanges, queues, bindings, permissions |
| Topic authorisation | RabbitMQ check of the routing key against a permission regex |
| Definitions | Exported/imported JSON of RabbitMQ topology (export_definitions) |
| Policy | Server-side rule applying arguments (AE, DLX, TTL) to matching entities |
| Kafka topic | Named, partitioned, replicated log |
| Consumer group | Set of consumers sharing a subscription and offsets; one per subscriber |
| Topic per aggregate | All event types of an aggregate type in one topic, keyed by entity id |
| Compacted topic | cleanup.policy=compact: keeps the latest value per key |
| Tombstone | Record with a null value that deletes a key in a compacted topic |
| Prefixed ACL | Kafka ACL on all resources starting with a prefix (KIP-290) |
CreateTopicPolicy | Kafka broker plug-in that validates topic creation (KIP-108) |
| Topic sprawl | Uncontrolled growth in topic count from encoding dimensions in names |
| Redis stream | Append-only log stored in one key |
| Hash tag | {...} part of a Redis key that alone decides the cluster slot |
| Hash slot | One of 16384 Redis Cluster shards, CRC16(key) mod 16384 |
CROSSSLOT | Redis Cluster error for multi-key commands spanning slots |
| Publish-Subscribe Channel | EIP: each subscriber receives a copy |
| Content-Based Router | EIP: chooses the output channel from message content |
| Message Filter | EIP: one-output router that drops unwanted messages |
| Recipient List | EIP: sends to a computed list of channels |
| Fan-out | One message to many independent subscribers |
| Fan-in | Many sources into one consumer or channel |
onQueue / onConnection | Laravel job methods choosing queue and connection |
Queue::route / Queue::forward | Laravel 13 central job routing and queue forwarding |
exchange_routing_key | laravel-queue-rabbitmq option; %s becomes the queue name |
| Multi-tenant topology | Channel layout separating tenants by key, prefix or space |
PRECONDITION_FAILED | RabbitMQ 406 channel error when an existing declaration differs |
| Quorum queue | RabbitMQ replicated queue type, independent of its exchange routing rule |
| Topic per event type / per aggregate | Separate type channels versus a shared aggregate-type history keyed by entity id |
| Bounded context | Model and ownership boundary used to group related event channels |
auto.create.topics.enable | Kafka broker control for automatic topic creation |
| Kafka name limit | At most 249 legal characters; no arbitrary consumer identity in names |
ConsumeRegex | franz-go subscription to topics whose names match the supplied regex |
XREADGROUP, XADD, XACK | Redis group read, append, and acknowledgement operations |
laravel-kafka, withKafkaKey | Kafka integration package and its record-key selector |
auto-delete | RabbitMQ lifecycle setting; conditions differ for queues and exchanges |
References
- RabbitMQ, Exchanges (source markdown): https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/exchanges.md
- RabbitMQ, AMQP 0-9-1 Model Explained: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/amqp-concepts/index.md
- RabbitMQ, Tutorial five: Topics (Go): https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-five-go.md
- RabbitMQ, Exchange to Exchange Bindings: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/e2e.md
- RabbitMQ, Alternate Exchanges: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/ae.md
- RabbitMQ, Publishers (unroutable messages): https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/publishers/index.md
- RabbitMQ, Consumer Acknowledgements and Publisher Confirms: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/confirms.md
- RabbitMQ, Dead Letter Exchanges: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/dlx.md
- RabbitMQ, Definitions: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/definitions.md
- RabbitMQ, Virtual Hosts: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/vhosts.md
- RabbitMQ, Access Control (topic authorisation): https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/access-control.md
- RabbitMQ, Local Random Exchange: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/local-random-exchange.md
- RabbitMQ consistent-hash exchange README: https://github.com/rabbitmq/rabbitmq-server/blob/main/deps/rabbitmq_consistent_hash_exchange/README.md
- RabbitMQ sharding plugin README: https://github.com/rabbitmq/rabbitmq-server/blob/main/deps/rabbitmq_sharding/README.md
- Apache Kafka, Multi-Tenancy: https://github.com/apache/kafka/blob/trunk/docs/operations/multi-tenancy.md
- Apache Kafka, Design (log compaction): https://github.com/apache/kafka/blob/trunk/docs/design/design.md
- Apache Kafka, Basic Kafka Operations: https://github.com/apache/kafka/blob/trunk/docs/operations/basic-kafka-operations.md
- Apache Kafka, Authorization and ACLs: https://github.com/apache/kafka/blob/trunk/docs/security/authorization-and-acls.md
- Apache Kafka,
Topic.java(name rules): https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/internals/Topic.java - KIP-290, Support for Prefixed ACLs: https://cwiki.apache.org/confluence/display/KAFKA/KIP-290%3A+Support+for+Prefixed+ACLs
- Martin Kleppmann, Should You Put Several Event Types in the Same Kafka Topic? (2018): https://www.confluent.io/blog/put-several-event-types-kafka-topic/
- Redis, Redis Streams: https://redis.io/docs/latest/develop/data-types/streams/
- Redis, Cluster specification (hash tags): https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/
- Enterprise Integration Patterns, Content-Based Router: https://www.enterpriseintegrationpatterns.com/patterns/messaging/ContentBasedRouter.html
- Enterprise Integration Patterns, Message Filter: https://www.enterpriseintegrationpatterns.com/patterns/messaging/Filter.html
- Enterprise Integration Patterns, Publish-Subscribe Channel: https://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html
- Laravel 13, Queues: https://laravel.com/docs/13.x/queues
- vladimir-yuldashev/laravel-queue-rabbitmq README: https://github.com/vyuldashev/laravel-queue-rabbitmq
- mateusjunges/laravel-kafka docs: https://github.com/mateusjunges/laravel-kafka/tree/master/docs
- php-amqplib
AMQPChannel: https://github.com/php-amqplib/php-amqplib/blob/master/PhpAmqpLib/Channel/AMQPChannel.php - amqp091-go: https://github.com/rabbitmq/amqp091-go
- franz-go: https://github.com/twmb/franz-go
- go-redis: https://github.com/redis/go-redis
- Redis transactions, runtime errors: https://redis.io/docs/latest/develop/using-commands/transactions/