System Management Patterns: Control Bus, Wire Tap, Detour, Message Store, Test Message
“How do you inspect messages that travel on a point-to-point channel?” — Gregor Hohpe and Bobby Woolf, Wire Tap
Summary: Eight patterns let you look into, steer, probe and clean a running messaging system without changing the business code that sends and receives the messages. Focus: Wire Tap, Detour and Test Message as safe production tools; Control Bus as the way to switch them; Message History and Message Store as evidence; Smart Proxy and Channel Purger as sharp tools with sharp edges. Learning goal: Pick the right pattern for an operational question, build it on RabbitMQ, Kafka or Redis Streams without endangering the main flow, and say what each one can and cannot prove.
This chapter owns the System Management group of Enterprise Integration Patterns: Control Bus, Detour, Wire Tap, Message History, Message Store, Smart Proxy, Test Message and Channel Purger. It does not re-teach tracing: trace context, lag metrics and dashboards live in the observability chapter, and test doubles and contract tests live in testing messaging systems. Failed messages are the job of the dead-letter queue. Here the question is different: how do operators get a safe handle on a system that is running right now?
Page map
| If you are looking for | Go to |
|---|---|
| The eight patterns in one table | One minute |
| Why a messaging system needs a management plane at all | Why it exists |
| How to copy traffic without slowing it | Wire Tap |
| How to send traffic through an inspector for ten minutes | Detour |
| How to change a running system by message | Control Bus |
| Who touched this message, in which order | Message History |
| An archive you can query | Message Store |
| Tracking a service that replies to a caller-chosen address | Smart Proxy |
| Proving the pipeline works with fake traffic | Test Message |
| Emptying a queue without a disaster | Channel Purger |
| Exact commands per broker | Broker differences |
| Pure-logic Go and Laravel code | Go, Laravel |
| Which pattern for which question | Choosing |
| Runnable-looking experiments | Lab |
Everything in one minute
| Pattern | In plain words | Tiny example | Broker-native form |
|---|---|---|---|
| Control Bus | A separate channel carries commands and status for the components, not business data | Tell the order router to start a detour for ten minutes | Admin queue, management API, config topic, queue:pause |
| Detour | A router with two outputs: straight through, or through extra inspection steps first | Send orders through a validator while debugging bad totals | Binding change, routing key switch, topic swap, feature flag |
| Wire Tap | Copy every message to a second channel; the original path is untouched | Audit service sees every OrderPlaced | Exchange-to-exchange binding, extra consumer group, second Streams group |
| Message History | The message carries the list of components it passed through | Header says: checkout, billing, shipping | Application header: hop list plus true hop count |
| Message Store | Keep a durable, queryable record of messages or their key fields | Find all messages for order 42 last Tuesday | Archive topic or queue, database table, event store |
| Smart Proxy | Sit between a requester and a service that replies to the requester's own address | Measure service latency per request | Rewrite reply-to, remember the original by correlation id |
| Test Message | Inject marked synthetic messages and check the results come out the other end | Canary order every minute, verified within 30 seconds | Header marker plus a router in front of business handlers |
| Channel Purger | Remove unwanted messages from a channel | Clear leftover replies in a test queue | rabbitmqctl purge_queue, offset reset, XTRIM, queue:clear |
| Danger | Which pattern | What prevents it |
|---|---|---|
| A tap slows the real traffic | Wire Tap | Publish to the main channel first, copy asynchronously into a bounded buffer, drop and count on overflow |
| A tap that nobody reads fills the broker | Wire Tap | Length limit and overflow policy on the tap queue, retention on the tap topic or stream |
| A detour is forgotten and traffic stays diverted | Detour | Switch state carries an expiry; unknown state means direct |
| A replayed control command undoes a newer one | Control Bus | Per-target sequence number and expiry |
| Test messages create real orders | Test Message | Marker in a header, separator before any side effect, failing closed |
| History header grows without bound | Message History | Byte bound on the trail, true hop counter, hop limit |
| Purge deletes real data in production | Channel Purger | Allow-list, dry run, depth re-check, typed confirmation |
| Smart proxy table leaks entries | Smart Proxy | TTL sweep and an unknown-reply counter |
Why it exists
Loose coupling is a strength of messaging and a weakness for operators. Hohpe and Woolf say it directly in Message History: the sender and receiver "make no (or few) assumptions about each other's identity", so "if we are not sure where a message goes, how can we assess the impact of a change". The management patterns are the answer to a practical question: how do we see, steer and test a distributed system that was designed so that its parts cannot see each other?
| Stay blind and simple | Add a management plane |
|---|---|
| Fewest moving parts | One more channel, one more component, one more failure mode |
| Nothing to secure beyond the data path | Admin commands become a powerful attack surface |
| No extra load | Taps, stores and canaries consume bandwidth and storage |
| Problems appear as customer complaints | Problems appear as failed canaries and gaps in history |
An everyday picture: a sorting office. The conveyor belts carry parcels (business traffic). A camera over the belt records what passes (Wire Tap). A clerk with a clipboard writes each parcel's ID and time (Message Store). Every parcel gets a stamp at each station (Message History). A switch can send parcels through an X-ray room for an hour (Detour). The foreman controls the switch over an intercom, not by running parcels across the room (Control Bus). Once a minute the office sends a dummy parcel and checks it arrives (Test Message). A trapdoor empties a jammed belt (Channel Purger).
Three misunderstandings to remove first. A tap is not free: it adds load and a failure mode. A Message Store is not an event store: it is evidence, not the system of record. A purge is not a harmless "reset": in production it destroys work that somebody still expects to be done.
Where it comes from
Enterprise Integration Patterns (Hohpe and Woolf, 2003) has a chapter called System Management. The pages are short, and several of them point to each other: Detour is "a context-based router controlled via the Control Bus"; Message Store can use a Wire Tap; Smart Proxy is the answer when a pair of Wire Taps cannot work because replies go to a Return Address chosen by the caller.
On the Control Bus page the pattern text says it "uses the same messaging mechanism used by the application data, but uses separate channels to transmit data that is relevant to the management of components". On the Test Message page, the authors note that heartbeats do not detect a component that "is actively processing messages, but garbles outgoing messages due to an internal fault", and propose injecting tagged messages instead. The Channel Purger page begins with a story: a superfluous message left on a reply queue made a requester appear to get a reply before the replier had acknowledged a request.
These are patterns, not protocols. No broker ships a "Control Bus" button. RabbitMQ gives you exchange-to-exchange bindings, a management HTTP API and a shovel plugin; Kafka gives you consumer groups and offset tools; Redis Streams gives you groups and trimming commands; Laravel gives you queue events and Artisan commands. The work is mapping each pattern onto what your broker really does, and knowing where the mapping leaks.
What it is really about
A management plane has three jobs: observe (tap, history, store), steer (control bus, detour, purger) and probe (test message, smart proxy). Each job must obey one rule: the management path may fail, slow down or be turned off without the business path noticing. If a tap can make a publish fail, it is no longer a tap but a new dependency.
The diagram shows one business flow along the middle and the management additions around it. Solid arrows are business data. Dashed arrows are copies or commands. Only the router and the consumer know about the extra hops; the producer and the business effect do not.
Concept catalogue
Wire Tap Must-know
In plain words: Make a copy of every message that passes a channel and send the copy somewhere else, so someone can look at it without touching the original traffic.
Common misunderstanding: "A tap sees exactly what the consumer sees." It does not. The tap copy is a separate delivery: it can arrive later, earlier, out of order, twice, or not at all, and it carries no proof that the business consumer processed anything.
Definition: In EIP terms a Wire Tap is a fixed Recipient List with two outputs: the main channel and a secondary channel, each receiving the unmodified message. In a broker with native fan-out the tap is rarely a component at all: it is a second subscription to the same stream of messages.
1 Producer -> orders exchange : publish OrderPlaced #42
2 Exchange -> billing queue : routed copy (business path)
3 Exchange -> orders.tap exchange : routed copy (exchange-to-exchange binding)
4 Tap queue -> audit consumer : reads copy, writes audit row
5 Audit consumer is stopped : tap queue reaches x-max-length, drop-head; billing unaffectedReal scenarios: An audit log of every payment event; a shadow consumer running next-version code against production traffic with its output discarded; a debugging window for one tenant; a feed into a search index; a security team that wants a copy of authentication events; capacity planning from real message sizes.
| Question | Native tap | Application-level tap |
|---|---|---|
| Where does the copy happen | Inside the broker, at routing time | In the producer or a proxy, after the main publish |
| Can the main publish fail because of the tap | No, if the tap target is a bounded queue or an independent group | Yes, if you publish both in one step and treat the tap error as fatal |
| Does the tap see messages that never left | No | Only if you tap before the main publish succeeds |
| Order relative to the main flow | Per-channel order within each destination | Whatever your buffer does |
| Cost | Broker memory and disk for the extra queue or group | Extra publish per message in your process |
How to use it: Prefer the broker-native form. Bound the tap's storage. Copy only the fields the analysis needs. Never let the tap error reach the producer. In Go: publish to main first, hand a deep copy to a bounded buffer, count drops (see the Go section). In Laravel, Queue::before and Queue::after listeners observe every job without modifying it.
Detour Important
In plain words: A switch in the router: normally messages go straight to the destination; when the switch is on they pass through an extra step first, such as a validator or a logger that can change the message, and then continue to the same destination.
Common misunderstanding: "A Detour is a Wire Tap with a different name." A tap copies and cannot change the original path. A detour moves the real messages through extra components, so it can slow, modify or block the business path. That is its purpose, and its risk.
Definition: The pattern text describes "a simple context-based router with two output channels" where one passes the unmodified message to the original destination, and the other, "when instructed by the Control Bus", goes through extra components that "can inspect and/or modify the message" before reaching the same destination.
1 Operator -> control bus : detour.enable orders, seq 7, expires 12:15
2 Router -> state : enabled until 12:15
3 Message A arrives : router sends it to orders.inspect
4 Inspector : logs, validates, republishes to orders with x-detour-seen=1
5 Message A (seen) : router sends it directly, no loop
6 12:15 passes : state expired, router reverts to direct without any commandReal scenarios: Validate a new field from one producer; add a temporary content filter during an incident; run a message through a profiler; quarantine traffic of one tenant for review; test a new transformer on live traffic before cutover.
| Implementation | How the switch works | What can go wrong |
|---|---|---|
| RabbitMQ | Change a binding or the routing key the producer-side router uses | Messages in flight stay on the old path; order between paths is not guaranteed |
| Kafka | Router service writes to orders or orders.inspect | Two topics, two partitionings; ordering across them is lost |
| Redis Streams | Router service chooses XADD target | Same, plus the inspector must XACK or its group's PEL grows |
| Laravel | onQueue($flag ? 'orders-inspect' : 'orders') from a cache flag | A flag with no TTL stays on forever |
How to use it: The switch must be fail-safe: unknown state means direct. Give it an expiry. Mark inspected messages so the router never diverts them twice. Decide up front whether the detour may reorder messages, and whether the inspector is allowed to drop one. In Go see detour.Router; in Laravel see DetourDispatcher.
Control Bus Must-know
In plain words: A second set of channels, built from the same messaging technology, over which operators send commands to components and components send back status.
Common misunderstanding: "A control bus means building a custom admin protocol." Often it is just a topic or queue with a small allow-listed command set. Many brokers already ship a management API; whether that API is the Control Bus or only a convenience depends on whether your components listen for commands on it.
Definition: Each component connects to two messaging subsystems: the application message flow and the control bus. Commands are applied idempotently, are allow-listed, expire, and carry a sequence number per target so replays and reordering do not undo newer state.
1 Operator -> admin.commands : {target: router-1, action: detour.enable, seq: 7, exp: 12:15}
2 router-1 : seq 7 > last 6, action on allow-list, not expired -> apply, last = 7
3 router-1 -> admin.status : {target: router-1, applied: 7, state: enabled}
4 Broker redelivers command : seq 7 <= last 7 -> stale, ignored, no effect
5 Old command seq 5 arrives late : stale, ignored| Control path | Used for | Delivery | Trap |
|---|---|---|---|
| Admin queue or topic | Commands to components | Same as any message: at-least-once | Must be idempotent and ordered per target |
| Management HTTP API | Broker objects: queues, bindings, policies, shovels | Request/response, not durable | Not a channel your application consumes |
| Config topic with compaction | Last known desired state per key | Replayable; new components read it on start | Consumers see old values until they catch up |
| Cache flag (Laravel) | On/off switches read by workers | Eventual, poll interval | Flag without TTL; no audit trail |
queue:pause and queue:resume | Stop workers from taking jobs | Workers poll the cache for the signal | Disabled interruption polling ignores the command |
Real scenarios: Pause consumption during a database failover; raise a rate limit; start a detour; ask each component to report its version; reload routing rules; request a canary run.
How to use it: Authenticate and authorise commands; see messaging security. Keep the command set small and explicit. Echo status. Do not use the control bus for bulk data. Go: controlbus.Bus.
Message History Important
In plain words: Every component that handles a message adds a short note to its header: who I am and when I touched it. At the end, the message tells its own story.
Common misunderstanding: "History makes tracing unnecessary." A header trail is small and travels with the message; it cannot show timing inside a service, branches from fan-out, or what happened to messages that died. Use history for routing questions ("which path did this take?") and use tracing for latency.
Definition: The pattern keeps "a list of all applications that the message passed through since its origination", in the header because it is control information. When an Aggregator combines messages the authors give two options: a tree of histories, or the history of one primary input.
1 checkout -> broker : x-history=checkout@t0, x-hop-count=1
2 billing receives : appends -> x-history=checkout@t0,billing@t1, x-hop-count=2
3 shipping receives : appends -> three entries, x-hop-count=3
4 A routing bug sends the message back to billing, again and again
5 x-hop-count reaches the limit (8) : consumer rejects it to the parking lot instead of looping| Question | Plain list in a header | Hierarchical tree | Rely on tracing |
|---|---|---|---|
| Size | Grows linearly with hops | Grows with fan-in | Constant (ids only) |
| Aggregation | Keeps one parent's history | Keeps all | Links between spans |
| Needs a backend | No | No | Yes |
| Survives broker hops that drop headers | No | No | No |
How to use it: Bound everything. Keep the origin and the newest entries, drop the middle, and keep a true hop count that is never truncated (x-hop-count). A hop limit also detects routing cycles. Check broker limits on header size before choosing a format.
Message Store Important
In plain words: A durable, searchable record of the messages that passed (or key fields of them), kept outside the path they travel on.
Common misunderstanding: "Our Kafka topic is our message store." A topic is a log with retention. A store answers questions: by order id, by tenant, by time window, with an index. Also, a store is not an event store: an event store is the system of record whose events define state; a message store is evidence about transport.
Definition: The pattern sends "a duplicate of the message to a special channel" collected by the store, either from the component itself or through a Wire Tap. The authors note that you may store "just a few key fields" such as message id, channel and timestamp, because copying everything costs network traffic and storage.
1 Tap consumer : reads copy from orders.tap
2 Insert row : (message_id, channel, received_at, correlation_id, body_hash)
3 Duplicate copy : insert conflicts on message_id -> ignore
4 Support query : SELECT ... WHERE correlation_id = 'c-42' ORDER BY received_at
5 Retention job : deletes rows older than 30 days| Store kind | Strength | Weakness | Fits |
|---|---|---|---|
| Archive topic or stream (Kafka, Redis Streams) | Cheap, replayable in order | No index; query means scanning | Replay and forensics |
| Archive queue (RabbitMQ) | Simple | Consumed once; no query | Short-term parking only |
| Relational table | Indexed queries, joins to business data | Write load, schema | Support tooling, audit |
| Object storage with manifest | Cheap long retention | Slow queries | Compliance archive |
| Event store | Authoritative history | A different thing | Event-sourced systems |
How to use it: Store identifiers and metadata by default; store bodies only where policy allows. Deduplicate on message id, because taps can deliver twice. Plan retention and erasure on day one; see messaging security. The SQL below is a minimal PostgreSQL store.
CREATE TABLE message_store (
message_id text PRIMARY KEY,
channel text NOT NULL,
correlation_id text,
received_at timestamptz NOT NULL DEFAULT now(),
hop_count int,
body_hash bytea,
body jsonb -- NULL when policy forbids storing payloads
);
CREATE INDEX message_store_corr ON message_store (correlation_id);
CREATE INDEX message_store_time ON message_store (received_at);Smart Proxy Good to know
In plain words: When a service replies to whatever address the caller wrote on the request, a middleman can swap in its own address, wait for the reply, then forward it to the original address. Now the middleman can time and count every reply.
Common misunderstanding: "A pair of wire taps is enough to track a service." Only when the service publishes to a fixed output channel. If the reply goes to the caller's reply-to, there is no fixed place to tap.
Definition: The pattern says to "store the Return Address supplied by the original requestor and replace it with the address of the Smart Proxy". On the reply it looks up the stored address and forwards the unmodified reply there. The lookup key is the correlation id (see request-reply).
1 Requester -> proxy : correlation-id c1, reply-to R
2 Proxy : table[c1] = R, sent_at = now; reply-to := proxy.replies
3 Proxy -> service : request c1
4 Service -> proxy : reply c1 (to proxy.replies)
5 Proxy : R = table[c1]; latency = now - sent_at; delete entry
6 Proxy -> R : reply c1| Failure | What happens | Defence |
|---|---|---|
| Reply never comes | Table entry stays forever | TTL sweep; timeout metric |
| Reply arrives twice | Second lookup finds nothing | Count unknown replies, drop |
| Request without correlation id | Cannot match | Reject or generate at the edge |
| Proxy dies | Table lost; replies go nowhere | Persist the table, or accept timeouts and let callers retry |
| RabbitMQ direct reply-to | Reply address is tied to the requester's channel | Proxy keeps its own reply queue; original address is stored as text |
Real scenarios: Per-service latency and error rates without changing the service; routing replies through a firewall component; recording every reply for a store; throttling replies.
How to use it: Prefer measuring at the caller with timers if you control it. Use a proxy when you cannot change either side. Go: smartproxy.Proxy.
Test Message Must-know
In plain words: Send fake but realistic messages through the real pipeline on a schedule, mark them, and check that the expected result comes out. A heartbeat tells you a component is alive; a test message tells you it still does the right thing.
Common misunderstanding: "Mark the test message by using a special value, such as order id 999999." The pattern warns that this mixes application data with control information and "should be used only as a last resort". A header marker is cleaner and cannot collide with a real order.
Definition: Four parts: a Test Data Generator, a Test Message Injector that tags messages, a Test Message Separator (usually a Content-Based Router) that pulls test results out of the output stream, and a Test Data Verifier that compares results with expectations. In the industry the same idea is called a canary message or a synthetic transaction.
1 Generator/Injector -> orders : message x-test-message=run-17 (valid order, test tenant)
2 Router (separator) : marker present -> send to verifier, never to business handler
3 Real pipeline stages : validate, price, route; each preserves the marker header
4 Verifier : expects run-17 within 30 s with price 100.00
5 Run-17 not seen after 30 s : alert "canary overdue" (pipeline broken or slow)| Marker style | Collision risk | Survives transformation | Verdict |
|---|---|---|---|
Header x-test-message | None | Only if every stage copies headers | Preferred |
| Special business value | Real data may match | Yes | Last resort |
| Dedicated test tenant | Needs tenant isolation everywhere | Yes | Good addition, not a replacement |
| Separate topic or queue | None | Skips the shared pipeline | Does not test the shared path |
Real scenarios: A canary order every minute; a synthetic payment against a sandbox gateway; a probe through an ETL pipeline after each deployment; a scheduled check that DLQ routing still works.
How to use it: The separator must come before the first side effect and must fail closed (an empty marker is still a test message). Never write test data into business tables; if the real handler must run to be tested, point it at a test tenant with its own storage. Run canaries on a schedule and alert on lateness, not only on failure. Go: canary.Separator, canary.Verifier. Laravel: SeparateCanary job middleware. Testing doubles belong to testing messaging systems.
Channel Purger Must-know
In plain words: A way to remove messages from a channel. For a test queue it clears leftovers. In production it deletes work.
Common misunderstanding: "Purge means everything on the queue is gone." On RabbitMQ a purge removes ready messages; messages delivered but not yet acknowledged stay. On Kafka there is no queue-purge; you change retention, reset a group's offsets or delete the group. On Redis Streams trimming removes entries for every group, and a deleted group loses its cursor and pending list.
Definition: Hohpe and Woolf: "A simple Channel Purger simply remove all the messages from a channel", and for production debugging "we may need to remove individual message or a set of messages based on specific criteria, such as the message ID". Selective removal is harder than total purge on every broker.
1 Operator : sees 40 stuck replies on test.replies
2 Tool : reads depth = 40, dry run prints "would delete 40 from test.replies"
3 Operator : confirms; tool re-reads depth (40), allow-list ok, environment staging
4 Broker : purge_queue test.replies -> 40 removed
5 Same tool on production orders.billing : refused, not on allow-list| Broker | Purge a queue | Selective removal | Hidden effect |
|---|---|---|---|
| RabbitMQ | rabbitmqctl purge_queue, rabbitmqadmin queues purge, management API | Not supported natively; consume and ack matching messages | Unacked messages remain |
| Kafka | None per topic; change retention.ms, reset offsets, delete group | Not supported | Retention change affects all consumers |
| Redis Streams | XTRIM, XDEL, XGROUP DESTROY | XDEL by id | XDEL leaves holes; group state differs |
| Laravel | queue:clear; horizon:clear with Horizon | Delete one job via the failed-job tools | SQS overflow cache may be flushed with the queue |
How to use it: Treat purge as a production change: allow-list, dry run, re-read depth just before acting, typed confirmation in production, audit record, and a copy of what was removed (a tap on the queue or a dump). Go: purger.Decide.
Mechanics and exact controls
Tap cost, order and semantics Important
A tap multiplies broker work. A RabbitMQ binding to a second exchange adds routing work per message and one stored copy per bound queue. A second Kafka consumer group adds fetch load and its own committed offsets but no extra stored data. A second Redis Streams group adds a cursor and pending list but no extra stored entries; the stored entries are shared. Order is preserved per channel and per partition within each destination, never across them.
| Cost item | RabbitMQ e2e binding | Kafka second group | Redis second group |
|---|---|---|---|
| Extra storage | Yes, one copy per queue | No | No |
| Extra read load | Per queue consumer | Per group fetch | Per group read |
| Independent progress | Yes (own queue) | Yes (own offsets) | Yes (own cursor and PEL) |
| Failure of tap blocks main | No, until memory or disk alarms | No | No, unless trimming depends on it |
| Delivery to tap | At-least-once typically | At-least-once | At-least-once |
Identity, headers and size Important
Every pattern here uses message identity: a message id for deduplication in the store, a correlation id for the smart proxy and for history queries, and a header marker for test messages. The message design chapter owns the envelope. Two rules matter here. Carry these headers through every transformation (a Content Enricher that rebuilds the message must copy them). And keep header size bounded: a history trail that grows on every hop eventually exceeds a broker or client header limit, so cap the trail in bytes and keep a separate integer hop count.
| Header | Purpose | Bound |
|---|---|---|
message-id | Deduplicate in store | Fixed length |
correlation-id | Smart proxy lookup, history query | Fixed length |
x-history | Hop trail | Byte cap, origin plus newest |
x-hop-count | Cycle detection | Integer, never truncated |
x-test-message | Canary marker | Run id |
x-detour-seen | Prevent double detour | One flag |
x-tap-origin | Where a tap copy came from | Channel name |
Management plane security Must-know
The management plane can read everything (tap), reroute everything (detour) and delete everything (purge). Treat it as production access: separate credentials, least privilege, audit of each command, and no payload in logs. The details of TLS, ACLs and vhosts are in messaging security. A control bus command must be authenticated before it is parsed.
Delivery guarantees of the management channels Good to know
Control and tap channels are messages too. At-least-once delivery means duplicates: commands must be idempotent (sequence numbers), store inserts must be deduplicated (message id), canary runs must tolerate duplicates (verifier flags a second sighting). Acknowledgment details are in message acknowledgment.
Solving classic problems
"Where did order 42 go?" Important
| Approach | How | Advantage | Cost or limit |
|---|---|---|---|
| Message History header | Read x-history on the last seen copy | Free, travels with the message | Only for messages that arrived somewhere |
| Message Store query | WHERE correlation_id = 'c-42' | Shows every channel it touched | Needs a tap on every channel |
| Tracing | Find the trace by id | Timing and branches | Needs instrumented services |
| Broker inspection | Management API, offsets | No code | Shows state, not history |
Workflow: query the store by correlation id; compare the list of channels with the expected route; read the history header on the last copy; find the first missing hop; check that component's lag and DLQ.
"Can we test this in production safely?" Important
Use a canary run: inject a marked message at the entry, route it by the separator to the verifier at the exit, and alert on lateness. If a stage cannot preserve headers, test it with a dedicated test tenant or a separate synthetic flow rather than a magic value. Keep the canary rate low and fixed.
"We want to try a new consumer on live traffic" Good to know
Add a second consumer group or tap queue for the candidate. It runs the new code against real messages and writes its output to a scratch store, never to production tables. Compare results with the main consumer's outputs by message id. Remove the tap when done.
"A test queue has leftovers" Good to know
Use the purger with an allow-list of test prefixes. For the production-like cases, first tap the queue to a dump, then delete selected ids rather than the whole queue.
Reducing noise: sampling and field selection Good to know
Taps and stores cost money. Sample (every nth message, or a tenant allow-list), store key fields, and apply retention. For legal or security reasons do not store bodies unless required.
Choosing a pattern
| Operational question | Pattern | Extra technique | Reason |
|---|---|---|---|
| What is flowing right now? | Wire Tap | Bounded tap queue, sampling | Zero effect on business path |
| Which path did this message take? | Message History | Hop count and byte cap | Travels with the message |
| What happened to order 42 last week? | Message Store | Index on correlation id | Searchable evidence |
| I need to change or validate messages for ten minutes | Detour | Expiry, seen marker | Reversible steering |
| Switch behaviour on many components | Control Bus | Sequence numbers, allow-list | Idempotent commands |
| Is the pipeline working end to end? | Test Message | Canary schedule, lateness alert | Detects silent failure |
| Time and count replies of a black-box service | Smart Proxy | TTL sweep | No change to either side |
| Clear a test channel | Channel Purger | Allow-list, dry run | Safe reset |
| Failed messages | Dead-letter queue | Replay tooling | Different pattern: see DLQ |
| Latency inside services | Tracing | Trace context in headers | See observability |
Go
Example
The Go module has one package per pattern and a tiny shared msg package. The logic is pure, so every package has tests without a broker. The three broker programs under brokers/ compile without a broker and exit unless an environment variable is set.
Wire tap: main publish first, deep copy into a bounded buffer, drop and count on overflow.
// Package wiretap copies every successfully published message to a side channel
// without ever letting the side channel slow down or fail the main path.
package wiretap
import (
"context"
"sync/atomic"
"academy/messaging-system-management/msg"
)
// Publisher is the minimal producer interface (an AMQP channel, a Kafka client, XADD).
type Publisher interface {
Publish(ctx context.Context, destination string, m msg.Message) error
}
// Tap publishes to main first, then hands a deep copy to a bounded buffer.
type Tap struct {
main Publisher
side Publisher
sideTo string
queue chan msg.Message
dropped atomic.Int64
failed atomic.Int64
}
func New(main, side Publisher, sideDestination string, buffer int) *Tap {
return &Tap{main: main, side: side, sideTo: sideDestination, queue: make(chan msg.Message, buffer)}
}
// Publish never blocks on the tap. A full buffer drops the copy and counts it:
// observing traffic must never become a reason the business message is late.
func (t *Tap) Publish(ctx context.Context, destination string, m msg.Message) error {
if err := t.main.Publish(ctx, destination, m); err != nil {
return err // no phantom copy of a message that never left
}
c := m.Clone()
c.Headers["x-tap-origin"] = destination
select {
case t.queue <- c:
default:
t.dropped.Add(1)
}
return nil
}
// Drain forwards buffered copies until ctx ends. Side-channel errors are counted, not returned.
func (t *Tap) Drain(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case c := <-t.queue:
if err := t.side.Publish(ctx, t.sideTo, c); err != nil {
t.failed.Add(1)
}
}
}
}
func (t *Tap) Dropped() int64 { return t.dropped.Load() }
func (t *Tap) Failed() int64 { return t.failed.Load() }Detour: an atomically swapped state with a deadline, a selector and a loop guard.
// Package detour is a context-based router with two outputs: the direct path and an
// inspection path. The switch carries a deadline so a forgotten detour switches itself off.
package detour
import (
"sync/atomic"
"time"
"academy/messaging-system-management/msg"
)
const SeenHeader = "x-detour-seen"
// State is what the control bus last told the router.
type State struct {
Enabled bool
Until time.Time
Match func(msg.Message) bool // nil means every message
}
type Router struct {
direct, via string
state atomic.Pointer[State]
now func() time.Time
}
func New(direct, via string, now func() time.Time) *Router {
return &Router{direct: direct, via: via, now: now}
}
// Set is called by the control-bus handler; it swaps the whole state atomically.
func (r *Router) Set(s State) { r.state.Store(&s) }
// Route returns the destination and whether the message takes the detour.
// Defaults are fail-safe: unknown state, expired state and already-inspected messages go direct.
func (r *Router) Route(m msg.Message) (string, bool) {
s := r.state.Load()
if s == nil || !s.Enabled || !r.now().Before(s.Until) {
return r.direct, false
}
if _, seen := m.Headers[SeenHeader]; seen {
return r.direct, false // the inspector republished it; do not loop
}
if s.Match != nil && !s.Match(m) {
return r.direct, false
}
return r.via, true
}
// MarkSeen is applied by the last inspection step before it republishes to the original destination.
func MarkSeen(m msg.Message) msg.Message {
c := m.Clone()
c.Headers[SeenHeader] = "1"
return c
}Control bus: allow-listed actions, per-target sequence numbers, expiry.
// Package controlbus applies management commands received on an admin channel. Commands are
// allow-listed, expire, and carry a per-target sequence so replays and reordering are harmless.
package controlbus
import (
"errors"
"sync"
"time"
)
var (
ErrExpired = errors.New("command expired")
ErrStale = errors.New("command sequence is not newer than the last applied")
ErrUnknownAction = errors.New("action is not on the allow-list")
)
type Command struct {
Target string // component name, e.g. "orders-router"
Action string // e.g. "detour.enable"
Arg string
Seq uint64
ExpiresAt time.Time
}
type Handler func(Command) error
type Bus struct {
mu sync.Mutex
handlers map[string]Handler
lastSeq map[string]uint64
now func() time.Time
}
func New(now func() time.Time) *Bus {
return &Bus{handlers: map[string]Handler{}, lastSeq: map[string]uint64{}, now: now}
}
func (b *Bus) Allow(action string, h Handler) { b.handlers[action] = h }
// Apply reports whether the command changed anything. A stale or expired command is an
// expected outcome (a redelivered message), not a failure of the component.
func (b *Bus) Apply(c Command) (bool, error) {
b.mu.Lock()
defer b.mu.Unlock()
h, ok := b.handlers[c.Action]
if !ok {
return false, ErrUnknownAction
}
if !b.now().Before(c.ExpiresAt) {
return false, ErrExpired
}
if c.Seq <= b.lastSeq[c.Target] {
return false, ErrStale
}
if err := h(c); err != nil {
return false, err // sequence not advanced: the same command may be retried
}
b.lastSeq[c.Target] = c.Seq
return true, nil
}Message history: bounded trail plus a true hop count.
// Package history maintains a bounded Message History header: a true hop counter that is
// never truncated, plus a trail of service@time entries that is.
package history
import (
"errors"
"fmt"
"maps"
"strconv"
"strings"
"time"
)
const (
TrailHeader = "x-history"
HopHeader = "x-hop-count"
DroppedHdr = "x-history-dropped"
)
var ErrHopLimit = errors.New("hop limit exceeded: probable routing cycle")
type Limits struct {
MaxHops int // refuse to forward beyond this many hops
MaxBytes int // upper bound for the trail header value
}
// Append returns new headers with one more hop; the input map is not modified.
func Append(in map[string]string, service string, at time.Time, l Limits) (map[string]string, error) {
hops, _ := strconv.Atoi(in[HopHeader])
if hops+1 > l.MaxHops {
return nil, fmt.Errorf("%w (hops=%d, max=%d)", ErrHopLimit, hops+1, l.MaxHops)
}
out := maps.Clone(in)
if out == nil {
out = map[string]string{}
}
entries := split(out[TrailHeader])
entries = append(entries, fmt.Sprintf("%s@%d", service, at.UnixMilli()))
dropped, _ := strconv.Atoi(out[DroppedHdr])
// Keep the origin (first entry) and the newest hops; drop from the middle.
for len(strings.Join(entries, ",")) > l.MaxBytes && len(entries) > 2 {
entries = append(entries[:1], entries[2:]...)
dropped++
}
out[TrailHeader] = strings.Join(entries, ",")
out[HopHeader] = strconv.Itoa(hops + 1)
if dropped > 0 {
out[DroppedHdr] = strconv.Itoa(dropped)
}
return out, nil
}
func split(v string) []string {
if v == "" {
return nil
}
return strings.Split(v, ",")
}Test message separator and verifier.
// Package canary implements the Test Message pattern: inject a tagged message, separate
// it from business traffic before any side effect, and verify that it arrives in time.
package canary
import (
"fmt"
"sync"
"time"
"academy/messaging-system-management/msg"
)
const Marker = "x-test-message"
// New builds a synthetic message. The marker is a header, never a magic business value.
func New(runID string, now time.Time) msg.Message {
return msg.Message{
ID: "canary-" + runID,
Headers: map[string]string{Marker: runID, "x-sent-at": now.UTC().Format(time.RFC3339)},
Body: []byte(`{"synthetic":true}`),
}
}
func IsTest(m msg.Message) bool { _, ok := m.Headers[Marker]; return ok }
// Separator is the content-based router in front of the business handler.
type Separator struct {
Business func(msg.Message) error
Verifier func(msg.Message) error
}
// Dispatch fails closed: anything carrying the marker, even with an empty value, never reaches Business.
func (s Separator) Dispatch(m msg.Message) error {
if IsTest(m) {
return s.Verifier(m)
}
return s.Business(m)
}
// Verifier knows which canaries it expects and when.
type Verifier struct {
mu sync.Mutex
pending map[string]time.Time
}
func NewVerifier() *Verifier { return &Verifier{pending: map[string]time.Time{}} }
func (v *Verifier) Expect(runID string, deadline time.Time) {
v.mu.Lock()
defer v.mu.Unlock()
v.pending[runID] = deadline
}
func (v *Verifier) Observe(m msg.Message) error {
v.mu.Lock()
defer v.mu.Unlock()
id := m.Headers[Marker]
if _, ok := v.pending[id]; !ok {
return fmt.Errorf("unexpected or duplicate canary %q", id)
}
delete(v.pending, id)
return nil
}
// Overdue lists canaries that did not come back in time; this is the alert condition.
func (v *Verifier) Overdue(now time.Time) []string {
v.mu.Lock()
defer v.mu.Unlock()
var late []string
for id, d := range v.pending {
if now.After(d) {
late = append(late, id)
}
}
return late
}Smart proxy: reply-to rewriting by correlation id.
// Package smartproxy implements reply-to rewriting: the proxy swaps the requester's return
// address for its own, remembers the original by correlation id, and restores it on the reply.
package smartproxy
import (
"errors"
"sync"
"time"
"academy/messaging-system-management/msg"
)
const (
CorrelationHeader = "correlation-id"
ReplyToHeader = "reply-to"
)
var (
ErrNoCorrelation = errors.New("request has no correlation id")
ErrDuplicate = errors.New("correlation id already in flight")
ErrUnknownReply = errors.New("reply matches no in-flight request (late, duplicate or foreign)")
)
type entry struct {
replyTo string
sentAt time.Time
deadline time.Time
}
type Proxy struct {
mu sync.Mutex
proxyAddr string
ttl time.Duration
inflight map[string]entry
now func() time.Time
}
func New(proxyAddr string, ttl time.Duration, now func() time.Time) *Proxy {
return &Proxy{proxyAddr: proxyAddr, ttl: ttl, inflight: map[string]entry{}, now: now}
}
// Request rewrites reply-to and returns the message to forward to the real service.
func (p *Proxy) Request(m msg.Message) (msg.Message, error) {
id := m.Headers[CorrelationHeader]
if id == "" {
return msg.Message{}, ErrNoCorrelation
}
p.mu.Lock()
defer p.mu.Unlock()
if _, busy := p.inflight[id]; busy {
return msg.Message{}, ErrDuplicate
}
t := p.now()
p.inflight[id] = entry{replyTo: m.Headers[ReplyToHeader], sentAt: t, deadline: t.Add(p.ttl)}
out := m.Clone()
out.Headers[ReplyToHeader] = p.proxyAddr
return out, nil
}
// Reply restores the original reply-to, returns where to send it and how long the service took.
func (p *Proxy) Reply(m msg.Message) (string, time.Duration, error) {
id := m.Headers[CorrelationHeader]
p.mu.Lock()
defer p.mu.Unlock()
e, ok := p.inflight[id]
if !ok {
return "", 0, ErrUnknownReply
}
delete(p.inflight, id)
return e.replyTo, p.now().Sub(e.sentAt), nil
}
// Sweep drops entries whose reply never came, so a dead service cannot grow the table forever.
func (p *Proxy) Sweep() int {
p.mu.Lock()
defer p.mu.Unlock()
n := 0
for id, e := range p.inflight {
if p.now().After(e.deadline) {
delete(p.inflight, id)
n++
}
}
return n
}Channel purger guard.
// Package purger decides whether a purge may run. It is pure logic: the caller performs the
// actual rabbitmqctl purge_queue, XTRIM or offset reset only after Decide says yes.
package purger
import (
"fmt"
"strings"
)
type Policy struct {
// AllowedPrefixes lists the queues a purge may ever touch, for example "test." or "tmp.".
AllowedPrefixes []string
// MaxDepthWithoutReview is the largest backlog an operator may delete without a second person.
MaxDepthWithoutReview int64
}
type Request struct {
Environment string // "staging", "production", ...
Queue string
ObservedLen int64 // depth the operator saw when they decided
CurrentLen int64 // depth right now, read again just before purging
Confirm string
DryRun bool
}
type Decision struct {
Allowed bool
Reason string
}
// ConfirmPhrase is what an operator must type in production: it names the queue and the depth.
func ConfirmPhrase(queue string, depth int64) string {
return fmt.Sprintf("purge %s (%d messages)", queue, depth)
}
func Decide(r Request, p Policy) Decision {
if !hasPrefix(r.Queue, p.AllowedPrefixes) {
return Decision{false, "queue is not on the purge allow-list"}
}
if r.DryRun {
return Decision{false, fmt.Sprintf("dry run: would delete %d messages from %s", r.CurrentLen, r.Queue)}
}
if r.CurrentLen != r.ObservedLen {
return Decision{false, "backlog changed since it was inspected; look again"}
}
if r.CurrentLen > p.MaxDepthWithoutReview {
return Decision{false, "backlog above the no-review limit; a second person must approve"}
}
if r.Environment == "production" && r.Confirm != ConfirmPhrase(r.Queue, r.CurrentLen) {
return Decision{false, "production purge needs the exact confirmation phrase"}
}
return Decision{true, "ok"}
}
func hasPrefix(s string, prefixes []string) bool {
for _, p := range prefixes {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}The Go angle
Keep decisions (should this message detour, may this queue be purged, has this hop count been exceeded) as pure functions with injected clocks, and keep broker calls in thin shells. That makes the dangerous parts testable without a broker. The wire tap test asserts that a failed main publish produces no tap copy, that a full buffer never blocks the main path, and that the copy does not alias the original. Run the tests with go test -race ./...; the tap and the smart proxy are concurrent.
package wiretap
import (
"context"
"errors"
"sync"
"testing"
"time"
"academy/messaging-system-management/msg"
)
type fake struct {
mu sync.Mutex
got []msg.Message
err error
seen chan struct{}
}
func (f *fake) Publish(_ context.Context, _ string, m msg.Message) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.err != nil {
return f.err
}
f.got = append(f.got, m)
if f.seen != nil {
f.seen <- struct{}{}
}
return nil
}
func (f *fake) count() int { f.mu.Lock(); defer f.mu.Unlock(); return len(f.got) }
func TestMainFailureProducesNoTapCopy(t *testing.T) {
main := &fake{err: errors.New("broker down")}
tap := New(main, &fake{}, "orders.tap", 4)
if err := tap.Publish(context.Background(), "orders", msg.Message{ID: "1"}); err == nil {
t.Fatal("main error must be returned")
}
if len(tap.queue) != 0 {
t.Fatal("a message that never left must not be tapped")
}
}
func TestFullBufferDropsButNeverBlocksMain(t *testing.T) {
main := &fake{}
tap := New(main, &fake{}, "orders.tap", 1)
for i := 0; i < 3; i++ {
if err := tap.Publish(context.Background(), "orders", msg.Message{ID: "x"}); err != nil {
t.Fatal(err)
}
}
if main.count() != 3 || tap.Dropped() != 2 {
t.Fatalf("main=%d dropped=%d, want 3 and 2", main.count(), tap.Dropped())
}
}
func TestTapCopyIsIndependentAndSideFailureIsCounted(t *testing.T) {
side := &fake{seen: make(chan struct{}, 1)}
tap := New(&fake{}, side, "orders.tap", 2)
orig := msg.Message{ID: "1", Headers: map[string]string{"k": "v"}, Body: []byte("abc")}
_ = tap.Publish(context.Background(), "orders", orig)
orig.Headers["k"] = "mutated"
orig.Body[0] = 'Z'
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go tap.Drain(ctx)
select {
case <-side.seen:
case <-time.After(time.Second):
t.Fatal("tap copy was not forwarded")
}
side.mu.Lock()
got := side.got[0]
side.mu.Unlock()
if got.Headers["k"] != "v" || string(got.Body) != "abc" || got.Headers["x-tap-origin"] != "orders" {
t.Fatalf("copy aliased the original: %+v", got)
}
side.mu.Lock()
side.err = errors.New("tap sink down")
side.mu.Unlock()
_ = tap.Publish(context.Background(), "orders", msg.Message{ID: "2"})
deadline := time.Now().Add(time.Second)
for tap.Failed() == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if tap.Failed() != 1 {
t.Fatalf("failed=%d, want 1", tap.Failed())
}
}Laravel
Example
Laravel's queue docs describe Queue::before and Queue::after callbacks that receive the connection name, the job and its payload. A provider using them is a wire tap that cannot change the job. Job middleware, returned from a job's middleware method, receives the job and a $next callback and can implement history, canary separation or the detour switch.
<?php
namespace App\Providers;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
// A passive wire tap on every queued job. It observes; it never modifies, delays or fails a job.
final class WireTapProvider extends ServiceProvider
{
public function boot(): void
{
Queue::before(function (JobProcessing $event) {
$this->record('before', $event->connectionName, $event->job->payload());
});
Queue::after(function (JobProcessed $event) {
$this->record('after', $event->connectionName, $event->job->payload());
});
}
/** @param array<string, mixed> $payload */
private function record(string $phase, string $connection, array $payload): void
{
try {
// Safe fields only: never the serialized command, which may hold personal data.
Log::channel('tap')->info('queue.tap', [
'phase' => $phase,
'connection' => $connection,
'uuid' => $payload['uuid'] ?? null,
'job' => $payload['displayName'] ?? null,
'attempts' => $payload['attempts'] ?? null,
]);
} catch (\Throwable) {
// A broken tap must not become a broken queue.
}
}
}<?php
namespace App\Jobs\Middleware;
use Closure;
use RuntimeException;
// Job middleware that appends one hop to a bounded history carried on the job itself.
// A job opts in by declaring: public array $history = [];
final class AppendHistory
{
public function __construct(
private readonly string $service,
private readonly int $maxHops = 8,
private readonly int $maxEntries = 6,
) {}
public function handle(object $job, Closure $next): mixed
{
if (! property_exists($job, 'history')) {
return $next($job);
}
$hops = ($job->hops ?? 0) + 1;
if ($hops > $this->maxHops) {
// Probable cycle between jobs that dispatch each other.
$job->fail(new RuntimeException("hop limit exceeded ({$hops})"));
return null;
}
$job->hops = $hops;
$job->history[] = $this->service.'@'.now()->getTimestampMs();
if (count($job->history) > $this->maxEntries) {
// Keep the origin and the newest entries; the true count stays in $hops.
$job->history = [$job->history[0], ...array_slice($job->history, -($this->maxEntries - 1))];
}
return $next($job);
}
}<?php
namespace App\Jobs\Middleware;
use Closure;
use Illuminate\Support\Facades\Cache;
// Test Message separator as job middleware. A canary job proves the queue and worker path
// is alive, then stops before any business side effect. Business jobs pass untouched.
final class SeparateCanary
{
public function handle(object $job, Closure $next): mixed
{
$runId = $job->canaryRunId ?? null;
if ($runId === null) {
return $next($job);
}
// The verifier is a monitor that checks this key within a deadline.
Cache::put("canary:seen:{$runId}", now()->toIso8601String(), now()->addHour());
return null;
}
}<?php
namespace App\Messaging;
use Illuminate\Support\Facades\Cache;
// Routing switch for a detour. The flag lives in the shared cache with a TTL, so the detour
// switches itself off when nobody remembers to. Absent flag means the direct queue.
final class DetourDispatcher
{
public function queueFor(string $stream): string
{
return Cache::has("detour:{$stream}") ? "{$stream}-inspect" : $stream;
}
// Called by an operator command, an admin endpoint or a control message handler.
public function enable(string $stream, int $minutes): void
{
Cache::put("detour:{$stream}", true, now()->addMinutes($minutes));
}
public function disable(string $stream): void
{
Cache::forget("detour:{$stream}");
}
}The Laravel angle
queue:pause and queue:resume (the docs name the pair queue:pause and queue:continue in prose and use queue:resume in the example) are a ready-made control bus for workers: workers poll the cache for the signal, which is why disabling interruption polling disables them. queue:clear is the Channel Purger for the default connection and queue (Horizon users run horizon:clear instead). Redis Streams are not used by Laravel's own queue driver, so stream administration goes through Redis::command.
<?php
namespace App\Messaging;
use Illuminate\Support\Facades\Redis;
// Raw Redis Streams administration through Redis::command; Laravel's queue driver does not use streams.
final class RedisAdmin
{
public function createTapGroup(string $stream): mixed
{
// A second group has its own cursor and pending list; '$' starts at new entries only.
return Redis::command('XGROUP', ['CREATE', $stream, 'audit-tap', '$', 'MKSTREAM']);
}
public function trimOlderThan(string $stream, int $hours): mixed
{
$minId = ((int) (microtime(true) * 1000) - $hours * 3_600_000).'-0';
return Redis::command('XTRIM', [$stream, 'MINID', $minId]);
}
public function destroyTapGroup(string $stream): mixed
{
return Redis::command('XGROUP', ['DESTROY', $stream, 'audit-tap']);
}
}Broker differences
RabbitMQ
An exchange-to-exchange binding (exchange.bind) connects one exchange to another with the same semantics as an exchange-to-queue binding; RabbitMQ detects and removes cycles during delivery, so each queue receives exactly one copy. A tap is therefore one binding from the business exchange (key # on a topic exchange) to a fanout exchange with its own bounded queue; deleting that binding removes the tap. Use a policy for limits such as max-length where possible, because a policy can be changed without redeclaring the queue.
The shovel plugin moves messages unidirectionally from a source (typically a queue) to a destination, in the same or another cluster; dynamic shovels are defined with runtime parameters (rabbitmqctl set_parameter shovel) and need no restart. A shovel consumes: it is a mover, not a copy. To use it as a tap, shovel from the tap queue. Federation links an upstream exchange or queue in another cluster to a local one, "replaying" published messages; it is the tool for geographic taps and is also configured by policy.
The management plane is the management API with rabbitmqadmin, plus rabbitmqctl for parameters, policies and purge_queue. Purge removes ready messages only: the AMQP 0-9-1 queue.purge method "removes all messages from a queue which are not awaiting acknowledgment".
// Command rabbitmq builds a wire tap with exchange-to-exchange bindings and shows the purge call.
// It exits unless AMQP_URL is set, so it compiles and vets without a broker.
package main
import (
"fmt"
"log"
"os"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
fmt.Println("set AMQP_URL to run; expected, not run in the book")
return
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
defer ch.Close()
// orders (topic) is the business exchange. orders.tap (fanout) is the side channel.
must(ch.ExchangeDeclare("orders", "topic", true, false, false, false, nil))
must(ch.ExchangeDeclare("orders.tap", "fanout", true, false, false, false, nil))
// Exchange-to-exchange binding: every message routed by orders with any key also reaches orders.tap.
// Removing this one binding removes the tap; no producer or consumer changes.
must(ch.ExchangeBind("orders.tap", "#", "orders", false, nil))
// The audit consumer owns its own queue, with a bound so a stopped tap cannot fill the broker.
q, err := ch.QueueDeclare("orders.tap.audit", true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-max-length": int64(100000),
"x-overflow": "drop-head",
})
if err != nil {
log.Fatal(err)
}
must(ch.QueueBind(q.Name, "", "orders.tap", false, nil))
// Channel Purger: removes every ready message from one queue. Unacknowledged deliveries stay.
if os.Getenv("ALLOW_PURGE") == "orders.tap.audit" {
n, err := ch.QueuePurge("orders.tap.audit", false)
must(err)
fmt.Println("purged", n, "messages")
}
}
func must(err error) {
if err != nil {
log.Fatal(err)
}
}# Expected, not run: the commands behind the pattern.
rabbitmqadmin --vhost "events" bindings declare --source "orders" --destination-type "exchange" --destination "orders.tap" --routing-key "#"
rabbitmqctl set_policy tap-limit "^orders\.tap\." '{"max-length":100000,"overflow":"drop-head"}' --apply-to queues
rabbitmqctl set_parameter shovel tap-copy '{"src-protocol":"amqp091","src-uri":"amqp://","src-queue":"orders.tap.audit","dest-protocol":"amqp091","dest-uri":"amqp://remote-host","dest-queue":"audit.archive"}'
rabbitmqadmin --vhost "events" queues purge --name "test.replies"
rabbitmqctl purge_queue test.repliesKafka
A Kafka tap is an extra consumer group: each group tracks its own committed offsets, so the audit group reads the topic without taking anything from the billing group. Nothing is copied; the log is shared, so a tap costs fetch bandwidth, not storage. A new group chooses where to start (auto.offset.reset, or the client's reset option). MirrorMaker 2 (connect-mirror-maker.sh, built on Kafka Connect) replicates topics and consumer groups between clusters; remote topics get the source cluster name as a prefix by default (DefaultReplicationPolicy, {source}.{topic}), which also stops replication loops inside one configuration.
The control and purge tools are kafka-consumer-groups (--list, --describe, --reset-offsets, --delete). --reset-offsets needs inactive consumers, defaults to --dry-run, and offers --execute, --export, --to-earliest, --to-latest, --to-offset, --to-datetime, --shift-by, --by-duration and --from-file. Deleting a group works only when it has no active members. There is no per-topic purge: retention (retention.ms, retention.bytes, cleanup.policy) decides when old segments go, and shortening it affects every consumer. An archive topic with long retention or compaction is the usual Message Store.
// Command kafka starts a wire tap as an independent consumer group. A group keeps its own committed
// offsets, so it observes the topic without taking records away from the business group.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
fmt.Println("set KAFKA_BROKERS to run; expected, not run in the book")
return
}
cl, err := kgo.NewClient(
kgo.SeedBrokers(strings.Split(brokers, ",")...),
kgo.ConsumerGroup("orders.audit-tap"), // the business group is, for example, "orders.billing"
kgo.ConsumeTopics("orders"),
kgo.ConsumeResetOffset(kgo.NewOffset().AtEnd()), // a new tap starts at "now", not at the beginning
kgo.DisableAutoCommit(),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
ctx := context.Background()
for {
fetches := cl.PollFetches(ctx)
if err := fetches.Err0(); err != nil {
log.Fatal(err)
}
fetches.EachRecord(func(r *kgo.Record) {
// Record only coordinates and safe headers, never the payload, in a real tap.
fmt.Printf("tap topic=%s partition=%d offset=%d key=%q\n", r.Topic, r.Partition, r.Offset, r.Key)
})
if err := cl.CommitUncommittedOffsets(ctx); err != nil {
log.Fatal(err)
}
}
}# Expected, not run.
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group orders.audit-tap
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group orders.audit-tap --topic orders --reset-offsets --to-latest --dry-run
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group orders.audit-tap --topic orders --reset-offsets --to-latest --execute
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --delete --group orders.audit-tap
bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters secondaryRedis Streams
A Redis Streams tap is a second consumer group on the same stream, created with XGROUP CREATE orders audit-tap $ MKSTREAM. Each group has its own last-delivered cursor and pending entries list, so the tap does not steal entries; it must XACK or its pending list grows. Three removal commands matter. XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] implements retention for the whole stream, so it also removes entries another group has not read; newer versions add KEEPREF, DELREF and ACKED to say how group references are treated (available since Redis 8.2). XDEL removes specific entries by id, which Redis documents as marking them deleted and freeing memory only when a whole internal node is empty. XGROUP DESTROY key group deletes a group with its cursor and pending list and replies 0 or 1; XGROUP DELCONSUMER removes one consumer.
// Command redis shows a tap as a second consumer group on the same stream, then the three
// removal commands: XTRIM (retention), XDEL (one entry) and XGROUP DESTROY (a whole group).
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("set REDIS_ADDR to run; expected, not run in the book")
return
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
// Each group has its own cursor and pending list. "$" means only entries added from now on.
if err := rdb.XGroupCreateMkStream(ctx, "orders", "audit-tap", "$").Err(); err != nil {
log.Printf("create group: %v", err)
}
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "audit-tap", Consumer: "tap-1", Streams: []string{"orders", ">"}, Count: 100, Block: time.Second,
}).Result()
if err != nil && err != redis.Nil {
log.Fatal(err)
}
for _, s := range res {
for _, m := range s.Messages {
fmt.Println("tap saw", m.ID) // the tap must XACK, or its own pending list grows without bound
rdb.XAck(ctx, "orders", "audit-tap", m.ID)
}
}
if os.Getenv("ALLOW_TRIM") == "orders" {
// Retention: drop entries older than 24 hours. Applies to all groups, including the business group.
cutoff := fmt.Sprintf("%d-0", time.Now().Add(-24*time.Hour).UnixMilli())
n, err := rdb.XTrimMinID(ctx, "orders", cutoff).Result()
if err != nil {
log.Fatal(err)
}
fmt.Println("trimmed", n)
}
if id := os.Getenv("DELETE_ENTRY"); id != "" {
fmt.Println(rdb.XDel(ctx, "orders", id).Result()) // erasure of one entry; ids are not renumbered
}
if os.Getenv("DESTROY_GROUP") == "audit-tap" {
fmt.Println(rdb.XGroupDestroy(ctx, "orders", "audit-tap").Result()) // removes cursor and pending list
}
}# Expected, not run.
redis-cli XGROUP CREATE orders audit-tap '$' MKSTREAM
redis-cli XREADGROUP GROUP audit-tap tap-1 COUNT 100 STREAMS orders '>'
redis-cli XTRIM orders MINID 1700000000000-0
redis-cli XDEL orders 1700000000000-0
redis-cli XGROUP DESTROY orders audit-tap| Capability | RabbitMQ | Kafka | Redis Streams | Laravel queue |
|---|---|---|---|---|
| Native wire tap | Exchange-to-exchange binding | Second consumer group | Second consumer group | Queue::before and Queue::after |
| Cross-cluster copy | Shovel, federation | MirrorMaker 2 | Application code | Not applicable |
| Control surface | Management API, rabbitmqadmin, policies | kafka-consumer-groups, topic configs | Commands via client | Artisan commands, cache flags |
| Purge | purge_queue | Retention or offset reset | XTRIM, XDEL, group destroy | queue:clear |
| Archive store | Queue with limits | Archive topic | Stream with trimming | Database table |
| Header limit and format | AMQP headers table | Record headers | Field-value pairs | Payload JSON |
| Selective deletion | Not native | Not native | XDEL by id | Per-job tools |
In production systems
- RabbitMQ documents that exchange-to-exchange bindings detect and eliminate cycles during delivery and give each queue exactly one copy, which is the property a tap relies on.
- RabbitMQ documents the shovel as unidirectional movement from a source to a destination and recommends dynamic shovels for most cases; federation is documented as policy-driven links to upstreams.
- Kafka documents that consumer group offsets can be reset only for inactive groups, with a dry run by default, and that MirrorMaker prefixes remote topics with the source cluster name by default.
- Redis documents that
XDELmarks entries deleted and frees memory only when a whole node of entries is deleted, which matters when deletion is used for erasure. - Laravel documents queue events and pause/clear commands; verify worker interruption polling before relying on
queue:pause. - Hohpe and Woolf's own Channel Purger page notes that many hosted systems, for example Amazon SQS, have a built-in purge function, which is why a purge must be treated as a deliberate act.
In architecture: from a single process to a distributed system
Monolith: one process, one database
In a modular Laravel monolith with the database queue, "management" is mostly a table and some Artisan commands: queue:pause for control, queue:clear for purge, a failed_jobs table, and Queue::before/after for a tap. A Message Store is another table written in the same transaction as the job, so it is exactly consistent. A canary job is a scheduled job with a marker property.
Modular monolith: explicit owners
Modules publish events on an internal bus. Give the bus one tap that writes to the store and one control channel for module switches. Decide who owns each management channel and each marker header; the test marker must be understood by every module's handler or the separator must sit in front of all of them.
Microservices: ownership follows the consumer
Each service owns its queues or groups; a tap on someone else's topic means a separate consumer group, not a shared one. A Control Bus per service plus a global admin topic works; commands name a target. Message History headers cross services and must be copied by every service that republishes. The Smart Proxy is a gateway-level component. Canaries should enter at the edge and exit at the last service, with each service passing the marker through.
1 Edge gateway : inject canary run-17 into orders
2 orders service : validate, publish OrderValidated with x-test-message=run-17
3 billing : separator diverts to verifier topic, skips the charge
4 verifier : confirms run-17 seen at billing in 4 s; alert threshold 30 sDistributed data: replicas, shards and regions
Across regions a tap becomes replication: RabbitMQ shovel or federation, Kafka MirrorMaker 2, application copy for Redis Streams. Remote copies lag; a store in region B lags region A. A purge applied in one region does not remove the replica copy. Control commands need ordering per target across regions, which is why sequence numbers and expiry are in the command, not inferred from arrival order. Do not interpret a gap in the store as loss until you account for replication lag.
Scaling path
| Load | Design | What changes |
|---|---|---|
| 1x: hundreds per second | Tap queue and a database store | Everything fits in one table; full bodies are fine |
| 10x | Archive topic, store holds ids and hashes | Sampling, retention, partitioned store tables |
| 100x | Taps by sampling or tenant allow-list, object-storage archive | Per-tenant canaries, rate-limited admin commands, history capped by bytes |
| Multi-region | Replicate archive, regional control buses | Per-region purge rules, lag-aware alerts |
Lab
All broker and Laravel experiments below are expected, not run. The Go tests do run and need no broker. Use a disposable environment.
1. Run the pure-logic tests
cd docs/snippets/messaging/messaging-system-management/go
go test -race ./...
# expected: ok for canary, controlbus, detour, history, purger, smartproxy, wiretap2. RabbitMQ tap with an exchange-to-exchange binding
rabbitmqadmin declare exchange --name orders --type topic
rabbitmqadmin declare exchange --name orders.tap --type fanout
rabbitmqadmin declare queue --name orders.tap.audit
rabbitmqadmin declare binding --source orders.tap --destination orders.tap.audit --destination-type queue
rabbitmqadmin declare binding --source orders --destination orders.tap --destination-type exchange --routing-key '#'
# expected, not run: publishing to orders with any key puts one copy in orders.tap.audit
# then delete the e2e binding: the next publish does not reach orders.tap.audit3. Kafka group as tap, then offset reset
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group orders.audit-tap --topic orders --reset-offsets --to-earliest --dry-run
# expected, not run: prints TOPIC PARTITION NEW-OFFSET for each partition; nothing changes without --execute4. Redis second group
redis-cli XGROUP CREATE orders audit-tap '$' MKSTREAM
redis-cli XADD orders '*' type OrderPlaced id 42
redis-cli XREADGROUP GROUP audit-tap tap-1 COUNT 10 STREAMS orders '>'
# expected, not run: the entry appears for audit-tap; the billing group still sees it as unread
redis-cli XGROUP DESTROY orders audit-tap
# expected, not run: (integer) 15. Canary and purge guard
Run go test ./canary ./purger -v. Expected: canaries never reach the business handler, overdue canaries are reported, a production purge without the confirmation phrase is refused.
Common misconceptions
| Belief | Reality |
|---|---|
| A wire tap is free | It adds routing, storage or fetch load and a failure mode |
| The tap sees what the consumer processed | It sees a separate delivery; it proves nothing about processing |
| A detour is a tap | A detour moves the real messages and can change or delay them |
| Control commands are always applied once | They are messages: at-least-once, so apply idempotently |
| A message store is an event store | A store is evidence about transport; an event store defines state |
| Message history replaces tracing | History shows the path; tracing shows timing and branches |
| Marking a test message with a special order id is fine | It mixes data and control; use a header marker |
| Purge removes everything on RabbitMQ | Unacknowledged messages remain |
| Kafka has a purge command | You change retention, reset offsets or delete the group |
XDEL frees memory immediately | Entries are marked deleted; memory frees when a whole node is empty |
| A forgotten detour is harmless | It adds latency and a single point of failure; give it an expiry |
| One canary proves everything works | It proves the path it takes; vary tenants, routes and payloads |
Cheat sheet
| Topic | What to remember |
|---|---|
| Wire Tap | Publish main first; bounded tap; drop and count; never fail the producer |
| RabbitMQ tap | Exchange-to-exchange binding to a fanout exchange with a bounded queue |
| Kafka tap | Another consumer group; own offsets; no extra storage |
| Redis tap | Second group with XGROUP CREATE; XACK or the PEL grows |
| Detour | Two outputs; expiry; seen marker; fail-safe default is direct |
| Control Bus | Allow-list, sequence per target, expiry, status echo |
| Message History | Origin plus newest hops; true hop count; hop limit |
| Message Store | Ids and key fields; dedupe on message id; retention |
| Smart Proxy | Rewrite reply-to; store by correlation id; TTL sweep |
| Test Message | Header marker; separator before side effects; alert on lateness |
| Channel Purger | Allow-list, dry run, depth re-check, typed confirmation |
| Kafka reset | --reset-offsets on inactive groups; dry run first |
| Redis removal | XTRIM for retention, XDEL by id, XGROUP DESTROY for a group |
| Laravel | Queue::before/after, queue:pause, queue:clear |
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 — Why must a wire tap publish to the main channel before copying? Important
Answer
Answer: A failed main publish must not leave a phantom copy of a message that never left, and a tap error must never reach the producer.
2 — What distinguishes a Detour from a Wire Tap? Must-know
Answer
Answer: A tap copies and leaves the business path alone. A detour moves the real messages through extra steps that can inspect, change or delay them.
3 — Why does a control command carry a sequence number and an expiry? Important
Answer
Answer: The control channel is at-least-once and may reorder. Sequence numbers make replays and old commands harmless; expiry stops stale commands from acting later.
4 — Why keep a true hop count separate from the history trail? Good to know
Answer
Answer: The trail must be size-bounded and so loses entries; the integer count stays exact and detects routing cycles.
5 — Why is a magic order id a poor test marker? Important
Answer
Answer: It overloads a business field with control meaning, can collide with real data and may reach business handlers. A header marker separated before side effects is safer.
6 — What does a RabbitMQ queue purge not remove? Must-know
Answer
Answer: Messages already delivered to consumers and awaiting acknowledgment.
7 — How do you "purge" a Kafka topic for one consumer group? Important
Answer
Answer: Reset that group's offsets (group inactive, dry run first) or delete the group. Changing retention affects every consumer.
8 — Why is a Message Store not an event store? Important
Answer
Answer: It records transport evidence and may hold only key fields; an event store is the authoritative record from which state is derived.
9 — What does the Smart Proxy key its table on, and what keeps the table bounded? Good to know
Answer
Answer: The correlation id; a TTL sweep removes entries whose reply never arrived.
10 — A Redis tap group is created but never acknowledged. What happens? Important
Answer
Answer: Its pending entries list grows without bound, because delivered entries stay pending until XACK.
Glossary
| Term | Meaning |
|---|---|
| Control Bus | Separate channels carrying management commands and status |
| Detour | Router with a direct path and an inspection path, switched by the control bus |
| Wire Tap | Fixed two-output recipient list that copies messages to a side channel |
| Message History | Header listing components the message passed through |
| Message Store | Durable queryable record of messages or key fields |
| Smart Proxy | Middleman that rewrites reply-to to track request-reply |
| Test Message | Marked synthetic message sent through the real pipeline |
| Channel Purger | Component or command that removes messages from a channel |
| exchange-to-exchange binding | RabbitMQ binding whose destination is another exchange |
| shovel | RabbitMQ plugin that moves messages from a source to a destination |
| federation | RabbitMQ plugin linking exchanges or queues across clusters |
| policy | RabbitMQ rule applied by name pattern to queues or exchanges |
| consumer group | Set of consumers sharing offsets; a second group is a tap |
| MirrorMaker 2 | Kafka Connect based cross-cluster replication |
| reset-offsets | kafka-consumer-groups option that moves a group's position |
| retention | How long or how much a log keeps (retention.ms, retention.bytes) |
| archive topic | Long-retention topic used as a message store |
| XTRIM | Redis command trimming a stream by length or minimum id |
| XDEL | Redis command deleting entries by id |
| XGROUP DESTROY | Redis command removing a consumer group |
| purge | Remove all ready messages from a queue |
| canary message | Synthetic marked message used as a health probe |
| synthetic transaction | End-to-end scripted probe of a business flow |
| correlation id | Identifier matching a reply to its request |
| reply-to rewriting | Replacing the reply address with the proxy's address |
| hop count | Number of components a message has passed |
| header size | Bytes in message headers; bounded for the history trail |
| feature flag | Runtime switch, here used as a routing switch |
| routing switch | State consulted by a router to choose a path |
| management API | Broker HTTP API for objects and operations |
| rabbitmqadmin | RabbitMQ command-line client for the management API |
| kafka-consumer-groups | Kafka tool to list, describe, reset and delete groups |
| dry run | Show what would happen without doing it |
| PEL | Redis pending entries list of a consumer group |
| message id | Identifier used to deduplicate stored messages |
References
- Hohpe and Woolf, Enterprise Integration Patterns: Control Bus, Detour, Wire Tap, Message History, Message Store, Smart Proxy, Test Message, Channel Purger.
- RabbitMQ: AMQP 0-9-1 extended spec, Queue length limits, Exchange to Exchange Bindings, Shovel, Dynamic Shovels, Federation, Policies, Management plugin, rabbitmqadmin, rabbitmqctl.
- Apache Kafka: Basic operations, Geo-replication and MirrorMaker, Topic configs, Design.
- Redis: XTRIM, XDEL, XGROUP CREATE, XGROUP DESTROY, XREADGROUP, XGROUP DELCONSUMER.
- Laravel 13: Queues, Redis.
- Go clients: amqp091-go, franz-go kgo, go-redis.