Skip to content

Consumer & Endpoint Patterns: Polling vs Event-Driven, Selective, Durable Subscriber, Transactional Client ​

"Connect an application to a messaging channel using a Message Endpoint, a client of the messaging system that the application can then use to send or receive messages." — Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, "Message Endpoint"

Summary: A Message Endpoint is the small piece of code where your application touches a broker; the other eight endpoint patterns are the decisions you make inside it (who asks for messages, who filters them, who remembers them, who routes them, who owns the transaction). Focus: Message Endpoint, Messaging Gateway, Polling vs Event-Driven Consumer, Message Dispatcher, Selective Consumer, Durable Subscriber, Transactional Client and Service Activator, realised on RabbitMQ, Kafka and Redis Streams, with Go and Laravel code, push-versus-pull trade-offs, what "durable" and "transaction" really mean per broker, endpoint resilience and testing. Learning goal: Design the consumer side of a service so that broker details stay in one thin layer, choose push or pull on purpose, know exactly what survives a disconnect or a crash, and stop trusting words ("durable", "transactional", "selector") until you have checked what the product does.

This page is the complete reference for the application side of messaging. Messaging Fundamentals draws the map, Integration Styles & Channels owns the channels themselves, Message Acknowledgment owns ack mechanics and Routing Topologies owns exchanges and bindings. Here the question is different: given a channel, how should the code that sends to it and reads from it be shaped? Scaling that code across many instances is Competing Consumers & Scaling Consumers; making it safe against duplicates is Idempotent Consumers & the Inbox Pattern. Compare the event side of the same ideas in Domain Events vs Integration Events and Designing for Failure: Reliable Messaging.

Page map ​

If you are looking forGo to
One table per pattern, memorisable in a minuteEverything in one minute
Why the endpoint layer exists, the analogyWhy it exists
Where the patterns come from, what the book actually saysWhere it comes from
The application-side client of a channelMessage Endpoint
Hiding the broker behind domain methodsMessaging Gateway
Application asks for messages (get, poll, XREADGROUP)Polling Consumer
Broker calls the application (callbacks, deliveries)Event-Driven Consumer
One channel, many handlers by typeMessage Dispatcher
Only some messages are wantedSelective Consumer
Messages saved while the subscriber is awayDurable Subscriber
Commit and rollback with the brokerTransactional Client
Message in, plain service call outService Activator
Push vs pull, reconnects, heartbeats, timers, error codesMechanics
Gateway leaks, one-consumer-for-everything, tight loops, testingSolving the classic problems
Go endpoints (amqp091-go, franz-go, go-redis)Go
Laravel worker loop, jobs, Horizon, packagesLaravel
RabbitMQ vs Kafka vs Redis StreamsBroker differences
Which pattern for which situationChoosing
Monolith to distributed, with the Fulfilment exampleIn architecture
Reproduce it step by stepLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The eight patterns. Each row is unpacked in the catalogue below.

PatternThe question it answersOne-line answerWhere it lives in code
Message EndpointHow does an application connect to a channel?Through a client of the messaging system, kept in one layerThe adapter package that imports the broker client
Messaging GatewayHow do I stop the broker API spreading through the app?An interface with domain methods, implemented once per brokerOrderEvents.orderPlaced()
Polling ConsumerHow do I receive a message when I am ready?Ask for it: basic.get, poll(), XREADGROUP BLOCKThe worker or poll loop
Event-Driven ConsumerHow do I receive messages as they arrive?Register a callback; the broker invokes itbasic.consume deliveries, a handler function
Message DispatcherHow do several handlers share one channel?One consumer reads, a table routes each message to a performerA type to handler map
Selective ConsumerHow do I receive only some messages?A selection value plus a filter, on the broker or in the clientA predicate on a header
Durable SubscriberHow do I not miss messages while I am offline?The broker keeps state for a named subscriptionA durable queue, a consumer group, a stream group
Transactional ClientHow do I control commit and rollback of my session?Make the session transactional, or ack after processingtx.commit, Kafka transaction, afterCommit
Service ActivatorHow do I call a service from a message and from elsewhere?Thin adapter: message in, plain call outA queued job's handle()

Push vs pull, as the products implement it.

ProductClient callWhat goes over the wireAPI style you write
RabbitMQbasic.consume (Go Channel.Consume)Broker pushes deliveries, bounded by prefetchEvent-driven
RabbitMQbasic.get (Go Channel.Get)One request, one reply (message or empty)Polling; the docs "strongly recommend against" it outside tests
Kafkapoll() (franz-go PollFetches)Fetch request, long poll on the brokerPolling
Redis StreamsXREADGROUP ... BLOCK msBlocking read, returns on data or timeoutPolling
Laravel queuequeue:work loop calling popDatabase query, BLPOP/Lua on Redis, SQS receivePolling (with block_for for Redis)

What "durable" means, per product.

ProductDurable subscription isIdentitySurvives
RabbitMQA durable queue bound to the exchange, with persistent messagesQueue nameConsumer disconnect, broker restart (persistent messages only)
KafkaA consumer group with committed offsetsgroup.idConsumer disconnect; offsets expire after offsets.retention.minutes (default 10080) once the group is empty
Redis StreamsA consumer group on the streamGroup name plus consumer nameConsumer disconnect; Redis restart only as far as persistence is configured
Redis Pub/SubNothing: fire and forgetnoneNothing

Why it exists ​

Without an endpoint layer, every class that needs a message calls the broker client directly: it sets properties, picks the exchange, parses frames, decides when to ack. After a year the broker is welded into the domain, the tests need a broker, and a migration from RabbitMQ to Kafka touches four hundred files. The endpoint patterns draw one line: everything that knows a broker's vocabulary lives on one side, everything that knows the business lives on the other.

Without the endpoint layerWith it
Domain code builds AMQP properties and Kafka recordsDomain code calls orderPlaced(order)
Every handler decides when to ackOne endpoint acks after the handler returns
One big callback with a switch on message typeA dispatcher and one small handler per type
Tests need a running brokerTests use a fake gateway and call handlers directly
Reconnect logic copied into each consumerOne reconnect loop in the endpoint
"Transaction" means whatever the author hopedThe transaction semantics are written down per broker

The everyday picture. A hotel with a front desk. Guests (the application) never walk into the mail room; they hand a request to the desk (Messaging Gateway), and the desk knows the courier's forms. Incoming parcels arrive at the desk (Message Endpoint). A bell-boy who stands at the door and takes each parcel when the courier rings is the Event-Driven Consumer; one who walks to the mail room every ten minutes to ask "anything for us?" is the Polling Consumer. A sorting rack that sends each parcel to the right department is the Message Dispatcher. A guest who says "only forward mail from my bank" is a Selective Consumer. A guest who is travelling and asks the desk to hold all mail until they return is a Durable Subscriber. A parcel signed for only when the room has accepted it is the Transactional Client.

Three common misunderstandings, up front.

  1. "Event-driven consumer means the broker pushes over the wire." The EIP text says the opposite: "How the messaging system gets the message is implementation-specific and may or may not be event-driven." Event-driven and polling describe the API the application sees, not the protocol. Kafka's poll() and Redis's XREADGROUP BLOCK are pull on the wire; a framework can wrap them in a callback and make them look event-driven.
  2. "Durable subscription is a switch you turn on." In RabbitMQ it is a queue you declare. In Kafka it is a group.id plus committed offsets plus a retention window. In Redis Streams it is a consumer group. If the subscriber's state is deleted (queue auto-deleted, offsets expired, group destroyed), the durability is gone and nothing warns you.
  3. "A transactional client makes the broker and my database atomic." No product on this page does that. RabbitMQ's own page calls its tx class "closer to providing a 'batching' feature than ACID capabilities". Kafka's transactions are atomic inside Kafka. Redis has no rollback. Atomicity between your database and a broker is what the Outbox Pattern is for.

Where it comes from ​

The nine patterns sit in the "Messaging Endpoints" chapter of Hohpe and Woolf's Enterprise Integration Patterns (2003). The book is written in the era of JMS and MSMQ, where an endpoint meant a Session, a MessageConsumer and a MessageListener. The authors' pattern pages (read for this chapter) are short and precise, and several have gained "NEW" notes that connect them to modern brokers:

  • Messaging Gateway is "a messaging-specific version of the more general Gateway pattern [EAA]" (Fowler's Patterns of Enterprise Application Architecture).
  • Event-Driven Consumer now carries a RabbitMQ example: "RabbitMQ consumers are by default event-driven." The example calls channel.basicConsume(queueName, autoAck, consumer) with autoAck = true and then says "This implementation is not a Transactional Client because the client acknowledges messages automatically on receipt but before processing."
  • Transactional Client carries an SQS note: "Transactional Client semantics can cause serious performance degradation in widely distributed systems. Many cloud-based messaging systems therefore don't implement Transactional Clients." The substitute is the visibility timeout, a consumer that does not delete a message lets it become visible again; the page adds that Cloud Computing Patterns documents this as a distinct pattern, Time-out Based Delivery.
  • Selective Consumer says outright that "a messaging system can optimize this process by not even delivering a message it knows the consumer will ignore", and warns that if no consumer is eligible for a selection value the message "will never be consumed and will clutter the channel forever".

Two adjacent patterns are owned elsewhere: Competing Consumers by Competing Consumers & Scaling Consumers, and Idempotent Receiver by Idempotent Consumers & the Inbox Pattern. The three brokers on this site came later and break several of the book's assumptions (a log instead of a queue, consumer groups instead of selectors); each catalogue block below says where.

The concept catalogue ​

Message Endpointthe application-side client of a channelMessaging Gatewayhides the broker APIbehind domain methodsTransactional Clientsession controlscommit / rollbackPolling Consumerapplication asks:get / poll / XREADGROUPEvent-Driven Consumerbroker calls back:deliveries / handlerMessage Dispatcherone channel, manyperformersSelective Consumeronly messages thatmatch a criterionDurable Subscribersaved while thesubscriber is awayService Activatormessage in, plainservice call outhow the application talks to the channelwhat the consumer does with what arrivesMessage Channel (broker)queue / topic / stream

The family has two halves. The first four patterns describe how the application talks to the channel (the endpoint itself, hiding it, controlling its transactions, asking versus being called). The other four describe what the consumer does with what arrives (route it, filter it, remember it for an absent subscriber, activate a service). The code that implements all of it for the worked example is in Go and Laravel.

Message Endpoint Must-know ​

In plain words: The Message Endpoint is the doorway: the one place in your program that knows how to talk to the broker, so the rest of the program does not have to.

Common misunderstanding: "An endpoint is the broker's address (host and port) or a REST-style URL." In EIP an endpoint is code on the application side: the sender or receiver that wraps a client library. The channel lives in the broker; the endpoint lives in your process.

Definition: "Message Endpoint code is custom to both the application and the messaging system's client API. The rest of the application knows little about message formats, messaging channels, or any of the other details of communicating with other applications via messaging." (Hohpe and Woolf.) An endpoint translates between the application's call and a message, and owns connection, channel/session, serialisation, acknowledgement and error handling.

Sending endpoint                        Receiving endpoint
1  domain call: orderPlaced(o)          1  broker -> endpoint: delivery / record / entry
2  endpoint: o -> bytes + properties    2  endpoint: bytes -> Envelope{id,type,key,headers,body}
3  endpoint -> channel: publish         3  endpoint -> application: handler(envelope)
4  channel -> endpoint: confirm         4  application -> endpoint: nil or error
5  endpoint -> domain: return           5  endpoint -> broker: ack / commit / XACK, or nack

Real scenario: Fulfilment consumes sales.order.placed. Its endpoint package imports amqp091-go or franz-go and nothing else does; every other package sees an Envelope. When the platform team moves Sales events from RabbitMQ to Kafka, the diff is one package and one line in main.

ProductThe endpoint objectIdentity it carries
RabbitMQA Channel on a Connection plus a consumer (consumer tag)Consumer tag, channel number
KafkaA Client (franz-go) or KafkaConsumer/KafkaProducer (Java)group.id, client.id, optionally group.instance.id
Redis StreamsA connection issuing XADD and XREADGROUPConsumer name inside a group
LaravelA queue connection (config/queue.php) plus a worker processConnection name, queue name

Fix / how to use it: keep the endpoint thin (translate, ack, reconnect) and put no business rules in it; see Go for endpoint.Source, and the anti-pattern list in Solving the classic problems.

Messaging Gateway Must-know ​

In plain words: A gateway is a class with business-named methods (orderPlaced, chargeCard) that hides every messaging detail behind them.

Common misunderstanding: "A gateway is an API gateway or a service mesh." The EIP Messaging Gateway is an in-process class, "a messaging-specific version of the more general Gateway pattern [EAA]". It is not a network hop.

Definition: "A Messaging Gateway [is] a class than wraps messaging-specific method calls and exposes domain-specific methods to the application", so that "only the Messaging Gateway code knows about the messaging system; the rest of the application code does not." (Hohpe and Woolf.) Its call can be fire-and-forget or request-reply; for the second form see Request-Reply over Messaging & REST vs AMQP.

1  checkout code      -> OrderEvents.orderPlaced(order)           (domain vocabulary)
2  gateway            -> builds id, type, key, region, JSON body
3  gateway            -> broker client: publish persistent + await confirm
4  broker             -> gateway: confirm (or nack)
5  gateway            -> checkout code: return / typed error
-- test: step 3 is replaced by Fake, steps 1-2 and 5 are asserted

Real scenario: The checkout service has forty call sites that publish OrderPlaced. With a gateway there is one place that sets the idempotency id, the partition key and the persistent flag. A missing message-id bug is fixed once. Unit tests use the Fake gateway and never see a broker.

ConcernGateway's jobPer-broker translation
IdentitySet a stable message idRabbitMQ MessageId property; Kafka header id; Redis field id
TypeSet the message typeRabbitMQ Type property and routing key; Kafka header type; Redis field type
Ordering keySet the keyRabbitMQ routing key or single queue; Kafka record key; Redis one stream
DurabilityMark persistent / wait for the brokerRabbitMQ DeliveryMode: Persistent + publisher confirm; Kafka acks=all (franz-go default); Redis XADD reply (and persistence config)
FailureReturn a typed errorAMQP nack, Kafka produce error, Redis error

Fix / how to use it: define the interface in the domain package, implement it once per broker, and inject it. Go: gateway.OrderEvents with gateway.AMQP, gateway.Kafka and gateway.Fake. Laravel: the OrderEvents interface bound in the container, QueueOrderEvents as the implementation, Queue::fake() in tests. Business logic does not belong in the gateway (it is in the anti-pattern list below).

Polling Consumer Must-know ​

In plain words: The application asks "is there a message for me?" when it is ready, takes one (or a batch), processes it, and asks again.

Common misunderstanding: "Polling is always a tight loop that burns CPU." A well-built polling consumer blocks inside the call (a long poll) and returns when data arrives or a timeout expires. Kafka's poll() and Redis's XREADGROUP ... BLOCK do exactly that. Only a loop that calls a non-blocking get and immediately repeats is wasteful; Kafka's own design page names the problem: "the consumer may end up polling in a tight loop, effectively busy-waiting for data to arrive", which is why the fetch request can "block in a 'long poll'".

Definition: "A Polling Consumer [is] one that explicitly makes a call when it wants to receive a message. This is also known as a synchronous receiver, because the receiver thread blocks until a message is received." (Hohpe and Woolf.) The application controls the pace.

Polling consumer (Kafka / Redis Streams)           clock
1  poll(max 500, wait up to 500 ms) -> 3 records   10:00:00.000
2  process 3 records (120 ms)
3  commit offset / XACK                           10:00:00.130
4  poll() -> blocks, no data                       10:00:00.131
5  ... broker holds the request ...
6  poll() returns 12 records (data arrived)        10:00:01.002
-- the consumer never receives more than it asked for

Real scenario: A nightly reconciliation worker reads 100,000 events as fast as the database can absorb them, then pauses when the database is busy: it simply stops polling. A flash-sale spike fills the stream, and the consumer falls behind and catches up when it can. Laravel's queue:work is a polling consumer: it pops a job, runs it, pops again, and sleeps --sleep seconds when the queue is empty.

ProductHow the poll is spelledWhat bounds the batchWhat happens if you stop polling
RabbitMQbasic.get (one message per call)One messageNothing; messages wait in the queue
Kafkapoll(Duration); franz-go PollFetches(ctx)max.poll.records (500), fetch.max.wait.ms (500), fetch.min.bytes (1)After max.poll.interval.ms (300000) the client leaves the group and a rebalance starts
Redis StreamsXREADGROUP GROUP g c COUNT n BLOCK ms STREAMS key >COUNT, BLOCKEntries stay pending for that consumer until claimed
Laravel databaseSELECT ... FOR UPDATE on jobs (the driver passes a lock to the query)One job per popThe worker sleeps --sleep between empty pops
Laravel RedisLua pop plus optional BLPOP when block_for is setOne job per popSame; block_for=0 blocks until a job arrives and delays SIGTERM handling

Fix / how to use it: poll with a timeout or a block, never in a bare loop; process, then ack or commit; keep processing time under the liveness limit (max.poll.interval.ms on Kafka, the delivery acknowledgement timeout on RabbitMQ quorum queues). Code in Go (kafka.Source, redisstream.Source, rabbitmq.Poll) and Laravel.

Event-Driven Consumer Must-know ​

In plain words: The application hands the broker a function and says "call this whenever a message arrives." The code has no loop of its own; the client library calls it.

Common misunderstanding: "Event-driven means no polling anywhere." Under a callback API there may still be a loop: the Go amqp091 client reads frames from a socket and feeds a channel, and a Java Kafka wrapper polls in a background thread and invokes a listener. Event-driven describes what your code looks like. In RabbitMQ the wire really is push: the docs say "applications can subscribe to have RabbitMQ push enqueued messages (deliveries) to them".

Definition: "An Event-Driven Consumer is an object that is invoked by the messaging system when a message arrives on the consumer's channel." Also called an asynchronous receiver: "the receiver does not have a running thread until a callback thread delivers a message." (Hohpe and Woolf.)

Event-driven consumer (RabbitMQ)
1  consumer -> broker: basic.qos(prefetch=10)
2  consumer -> broker: basic.consume(queue, tag="fulfilment-1", autoAck=false)
3  broker -> consumer: deliver #1 ... #10     (unprompted, up to the prefetch window)
4  consumer: handler(#1) -> ok
5  consumer -> broker: basic.ack(#1)
6  broker -> consumer: deliver #11            (window slid by one)

Real scenario: Fulfilment needs the lowest possible latency from "order placed" to "stock reserved"; the broker pushes each message the moment it is routed, and the consumer never idles between polls. A web notification service attached to a durable queue gets each event within milliseconds.

ProductWire behaviourAPI you writeBackpressure
RabbitMQ AMQP 0-9-1True push; consumer tag identifies the subscriptionCallback or Go channel of DeliveryPrefetch (basic.qos) bounds unacknowledged deliveries
KafkaPull (long poll)Listener wrappers hide the loop (Spring-style, laravel-kafka handler)You stop polling
Redis StreamsPull (blocking read)Same: wrapper around XREADGROUP BLOCKYou stop reading
Redis Pub/SubPush, fire-and-forgetSUBSCRIBE callbackNone, and nothing is stored: "fire and forget"

Fix / how to use it: set prefetch, ack manually after processing, and make the shutdown path explicit: cancel the consumer tag (Channel.Cancel), finish the in-flight deliveries, then close. The shape is rabbitmq.Source in Go. The push-vs-pull comparison is in Mechanics.

PUSH (RabbitMQ basic.consume)PULL (Kafka poll, XREADGROUP BLOCK, basic.get)BrokerConsumerConsumerBrokerbasic.qos(prefetch=10)basic.consume(tag)deliver 1..10, unpromptedbasic.ack(1)deliver 11 (window slid)idle: nothing sentthe broker decides when; prefetch bounds itlatency: lowest. backpressure: the windowpoll(max.poll.records=500)records (long poll up to fetch.max.wait.ms)process, then commit offsetpoll() again, when readyempty: wait for data or timeoutmiss max.poll.interval.ms: evictedthe consumer decides when; batch size is its choicebackpressure: free (just do not poll)

Message Dispatcher Important ​

In plain words: One consumer reads the channel; a dispatcher hands each message to the right worker (the "performer") and the worker does the job.

Common misunderstanding: "A dispatcher is a load balancer between consumer instances." That is Competing Consumers. A Message Dispatcher works inside one consumer (or one process): "consume messages from a channel and distribute them to performers", where a performer is "newly created by the dispatcher, or ... selected from a pool of available performers", and "the dispatcher may match a message to a specialized performer based on properties of the message." (Hohpe and Woolf.)

Definition: Two parts: a Dispatcher that consumes from the channel and a Performer that processes. Dispatch can be by message type (routing table), by availability (worker pool) or both.

1  endpoint -> dispatcher: Envelope{type=sales.order.cancelled}
2  dispatcher: table["sales.order.cancelled"] -> releaseStock
3  dispatcher -> performer: releaseStock(envelope)
4  performer -> domain service: release(orderId)   (idempotent on message id)
5  performer -> dispatcher: nil
6  dispatcher -> endpoint: nil  -> endpoint acks
-- unknown type: dispatcher returns Permanent(ErrUnknownType) -> endpoint rejects, no requeue

Real scenario: Fulfilment subscribes to one queue fulfilment.sales-events bound with sales.order.#. A dispatcher maps placed to reserveStock, cancelled to releaseStock, paid to scheduleShipment. Adding a type is a one-line registration and a new handler, not a new consumer process.

ConcernDispatch by typeDispatch by availability
PurposeRoute to the right codeBound concurrency, use all cores
Built frommap[type]handlerSemaphore or worker pool (see Competing Consumers)
OrderingPreserved if handlers run seriallyLost unless keyed per partition/key
Laravel analogueThe worker resolving payload['job'] to a class and calling fire()The multiple workers a supervisor starts
Failure of unknown typePermanent error, rejectNot applicable

Fix / how to use it: keep the dispatcher a pure routing table (no I/O), make "unknown type" a loud permanent failure (not a silent drop) and let each performer be tiny. endpoint.Dispatcher in Go and SalesEventRouter in Laravel are the examples. Note on Horizon: it supervises and balances worker processes across queues (its docs describe "worker process configuration" and automatic balancing); that is closer to Competing Consumers than to a Message Dispatcher. The dispatch of a payload to a class is done by the worker, in Job::fire() and CallQueuedHandler::call().

Selective Consumer Important ​

In plain words: A consumer says "I only want messages that match this", and everything else is skipped.

Common misunderstanding: "Brokers filter for you, like SQL WHERE." RabbitMQ queues, Kafka topics and Redis stream groups have no per-message selector on the consumer side. (JMS had message selectors; EIP was written with them in mind.) The product gives you routing (which messages reach the channel) and, in a few cases, coarse filters; precise filtering is yours.

Definition: Three parts: a specifying producer sets a selection value, the message carries it, and the Selective Consumer "only receives messages that meet its selection criteria". With competing selective consumers on a point-to-point channel, the book warns: "Consumers should be designed to ensure that at least one of them is eligible to consume every valid selection value. Otherwise, a message with an unmatched selection value will never be consumed and will clutter the channel forever." On a publish-subscribe channel "each message will be delivered to each subscriber, but a subscriber will simply ignore its copy".

1  producer -> channel: Envelope{type=placed, headers.region=us}
2  channel  -> consumer-eu: copy (broker cannot filter: it delivers everything)
3  consumer-eu: predicate(region == "eu") -> false
4  consumer-eu -> broker: ack (skip == success; do not requeue, do not redeliver)
-- cost: the message was delivered, parsed, and discarded

Real scenario: A regional fulfilment worker should handle only region=eu. If Sales publishes all regions to one topic, every worker receives every message and throws most away. The better design is a topic or routing key per region so the broker never delivers the wrong ones.

ProductBroker-side selectionClient-side
RabbitMQ queues (classic, quorum)None on the consumer; select by exchange and binding (direct, topic, headers)Filter in the handler, then ack
RabbitMQ streamsThree stages: Bloom filter on chunks (publisher sets a filter value), AMQP filter expressions (property or SQL), then client-side filteringStage 3
KafkaNone per record. A regex subscription (kgo.ConsumeRegex) picks topics, not recordsFilter on a header before decoding the body; or Kafka Streams
Redis StreamsNone in XREADGROUP; separate streams or filtering in the clientFilter, then XACK
Laravel queuesSelect by queue name: queue:work --queue=emailsJob middleware or a guard clause in handle()

Fix / how to use it: prefer routing to selecting (more in Choosing and Routing Topologies); if you must filter in the client, filter on a header or key cheaply, ack the skipped message, and count skips as a metric. endpoint.Selective in Go is the wrapper.

Durable Subscriber Must-know ​

In plain words: A durable subscription makes the broker keep your messages while you are offline, and hand them over when you reconnect.

Common misunderstanding: "Durable means the messages are written to disk." That is persistence of the messages. A durable subscriber is about who the broker keeps state for. A durable queue with transient messages loses them on restart; a non-durable subscriber on a durable broker misses everything published while it was away.

Definition: "A durable subscription saves messages for an inactive subscriber and delivers these saved messages when the subscriber reconnects. In this way, a subscriber will not lose any messages even though it disconnected. A durable subscription has no effect on the behavior of the subscriber or the messaging system while the subscriber is active." (Hohpe and Woolf.) It applies to publish-subscribe channels; a point-to-point channel already keeps messages.

Subscriber B, durable vs not, on a publish-subscribe channel
09:00  B connected                     publish m1  -> B receives m1
09:05  B disconnected (deploy)         publish m2, m3
09:10  B reconnects
        durable    -> receives m2, m3 (broker kept them under B's identity)
        non-durable-> receives nothing from the gap; only m4 onward

Real scenario: The billing service is down for a 15-minute deploy while Sales publishes 4,000 events. On restart it must see all 4,000. A new analytics consumer joins next month and wants history: that is a replay (Kafka, Redis stream, RabbitMQ stream), which a plain durable queue cannot give.

ProductPrimitiveIdentityWhat can silently end the durability
RabbitMQDurable queue (metadata on disk) bound to the exchange; messages published delivery_mode=2Queue nameAuto-delete or exclusive queue; transient messages ("discarded during recovery"); a queue TTL; deleting the queue
KafkaConsumer group; offsets committed to __consumer_offsetsgroup.idOffsets expire offsets.retention.minutes (default 10080, 7 days) after the group becomes empty; log retention deleting records first, then auto.offset.reset (default latest) silently jumps ahead
Redis StreamsConsumer group with last_delivered_id and a pending listGroup name, consumer nameGroup destroyed; stream trimmed past the group's position; Redis restart without persistence
Redis Pub/SubNonenoneEverything: messages are "fire and forget"
LaravelNot a subscription model; a queue holds jobs until a worker takes themQueue namefailed_jobs pruning, queue flush

Fix / how to use it: RabbitMQ: QueueDeclare(name, durable=true, ...) plus persistent messages; do not use exclusive or auto-delete for a subscription that must survive. Kafka: choose auto.offset.reset=earliest for a new group that must see history, commit offsets, and alert on lag. Redis: XGROUP CREATE ... MKSTREAM, read pending entries (id 0) before new ones (>) after a restart. See the code in Go. Dead subscribers that never return fill the broker; give them a retention or expiry decision.

Transactional Client Must-know ​

In plain words: The client can say "treat these sends and receives as one unit: either all of them happen or none."

Common misunderstanding: "Transactional means ACID across my database and the broker." The EIP definition is narrower: "make the client's session with the messaging system transactional so that the client can specify transaction boundaries. ... With a sender, the message isn't 'really' added to the channel until the sender commits the transaction. With a receiver, the message isn't 'really' removed from the channel until the receiver commits the transaction." Boundaries are with the messaging system. Your database is another resource.

Definition: A session with commit and rollback. Both sender and receiver can be transactional; explicit and implicit transactional peers can share a channel.

Receive-process-send on RabbitMQ (channel in tx mode)
1  ch.Tx()                                   (once; the channel stays in tx mode)
2  deliver m1 <- queue in
3  handler(m1)                                -> result r
4  publish r -> exchange out                  (held by the broker until commit)
5  ack m1                                     (held until commit)
6  ch.TxCommit()   -> publish and ack become visible together
   -- failure at 3-5: ch.TxRollback() -> publish discarded, ack discarded;
      the delivery is NOT requeued by rollback (the client can still ack/reject it)

Real scenario: A stage that reads order.placed, writes stock.reserved and acks the input must not ack without publishing (stage lost) or publish without acking (duplicate on redelivery). A transactional session is the broker-level tool for that. Across a database write it is not enough: see In architecture.

ProductWhat "transaction" meansWhat it coversWhat it does not
RabbitMQ AMQP 0-9-1tx.select, tx.commit, tx.rollbackPublishes and acks (reject too since 2.8.0)Consuming itself ("acknowledgements are transactional, not the consuming"); atomicity across queues; resource declarations. The docs call it "closer to ... 'batching' ... than ACID" and measure "a factor of 250" lower throughput than confirms
KafkaProducer transactions (transactional.id); read_committed consumersRecords to several topics/partitions plus consumed offsets, atomicallyAnything outside Kafka; the consumer itself is not transactional
Redis StreamsMULTI/EXEC is atomic but "Redis does not support rollbacks"A batch of commands runs togetherRollback; undoing a partially applied batch
SQS (EIP note)Not a Transactional Client; visibility timeoutA consumer that crashes before delete lets the message reappearAnything resembling commit
LaravelDB::transaction plus afterCommitThe push happens only if the DB transaction commitsA crash between COMMIT and the push; Laravel does not undo the push if something later fails

Fix / how to use it: prefer ack after processing (at-least-once) plus idempotent handlers over exotic transactions; use confirms rather than RabbitMQ tx; use Kafka transactions only for consume-transform-produce inside Kafka; use the outbox for DB plus broker. Code: rabbitmq.AckAndForward, kafka.ConsumeProcessProduce, PlaceOrder with afterCommit.

Service Activator Important ​

In plain words: A tiny adapter takes a message off the channel and calls an ordinary function in your domain; the function never learns it was called through a queue.

Common misunderstanding: "The handler class is the service." A Service Activator should be thin: it unpacks the message and invokes a service "like any other client, such that the service doesn't even know it's being invoked through messaging." (Hohpe and Woolf.) If the same rule is needed from an HTTP controller and from a message, the rule belongs in the service, not the activator.

Definition: "Design a Service Activator that connects the messages on the channel to the service being accessed." One-way (request only) or two-way (request-reply); hard-coded to one service or selecting it by reflection from the message.

1  worker pops job {"job":"...CallQueuedHandler@call","data":{"command":"...ReserveStock"}}
2  CallQueuedHandler: unserialize command ReserveStock(messageId, orderId)
3  ReserveStock::handle(StockService $stock)         <- the Service Activator
4  StockService::reserveOnce(messageId, orderId)      <- plain domain call
5  handler returns -> worker deletes the job (the ack)

Real scenario: StockService::reserveOnce is called from the HTTP admin screen ("reserve manually") and from the job. Only the job knows about retries and backoff; only the service knows about stock.

Product / frameworkActivator isDispatch to the service
LaravelA queued job's handle() or a queued listenerContainer injects the service into handle()
GoA Handler func registered in the dispatcherPlain function call with decoded input
Kafka via laravel-kafkaAn invokable handler passed to withHandlerYou call the service inside it

Fix / how to use it: keep it to decode, validate, call, return; map "bad payload" to a permanent error, transient failures to retryable ones. ReserveStock (Laravel) and reserveStock (Go worked example) show the shape. The activator is also where an Idempotent Receiver check goes.

Mechanics ​

Push versus pull, the trade-offs Must-know ​

In plain words: Push gives the lowest delay; pull gives the consumer control. Both need a limit so the consumer is not buried.

Common misunderstanding: "Push is faster, so it is better." Kafka's design page says a push-based system "has difficulty dealing with diverse consumers as the broker controls the rate at which data is transferred" and that "the consumer tends to be overwhelmed when its rate of consumption falls below the rate of production (a denial of service attack, in essence)". Pull's property: "the consumer simply falls behind and catches up when it can."

AxisPush (RabbitMQ basic.consume)Pull (Kafka poll, Redis XREADGROUP BLOCK, basic.get)
LatencyLowest: delivered as soon as routedOne poll round trip, or the long-poll wait; with fetch.min.bytes larger, deliberately higher
BackpressurePrefetch window (basic.qos); the broker stops sending at the limitFree: do not poll; lag grows in the log
BatchingMessage by message; throughput comes from prefetchNatural: the consumer takes everything after its position, "optimal batching without introducing unnecessary latency" (Kafka design)
Fairness between consumersRound-robin over consumers with window room; one slow message can sit in a bufferPer partition or per entry; a slow consumer only delays itself
Empty-queue costZero: nothing is sentA long-poll request outstanding; basic.get is "extremely wasteful"
Failure detectionHeartbeats and TCP; consumer cancel notificationPoll/heartbeat timers: session.timeout.ms 45000, max.poll.interval.ms 300000
Who owns the paceThe broker (bounded by you)The consumer
Typical riskPrefetch too high: unacked messages pile up in one consumerNot polling often enough: rebalance (Kafka), pending growth (Redis)

The two axes people confuse Important ​

In plain words: "Does the broker push bytes?" and "does my code have a loop?" are separate questions.

Common misunderstanding: "If my code has a callback, the system is push." The callback may sit on top of a poll.

Client callWire directionAPI style
Go Channel.ConsumePushYou read a Go channel in a loop (event-driven in spirit, a loop in form)
Go Channel.GetPull, one messagePolling
franz-go PollFetchesPull (long poll)Polling
laravel-kafka withHandlerPullHandler callback over a loop inside the package
go-redis XReadGroup with BlockPull (blocking)Polling
Laravel queue:work against RabbitMQ packagebasic_get per the package READMEPolling
rabbitmq:consume from the same packagebasic_consume, "more performant than basic_get by ~2x" per its READMEEvent-driven
Sales codecallsorderPlaced()MessagingGateway(interface)BrokerchanneldurableMessage Endpoint(Source)EnvelopeSelectiveConsumerregion = eu?domain callpublishpush or pullskip = ackMessage Dispatchertype to performerService ActivatorreserveStockService ActivatorreleaseStockFulfilment domain service (idempotent on message id)knows nothing about the brokerAck / commit only after theperformer returns nilRabbitMQ: basic.ack, Kafka: commit offsetRedis Streams: XACKunknown type = permanent error: reject, do not requeue

Endpoint resilience Must-know ​

In plain words: An endpoint must expect the connection to die, the handler to hang and the broker to move people around; each has a timer, and the timers must be set together.

Common misunderstanding: "The client library reconnects for me." It depends: Java, .NET and Bunny for RabbitMQ offer connection recovery (including consumer recovery); the Go amqp091 client documents none (its README mentions no recovery), so the loop in rabbitmq.Source.Run is yours. franz-go reconnects and rejoins groups by itself.

Dead TCP peer, RabbitMQ, heartbeat 30 s
00:00  network drops, nothing arrives, no FIN
00:30  two heartbeat intervals missed -> client closes the connection
00:30  NotifyClose fires -> session() returns error -> Run() waits backoff (1s, 2s, 4s ... 30s)
00:31  reconnect, QueueDeclare/Bind are idempotent, Consume resumes
       unacked deliveries from the dead channel were requeued by the broker (redelivered=true)
-- without heartbeats the OS needs about 11 minutes (Linux defaults) to notice
TimerProductDefaultWhat happens at expiryRule
Heartbeat timeoutRabbitMQ60 s suggested, negotiatedConnection considered dead, closedDo not set very low (false positives); do not disable
Delivery acknowledgement timeout (consumer_timeout)RabbitMQ 4.3 quorum queues30 minutesMessages returned to the queue; AMQP 0-9-1 consumer cancelled or channel closed with PRECONDITION_FAILEDRaise it only for jobs that really need it
session.timeout.msKafka45000Broker removes member, rebalanceHeartbeat interval 3000, about a third of it
max.poll.interval.msKafka300000Client leaves the group; commitSync may throw CommitFailedExceptionSlow handlers: lower max.poll.records or process off-thread
RebalanceKafkan/aPartitions revoked and reassignedCommit before revoke; see Competing Consumers
BLOCK msRedis XREADGROUPnone (0 = forever)Reply nilUse a finite block so the loop can see ctx.Done()
--timeout / retry_afterLaravel60 s / 90 s (config default)Worker killed; job released--timeout several seconds below retry_after
block_forLaravel RedisnullWorker blocks in BLPOP0 delays SIGTERM handling

Graceful shutdown order, the same in every product: stop receiving new work (cancel the consumer tag, stop polling), let in-flight handlers finish under a deadline, ack or commit, then close connections. signal.NotifyContext turns SIGTERM into a cancelled context in Go; Laravel's worker checks for queue:restart and signals between jobs.

Error codes and replies you will meet Important ​

WhereCode or messageMeaningRetry?
RabbitMQAMQP 406 PRECONDITION_FAILEDDelivery acknowledgement timeout exceeded (consumer holds an unacked delivery too long); also a queue redeclared with different argumentsFix the cause; raise consumer_timeout only if legitimate
RabbitMQConsumer cancelled by the broker (consumer cancel notification)Delivery acknowledgement timeout on a quorum queue, when the client supports cancel notificationsRe-consume after fixing the slow handler
KafkaCommitFailedExceptionCommit after the member left the group (poll gap)Re-poll; offsets will be re-read
KafkaRebalanceInProgressException (Java commitSync)Commit attempted in the middle of a rebalanceRetry after the rebalance; poll again
RedisBUSYGROUP Consumer Group name already existsXGROUP CREATE on an existing groupIgnore
LaravelMaxAttemptsExceededException, TimeoutExceededExceptionJob exceeded tries or --timeoutGoes to failed_jobs; see Dead-Letter Queue

Solving the classic problems ​

The broker leaks into the domain Must-know ​

SolutionHowAdvantageCost / limitation
Messaging Gateway interfaceDomain package owns OrderEvents; one adapter per brokerSwappable, testable with a FakeOne more layer to maintain
Anti-corruption mapping at the edgeEndpoint maps broker types to Envelope; domain never imports a clientVersion upgrades of the client touch one packageA mapping per message type
Do nothing, call the clientDirect publish in handlersFewest lines todayEvery test needs a broker; migration is a rewrite

Go: gateway.OrderEvents with gateway.AMQP and gateway.Kafka (see Go). Laravel: OrderEvents bound to QueueOrderEvents; tests swap in Queue::fake(). The cost of the layer is a few dozen lines; the cost of its absence is every test.

One consumer for every message type Important ​

A single consumer with a growing switch becomes the system's bottleneck and its blast radius: one slow handler delays every type, one panic stops all of them, and a deploy for one type restarts the others.

SolutionHowAdvantageCost / limitation
Dispatcher in one processtype to handler map, bounded per-type concurrencySimple, one deployableShared fate of handlers
One queue / topic per type or per bounded contextRouting at the broker (Routing Topologies)Independent scaling, lag per typeMore channels to operate
Separate consumer groups per concernSame topic, groups fulfilment, billingEach progresses independentlyEach reads the whole topic

Rule of thumb: one dispatcher per bounded context's queue, not one per company. Unknown types are a permanent error, never a silent drop.

Selective Consumer vs routing Important ​

In plain words: Filtering after delivery wastes the delivery; routing before delivery does not.

Common misunderstanding: "Selectors scale because the broker does the work." In the products here the broker does not evaluate your predicate (outside RabbitMQ streams' filter stages). Every selective consumer receives, deserialises and discards its non-matches. Ten regional consumers on one topic means each message crosses the network ten times and nine copies are thrown away.

ApproachWhere the filter runsCost per skipped messageUse when
Separate channel per interest (topic per region, routing key per region)Broker routingZero for the consumerThe interest is stable and known: region, tenant tier, event type
RabbitMQ exchange bindings (direct, topic, headers)BrokerZero for the consumerFew consumers with distinct interests
RabbitMQ stream filters (Bloom filter, AMQP filter expression)Broker, chunk or message levelLower; Bloom filters allow false positives, so a client stage still runsLarge streams, rare matches
Client-side predicate on a headerConsumerDelivery + header parse + ackInterests change often or are cheap to check
Kafka Streams / stream processor filterA separate processor writes a filtered topicOne pass for everyoneMany consumers want the same subset
Content-based router upstreamA router app publishes to per-interest channelsOne extra hopRouting logic changes more often than consumers; see Advanced Routing

The EIP vs Kafka reality, in one line: the book imagines a broker that "can optimize this process by not even delivering a message it knows the consumer will ignore"; Kafka, Redis Streams and RabbitMQ queues deliver everything on the channel and leave the decision to you, which is why the scalable answer is more channels (topic per interest) rather than smarter consumers. Skipping is also a correctness trap: a skipped message must be acked (or its offset committed), otherwise it blocks the partition or sits pending forever.

What "durable" actually promises Must-know ​

Durability has three independent layers, and a subscription is only as durable as the weakest:

LayerQuestionRabbitMQKafkaRedis Streams
Subscription stateDoes the broker remember who I am and how far I got?Durable queue existsgroup.id offsets retained (offsets.retention.minutes, 10080 default)Group exists in the stream key
Message storageDo the messages survive a broker restart?Persistent messages (delivery_mode=2) on a durable queueLog on disk, replicated (ISR)Depends on RDB/AOF; async replication
Message retentionAre messages still there when I return?Until consumed (or queue TTL)Until log retention deletes themUntil XTRIM/MAXLEN removes them

Failure to know the third layer is the Kafka classic: the group returns after the topic's retention has deleted its position, the offset is invalid, and auto.offset.reset (default latest) jumps to the end with no error. Set it to earliest for subscribers that must not skip, and alert on lag so you notice before retention does. See Delivery Guarantees and Dead-Letter Queue for what happens to messages that cannot be processed.

Transactional semantics and the XA myth Must-know ​

In plain words: Each broker has its own meaning of "transaction", none of them includes your database, and a distributed transaction between the two is not on the menu.

What you wantRabbitMQKafkaRedis StreamsHonest answer
Publish only if my DB commit succeedsNoNoNoOutbox (Outbox Pattern)
Ack only if my DB commit succeedsAck after commit (at-least-once)Commit offset after commitXACK after commitIdempotent handler (Inbox)
Consume + produce atomicallytx on a single queue; "closer to batching than ACID"Transactions with read_committedMULTI/EXEC, no rollbackKafka only, inside Kafka
Many publishes as one unittx.commit (throughput cost) or confirms per batchTransactionsMULTI/EXECBatch confirms

XA, in one paragraph. The classic answer to "database and broker atomically" was two-phase commit through an XA transaction manager (JMS-era application servers). The documentation read for this page offers nothing like it for RabbitMQ, Kafka or Redis Streams: their transactions are internal. The practical consequences are inference, not a quote: you will get at-least-once delivery with idempotent processing, or outbox plus relay, never "exactly once" across both. The theory of 2PC is in Distributed SQL, Consensus & 2PC and the exactly-once argument in Delivery Guarantees.

sql
-- Fulfilment inbox: the consumer-side half of the guarantee (see the Inbox page).
-- "Mark then process" inside ONE database transaction makes redelivery harmless.
CREATE TABLE inbox_messages (
    message_id   text        PRIMARY KEY,
    consumer     text        NOT NULL,
    received_at  timestamptz NOT NULL DEFAULT now()
);

BEGIN;
INSERT INTO inbox_messages (message_id, consumer)
VALUES ($1, 'fulfilment.reserve-stock')
ON CONFLICT (message_id) DO NOTHING;      -- 0 rows inserted = already processed
-- if 1 row was inserted: UPDATE stock ... ; INSERT INTO reservations ...
COMMIT;
-- only now ack / commit the offset / XACK

Polling with a tight loop Important ​

SymptomCauseFix
100% CPU on an idle systemNon-blocking get in a for {}Block: Kafka long poll, Redis BLOCK, or sleep with backoff (rabbitmq.Poll)
Redis loop never sees SIGTERMBLOCK 0Finite BLOCK and check ctx.Done()
basic.get shows up in the RabbitMQ management metricsPolling a queue that is usually emptySwitch to basic.consume; "Use long-lived consumers instead of polling"
Laravel workers hammer the database--sleep=0 on the database driverRaise --sleep, or move to the Redis driver with block_for

Testing endpoints Important ​

The layering is what makes testing cheap. Three levels, from fastest:

LevelWhat is testedToolNeeds a broker
Unit: domain with a fake gatewaySales calls orderPlaced exactly onceGo gateway.Fake; Laravel Queue::fake()No
Unit: dispatcher, selective filter, handlersRouting table, skip rules, permanent vs transient errorsendpoint_test.go (go test)No
Contract: gateway and endpoint agree on the envelopeThe id, type, key, headers a gateway writes are what the endpoint readsOne shared test that publishes through AMQP/Kafka and reads through SourceYes, in CI
End to endOrder placed leads to stock reservedA throwaway brokerYes

Go: go test ./endpoint ./gateway runs without a broker (see Lab). The broker-backed contract tests and Event::fake/Bus::fake belong to Testing Messaging Systems.

Anti-patterns Must-know ​

Anti-patternWhy it hurtsInstead
Business logic in the gatewayThe gateway grows rules, is no longer swappableGateway = map and send; rules in services
Business logic in the endpointCannot be tested without a brokerEndpoint = translate, ack, reconnect
One consumer for all typesShared fate, no per-type scalingDispatcher, or channel per context
Auto-ack (autoAck=true)A crash after delivery loses the message (the EIP RabbitMQ example is "not a Transactional Client" for this reason)Manual ack after processing
Dispatching inside a DB transaction without afterCommitWorker may run before COMMITafterCommit or after_commit => true
Polling in a tight loopCPU, broker loadBlock or back off
Silent drop of unknown typesLost events nobody seesPermanent error, reject to DLQ
Selecting client-side what routing could doWasted deliveryChannel per interest
Treating tx.commit as ACIDIt is "batching"Confirms + idempotency

Go ​

Before ​

One consumer, auto-ack, a type switch, SQL in the callback, no shutdown, no reconnect. It compiles and demonstrates every anti-pattern at once.

go
// Before: the consumer, the router and the business logic are one blob.
// Auto-ack, a type switch inside the delivery loop, SQL in the callback, no
// shutdown, no reconnect. Compiles, runs, and loses messages on the first crash.
package main

import (
	"database/sql"
	"encoding/json"
	"log"
	"os"

	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)
	}
	ch, _ := conn.Channel()
	var db *sql.DB // imagine it is opened here

	// autoAck=true: the broker forgets the message the moment it is written to
	// the socket. A crash inside the loop body loses it.
	msgs, _ := ch.Consume("everything", "", true, false, false, false, nil)
	for d := range msgs {
		switch d.Type { // one consumer for all types, one queue for all types
		case "sales.order.placed":
			var o struct{ ID string }
			_ = json.Unmarshal(d.Body, &o)
			_, _ = db.Exec("UPDATE stock SET reserved = reserved + 1 WHERE order_id = $1", o.ID)
		case "sales.order.cancelled":
			_, _ = db.Exec("DELETE FROM reservations WHERE order_id = $1", string(d.Body))
		default:
			// silently dropped
		}
	}
}

After ​

The broker-neutral core: an Envelope, a Handler, a Dispatcher with unknown-type-is-permanent, Selective and HasHeader. No broker import; go test runs it.

go
// Package endpoint holds the broker-neutral part of a consumer: the envelope,
// the handler signature, the dispatcher and the selective filter. It imports
// no broker client, so every type here is testable without a broker.
package endpoint

import (
	"context"
	"errors"
	"fmt"
)

// Envelope is what an endpoint hands to the application. The broker-specific
// code (a Message Endpoint) translates its delivery, record or stream entry
// into this shape and nothing broker-specific leaks further in.
type Envelope struct {
	ID      string            // message id, the idempotency key
	Type    string            // e.g. "sales.order.placed"
	Key     string            // ordering / partition key, may be empty
	Headers map[string]string // free-form metadata (region, trace id, ...)
	Body    []byte
}

// Handler processes one message. Returning nil means "done, acknowledge".
type Handler func(ctx context.Context, e Envelope) error

// Source is the receiving side of a Message Endpoint: it connects to a broker,
// pulls or is pushed messages and calls h until ctx is cancelled.
type Source interface {
	Run(ctx context.Context, h Handler) error
}

// ErrUnknownType is returned by the Dispatcher when no performer is registered.
var ErrUnknownType = errors.New("endpoint: no handler registered for message type")

type permanent struct{ err error }

func (p permanent) Error() string { return p.err.Error() }
func (p permanent) Unwrap() error { return p.err }

// Permanent marks an error that a retry cannot fix (bad payload, unknown type).
// Endpoints reject such messages instead of requeueing them forever.
func Permanent(err error) error { return permanent{err: err} }

// IsPermanent reports whether err, or anything it wraps, was marked Permanent.
func IsPermanent(err error) bool {
	var p permanent
	return errors.As(err, &p)
}

// Dispatcher is the EIP Message Dispatcher: it consumes from one channel and
// hands every message to the performer registered for its type.
type Dispatcher struct {
	performers map[string]Handler
}

// NewDispatcher returns an empty dispatcher.
func NewDispatcher() *Dispatcher {
	return &Dispatcher{performers: make(map[string]Handler)}
}

// On registers the performer for one message type and returns d for chaining.
func (d *Dispatcher) On(msgType string, h Handler) *Dispatcher {
	d.performers[msgType] = h
	return d
}

// Handle makes *Dispatcher usable wherever a Handler is expected.
func (d *Dispatcher) Handle(ctx context.Context, e Envelope) error {
	h, ok := d.performers[e.Type]
	if !ok {
		return Permanent(fmt.Errorf("%w: %q", ErrUnknownType, e.Type))
	}
	return h(ctx, e)
}

// Selective is the client-side Selective Consumer: messages that do not match
// pred are acknowledged and skipped (returned as success), the rest go to next.
func Selective(pred func(Envelope) bool, next Handler) Handler {
	return func(ctx context.Context, e Envelope) error {
		if !pred(e) {
			return nil
		}
		return next(ctx, e)
	}
}

// HasHeader builds a predicate that matches one header value.
func HasHeader(key, value string) func(Envelope) bool {
	return func(e Envelope) bool { return e.Headers[key] == value }
}

A fake gateway and message-shape tests, and the dispatcher tests, run without a broker:

go
package endpoint_test

import (
	"context"
	"errors"
	"testing"

	"academy/consumer-endpoint-patterns/endpoint"
)

func TestDispatcherRoutesByType(t *testing.T) {
	var got []string
	d := endpoint.NewDispatcher().
		On("sales.order.placed", func(_ context.Context, e endpoint.Envelope) error {
			got = append(got, "placed:"+e.ID)
			return nil
		}).
		On("sales.order.cancelled", func(_ context.Context, e endpoint.Envelope) error {
			got = append(got, "cancelled:"+e.ID)
			return nil
		})

	ctx := context.Background()
	for _, e := range []endpoint.Envelope{
		{ID: "1", Type: "sales.order.placed"},
		{ID: "2", Type: "sales.order.cancelled"},
	} {
		if err := d.Handle(ctx, e); err != nil {
			t.Fatalf("handle %s: %v", e.ID, err)
		}
	}
	if len(got) != 2 || got[0] != "placed:1" || got[1] != "cancelled:2" {
		t.Fatalf("unexpected routing: %v", got)
	}
}

func TestUnknownTypeIsPermanent(t *testing.T) {
	d := endpoint.NewDispatcher()
	err := d.Handle(context.Background(), endpoint.Envelope{Type: "nope"})
	if !errors.Is(err, endpoint.ErrUnknownType) || !endpoint.IsPermanent(err) {
		t.Fatalf("want permanent ErrUnknownType, got %v", err)
	}
}

func TestSelectiveSkipsNonMatching(t *testing.T) {
	calls := 0
	h := endpoint.Selective(endpoint.HasHeader("region", "eu"), func(context.Context, endpoint.Envelope) error {
		calls++
		return nil
	})
	ctx := context.Background()
	_ = h(ctx, endpoint.Envelope{Headers: map[string]string{"region": "us"}})
	_ = h(ctx, endpoint.Envelope{Headers: map[string]string{"region": "eu"}})
	if calls != 1 {
		t.Fatalf("want 1 call, got %d", calls)
	}
}

func TestHandlerErrorIsNotPermanentByDefault(t *testing.T) {
	boom := errors.New("db down")
	d := endpoint.NewDispatcher().On("x", func(context.Context, endpoint.Envelope) error { return boom })
	err := d.Handle(context.Background(), endpoint.Envelope{Type: "x"})
	if !errors.Is(err, boom) || endpoint.IsPermanent(err) {
		t.Fatalf("a transient error must stay retryable, got %v", err)
	}
}

The Messaging Gateway: the interface the domain depends on, the Fake for tests, and the shared envelope builder.

go
// Package gateway is the Messaging Gateway for the Sales service: the rest of
// the application calls OrderPlaced and never sees a channel, topic or record.
package gateway

import (
	"context"
	"encoding/json"
	"sync"
)

// Order is the domain value Sales hands to the gateway.
type Order struct {
	ID         string `json:"id"`
	CustomerID string `json:"customer_id"`
	Region     string `json:"region"`
	TotalCents int64  `json:"total_cents"`
}

// OrderEvents is the whole surface the domain code depends on.
type OrderEvents interface {
	OrderPlaced(ctx context.Context, o Order) error
	OrderCancelled(ctx context.Context, orderID string) error
}

// Fake records calls; it is the gateway used in unit tests of Sales.
type Fake struct {
	mu        sync.Mutex
	Placed    []Order
	Cancelled []string
}

func (f *Fake) OrderPlaced(_ context.Context, o Order) error {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.Placed = append(f.Placed, o)
	return nil
}

func (f *Fake) OrderCancelled(_ context.Context, id string) error {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.Cancelled = append(f.Cancelled, id)
	return nil
}

// message is the broker-neutral form every implementation serialises.
type message struct {
	ID     string
	Type   string
	Key    string
	Region string
	Body   []byte
}

func orderPlaced(o Order) (message, error) {
	b, err := json.Marshal(o)
	return message{ID: "order-placed-" + o.ID, Type: "sales.order.placed", Key: o.ID, Region: o.Region, Body: b}, err
}

func orderCancelled(id string) (message, error) {
	b, err := json.Marshal(map[string]string{"id": id})
	return message{ID: "order-cancelled-" + id, Type: "sales.order.cancelled", Key: id, Body: b}, err
}
go
package gateway

import (
	"context"
	"testing"
)

// The domain depends on the interface, so a Fake satisfies it in tests.
var _ OrderEvents = (*Fake)(nil)

func TestFakeRecordsCalls(t *testing.T) {
	f := &Fake{}
	ctx := context.Background()
	_ = f.OrderPlaced(ctx, Order{ID: "o-1", Region: "eu"})
	_ = f.OrderCancelled(ctx, "o-1")
	if len(f.Placed) != 1 || len(f.Cancelled) != 1 {
		t.Fatalf("unexpected state: %+v", f)
	}
}

func TestMessageShape(t *testing.T) {
	m, err := orderPlaced(Order{ID: "o-1", Region: "eu", TotalCents: 4200})
	if err != nil || m.Type != "sales.order.placed" || m.Key != "o-1" || m.Region != "eu" {
		t.Fatalf("bad message %+v err=%v", m, err)
	}
}

The same interface on RabbitMQ (persistent, publisher confirm awaited) and on Kafka (keyed record, headers carry id, type and region):

go
package gateway

import (
	"context"
	"fmt"

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

// AMQP implements OrderEvents on RabbitMQ: persistent messages on a durable
// topic exchange, with a publisher confirm awaited per call.
type AMQP struct {
	Ch       *amqp.Channel // must already be in confirm mode (ch.Confirm(false))
	Exchange string
}

func (g *AMQP) OrderPlaced(ctx context.Context, o Order) error {
	m, err := orderPlaced(o)
	if err != nil {
		return err
	}
	return g.publish(ctx, m)
}

func (g *AMQP) OrderCancelled(ctx context.Context, id string) error {
	m, err := orderCancelled(id)
	if err != nil {
		return err
	}
	return g.publish(ctx, m)
}

func (g *AMQP) publish(ctx context.Context, m message) error {
	dc, err := g.Ch.PublishWithDeferredConfirmWithContext(ctx, g.Exchange, m.Type, false, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent, // durable queue + persistent message
		ContentType:  "application/json",
		MessageId:    m.ID,
		Type:         m.Type,
		Headers:      amqp.Table{"region": m.Region},
		Body:         m.Body,
	})
	if err != nil {
		return err
	}
	acked, err := dc.WaitContext(ctx)
	if err != nil {
		return err
	}
	if !acked {
		return fmt.Errorf("broker nacked message %s", m.ID)
	}
	return nil
}
go
package gateway

import (
	"context"

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

// Kafka implements the same OrderEvents interface on a Kafka topic. Swapping
// RabbitMQ for Kafka changes the constructor in main, not one line of domain code.
type Kafka struct {
	Client *kgo.Client // created with kgo.RequiredAcks(kgo.AllISRAcks()) (the default)
	Topic  string
}

func (g *Kafka) OrderPlaced(ctx context.Context, o Order) error {
	m, err := orderPlaced(o)
	if err != nil {
		return err
	}
	return g.produce(ctx, m)
}

func (g *Kafka) OrderCancelled(ctx context.Context, id string) error {
	m, err := orderCancelled(id)
	if err != nil {
		return err
	}
	return g.produce(ctx, m)
}

func (g *Kafka) produce(ctx context.Context, m message) error {
	rec := &kgo.Record{
		Topic: g.Topic,
		Key:   []byte(m.Key), // same order id, same partition, same order
		Value: m.Body,
		Headers: []kgo.RecordHeader{
			{Key: "id", Value: []byte(m.ID)},
			{Key: "type", Value: []byte(m.Type)},
			{Key: "region", Value: []byte(m.Region)},
		},
	}
	return g.Client.ProduceSync(ctx, rec).FirstErr()
}

The Event-Driven Consumer on RabbitMQ: durable queue, prefetch, consumer tag, manual ack, heartbeat, reconnect with backoff, cancel-and-drain on shutdown.

go
// Package rabbitmq holds the RabbitMQ Message Endpoints for the Fulfilment
// service: an event-driven consumer (basic.consume), a polling consumer
// (basic.get) and a transactional client (tx.select / tx.commit).
package rabbitmq

import (
	"context"
	"errors"
	"log"
	"time"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Source is an Event-Driven Consumer: the broker pushes deliveries and the
// client library hands them to us on a Go channel.
type Source struct {
	URL      string
	Exchange string // durable topic exchange owned by Sales
	Queue    string // durable queue owned by Fulfilment = the durable subscription
	Binding  string // e.g. "sales.order.#"
	Tag      string // consumer tag, shows up in the management UI
	Prefetch int
}

// Run connects, consumes and reconnects with backoff until ctx is cancelled.
func (s *Source) Run(ctx context.Context, h endpoint.Handler) error {
	backoff := time.Second
	for ctx.Err() == nil {
		err := s.session(ctx, h)
		if ctx.Err() != nil {
			return nil
		}
		log.Printf("rabbitmq: session ended: %v; reconnecting in %s", err, backoff)
		select {
		case <-ctx.Done():
			return nil
		case <-time.After(backoff):
		}
		if backoff < 30*time.Second {
			backoff *= 2
		}
	}
	return nil
}

func (s *Source) session(ctx context.Context, h endpoint.Handler) error {
	conn, err := amqp.DialConfig(s.URL, amqp.Config{
		Heartbeat: 30 * time.Second, // RabbitMQ suggests 60; very low values give false positives
		Locale:    "en_US",
	})
	if err != nil {
		return err
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()

	// Durable queue: the subscription outlives the consumer and the broker restart.
	if err := ch.ExchangeDeclare(s.Exchange, "topic", true, false, false, false, nil); err != nil {
		return err
	}
	if _, err := ch.QueueDeclare(s.Queue, true, false, false, false, nil); err != nil {
		return err
	}
	if err := ch.QueueBind(s.Queue, s.Binding, s.Exchange, false, nil); err != nil {
		return err
	}
	if err := ch.Qos(s.Prefetch, 0, false); err != nil {
		return err
	}

	deliveries, err := ch.Consume(s.Queue, s.Tag, false, false, false, false, nil)
	if err != nil {
		return err
	}
	closed := ch.NotifyClose(make(chan *amqp.Error, 1))

	for {
		select {
		case <-ctx.Done():
			// Stop new deliveries, finish what is already buffered, then leave.
			_ = ch.Cancel(s.Tag, false)
			for d := range deliveries {
				s.handle(context.WithoutCancel(ctx), h, d)
			}
			return nil
		case amqpErr := <-closed:
			if amqpErr == nil {
				return errors.New("channel closed")
			}
			return amqpErr
		case d, ok := <-deliveries:
			if !ok {
				return errors.New("deliveries channel closed")
			}
			s.handle(ctx, h, d)
		}
	}
}

func (s *Source) handle(ctx context.Context, h endpoint.Handler, d amqp.Delivery) {
	region, _ := d.Headers["region"].(string)
	err := h(ctx, endpoint.Envelope{
		ID:      d.MessageId,
		Type:    d.Type,
		Key:     d.RoutingKey,
		Headers: map[string]string{"region": region},
		Body:    d.Body,
	})
	switch {
	case err == nil:
		_ = d.Ack(false)
	case endpoint.IsPermanent(err):
		_ = d.Nack(false, false) // requeue=false: dead-letter it if a DLX is set
	default:
		_ = d.Nack(false, true) // transient: requeue
	}
}

The Polling Consumer on RabbitMQ with basic.get (shown for shape; the docs recommend against it outside tests), and the Transactional Client with tx:

go
package rabbitmq

import (
	"context"
	"time"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Poll is a true Polling Consumer: it asks with basic.get and gets either one
// message or nothing. The RabbitMQ docs recommend against it outside tests;
// it is here to show the shape, including the sleep that stops a tight loop.
func Poll(ctx context.Context, ch *amqp.Channel, queue string, h endpoint.Handler) error {
	idle := 100 * time.Millisecond
	for ctx.Err() == nil {
		d, ok, err := ch.Get(queue, false)
		if err != nil {
			return err
		}
		if !ok { // queue empty: back off instead of spinning
			select {
			case <-ctx.Done():
				return nil
			case <-time.After(idle):
			}
			if idle < 2*time.Second {
				idle *= 2
			}
			continue
		}
		idle = 100 * time.Millisecond
		if err := h(ctx, endpoint.Envelope{ID: d.MessageId, Type: d.Type, Body: d.Body}); err != nil {
			_ = d.Nack(false, !endpoint.IsPermanent(err))
			continue
		}
		_ = d.Ack(false)
	}
	return nil
}
go
package rabbitmq

import (
	"context"

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

// AckAndForward is a Transactional Client on a channel in tx mode: the ack of
// the inbound delivery and the publish of the outbound message become visible
// together on tx.commit, or neither does on tx.rollback.
//
// What this does NOT give you: atomicity across several queues, or any link to
// your database. RabbitMQ documents its tx class as closer to batching than ACID.
func AckAndForward(ctx context.Context, ch *amqp.Channel, in amqp.Delivery, exchange, key string, body []byte) error {
	// The caller has already called ch.Tx() once; a channel cannot leave tx mode.
	err := ch.PublishWithContext(ctx, exchange, key, false, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		ContentType:  "application/json",
		Body:         body,
	})
	if err == nil {
		err = in.Ack(false)
	}
	if err != nil {
		_ = ch.TxRollback()
		return err
	}
	return ch.TxCommit()
}

The Polling Consumer on Kafka with franz-go: group, manual commit after processing, BlockRebalanceOnPoll, read_committed, and Kafka's own transaction loop:

go
// Package kafka holds the Kafka Message Endpoints for the Fulfilment service:
// a polling consumer in a consumer group and a consume-process-produce loop
// inside a Kafka transaction.
package kafka

import (
	"context"
	"errors"
	"fmt"
	"log"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Source is a Polling Consumer: the application calls PollFetches when it is
// ready, processes the batch, then commits. The consumer group is the durable
// subscription: its committed offsets are what "remembers" the position.
type Source struct {
	Brokers []string
	Group   string // group.id = the durable subscriber's identity
	Topic   string
}

func (s *Source) Run(ctx context.Context, h endpoint.Handler) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(s.Brokers...),
		kgo.ConsumerGroup(s.Group),
		kgo.ConsumeTopics(s.Topic),
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), // auto.offset.reset=earliest for a NEW group
		kgo.DisableAutoCommit(),                           // commit after processing, never before
		kgo.BlockRebalanceOnPoll(),                        // no rebalance while we process a batch
		kgo.FetchIsolationLevel(kgo.ReadCommitted()),      // skip aborted transactional records
	)
	if err != nil {
		return err
	}
	defer cl.Close()

	for {
		fetches := cl.PollFetches(ctx) // long poll: blocks until data or ctx is done
		if fetches.IsClientClosed() || ctx.Err() != nil {
			break
		}
		fetches.EachError(func(t string, p int32, err error) {
			log.Printf("kafka: fetch error %s/%d: %v", t, p, err)
		})

		var firstErr error
		fetches.EachRecord(func(r *kgo.Record) {
			if firstErr != nil {
				return // stop at the first failure so offsets stay in order
			}
			err := h(ctx, toEnvelope(r))
			if err != nil && endpoint.IsPermanent(err) {
				log.Printf("kafka: skipping poison record %s/%d@%d: %v", r.Topic, r.Partition, r.Offset, err)
				err = nil // park it elsewhere (retry/DLQ topic) in a real system
			}
			firstErr = err
		})
		if firstErr != nil {
			// Do not commit: the group will re-read from the last committed offset.
			cl.AllowRebalance()
			return fmt.Errorf("kafka: handler failed: %w", firstErr)
		}
		if err := cl.CommitUncommittedOffsets(ctx); err != nil && !errors.Is(err, context.Canceled) {
			cl.AllowRebalance()
			return err
		}
		cl.AllowRebalance()
	}
	return nil
}

func toEnvelope(r *kgo.Record) endpoint.Envelope {
	e := endpoint.Envelope{Key: string(r.Key), Body: r.Value, Headers: map[string]string{}}
	for _, hd := range r.Headers {
		switch hd.Key {
		case "id":
			e.ID = string(hd.Value)
		case "type":
			e.Type = string(hd.Value)
		default:
			e.Headers[hd.Key] = string(hd.Value)
		}
	}
	return e
}
go
package kafka

import (
	"context"

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

// ConsumeProcessProduce is the Kafka meaning of "Transactional Client": read
// from one topic, write to another and commit the consumed offsets in ONE
// transaction. It is atomic inside Kafka only; a database write in the middle
// is not part of it.
func ConsumeProcessProduce(ctx context.Context, brokers []string, group, in, out, txID string) error {
	sess, err := kgo.NewGroupTransactSession(
		kgo.SeedBrokers(brokers...),
		kgo.TransactionalID(txID),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(in),
		kgo.FetchIsolationLevel(kgo.ReadCommitted()),
	)
	if err != nil {
		return err
	}
	defer sess.Close()

	for ctx.Err() == nil {
		fetches := sess.PollFetches(ctx)
		if fetches.IsClientClosed() || ctx.Err() != nil {
			return nil
		}
		if err := sess.Begin(); err != nil {
			return err
		}
		var recs []*kgo.Record
		fetches.EachRecord(func(r *kgo.Record) {
			recs = append(recs, &kgo.Record{Topic: out, Key: r.Key, Value: r.Value})
		})
		if len(recs) > 0 {
			if err := sess.ProduceSync(ctx, recs...).FirstErr(); err != nil {
				_, _ = sess.End(ctx, kgo.TryAbort)
				return err
			}
		}
		// TryCommit sends the produced records and the consumed offsets together.
		if _, err := sess.End(ctx, kgo.TryCommit); err != nil {
			return err
		}
	}
	return nil
}

The blocking-pull consumer on Redis Streams: group creation, pending-first resume, XACK after success:

go
// Package redisstream is the Redis Streams Message Endpoint for Fulfilment:
// a blocking-pull consumer group member (XREADGROUP BLOCK).
package redisstream

import (
	"context"
	"errors"
	"log"
	"strings"
	"time"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Source is a Polling Consumer with a blocking read. The consumer group is the
// durable subscription: the server keeps last-delivered-id and the pending list.
type Source struct {
	Client   *redis.Client
	Stream   string
	Group    string
	Consumer string // unique per instance; reuse the same name after a restart
}

func (s *Source) Run(ctx context.Context, h endpoint.Handler) error {
	// "$" = deliver only entries added after the group is created; "0" = from the start.
	err := s.Client.XGroupCreateMkStream(ctx, s.Stream, s.Group, "$").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}

	// First drain our own pending entries (id "0"), then switch to new ones (">").
	// This is how a durable subscriber resumes after a crash.
	id := "0"
	for ctx.Err() == nil {
		res, err := s.Client.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group:    s.Group,
			Consumer: s.Consumer,
			Streams:  []string{s.Stream, id},
			Count:    10,
			Block:    5 * time.Second, // the long poll; ignored when id is not ">"
		}).Result()
		if errors.Is(err, redis.Nil) {
			continue // timeout, nothing new: poll again
		}
		if err != nil {
			if ctx.Err() != nil {
				return nil
			}
			log.Printf("redis: read failed: %v", err)
			time.Sleep(time.Second)
			continue
		}
		n := 0
		for _, st := range res {
			for _, m := range st.Messages {
				n++
				if id != ">" {
					id = m.ID // walk forward through our own pending entries
				}
				env := endpoint.Envelope{
					ID:      str(m.Values["id"]),
					Type:    str(m.Values["type"]),
					Key:     str(m.Values["key"]),
					Headers: map[string]string{"region": str(m.Values["region"])},
					Body:    []byte(str(m.Values["body"])),
				}
				err := h(ctx, env)
				if err != nil && !endpoint.IsPermanent(err) {
					log.Printf("redis: %s failed, leaving it pending: %v", m.ID, err)
					continue // stays in the PEL; XAUTOCLAIM can move it later
				}
				if err := s.Client.XAck(ctx, s.Stream, s.Group, m.ID).Err(); err != nil {
					log.Printf("redis: ack %s: %v", m.ID, err)
				}
			}
		}
		if id == "0" && n == 0 {
			id = ">" // pending list drained
		}
	}
	return nil
}

func str(v any) string {
	s, _ := v.(string)
	return s
}

The wiring for the worked example, with graceful shutdown through signal.NotifyContext:

go
// Command fulfilment is the worked example: Fulfilment consumes Sales events.
// The wiring is the only place that knows which broker is in use.
//
//	BROKER=rabbitmq AMQP_URL=amqp://guest:guest@localhost:5672/ go run ./cmd/fulfilment
//	BROKER=kafka    KAFKA_BROKERS=localhost:9092                go run ./cmd/fulfilment
//	BROKER=redis    REDIS_ADDR=localhost:6379                   go run ./cmd/fulfilment
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"

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

	"academy/consumer-endpoint-patterns/endpoint"
	"academy/consumer-endpoint-patterns/kafka"
	"academy/consumer-endpoint-patterns/rabbitmq"
	"academy/consumer-endpoint-patterns/redisstream"
)

// Service Activators: thin adapters from a message to a plain domain call.
func reserveStock(_ context.Context, e endpoint.Envelope) error {
	var o struct {
		ID         string `json:"id"`
		TotalCents int64  `json:"total_cents"`
	}
	if err := json.Unmarshal(e.Body, &o); err != nil {
		return endpoint.Permanent(fmt.Errorf("bad payload: %w", err))
	}
	log.Printf("fulfilment: reserve stock for order %s (message %s)", o.ID, e.ID)
	return nil // call the Fulfilment domain service here; it is idempotent on e.ID
}

func releaseStock(_ context.Context, e endpoint.Envelope) error {
	log.Printf("fulfilment: release stock for message %s", e.ID)
	return nil
}

func newSource(kind string) (endpoint.Source, error) {
	switch kind {
	case "rabbitmq":
		return &rabbitmq.Source{
			URL: os.Getenv("AMQP_URL"), Exchange: "sales.events", Queue: "fulfilment.sales-events",
			Binding: "sales.order.#", Tag: "fulfilment-1", Prefetch: 10,
		}, nil
	case "kafka":
		return &kafka.Source{
			Brokers: strings.Split(os.Getenv("KAFKA_BROKERS"), ","),
			Group:   "fulfilment", Topic: "sales.events",
		}, nil
	case "redis":
		host, _ := os.Hostname()
		return &redisstream.Source{
			Client: redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDR")}),
			Stream: "sales.events", Group: "fulfilment", Consumer: host,
		}, nil
	}
	return nil, fmt.Errorf("unknown BROKER %q", kind)
}

func main() {
	kind := os.Getenv("BROKER")
	if kind == "" {
		log.Println("BROKER not set (rabbitmq | kafka | redis); nothing to do")
		return
	}
	src, err := newSource(kind)
	if err != nil {
		log.Fatal(err)
	}

	// One Message Dispatcher, two performers, one Selective Consumer on top.
	dispatcher := endpoint.NewDispatcher().
		On("sales.order.placed", reserveStock).
		On("sales.order.cancelled", releaseStock)
	handler := endpoint.Selective(endpoint.HasHeader("region", "eu"), dispatcher.Handle)

	// SIGTERM cancels ctx; every loop in the endpoints watches it.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	if err := src.Run(ctx, handler); err != nil {
		log.Fatal(err)
	}
	log.Println("fulfilment: stopped cleanly")
}

The Go angle ​

Go has no consumer framework, so the endpoint patterns are small interfaces. endpoint.Source (a Run(ctx, handler) method) is the Message Endpoint; endpoint.Handler is the Service Activator contract; endpoint.Dispatcher is a map. Three Go idioms carry most of the weight:

  • context.Context is the shutdown signal. signal.NotifyContext cancels it on SIGTERM; every loop selects on ctx.Done(). The drain after cancel uses context.WithoutCancel(ctx) so in-flight handlers are not cancelled by the very signal that told them to finish.
  • A channel of deliveries is an Event-Driven Consumer. amqp091's Consume returns <-chan Delivery; for d := range deliveries is your callback, and the buffered channel is the prefetch window made visible.
  • errors.As carries error classes. endpoint.Permanent(err) wraps an error so the endpoint can choose between Nack(requeue=true) and Nack(requeue=false), skip and commit, or XACK, with one decision site.

The clients are github.com/rabbitmq/amqp091-go, github.com/twmb/franz-go/pkg/kgo and github.com/redis/go-redis/v9; every call above was read in go doc output (saved with the sources) and the module compiles and vets clean without a broker. Nothing here was run against a live broker.

Laravel ​

Before ​

A controller that dispatches a do-everything job inside the transaction. The worker can pop the job before the transaction commits and find no row.

php
<?php

namespace App\Services;

use App\Jobs\SyncOrderEverywhere;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

// Before: the controller-side code knows the queue and dispatches INSIDE the
// transaction; the job does routing, mapping and business logic in one handle().
final class PlaceOrderBefore
{
    public function __invoke(array $data): Order
    {
        return DB::transaction(function () use ($data) {
            $order = Order::create($data);

            // The worker can pop this before the COMMIT below: it may not find the row.
            SyncOrderEverywhere::dispatch($order->id, 'placed');

            return $order;
        });
    }
}

After ​

The Messaging Gateway interface and its queue implementation; the outbound job and its narrow port:

php
<?php

namespace App\Messaging;

use App\Models\Order;

// The Messaging Gateway: the only thing Sales code knows about messaging.
// No queue names, no payload arrays, no broker types.
interface OrderEvents
{
    public function orderPlaced(Order $order): void;

    public function orderCancelled(int $orderId): void;
}
php
<?php

namespace App\Messaging;

use App\Jobs\PublishSalesEvent;
use App\Models\Order;

// Laravel-queue implementation of the gateway. Swapping it for a Kafka or
// RabbitMQ publisher changes the container binding, not the callers.
final class QueueOrderEvents implements OrderEvents
{
    public function orderPlaced(Order $order): void
    {
        PublishSalesEvent::dispatch('sales.order.placed', [
            'id' => $order->id,
            'customer_id' => $order->customer_id,
            'region' => $order->region,
            'total_cents' => $order->total_cents,
        ])->onQueue('sales-events')->afterCommit();
    }

    public function orderCancelled(int $orderId): void
    {
        PublishSalesEvent::dispatch('sales.order.cancelled', ['id' => $orderId])
            ->onQueue('sales-events')
            ->afterCommit();
    }
}
php
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

// A job whose handle() is the outbound Message Endpoint: it turns the domain
// call into a broker message. Here the "broker" is whatever the app container
// binds for the publisher (RabbitMQ package, Kafka package, Redis XADD).
final class PublishSalesEvent implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 5;

    /** @param array<string, mixed> $payload */
    public function __construct(
        public string $type,
        public array $payload,
    ) {
    }

    public function handle(SalesEventPublisher $publisher): void
    {
        $publisher->publish($this->type, $this->payload);
    }
}
php
<?php

namespace App\Jobs;

// The narrow port behind the publishing job; one adapter per broker lives
// elsewhere. Tests bind a recording fake here.
interface SalesEventPublisher
{
    /** @param array<string, mixed> $payload */
    public function publish(string $type, array $payload): void;
}

Transactional-client behaviour with DB::transaction and afterCommit:

php
<?php

namespace App\Services;

use App\Messaging\OrderEvents;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

// Transactional client behaviour in Laravel: the message is "added to the
// channel" only when the database transaction commits. afterCommit() on the
// gateway call (or after_commit => true on the connection) delays the push
// until the outermost transaction has committed; a rollback discards it.
//
// This is NOT atomic: a crash between COMMIT and the push still loses the
// message. That gap is what the outbox pattern closes.
final class PlaceOrder
{
    public function __construct(private OrderEvents $events)
    {
    }

    /** @param array<string, mixed> $data */
    public function __invoke(array $data): Order
    {
        return DB::transaction(function () use ($data) {
            $order = Order::create($data);
            $this->events->orderPlaced($order);

            return $order;
        });
    }
}

The Service Activator, a thin queued job:

php
<?php

namespace App\Jobs;

use App\Fulfilment\StockService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

// Service Activator: handle() is thin. It receives the message, calls the
// domain service like any other client and returns. StockService does not
// know it is being invoked from a queue.
final class ReserveStock implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public int $tries = 5;

    /** @var array<int, int> seconds between attempts */
    public array $backoff = [5, 30, 120];

    public function __construct(
        public string $messageId,
        public int $orderId,
    ) {
    }

    public function handle(StockService $stock): void
    {
        $stock->reserveOnce($this->messageId, $this->orderId);
    }
}

A Message Dispatcher plus Selective Consumer for broker-driven consumers (no job class in the payload):

php
<?php

namespace App\Messaging;

use InvalidArgumentException;

// Message Dispatcher + Selective Consumer for the broker-driven consumers
// (Kafka package, Redis stream loop). The queue worker does this by itself for
// Laravel jobs; here there is no job class in the payload, so we route by type.
final class SalesEventRouter
{
    /** @var array<string, callable(array<string, mixed>, string): void> */
    private array $performers = [];

    /** @param callable(array<string, string>): bool $selector */
    public function __construct(private $selector)
    {
    }

    /** @param callable(array<string, mixed>, string): void $performer */
    public function on(string $type, callable $performer): self
    {
        $this->performers[$type] = $performer;

        return $this;
    }

    /**
     * @param array<string, string> $headers
     * @param array<string, mixed> $payload
     */
    public function dispatch(string $type, string $messageId, array $headers, array $payload): void
    {
        if (! ($this->selector)($headers)) {
            return; // selective: not ours, acknowledge by returning
        }

        $performer = $this->performers[$type]
            ?? throw new InvalidArgumentException("No performer for message type {$type}");

        $performer($payload, $messageId);
    }
}

A Redis Streams polling consumer (phpredis) and a Kafka consumer through mateusjunges/laravel-kafka:

php
<?php

namespace App\Console\Commands;

use App\Messaging\SalesEventRouter;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Throwable;

// A Polling Consumer on Redis Streams (written against the phpredis client,
// Laravel's default; predis has different method signatures). Not run here.
final class ConsumeSalesStream extends Command
{
    protected $signature = 'sales:consume {--consumer=} {--block=5000}';

    protected $description = 'Consume sales.events through the fulfilment consumer group';

    private bool $stop = false;

    public function handle(SalesEventRouter $router): int
    {
        $stream = 'sales.events';
        $group = 'fulfilment';
        $consumer = $this->option('consumer') ?: gethostname();

        $redis = Redis::connection();

        try {
            // "$" = only entries added from now on; the 4th argument creates the stream.
            $redis->xGroup('CREATE', $stream, $group, '$', true);
        } catch (Throwable $e) {
            if (! str_contains($e->getMessage(), 'BUSYGROUP')) {
                throw $e;
            }
        }

        pcntl_async_signals(true);
        pcntl_signal(SIGTERM, fn () => $this->stop = true);
        pcntl_signal(SIGINT, fn () => $this->stop = true);

        while (! $this->stop) {
            // BLOCK is the long poll; ">" asks for entries never delivered to anyone in the group.
            $batch = $redis->xReadGroup($group, $consumer, [$stream => '>'], 10, (int) $this->option('block'));

            foreach ($batch[$stream] ?? [] as $id => $fields) {
                try {
                    $router->dispatch(
                        $fields['type'],
                        $fields['id'],
                        ['region' => $fields['region'] ?? ''],
                        json_decode($fields['body'], true, 512, JSON_THROW_ON_ERROR),
                    );
                    $redis->xAck($stream, $group, [$id]);
                } catch (Throwable $e) {
                    $this->error("entry {$id} failed, left pending: {$e->getMessage()}");
                }
            }
        }

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

namespace App\Console\Commands;

use App\Messaging\SalesEventRouter;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;

// Kafka consumer through mateusjunges/laravel-kafka. Only the calls shown in
// its documentation are used (consumer, withConsumerGroupId, withHandler,
// build, consume, and the ConsumerMessage getters). Not run here.
final class ConsumeSalesKafka extends Command
{
    protected $signature = 'sales:consume-kafka';

    protected $description = 'Consume the sales.events topic as the fulfilment consumer group';

    public function handle(SalesEventRouter $router): int
    {
        $consumer = Kafka::consumer(['sales.events'])
            ->withBrokers(config('services.kafka.brokers'))
            ->withConsumerGroupId('fulfilment') // the durable subscription's identity
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($router) {
                $headers = $message->getHeaders();

                $router->dispatch(
                    $headers['type'],
                    $headers['id'],
                    ['region' => $headers['region'] ?? ''],
                    $message->getBody(),
                );
            })
            ->build();

        $consumer->consume();

        return self::SUCCESS;
    }
}

A broker-free contract test of the gateway:

php
<?php

namespace Tests\Feature;

use App\Jobs\PublishSalesEvent;
use App\Messaging\OrderEvents;
use App\Models\Order;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

// Contract test for the gateway without a broker: Queue::fake() records pushes,
// and afterCommit() is honoured for transactions the test opens itself.
final class OrderEventsTest extends TestCase
{
    use RefreshDatabase;

    public function test_event_is_pushed_only_after_the_transaction_commits(): void
    {
        Queue::fake();
        $events = app(OrderEvents::class);
        $order = Order::factory()->create(['region' => 'eu']);

        DB::transaction(function () use ($events, $order) {
            $events->orderPlaced($order);
            Queue::assertNothingPushed();
        });

        Queue::assertPushed(PublishSalesEvent::class, fn ($job) => $job->type === 'sales.order.placed');
    }
}

The Laravel angle ​

Laravel's own endpoint is the queue worker loop, and it is a Polling Consumer. Worker::daemon() is a while (true) that calls getNextJob() (which calls $connection->pop($queue)), runs the job, and, when pop returns nothing, dispatches a WorkerIdle event and sleeps --sleep seconds. The Redis driver's pop runs a Lua script and, if block_for is set, waits in BLPOP on a notify list: Laravel's long poll. The database driver's pop selects the next job with a lock taken in the query. For the line-by-line walk-through and the driver internals see Laravel Queue Internals (it owns the framework side); this page only uses the mapping:

EIP patternLaravel realisation
Messaging GatewayQueue::push / Bus::dispatch behind your own interface (OrderEvents); Queue::fake() is the fake gateway
Message EndpointThe queue connection plus the queue:work process
Polling ConsumerWorker::daemon() loop calling pop; --sleep, block_for
Event-Driven Consumerrabbitmq:consume from vladimir-yuldashev/laravel-queue-rabbitmq ("utilizes basic_consume"), or a laravel-kafka handler
Message DispatcherWorker resolves payload['job'] and calls fire(); CallQueuedHandler::call() unserialises the command and runs it through middleware
Service ActivatorThe job's handle() with container-injected services
Selective Consumerqueue:work --queue=high,default; a named queue per interest
Durable SubscriberA durable queue (database, Redis, SQS) holds jobs; Kafka via a group id (withConsumerGroupId)
Transactional ClientDB::transaction + afterCommit / after_commit => true; "ack" is deleting the job after handle() returns
HorizonProcess supervisor and balancer for Redis queues, not a message dispatcher

Notes read from the Laravel 13 docs: the queue:work command "will continue to run until it is manually stopped", so keep it alive with Supervisor; --timeout (default 60) "should always be at least several seconds shorter than your retry_after value" (default 90 in the sample config) or "your jobs may be processed twice"; after_commit makes Laravel "wait until the open parent database transactions have been committed before actually dispatching the job". The laravel-queue-rabbitmq README states that queue:work "utilizes basic_get" and supports several queues, while rabbitmq:consume "utilizes basic_consume and is more performant than basic_get by ~2x, but does not support multiple queues". The RabbitMQ docs call polling with basic.get "highly discouraged"; that is the live trade-off in a Laravel RabbitMQ deployment. For Kafka, Laravel does not ship a driver; the mateusjunges/laravel-kafka documentation shows Kafka::consumer([...])->withBrokers(...)->withConsumerGroupId(...)->withHandler(...)->build() and consume(). For Redis Streams use the Redis facade (Laravel's own Redis queue driver uses lists and sorted sets, not streams); the command above is written against phpredis and was not run.

Broker differences ​

The same nine patterns, product by product. Details of acks are in Message Acknowledgment; of channels and exchanges in Routing Topologies.

RabbitMQ ​

RabbitMQ is the one broker here with a real push consumer: basic.consume registers a consumer, returns a consumer tag, and the broker sends deliveries, bounded by basic.qos (consumer prefetch, which RabbitMQ applies per consumer rather than per channel in its default mode). basic.get is the polling form and "strongly recommended against" outside integration tests. A durable subscription is a durable queue (metadata on disk) bound to the exchange, receiving persistent messages (delivery_mode=2): "Messages published as transient will be discarded during recovery, even if they were stored in durable queues." Quorum queues must be durable. Exclusive queues and auto-delete queues are the non-durable subscriber (temporary WebSocket clients, for example). Selectors do not exist on queue consumers: the broker's answer is the exchange and its bindings, plus filtering on streams (Bloom filter per chunk, AMQP filter expressions, client side). Transactions are the AMQP tx class (publishes and acks, one queue, "batching, not ACID"); publisher confirms replace them for publishers. Tags matter operationally: the management UI and basic.cancel use the consumer tag, so set a meaningful one (fulfilment-1).

go
// Package rabbitmq holds the RabbitMQ Message Endpoints for the Fulfilment
// service: an event-driven consumer (basic.consume), a polling consumer
// (basic.get) and a transactional client (tx.select / tx.commit).
package rabbitmq

import (
	"context"
	"errors"
	"log"
	"time"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Source is an Event-Driven Consumer: the broker pushes deliveries and the
// client library hands them to us on a Go channel.
type Source struct {
	URL      string
	Exchange string // durable topic exchange owned by Sales
	Queue    string // durable queue owned by Fulfilment = the durable subscription
	Binding  string // e.g. "sales.order.#"
	Tag      string // consumer tag, shows up in the management UI
	Prefetch int
}

// Run connects, consumes and reconnects with backoff until ctx is cancelled.
func (s *Source) Run(ctx context.Context, h endpoint.Handler) error {
	backoff := time.Second
	for ctx.Err() == nil {
		err := s.session(ctx, h)
		if ctx.Err() != nil {
			return nil
		}
		log.Printf("rabbitmq: session ended: %v; reconnecting in %s", err, backoff)
		select {
		case <-ctx.Done():
			return nil
		case <-time.After(backoff):
		}
		if backoff < 30*time.Second {
			backoff *= 2
		}
	}
	return nil
}

func (s *Source) session(ctx context.Context, h endpoint.Handler) error {
	conn, err := amqp.DialConfig(s.URL, amqp.Config{
		Heartbeat: 30 * time.Second, // RabbitMQ suggests 60; very low values give false positives
		Locale:    "en_US",
	})
	if err != nil {
		return err
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()

	// Durable queue: the subscription outlives the consumer and the broker restart.
	if err := ch.ExchangeDeclare(s.Exchange, "topic", true, false, false, false, nil); err != nil {
		return err
	}
	if _, err := ch.QueueDeclare(s.Queue, true, false, false, false, nil); err != nil {
		return err
	}
	if err := ch.QueueBind(s.Queue, s.Binding, s.Exchange, false, nil); err != nil {
		return err
	}
	if err := ch.Qos(s.Prefetch, 0, false); err != nil {
		return err
	}

	deliveries, err := ch.Consume(s.Queue, s.Tag, false, false, false, false, nil)
	if err != nil {
		return err
	}
	closed := ch.NotifyClose(make(chan *amqp.Error, 1))

	for {
		select {
		case <-ctx.Done():
			// Stop new deliveries, finish what is already buffered, then leave.
			_ = ch.Cancel(s.Tag, false)
			for d := range deliveries {
				s.handle(context.WithoutCancel(ctx), h, d)
			}
			return nil
		case amqpErr := <-closed:
			if amqpErr == nil {
				return errors.New("channel closed")
			}
			return amqpErr
		case d, ok := <-deliveries:
			if !ok {
				return errors.New("deliveries channel closed")
			}
			s.handle(ctx, h, d)
		}
	}
}

func (s *Source) handle(ctx context.Context, h endpoint.Handler, d amqp.Delivery) {
	region, _ := d.Headers["region"].(string)
	err := h(ctx, endpoint.Envelope{
		ID:      d.MessageId,
		Type:    d.Type,
		Key:     d.RoutingKey,
		Headers: map[string]string{"region": region},
		Body:    d.Body,
	})
	switch {
	case err == nil:
		_ = d.Ack(false)
	case endpoint.IsPermanent(err):
		_ = d.Nack(false, false) // requeue=false: dead-letter it if a DLX is set
	default:
		_ = d.Nack(false, true) // transient: requeue
	}
}

Kafka ​

Kafka is pull-only: "data is pushed to the broker from the producer and pulled from the broker by the consumer". poll() is the endpoint; liveness depends on calling it (max.poll.interval.ms, default 300000) and on heartbeats (session.timeout.ms, default 45000). The consumer group is the durable subscriber: committed offsets in __consumer_offsets are the saved position, and a group that is gone for longer than offsets.retention.minutes (default 10080) after it becomes empty loses them. There is no broker-side selector: a regex subscription chooses topics, not records, and anything finer is a client-side filter or a Kafka Streams job that writes a filtered topic (Stream Processing). "Transactional client" means a transactional producer (transactional.id) that also commits the consumer's offsets, with isolation.level=read_committed on the readers; "in Kafka, the consumer and producer are separate, and it is only the producer which is transactional". The default isolation.level is read_uncommitted.

go
// Package kafka holds the Kafka Message Endpoints for the Fulfilment service:
// a polling consumer in a consumer group and a consume-process-produce loop
// inside a Kafka transaction.
package kafka

import (
	"context"
	"errors"
	"fmt"
	"log"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Source is a Polling Consumer: the application calls PollFetches when it is
// ready, processes the batch, then commits. The consumer group is the durable
// subscription: its committed offsets are what "remembers" the position.
type Source struct {
	Brokers []string
	Group   string // group.id = the durable subscriber's identity
	Topic   string
}

func (s *Source) Run(ctx context.Context, h endpoint.Handler) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(s.Brokers...),
		kgo.ConsumerGroup(s.Group),
		kgo.ConsumeTopics(s.Topic),
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), // auto.offset.reset=earliest for a NEW group
		kgo.DisableAutoCommit(),                           // commit after processing, never before
		kgo.BlockRebalanceOnPoll(),                        // no rebalance while we process a batch
		kgo.FetchIsolationLevel(kgo.ReadCommitted()),      // skip aborted transactional records
	)
	if err != nil {
		return err
	}
	defer cl.Close()

	for {
		fetches := cl.PollFetches(ctx) // long poll: blocks until data or ctx is done
		if fetches.IsClientClosed() || ctx.Err() != nil {
			break
		}
		fetches.EachError(func(t string, p int32, err error) {
			log.Printf("kafka: fetch error %s/%d: %v", t, p, err)
		})

		var firstErr error
		fetches.EachRecord(func(r *kgo.Record) {
			if firstErr != nil {
				return // stop at the first failure so offsets stay in order
			}
			err := h(ctx, toEnvelope(r))
			if err != nil && endpoint.IsPermanent(err) {
				log.Printf("kafka: skipping poison record %s/%d@%d: %v", r.Topic, r.Partition, r.Offset, err)
				err = nil // park it elsewhere (retry/DLQ topic) in a real system
			}
			firstErr = err
		})
		if firstErr != nil {
			// Do not commit: the group will re-read from the last committed offset.
			cl.AllowRebalance()
			return fmt.Errorf("kafka: handler failed: %w", firstErr)
		}
		if err := cl.CommitUncommittedOffsets(ctx); err != nil && !errors.Is(err, context.Canceled) {
			cl.AllowRebalance()
			return err
		}
		cl.AllowRebalance()
	}
	return nil
}

func toEnvelope(r *kgo.Record) endpoint.Envelope {
	e := endpoint.Envelope{Key: string(r.Key), Body: r.Value, Headers: map[string]string{}}
	for _, hd := range r.Headers {
		switch hd.Key {
		case "id":
			e.ID = string(hd.Value)
		case "type":
			e.Type = string(hd.Value)
		default:
			e.Headers[hd.Key] = string(hd.Value)
		}
	}
	return e
}

Redis Streams ​

Redis Streams read with XREADGROUP, which can BLOCK for a time: a blocking pull. The consumer group is the durable subscriber: the server keeps the group's last-delivered id and a pending list per consumer, "even after a disconnect, the stream consumer group retains all the state, since the client will claim again to be the same consumer". Reading with id > yields "messages never delivered to other consumers"; reading with 0 returns the consumer's own pending history, which is the resume path after a crash. Redis has no selectors, no per-message filter on XREADGROUP, and MULTI/EXEC has no rollback ("Redis does not support rollbacks of transactions"). Redis Pub/Sub is the non-durable alternative: "fire and forget and are never stored". XACK is the commit; unacknowledged entries are XAUTOCLAIM candidates (see Message Acknowledgment).

go
// Package redisstream is the Redis Streams Message Endpoint for Fulfilment:
// a blocking-pull consumer group member (XREADGROUP BLOCK).
package redisstream

import (
	"context"
	"errors"
	"log"
	"strings"
	"time"

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

	"academy/consumer-endpoint-patterns/endpoint"
)

// Source is a Polling Consumer with a blocking read. The consumer group is the
// durable subscription: the server keeps last-delivered-id and the pending list.
type Source struct {
	Client   *redis.Client
	Stream   string
	Group    string
	Consumer string // unique per instance; reuse the same name after a restart
}

func (s *Source) Run(ctx context.Context, h endpoint.Handler) error {
	// "$" = deliver only entries added after the group is created; "0" = from the start.
	err := s.Client.XGroupCreateMkStream(ctx, s.Stream, s.Group, "$").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}

	// First drain our own pending entries (id "0"), then switch to new ones (">").
	// This is how a durable subscriber resumes after a crash.
	id := "0"
	for ctx.Err() == nil {
		res, err := s.Client.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group:    s.Group,
			Consumer: s.Consumer,
			Streams:  []string{s.Stream, id},
			Count:    10,
			Block:    5 * time.Second, // the long poll; ignored when id is not ">"
		}).Result()
		if errors.Is(err, redis.Nil) {
			continue // timeout, nothing new: poll again
		}
		if err != nil {
			if ctx.Err() != nil {
				return nil
			}
			log.Printf("redis: read failed: %v", err)
			time.Sleep(time.Second)
			continue
		}
		n := 0
		for _, st := range res {
			for _, m := range st.Messages {
				n++
				if id != ">" {
					id = m.ID // walk forward through our own pending entries
				}
				env := endpoint.Envelope{
					ID:      str(m.Values["id"]),
					Type:    str(m.Values["type"]),
					Key:     str(m.Values["key"]),
					Headers: map[string]string{"region": str(m.Values["region"])},
					Body:    []byte(str(m.Values["body"])),
				}
				err := h(ctx, env)
				if err != nil && !endpoint.IsPermanent(err) {
					log.Printf("redis: %s failed, leaving it pending: %v", m.ID, err)
					continue // stays in the PEL; XAUTOCLAIM can move it later
				}
				if err := s.Client.XAck(ctx, s.Stream, s.Group, m.ID).Err(); err != nil {
					log.Printf("redis: ack %s: %v", m.ID, err)
				}
			}
		}
		if id == "0" && n == 0 {
			id = ">" // pending list drained
		}
	}
	return nil
}

func str(v any) string {
	s, _ := v.(string)
	return s
}

Side by side

PatternRabbitMQKafkaRedis Streams
Event-Driven Consumerbasic.consume, push, prefetchNone natively; wrapper around pollNone natively; wrapper around XREADGROUP
Polling Consumerbasic.get (discouraged)poll() long pollXREADGROUP ... BLOCK
Durable SubscriberDurable queue + persistent messagesConsumer group + committed offsetsConsumer group on the stream
Selective ConsumerRouting; stream filtersClient-side or StreamsClient-side or separate streams
Transactional Clienttx (batching) or confirmsProducer transactions + read_committedMULTI/EXEC, no rollback
Consumer identityConsumer taggroup.id (+ group.instance.id)Group + consumer name
BackpressurePrefetchDo not poll; max.poll.recordsDo not read; COUNT

Other brokers in one line each (see Other Brokers): SQS has no Transactional Client but a visibility timeout (the EIP note); NATS JetStream, Pulsar and Google Pub/Sub are surveyed on that page.

In production systems ​

  • RabbitMQ documents polling as an anti-pattern. The consumers guide says basic.get is "highly discouraged" and that the management and Prometheus plugins "provide several metrics that help detect applications that use polling". Check it in the consumers guide; it matters for Laravel deployments that run queue:work against the RabbitMQ package.
  • Kafka's group liveness is a pair of timers. The KafkaConsumer javadoc describes heartbeats to the broker and, separately, max.poll.interval.ms as protection against a livelock where heartbeats continue but no progress is made; a commit after eviction throws CommitFailedException.
  • Redis Streams consumer groups keep their state on the server, including pending entries and the group's last-delivered id; reading from id 0 returns the consumer's pending history. This is in the Redis streams tutorial.
  • Laravel's worker is a polling loop with a built-in long poll for Redis (block_for), documented with the caution that 0 "will also prevent signals such as SIGTERM from being handled until the next job has been processed". The loop is in Illuminate\Queue\Worker.
  • The EIP authors themselves updated the book's pattern pages with RabbitMQ and SQS notes (Event-Driven Consumer: RabbitMQ consumers "are by default event-driven"; Transactional Client: cloud systems "therefore don't implement Transactional Clients").

Choosing ​

SituationPattern and product choiceExtra techniqueReason
Lowest latency from event to actionEvent-Driven Consumer on RabbitMQ with moderate prefetchManual ack, idempotent handlerPush has no poll delay
Bursty producers, slow consumers, replay wantedPolling Consumer on Kafkamax.poll.records, lag alertPull gives backpressure and batching
Simple background jobs in a Laravel appqueue:work on Redis with block_forSupervisor, --max-jobsBuilt in, no new infrastructure
Subscriber that must not miss events while deployingDurable Subscriber (durable queue, group, stream group)Lag alerts, retention longer than longest outageOffline gaps are normal
Consumer wants a small subset of a busy channelSeparate channels (routing)Content-based router upstreamClient-side filters waste delivery
Several handlers on one queueMessage Dispatcher with a type tablePermanent error on unknown typeOne consumer, small handlers
DB write plus event publishNot a Transactional ClientOutbox + relayNo cross-resource transaction exists
Consume, transform, produce inside KafkaKafka transactions, read_committedtransactional.id per instanceAtomic offsets and output
Admin call and message must trigger the same ruleService Activator calling a serviceIdempotency keyOne implementation of the rule
Tests must run without infrastructureMessaging Gateway + fakeContract test in CIFast feedback

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

Monolith (one process, one database) Must-know ​

In a Laravel monolith the whole endpoint layer is the queue. PlaceOrder runs DB::transaction, calls OrderEvents::orderPlaced, and the gateway dispatches PublishSalesEvent with afterCommit(); queue:work (a Polling Consumer) pops it; the ReserveStock job (a Service Activator) calls StockService. The database driver or Redis suffices; the interface costs nothing and prepares the later split. Even here: dispatch after commit, make handle() idempotent, and keep a failed_jobs plan.

Modular monolith / multiple databases ​

Sales and Fulfilment are modules with their own tables. Sales publishes through OrderEvents; Fulfilment's module has an endpoint and a dispatcher and may share the same Redis or RabbitMQ. Each module owns its queue (fulfilment.sales-events), so a slow Fulfilment handler cannot block Billing. The gateway interface is now a module boundary: Fulfilment depends on the envelope, not on Sales classes.

Microservices ​

Fulfilment is a separate service consuming Sales events. The worked example, end to end:

Sales service                                Broker                         Fulfilment service
1  PlaceOrder: DB tx (orders row)
2  OrderEvents.orderPlaced(o)  --gateway-->  sales.events (durable topic)
3  persistent publish + confirm              4  queue fulfilment.sales-events
                                                (durable, bound sales.order.#)
                                             5  push / pull  ------------------>  endpoint -> Envelope
                                                                                   6  Selective: region == "eu"
                                                                                   7  Dispatcher: type -> reserveStock
                                                                                   8  Service Activator -> StockService
                                                                                   9  inbox row inserted, stock updated
                                             <-------- ack / commit / XACK ------- 10 endpoint acks after handler returns

On RabbitMQ the exchange sales.events is a durable topic exchange and fulfilment.sales-events a durable queue: Fulfilment's durable subscription. On Kafka the topic sales.events is keyed by order id and the group fulfilment is the subscription. On Redis the stream sales.events has the group fulfilment. In all three the endpoint, dispatcher and activators are the same code; only newSource changes. Compare the event design in Domain Events vs Integration Events and the failure side in Designing for Failure: Reliable Messaging; service-to-service styles are in Service Communication.

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

Endpoints see the distribution as redelivery, reordering and lag. A consumer that reads a replica database for its own idempotency check can miss that a duplicate was already processed (see Replication, Read Replicas & Failover); the inbox row belongs on the primary. A cache in front of Fulfilment's stock view lags the events (see Redis). In a multi-region deployment a durable subscription is regional: RabbitMQ queues and Kafka consumer groups do not move between clusters by themselves, so cross-region consumers are separate subscribers fed by replication or a bridge. Persistence and acknowledgement settings interact with Durability, WAL & Crash Recovery; acks and offsets are only as durable as the broker's replication.

Scaling path ​

LoadEndpoint designWhat changes
1x: dozens of events/sOne worker, database or Redis queue, gateway interfaceNothing to tune; keep the interface
10xSeveral workers; RabbitMQ with prefetch, or Kafka with a few partitionsCompeting Consumers; idempotency becomes mandatory
100xChannel per bounded context; Kafka partition key per order; dedicated dispatcher per queueLag alerts, per-type queues, stop filtering client-side
BeyondStreams processors split and filter into topics; separate consumer groups per teamSelective consumers become topics; transactions only inside Kafka

Lab ​

Expected output is "expected, not run": no broker was started for this page. The Go checks below were run on the host.

Run on the host (no broker).

cd docs/snippets/messaging/consumer-endpoint-patterns/go
gofmt -l .                 # prints nothing
go vet ./...               # prints nothing
go test ./endpoint ./gateway
# ok  academy/consumer-endpoint-patterns/endpoint
# ok  academy/consumer-endpoint-patterns/gateway
go run ./cmd/fulfilment    # BROKER not set (rabbitmq | kafka | redis); nothing to do

Experiments with a broker (expected, not run).

  1. Event-driven vs polling latency (RabbitMQ). Publish one message to fulfilment.sales-events; consume it with BROKER=rabbitmq. Expected: the log line appears within milliseconds. Stop the consumer, poll the queue with Channel.Get (rabbitmq.Poll) and compare idle CPU; expected: a steady stream of basic.get requests in the management UI even when the queue is empty.
  2. Durable vs non-durable (RabbitMQ). Stop the consumer, publish three persistent messages, restart the broker, restart the consumer. Expected: three messages delivered. Repeat with DeliveryMode: Transient: expected, none.
  3. Durable subscriber (Kafka). Start BROKER=kafka, process two records, stop, produce three more, start again. Expected: only the three new records, because the group's committed offset was kept. Run with a new group name and AtStart: expected, all five.
  4. Pending-first resume (Redis). Make the handler return a transient error for one entry, kill the process, restart. Expected: the first read (id 0) re-delivers that entry before any new one.
  5. Selective consumer cost. Publish 1000 messages with 10% region=eu. Expected: the handler logs 100 lines, but the consumer's receive counter shows 1000; this is the cost of client-side selection.
  6. Transaction semantics. On a channel in tx mode publish, then TxRollback. Expected: nothing visible in the target queue; the delivery you were holding is not requeued, you can still ack or reject it.

Common misconceptions ​

BeliefReality
"Event-driven means push on the wire."EIP: how the message arrives is "implementation-specific"; Kafka and Redis are pull under any callback.
"Polling is always wasteful."Long polling (Kafka poll, Redis BLOCK) waits on the broker; only tight non-blocking loops and basic.get are wasteful.
"A gateway is an API gateway."It is an in-process class that hides the broker API.
"Durable means persisted to disk."Durable subscription is broker-kept subscriber state; persistence of messages is a separate switch.
"A durable subscriber never loses messages."Retention, TTL, trimmed streams and expired offsets can all delete what it was owed.
"The broker filters for a Selective Consumer."Not on RabbitMQ queues, Kafka or Redis Streams; only RabbitMQ streams filter in stages.
"Transactional Client gives exactly-once with my database."No product here provides a cross-resource transaction; use idempotency or the outbox.
"RabbitMQ tx is ACID."The docs call it "closer to ... batching", with no atomicity guarantee even for a single queue.
"Horizon is the message dispatcher."It supervises and balances worker processes for Redis queues; dispatch to a class happens in the worker.
"Rollback requeues the message I consumed."In RabbitMQ the acks are transactional, "not the consuming of the messages themselves".
"Auto-ack is fine because the handler is fast."A crash between delivery and processing loses the message; the EIP example is explicitly not a Transactional Client for this reason.

Cheat sheet ​

TopicRemember
Message EndpointApplication-side client of a channel; one layer imports the broker
Messaging GatewayInterface with domain methods; one impl per broker; fake in tests
Polling ConsumerApplication asks; block or back off; never spin
Event-Driven ConsumerBroker or library calls you; set prefetch; ack after processing
Push vs pullPush: latency. Pull: control, batching, free backpressure
Message Dispatchertype to performer; unknown type is a permanent error
Selective ConsumerPrefer a channel per interest; skipped messages must be acked
Durable SubscriberRabbitMQ durable queue + persistent; Kafka group + offsets; Redis group
Kafka durability trapoffsets.retention.minutes 10080 and auto.offset.reset=latest skip silently
Transactional ClientBroker-internal only; RabbitMQ tx is batching; Kafka producer transactions; Redis no rollback
DB plus brokerOutbox for publish, inbox for consume; never XA
Service ActivatorThin handle(): decode, validate, call service
Laravel workerWorker::daemon() polls; --sleep, block_for, --timeout below retry_after
Shutdown orderStop receiving, drain in-flight under a deadline, ack, close
HeartbeatsRabbitMQ 60 s suggested; Kafka session.timeout.ms 45000 and max.poll.interval.ms 300000

Self-check: questions & answers ​

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

1 — Why does the EIP say an Event-Driven Consumer "may or may not" be event-driven underneath? Good to know ​

Answer

Answer: Because the pattern describes the API the application sees, not the protocol. A callback can sit on a poll loop (Kafka, Redis) or on a true push (RabbitMQ basic.consume).

2 — Which RabbitMQ call is the polling form, and what do the docs recommend? Must-know ​

Answer

Answer: basic.get. The docs call it "highly discouraged" and "very inefficient", recommending long-lived consumers (basic.consume) except in integration tests.

3 — What exactly makes a Kafka subscriber "durable", and how can that durability end silently? Important ​

Answer

Answer: The consumer group's committed offsets. They expire offsets.retention.minutes (default 10080) after the group becomes empty, and if log retention deleted the records first, auto.offset.reset (default latest) jumps ahead without an error.

4 — A RabbitMQ queue is durable but messages disappear after a broker restart. Why? Must-know ​

Answer

Answer: The messages were published as transient (not delivery_mode=2). "Messages published as transient will be discarded during recovery, even if they were stored in durable queues."

5 — Why is a client-side Selective Consumer a smell at scale, and what is the alternative? Important ​

Answer

Answer: Every consumer receives and discards every non-match: wasted network and parsing. Route to a channel per interest (topic, routing key, binding) or filter once upstream.

6 — What does RabbitMQ's tx class cover, and what does it not? Good to know ​

Answer

Answer: Publishes and acks (reject since 2.8.0). Not the consuming itself, not resource declarations, not atomicity across queues; RabbitMQ calls it closer to batching than ACID.

7 — How does Laravel make dispatch-inside-a-transaction safe, and what gap remains? Must-know ​

Answer

Answer: afterCommit() or after_commit => true delays the push until the transaction commits. A crash between COMMIT and the push still loses the message; the outbox closes it.

8 — Is Laravel Horizon an EIP Message Dispatcher? Good to know ​

Answer

Answer: No. It supervises and balances worker processes for Redis queues. The dispatch of a payload to a class happens in the worker (Job::fire(), CallQueuedHandler::call()).

9 — Why should the shutdown path cancel the consumer before closing the channel? Important ​

Answer

Answer: Cancelling stops new deliveries while allowing in-flight ones to finish and be acked; closing first would redeliver work that was nearly done.

10 — What is the Redis Streams resume path for a durable subscriber after a crash? Important ​

Answer

Answer: Read with id 0 to get your own pending entries, process and XACK them, then switch to > for new messages.

Glossary ​

TermMeaning
Message EndpointApplication-side code that connects to a channel and sends or receives messages
Messaging GatewayIn-process class exposing domain methods and hiding the messaging API
Polling ConsumerReceiver that explicitly asks for a message when ready (synchronous receiver)
Event-Driven ConsumerReceiver invoked by the messaging system on arrival (asynchronous receiver)
Message DispatcherConsumer that distributes each message from a channel to a performer
PerformerThe object that processes a message handed over by a dispatcher
Selective ConsumerConsumer that only receives messages matching a selection value
Selection valueThe message property a Selective Consumer filters on
Durable SubscriberSubscriber whose messages are kept by the broker while it is disconnected
Transactional ClientA client session with commit and rollback boundaries
Service ActivatorAdapter that invokes a service from a message
basic.consumeAMQP 0-9-1 method that registers a push consumer
basic.getAMQP 0-9-1 method that fetches one message (polling)
Consumer tagIdentifier of a RabbitMQ consumer, used to cancel it
Prefetch (basic.qos)Limit on unacknowledged deliveries per consumer
poll()Kafka consumer call that fetches records and keeps the member alive
Consumer groupKafka (and Redis Streams) construct that shares a stream among members and stores positions
Committed offsetThe position stored for a group in __consumer_offsets
offsets.retention.minutesKafka broker config: how long an empty group's offsets are kept (default 10080)
auto.offset.resetKafka consumer config: what to do without a valid offset (default latest)
XREADGROUPRedis command to read a stream as a group member, optionally BLOCKing
Pending entries list (PEL)Redis group's record of delivered, unacknowledged entries
XACKRedis command that acknowledges an entry
tx.select / tx.commitAMQP 0-9-1 transaction methods
Publisher confirmRabbitMQ acknowledgement that the broker accepted a publish
read_committedKafka isolation level that hides aborted transactional records
Last Stable OffsetOffset below which a read_committed consumer may read
afterCommitLaravel option that dispatches a job only after the outer DB transaction commits
block_forLaravel Redis queue option: how long pop waits for a job
HeartbeatPeriodic frame that detects dead connections
Idempotent ReceiverConsumer that tolerates redelivered messages

References ​

All pages were fetched and read; saved copies are kept with the authoring sources. RabbitMQ documentation was read from the rabbitmq-website repository (the site sits behind Cloudflare).

Built by Morteza Negahi