Skip to content

Advanced Routing: Splitter, Aggregator, Resequencer, Scatter-Gather, Routing Slip, Process Manager ​

"using a Process Manager for every situation may be overkill." — Gregor Hohpe & Bobby Woolf, Enterprise Integration Patterns, "Process Manager"

Summary: Eleven routing patterns from Enterprise Integration Patterns that decide where a message goes, how one message becomes many, and how many messages become one again. Focus: Correlation, completeness, timeouts and persisted state for the stateful patterns (Aggregator, Resequencer, Process Manager), and how each pattern is built on RabbitMQ, Kafka, Redis Streams, Go and Laravel. Learning goal: Pick the right router for a flow, implement the stateful ones so they survive restarts, duplicates and missing parts, and know where a Process Manager stops and a Saga starts.

This page is the complete reference for the composed and stateful routers of the EIP catalogue: Message Filter, Dynamic Router, Recipient List, Splitter, Aggregator, Resequencer, Composed Message Processor, Scatter-Gather, Routing Slip, Process Manager and the Message Broker architecture pattern. It assumes the basic router vocabulary. Exchange types, bindings, topic design and the Content-Based Router are taught in Routing Topologies; this page links there instead of re-teaching them. Correlation ids and reply queues for one request and one reply live in Request-Reply; the dedup table every stateful router needs is taught in Idempotent Consumers & Inbox; windows and watermarks in Kafka Streams are in Stream Processing; compensation is in Saga Pattern; Laravel batch and chain internals are in Durable Workflows & Jobs and Laravel Queue Internals. Message Sequence as a channel-level idea is introduced in Integration Styles & Channels.

Page map ​

If you are looking forGo to
Eleven patterns in one tableEverything in one minute
Why routing outgrows one routerWhy these patterns exist
Hohpe & Woolf, the three router groupsWhere it comes from
One block per pattern: plain words, misunderstanding, definition, timeline, scenarios, per-broker tableThe concept catalogue
Correlation, completeness, timeouts, state, idempotency, ordering, observabilityMechanics
Generic splitter/aggregator, scatter-gather, routing slip, process manager in GoGo
Bus::batch, Bus::chain, Http::pool, a process manager modelLaravel
Headers exchange and CC, keyed topics and Kafka Streams, consumer groups and sorted setsBroker differences
Camel, Step Functions, Kafka Streams in real systemsIn production systems
Order with 3 shipments, carrier quotes, refund slip, fulfilment process manager vs sagaSolving the classic problems
Which pattern for which flowChoosing
Monolith → microservices → distributed scaleIn architecture
Run itLab
Wrong beliefs, a cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The patterns. Every row is unpacked in the concept catalogue.

PatternIn plain wordsTiny exampleState?Typical host
Message FilterDrop what this consumer does not wantGadget buyer ignores widget promotionsNoRabbitMQ binding, Kafka Connect Filter SMT, filter() in Kafka Streams, a consumer guard
Dynamic RouterA router that learns its rules from participants at run timeA new warehouse registers "I ship EU parcels under 30 kg"Rule base onlyGo/Laravel service reading a control channel
Recipient ListCompute a list, send one copy to eachLarge order → 3 credit agencies, small → 1NoRabbitMQ CC header, a loop of publishes
SplitterOne composite message becomes N messagesOrder with 3 shipments → 3 ShipmentRequestedNoAny consumer, Kafka Streams flatMap, Bus::batch
AggregatorN related messages become one3 ShipmentCompleted → 1 OrderShippedYesPostgreSQL-backed consumer, Kafka Streams aggregate, batch callbacks
ResequencerPut an out-of-order stream back in orderAccount events 3, 1, 2 → 1, 2, 3Yes (bounded buffer)Sorted set, in-memory buffer per key, Apache Camel resequence
Composed Message ProcessorSplit → route each part → aggregateCheck each order line in its own inventory systemYes (aggregate)Splitter + Content-Based Router + Aggregator
Scatter-GatherBroadcast one request, gather the replies into oneAsk DHL, UPS, PostNL for a price, pick the cheapestYes (short-lived)errgroup with deadline, Http::pool, reply queue + aggregator
Routing SlipThe itinerary travels with the messageRefund: validate → approve → reverse card → notifyIn the messageHeader with remaining steps, Bus::chain
Process ManagerA central brain keeps per-instance state and picks the next stepOrder fulfilment with parallel checks and a fraud branchYes (persisted)State table + outbox, Temporal, AWS Step Functions
Message Broker (EIP)A hub that owns routing between many appsESB, an integration service in front of legacy systemsDependsRabbitMQ + routing services, Kafka + stream apps

The stateful three, and what they must answer.

PatternCorrelationCompletenessTimeoutStorageDuplicate handling
Aggregatorcorrelation-id headerdistinct parts = sequence-size, or a ruleemit partial or failaggregate row + parts tablePK (correlation id, seq)
Resequencersequence key (account, order)next expected number presentgap timeout: skip and reportbuffer per key, next counterdrop seq < next, drop already buffered
Process Managerprocess idterminal state reachedper-state deadlineprocess row + processed eventsprocessed-events table

The three rules to remember.

SituationDo this
Anything that waits for "the other messages"Persist its state, dedup by (correlation id, part), close exactly once under a lock
Anything that waits at allGive it a deadline and decide in advance: emit partial or fail
More than a linear list of steps, or decisions on intermediate resultsProcess Manager (and link the Saga Pattern if steps need undoing)

Why these patterns exist ​

A single Content-Based Router answers one question: "this message, which channel?" Real flows ask harder ones. An order contains three shipments that three warehouses handle; you need one message per shipment, then one "order shipped" when all three are done. A price comparison asks three carriers and must answer in 300 ms even if one is down. A refund needs a different sequence of steps depending on amount and payment method. A fulfilment flow runs payment and stock checks in parallel and branches on a fraud score. Each of these is a combination of routers plus, in most cases, state that outlives one message. That state is what makes these patterns hard: it must survive restarts, duplicates, out-of-order arrival and missing messages.

Stateless routers (Filter, Recipient List, Splitter, Routing Slip)Stateful routers (Aggregator, Resequencer, Process Manager)
Scale by adding consumers; any instance handles any messageNeed all related messages to meet the same state: key affinity or shared storage
A crash loses nothing: the broker redeliversA crash loses open aggregates unless state is persisted
Duplicates produce duplicate outputs, handled downstreamDuplicates corrupt counts unless deduplicated inside the state
No timersNeed deadlines, sweepers and a policy for "never came"
Easy to test: input → outputTest sequences, interleavings and time

The analogy we reuse on this page: a restaurant kitchen. The order ticket is the composite message. The expediter tears it into per-station tickets (Splitter). Each station cooks its part (grill, salad, dessert). At the pass, the expediter waits until every plate for table 12 is there before sending them out together (Aggregator); if the dessert is still missing after ten minutes, they either send what is ready with an apology (emit partial) or call the manager (fail). When a waiter asks three suppliers for today's fish price and takes the cheapest answer that arrives before the market closes, that is Scatter-Gather. A banquet menu card that says "soup station, then fish, then dessert" and travels with the tray is a Routing Slip. The head chef with a clipboard who tracks every table's state and decides what to fire next is the Process Manager.

Three common misunderstandings, up front ​

  1. "The Aggregator just counts messages." Counting is the completeness condition, which is one of three design items. Hohpe & Woolf list them as correlation, completeness condition and aggregation algorithm, and in production you add a fourth and fifth: where the state lives, and what happens at the timeout. A counter in memory loses every open aggregate at deploy time and double-counts every redelivery.
  2. "A Routing Slip and a Process Manager are the same thing." The slip is decided up front, is linear, and travels inside the message, so there is no central component. The EIP text says the Process Manager exists exactly for the cases where "the sequence of processing steps has to be determined up-front and the sequence is linear" does not hold.
  3. "A Process Manager is a Saga." A Process Manager is a routing and state hub: it decides the next step. A Saga is a consistency technique: completed compensatable steps have business actions that semantically undo their effects. Most saga orchestrators are built as process managers, but a process manager with no compensations is not a saga, and a choreographed saga has no process manager.

Where it comes from ​

Gregor Hohpe and Bobby Woolf published Enterprise Integration Patterns in 2003 (Addison-Wesley). Its routing chapter groups the patterns into three families, and the group decides how hard a pattern is to run:

  • Simple routers route one inbound message to one or more outbound channels: Content-Based Router, Message Filter, Dynamic Router, Recipient List, Splitter, Aggregator, Resequencer.
  • Composed routers combine simple ones: Composed Message Processor, Scatter-Gather, Routing Slip, Process Manager.
  • Architectural patterns: Message Broker.

The catalogue refines basic routing and composes those refinements into larger flows. Aggregators and Resequencers retain messages across calls, so their storage is part of the mechanism. A Process Manager coordinates persisted workflow decisions; the EIP serverless Loan Broker demonstrates this with AWS Step Functions. A workflow engine does not remove the need to define correlation, deadlines and business outcomes.

The vocabulary on this page is the book's: correlation, completeness condition, aggregation algorithm, trigger message, hub-and-spoke, control channel. The completion strategies (Wait for All, Time Out, First Best, Time Out with Override, External Event) come straight from the Aggregator page. The modern additions (persisted state, outbox, deterministic part ids, key affinity on Kafka partitions) are what twenty years of running these patterns on brokers taught; where a number comes from a product (Apache Camel's resequencer capacity of 1000), the product is named.

OrderPlacedorder 42, 3 shipmentsSplitter1 in, N outpart 1/3 → EU-1corr=42 seq=1 size=3part 2/3 → EU-2corr=42 seq=2 size=3part 3/3 → US-1corr=42 seq=3 size=3arrive 3, 1, 1(dup), 2Aggregator (stateful)correlation: corr headerdedup: PK (corr, seq)complete: distinct parts = sizetimeout: partial or failedstrategy: merge shipmentsOrderShippedone outbox row; retriesPostgreSQLaggregates + parts + outbox

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition paraphrased from the EIP pattern page, a timeline, real scenarios, how each broker provides it, and a pointer to the code. The full code is in Go, Laravel and Broker differences.

Message Filter Must-know ​

In plain words: a router with one exit. Messages that match go through; the rest are thrown away on purpose.

Common misunderstanding: "Filtering in the consumer is the same as a Message Filter." Close, but not identical: the book distinguishes a Message Filter, which is part of the messaging system and routes qualifying messages to another channel, from a Selective Consumer, which is built into the endpoint (see Consumer & Endpoint Patterns). The difference matters for cost: a broker-side filter never ships the dropped message over the network to you.

Definition: A Message Filter forwards messages satisfying its predicate and discards the rest. One filter per pub-sub subscriber lets each destination define its own interest.

text
     Producer                    Filter (warehouse = eu-1)          eu-1 consumer
1    publish {warehouse: eu-1} -> match                          -> process
2    publish {warehouse: us-1} -> no match: ack + count dropped
3    publish {warehouse: eu-1} -> match                          -> process

Real scenarios: customers who only want price alerts for categories they buy; a fraud service that only needs payments above 1,000 EUR; a reporting sink that only exports status = completed; a test environment that drops messages tagged x-test-message.

BrokerWhat implements the filterWhere it runs
RabbitMQA binding: direct key, topic pattern, or headers exchange with x-matchIn the broker; unmatched messages never reach the queue
KafkaKafka Streams filter() / filterNot(); Kafka Connect Filter SMT with a predicate (KIP-585)In a stream app or connector; the source topic still holds everything
Redis StreamsNo server-side filter on XREADGROUP; filter in the consumer and XACK the dropped entryIn the consumer
NATSSubject wildcards per subscriptionIn the server
SQS/SNSSNS subscription filter policiesIn the service

Fix / how to use it: filterrouter.Filter in Go counts what it drops; in Laravel return early from handle() and still let the job succeed. Never make "not interested" an exception, or the broker will retry and dead-letter messages that were never errors.

Dynamic Router Good to know ​

In plain words: a router whose rule table is filled by the destinations themselves, through a separate control channel.

Common misunderstanding: "Dynamic routing means computing the destination from the message at run time." That is a Content-Based Router with clever code. A Dynamic Router is about who owns the rules: participants announce them, so adding a destination does not require redeploying the router.

Definition: A Dynamic Router accepts participant registrations over a control channel, stores their routing predicates and evaluates those rules for subsequent business messages.

text
     Control channel                         Router rule base                  Data message
1    {dest: wh.eu-2, match: {zone: EU}}  ->  wh.eu-2: zone=EU (prio 1)
2    {dest: wh.eu-3, match: {zone: EU}, prio 5} -> wh.eu-3: zone=EU (prio 5)
3                                                                               {zone: EU} -> wh.eu-3
4    {dest: wh.eu-3, match: {}}          ->  wh.eu-3 removed (drained for maintenance)
5                                                                               {zone: EU} -> wh.eu-2

Real scenarios: warehouses joining and leaving a fulfilment network; tenants with their own processing queue that register on sign-up; A/B routing of a percentage of traffic to a new consumer; draining a consumer before maintenance.

ConcernChoice
Rule base durabilityRebuild from a compacted Kafka topic, a RabbitMQ stream, or a table; never only in memory
Conflicting rulesPriority field, then deterministic tie-break
Stale rules (participant died)Heartbeat + TTL on each rule
Broker-native alternativeRabbitMQ bindings created by the participant itself are a dynamic router run by the broker

Fix: filterrouter.DynamicRouter with OnControl and Route; in Laravel a routing_rules table that participants write through an API, cached with Cache::remember.

Recipient List Important ​

In plain words: decide who should get this message, then send each of them a copy.

Common misunderstanding: "That is just fan-out." Fan-out (a pub-sub channel) sends to whoever subscribed; the sender has no say. A Recipient List computes the list per message, so the same message type can go to one recipient or five.

Definition: A Recipient List calculates destinations for each message, then sends a copy to each destination. For example, a large order may request several credit assessments.

text
     Router                                   credit.experian   credit.equifax   credit.transunion
1    order 42, 20,000 EUR -> list = [E, Q, T]
2    publish once, CC = [Q, T]          ->    copy              copy             copy
3    order 43, 80 EUR     -> list = [E]
4    publish                            ->    copy

Real scenarios: credit checks by order size; notifying only the warehouses that stock the SKUs in an order; sending a document to the regulators of the countries involved; quote requests to the suppliers the customer has enabled.

BrokerMechanismAtomicity of "send to all"
RabbitMQOne publish with routing key + CC / BCC headers (sender-selected distribution)One publish; with publisher confirms the message is confirmed when all queues confirm
KafkaN produces (one per topic)Atomic only inside a Kafka transaction
Redis StreamsN XADD in MULTI/EXECAtomic on one node
LaravelDispatch N jobs; for a database queue, inside the same DB::transactionAtomic with the database queue driver only

Fix: filterrouter.CreditCheckRecipients + SendToAll, and rabbitmq.RecipientList with the CC header. Copies keep the same message id and get a recipient header so each recipient can deduplicate independently.

Splitter Must-know ​

In plain words: take a message that contains a list and emit one message per element.

Common misunderstanding: "Splitting is trivial, it is a loop." The loop is trivial; the headers are not. If the parts do not carry a correlation id, a sequence number and the total size, nothing downstream can put them back together, detect a missing one, or ignore a duplicate. And if the part ids are random, a splitter that crashes halfway and runs again produces a second, different set of parts.

Definition: A Splitter emits an individual message for each element of a composite input. The parts carry group and sequence metadata so downstream processing can reconstruct the whole.

text
     Splitter (order 42)                     shipment.requested channel
1    consume OrderPlaced(42, [s1, s2, s3])
2    emit id=42/s1 corr=42 seq=1 size=3  ->  part 1
3    emit id=42/s2 corr=42 seq=2 size=3  ->  part 2
4    crash before ack
5    redelivery: emit 42/s1, 42/s2, 42/s3 -> parts 1, 2 again (same ids) + part 3
6    downstream dedup on message id: parts 1, 2 ignored the second time

Real scenarios: an order into shipments; a CSV import into row batches; an invoice run into one message per customer; a bulk email into per-recipient sends; a large Kafka record into chunks (with a claim check for the body).

BrokerSplitter hostOrdering of parts
RabbitMQA consumer publishing N messages with confirmsPer queue; parts to different queues have no order
KafkaKafka Streams flatMap / flatMapValues, or a consumer producing N records keyed by the parent idStable key/partition mapping → partition append order; not completion order
Redis StreamsXADD N entries in a MULTIStream order
LaravelBus::batch of N jobs, or a loader job that calls $this->batch()->add()None: "the order in which the jobs complete may not be the same as the order in which they were added"

Fix: generic splitter.Split[T] in Go stamps the headers and derives ids from the element key; in Laravel, Bus::batch gives every job the batch id as its correlation.

Aggregator Must-know ​

In plain words: collect related messages until the set is complete, then publish one message built from all of them.

Common misunderstanding: "When the last part arrives, publish." Which one is last? With redeliveries, the third message to arrive can be a duplicate of the first. With two aggregator instances, both can see "3 of 3" at the same moment and both publish. With a missing part, nothing ever publishes. The Aggregator is the pattern where at-least-once delivery hurts most.

Definition: An Aggregator stores related messages and produces a combined result when its completeness rule is satisfied. Its design specifies correlation, completeness and the aggregation algorithm; deployment also needs durable storage and timeout behavior.

The completeness strategies from the pattern page:

StrategyRuleGood forRisk
Wait for AllAll expected parts arrivedOrder shipments, invoice linesOne absent or late part can hold the entire aggregate open.
Time OutDecide with what arrived when the timer firesBids, quotesSlow-but-best answer ignored
First BestFirst response winsLatency-critical quotesIgnores better later answers
Time Out with OverrideTimer, or earlier if a response beats a thresholdQuotes with a "good enough" priceThreshold tuning
External EventA business event closes the aggregateEnd-of-day price aggregationNeeds a control channel
text
     Worker A                         aggregates row (order 42)           Worker B
1    part 3 -> insert part (3)        received=1/3
2                                                                         part 1 -> insert part (1), received=2/3
3    part 1 (redelivered) -> PK conflict: Duplicate, not counted
4                                                                         part 2 -> received=3/3
5                                     SELECT ... FOR UPDATE (B holds)
6                                     B: status open & complete -> outbox OrderShipped, status=complete
7    part 2 (dup) -> status complete: Late, ack and ignore

Real scenarios: "order shipped" after all shipments; one invoice after all usage records of a billing period (External Event: period closed); best bid from several vendors; a report after all partitions of a parallel export finished; a payment batch file after all payments of the day.

Design itemChoice on this pageAlternatives
Correlationcorrelation-id header set by the SplitterOrder id in the body; Laravel batch id; Kafka record key
Completenessdistinct seq count = sequence-sizePredicate on content; external event; minimum count
StrategyMerge parts ordered by seqBest-of, sum, last-write-wins, list
TimeoutDeadline from first part, sweeper, policy EmitPartial or FailKafka Streams window + grace + suppress
StatePostgreSQL aggregates + aggregate_partsKafka Streams state store (RocksDB + changelog), Redis hash, DynamoDB item
OutputOutbox row in the closing transactionDirect publish (loses or duplicates on crash)

Fix: aggregator.Aggregator[R] with PgStore (Go), ShipmentAggregator with insertOrIgnore + lockForUpdate (Laravel), or Bus::batch + then when the parts are jobs in the same app. See State persistence and idempotency.

Resequencer Important ​

In plain words: hold back messages that arrived too early until the ones before them show up, then release them in order.

Common misunderstanding: "Kafka keeps order, so I never need one." Kafka keeps order inside a partition. Order breaks as soon as messages take different routes (a Splitter fanning out to parallel workers, a retry topic, two producers, a Redis Streams consumer group with several consumers). And a resequencer is not free: it needs a buffer bound and a rule for a hole that never fills.

Definition: A Resequencer buffers messages that arrive ahead of their sequence position, then releases consecutive messages through an order-preserving output channel.

text
     arrives      next   buffer         released          note
1    seq 2        1      {2}            -
2    seq 1        1      {}             1, 2              hole filled
3    seq 1 (dup)  3      {}             -                 seq < next: dropped
4    seq 5        3      {5}            -
5    seq 4        3      {4, 5}         -                 capacity 2 reached
6    seq 6        3      {4, 5}         ERROR buffer full backpressure
7    (gap timeout 5 s)   {}             4, 5              skipped [3] -> alert / DLQ

Real scenarios: account ledger events that must apply in order after a parallel enrichment step; chunks of a split file that must be reassembled in order; CDC events for one row after they crossed two partitions; chat messages per conversation after a retry.

BoundWhat it protectsApache Camel defaultWhat to do when hit
CapacityMemory"The default capacity is 1000 elements" (stream resequencer)Stop consuming (backpressure) or force a skip
Gap timeoutLatencytimeout (configurable)Skip the missing sequence numbers, report them
Batch size / batch timeoutBatch resequencing modebatchTimeoutSort and release what the batch holds
DuplicatesCorrectness"By default, the Resequencer does not support duplicate messages." (keeps the first)Drop seq < next and already buffered

Fix: resequencer.Resequencer[T] (in-memory, per key), redisstreams.Resequence (sorted set + Lua), RedisStreamsResequencer (Laravel). In Kafka the usual answer is to avoid needing one: keep the key on the same partition all the way through, as Ordering & Partitioning explains.

Composed Message Processor Good to know ​

In plain words: split a message, send each part to whichever system handles that kind of part, and stitch the answers back into one message.

Common misunderstanding: "It is a new pattern to implement." It is a composition: Splitter + Content-Based Router + Aggregator. Building it means getting those three right, especially the Aggregator's completeness when parts go to systems with different speeds.

Definition: A Composed Message Processor splits a composite input, routes each item to its appropriate processor, then aggregates the replies into a combined output.

text
1    Order(lines: widget x2, gadget x1, gizmo x5) -> Splitter -> 3 line messages
2    widget line -> router -> widget inventory     gadget line -> gadget inventory    gizmo -> gizmo inventory
3    replies (any order) -> Aggregator (corr = order id, size = 3)
4    -> ValidatedOrder(all lines checked) or OrderLinesUnavailable(missing = [gizmo])

Real scenarios: per-line inventory checks across several ERP systems; per-item tax calculation by jurisdiction; KYC checks per document type; per-file virus scanning of an upload batch.

Fix: reuse splitter.Split, a router, and aggregator.Aggregator; in Laravel, Bus::batch on one connection and queue, with each job invoking the appropriate processor. For distinct destination queues, use separate dispatches plus a durable application Aggregator.

Scatter-Gather Must-know ​

In plain words: ask many, wait a bounded time, combine the answers into one.

Common misunderstanding: "Use errgroup.WithContext and fail fast." For a quote comparison that is wrong: the context of WithContext is cancelled the first time one function returns an error, so one carrier returning 503 cancels the other two in-flight requests. Scatter-Gather wants per-recipient errors and a deadline, not fail-fast.

Definition: A Scatter-Gather sends one request to multiple recipients and combines their replies. An explicit Recipient List gives a known expected count; an open pub-sub auction usually needs a deadline because the possible responder count is unknown.

text
     t(ms)  gatherer                          DHL            UPS             PostNL
1    0      scatter q-9, deadline 300        request        request         request
2    40                                       13.02 EUR
3    60                                                      503
4    300    deadline: stop waiting                                           (still running, cancelled)
5    300    best = DHL, complete=false, errors = {ups: 503, postnl: deadline exceeded}

Real scenarios: shipping quotes; flight and hotel search across providers; loan offers from banks (the book's Loan Broker); search over several shards or indexes; price checks across marketplaces.

HostScatterGatherDeadline
Go, one processgoroutines via errgroup.Group with SetLimitindexed result slicecontext.WithTimeout
Laravel, one requestHttp::poolnamed responses with as()timeout() per request
RabbitMQRecipient List or fanout exchange; reply-to queueAggregator on the reply queue by correlation_idSweeper or per-message TTL on the request
KafkaRequest topic (auction) or per-recipient topicsAggregator consumer keyed by request idKafka Streams window + suppress or sweeper
Redis StreamsXADD to request streamReply stream per gathererXREADGROUP BLOCK + deadline

Fix: scattergather.ScatterGather (Go, runnable), CarrierQuotes (Laravel). Over a broker, the gather side is an Aggregator with the "Time Out with Override" strategy, and the reply plumbing is Request-Reply.

QuoteRequest1.2 kg, corr=q-9Scatterrecipient listor pub-subDHL40 ms → 13.02 EURUPS60 ms → 503PostNL900 ms (too slow)deadline 300 msGather (Aggregator)wait for all, but not past deadlinestop early if price ≤ overrideerrors per carrier, never fatalstrategy: cheapest, then fastestbest = DHLcomplete=false, 2 errors

Routing Slip Important ​

In plain words: compute the list of steps once, staple it to the message, and let every step pass the message to the next one on the list.

Common misunderstanding: "Then the message decides the route at each step." No: the slip is decided at the start and only shrinks. If a step must choose the next step from its own result, or two steps must run in parallel, you have left Routing Slip territory and need a Process Manager. (Laravel's prependToChain/appendToChain and a step rewriting the slip header bend this rule; do it sparingly.)

Definition: A Routing Slip carries the remaining itinerary with each message. A component handles its step, updates that itinerary and forwards the message to the next destination.

text
     slip header after each hop                                   destination
1    steps=[validate, approve, card, notify] done=[]              refund.validate
2    steps=[approve, card, notify] done=[validate]                refund.manager-approval
3    steps=[card, notify] done=[validate, approve]                refund.card-reversal
4    card reversal fails -> on_error                              refund.failed (slip-failed-step=card)

Real scenarios: refunds whose steps depend on amount and payment method; document processing (decrypt → virus scan → OCR → classify, skipping decrypt for unencrypted uploads); order validation chains that differ per channel (B2B skips credit card validation, as in the book's example); media pipelines (transcode → thumbnail → publish).

HostWhere the slip livesWho forwards
RabbitMQrouting-slip header (JSON)Wrapper publishes to the next queue on the default exchange
KafkaRecord headerWrapper produces to the next topic
Redis StreamsEntry fieldWrapper XADDs to the next stream
Laravel$chained property: the remaining jobs, serialized into the running job's payloadQueueable::dispatchNextJobInChain() after handle() succeeds

Fix: routingslip.Wrap + RefundSlip (Go), StartRefund with Bus::chain (Laravel).

Slip computeramount 600 EUR, card→ 4 stepsvalidatequeue refund.validatemanager approvalonly if > 500 EURcard reversalor store creditnotify→ refund.completedheader routing-slip after step 2:steps=[card-reversal, notify] done=[validate, manager-approval]refund.failedfault: on_errorEach box: step + routerrun, pop self, forward.No central coordinator.

Process Manager Must-know ​

In plain words: one component remembers where each order is, reacts to every reply, and decides what to do next, including running things in parallel and branching on results.

Common misunderstanding: "Every flow should go through a Process Manager because it is the most flexible." The authors warn the opposite (see the quote at the top): it becomes the hub every message passes through, "The downside of this central control element is the danger of turning the Process Manager into a performance bottleneck." Use it when the flow really branches, joins or waits on people; use a Routing Slip or plain choreography for linear flows.

Definition: A Process Manager persists the state of each process instance and chooses subsequent commands from incoming results. A trigger creates the instance; replies return to the manager, forming a hub-and-spoke flow. It can coordinate parallel checks and embed Splitters or Aggregators.

text
     event                         state before        decision                                   state after
1    OrderPlaced (trigger)         started             send payment.authorize + stock.reserve     awaiting_checks
2    StockReserved                 awaiting_checks     wait for payment (join)                    awaiting_checks
3    PaymentAuthorized(fraud=95)   awaiting_checks     send review.request                        manual_review
4    ReviewDecided(approved)       manual_review       both checks done -> order.split-shipments  awaiting_shipments
5    OrderShipped (from Aggregator) awaiting_shipments send payment.capture + notify              completed
6    StockReserved (redelivered)   -                   processed_events conflict: ignored         completed

Real scenarios: order fulfilment; loan origination with manual underwriting; employee onboarding (accounts, hardware, training, each with people in the loop); insurance claims; KYC with retries and document re-requests.

OptionState storageTimersWhen
Hand-rolled (this page)Process table + processed events + outbox in PostgreSQLdeadline column + sweeperA few flows, your team owns the DB
Temporal / CadenceEvent history in the Temporal clusterDurable timersMany long flows, complex retries (see Durable Workflows)
AWS Step FunctionsJSON state between tasksWait statesAWS-native, the EIP site's Loan Broker example
Camunda / BPMN enginesEngine databaseBPMN timer eventsBusiness-modelled processes

Fix: processmanager.Decide (pure transition table) + Manager.Handle (persisted), FulfilmentProcessManager (Laravel). The comparison with a Saga is in Fulfilment Process Manager vs Saga.

startedOrderPlacedawaiting_checkspayment ∥ stockboth OK (join)awaiting_shipmentssplit → aggregatecompletedOrderShippedmanual_reviewfraud ≥ 80approvedshipment_reviewops; no automatic reshipaggregate failedcancelledrejecteddeclined /out of stockPer event, one transaction1. insert processed_events (dedup)2. SELECT process FOR UPDATE3. Decide(state, data, event) → commands4. update state + deadline, commands → outbox

Message Broker (the EIP pattern) Good to know ​

In plain words: instead of every application knowing where to send things, all of them send to one hub that knows the routes.

Common misunderstanding: "Message Broker means RabbitMQ." In EIP it is an architecture pattern (hub-and-spoke), not a product. RabbitMQ, Kafka and Redis are messaging systems you can use to build one; an ESB such as MuleSoft is one; a team's "integration service" with routing tables is one.

Definition: A Message Broker is an integration hub responsible for directing traffic between applications. Central routing simplifies connection ownership but can create a throughput and organizational bottleneck; stateless routing instances can be scaled behind a work queue.

text
1    CRM -> hub: CustomerUpdated
2    hub: content-based router + translator -> billing.customer, support.customer
3    ERP -> hub: InvoicePaid
4    hub: recipient list (tenant prefs) -> crm.payments, warehouse.release

Real scenarios: integrating legacy systems with incompatible formats; a central routing team in a bank; an API-to-messaging integration layer in a mid-size company.

AdvantageCost
One place to change routesOne team becomes everyone's bottleneck (organisationally too)
Senders and receivers decoupled from each otherSenders coupled to the hub's canonical format
Central monitoringSingle point of failure unless stateless and replicated

In microservices this pattern is usually rejected in favour of "smart endpoints and dumb pipes": routing logic lives in services and the broker only moves bytes. Keep the hub for integrating systems you cannot change.

Mechanics ​

Correlation: what ties parts together Must-know ​

Every stateful router needs a key that says "these messages belong together". The EIP Correlation Identifier pattern was written for request-reply (a reply carries the request's id), and the same idea scales to N parts: the Splitter stamps the parent's id on every part, each processor copies it to its reply, and the Aggregator groups by it. Rules that keep it working:

RuleWhy
Correlation id goes in a header, not only the bodyRouters, filters and tracing tools can read it without parsing the payload
Processors copy it unchanged into their outputOtherwise the Aggregator cannot find the reply's group
Part ids are deterministic (42/s1, not a random UUID)A re-run of the Splitter produces the same ids; dedup works
sequence-number is 1-based and sequence-size is in every partThe Aggregator knows completeness from any part, even the first to arrive
Extract the incoming trace context, create child spans and inject outgoing traceparentOne trace shows the split, every part and the aggregate (Messaging Observability)
On Kafka, the correlation id is also the record keyAll parts of one aggregate land in one partition, so one consumer owns it

On RabbitMQ the AMQP correlation_id and message_id properties exist for exactly this; on Kafka and Redis Streams they are ordinary headers or fields.

Completeness, timeouts and partial results Must-know ​

Completeness is "distinct parts seen = expected size" in the common case, and the word distinct is the whole point: count rows in a table with a primary key on (correlation id, seq), never increment a counter per delivery. When the size is unknown (an auction-style Scatter-Gather), completeness is time-based or event-based.

A timeout needs three decisions, written down before the first incident:

DecisionOptionsRecommendation
When does the clock start?First part, trigger message, or the split timeFirst part (the Aggregator may never see the trigger)
What happens at expiry?Emit partial result, emit failure, re-request missing partsDecide per business flow: quotes → partial; shipments → failure to a human or the Process Manager
What happens to late parts?Ignore, re-open, send to a "late" channelIgnore and count (Late outcome); re-opening breaks "exactly one result"
text
     time   event                                 aggregate 77 (size 3)          output
1    10:00  part 1                                open, 1/3, deadline 10:30
2    10:04  part 3                                open, 2/3
3    10:31  sweeper: deadline passed              lock (SKIP LOCKED), close      order.shipped.failed {missing: [2]}
4    10:45  part 2 arrives late                   status=failed -> Late          none (late_parts_total +1)

The sweeper runs in every instance; one transaction claims closure under the row lock, writes one outbox result and changes the open status. The relay may deliver duplicates. Kafka Streams can use a window with a grace period and suppress(Suppressed.untilWindowCloses(...)), but window closure follows stream-time advancement: silent input can postpone output, so this is not a wall-clock sweeper.

State persistence and idempotency Must-know ​

An Aggregator, a Resequencer and a Process Manager all hold state across messages, so all three face the same four failure cases:

FailureWhat goes wrong without careDefence
Aggregator restartsOpen aggregates in memory are lost; parts were acked, so they never come backStore parts before acking; ack only after commit
Duplicate part (redelivery, producer retry, splitter re-run)Counted twice: "3 of 3" with only two real partsPrimary key (correlation id, seq) + ON CONFLICT DO NOTHING
Two instances close the same aggregateTwo OrderShipped eventsSELECT ... FOR UPDATE + status check + update in one transaction
Crash between "closed" and "published"Aggregate closed, event never sent (or sent twice if published first)Write the result to an outbox in the closing transaction

The schema behind aggregator.PgStore (Go) and ShipmentAggregator (Laravel):

sql
CREATE TABLE aggregates (
  correlation_id text PRIMARY KEY,
  expected       int  NOT NULL,
  received       int  NOT NULL DEFAULT 0,
  status         text NOT NULL DEFAULT 'open'
                 CHECK (status IN ('open','complete','partial','failed')),
  deadline       timestamptz NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now(),
  closed_at      timestamptz
);
CREATE INDEX aggregates_open_deadline ON aggregates (deadline) WHERE status = 'open';

CREATE TABLE aggregate_parts (
  correlation_id text NOT NULL REFERENCES aggregates ON DELETE CASCADE,
  seq            int  NOT NULL,
  body           bytea NOT NULL,
  received_at    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (correlation_id, seq)          -- the dedup
);

-- Store a part (one transaction):
INSERT INTO aggregates (correlation_id, expected, deadline)
VALUES ($1, $2, now() + interval '30 minutes') ON CONFLICT (correlation_id) DO NOTHING;
SELECT status, expected FROM aggregates WHERE correlation_id = $1 FOR UPDATE;
-- Application: reject size mismatch / seq outside 1..expected; return if closed.
WITH inserted AS (
  INSERT INTO aggregate_parts (correlation_id, seq, body) VALUES ($1, $3, $4)
  ON CONFLICT DO NOTHING RETURNING 1
)
UPDATE aggregates SET received = received + (SELECT count(*) FROM inserted)
WHERE correlation_id = $1;

-- Sweeper: find candidates, then close each with FOR UPDATE SKIP LOCKED
SELECT correlation_id FROM aggregates
WHERE status = 'open' AND deadline < now() ORDER BY deadline LIMIT 100;

Why lock the aggregate row before inserting the part: without it, a part can be inserted after another transaction has read the parts and closed the aggregate, and it would sit in the table forever as an uncounted orphan. The row lock serialises parts of one aggregate (cheap: they are few) while different aggregates proceed in parallel. The isolation details are in Isolation Levels and the lock modes in ACID & Transactions. Clean up closed aggregates with a retention job, as Laravel does for job_batches with queue:prune-batches.

Ordering and the Resequencer's buffer bounds Important ​

A Resequencer trades latency and memory for order. Its buffer is bounded twice: by capacity (how many messages may wait) and by a gap timeout (how long a hole may stay open). Our implementation also rejects forward distances beyond MaxGap to bound skipped-number materialization. When capacity is hit, the only correct options are to stop consuming (backpressure, see Backpressure & Flow Control) or to give up on the hole. Giving up must be visible: count skipped sequence numbers, log them with the key, and send a marker to a dead-letter or reconciliation channel. Apache Camel's two modes map to the two shapes of the problem: batch resequencing sorts a collected set before output; stream resequencing tracks holes in an ongoing sequence and requires consecutive integer sequence numbers.

DesignLatencyMemorySurvives restart
In-memory per key (Go resequencer)LowestCapacity × keysNo: persist next + buffer or replay from the log
Redis sorted set per keyLow (one round trip + Lua)In Redis, ZCARD boundedDepends on persistence and failover; asynchronous replication can lose acknowledged writes
PostgreSQL table per keyHigherDiskYes
Avoid it: one partition per key end to endNoneNoneYes

Failure handling: partial aggregates and fault channels Important ​

FailureAggregatorScatter-GatherRouting SlipProcess Manager
A part never arrivesTimeout → partial or failedDeadline → best of what arrivedStep times out in the broker → DLQState deadline → reminder, retry or escalate
A part is a business errorStrategy decides (e.g. "1 of 3 shipments failed")Recorded per recipientSlip's on_error channelTransition to a compensation or review state
Poison messageInvalid message channel (ErrNotCorrelated)n/aDLQ after retries (Dead-Letter Queue)Parking state, alert
Router crash mid-flowParts stored; resumesRequest lost: caller retriesMessage redelivered; step must be idempotentResumes from persisted state

The partial aggregate must be self-describing: complete=false, the expected count, the received count and the missing sequence numbers. A consumer that cannot tell a partial result from a full one will treat "2 of 3 shipments" as "all shipped".

Observability for stateful routers Important ​

SignalMetric / fieldAlert when
Open aggregatesaggregates_open (gauge, by type)Grows without bound
Oldest open aggregateaggregate_oldest_open_secondsAbove the timeout: the sweeper is not running
Completion outcomeaggregates_closed_total{outcome=complete|partial|failed}Partial/failed ratio rises
Duplicates and late partsaggregate_parts_total{outcome=stored|duplicate|late}Duplicates spike (producer retries, rebalances)
Completenessaggregate_completeness_ratio (received/expected at close)Below 1 for flows that require all
Resequencerbuffer size, gap age, reseq_skipped_totalAny skip on a ledger flow
Process Managerinstances per state, time in state, unexpected eventsInstances stuck past deadline
Routing Slipdone list in logs = Message HistorySteps that fault most often

Extract the incoming trace context, create child spans, and inject the resulting outgoing context rather than reusing an unchanged parent header. Put the correlation id on every log line and span attribute; with W3C traceparent propagated by the Splitter, the trace of one order shows the split, the three parallel shipments and the aggregate as one tree. Laravel exposes batch progress directly: $batch->progress(), pendingJobs, failedJobs, and Bus::findBatch($id).

Go ​

Example: the building blocks ​

The module academy/routing-patterns-advanced has one package per pattern; all share the eip.Message envelope and its header names.

go
// Package eip holds the message envelope shared by every pattern in this
// chapter. Broker adapters map it to AMQP headers, Kafka record headers or
// Redis stream fields.
package eip

import (
	"maps"
	"strconv"
)

// Header names used across the chapter. Keep them stable: they are part of
// the contract between producers, routers and aggregators.
const (
	HdrMessageID     = "message-id"
	HdrCorrelationID = "correlation-id"  // which aggregate / process a message belongs to
	HdrSequence      = "sequence-number" // 1-based position inside the split
	HdrSequenceSize  = "sequence-size"   // total number of parts (completeness)
	HdrRoutingSlip   = "routing-slip"    // JSON-encoded remaining itinerary
	HdrTraceparent   = "traceparent"     // W3C trace context, propagated untouched
)

// Message is a minimal broker-neutral envelope.
type Message struct {
	ID      string
	Headers map[string]string
	Body    []byte
}

// Header returns a header value or "".
func (m Message) Header(k string) string { return m.Headers[k] }

// IntHeader parses an integer header; ok is false when missing or invalid.
func (m Message) IntHeader(k string) (int, bool) {
	n, err := strconv.Atoi(m.Headers[k])
	return n, err == nil
}

// Clone copies the header map so routers can modify headers without
// aliasing the original message.
func (m Message) Clone() Message {
	c := m
	c.Headers = maps.Clone(m.Headers)
	if c.Headers == nil {
		c.Headers = map[string]string{}
	}
	return c
}

The generic Splitter stamps correlation headers and derives deterministic ids:

go
// Package splitter implements the EIP Splitter: one composite message in,
// one message per element out, each stamped with the headers an Aggregator
// needs (correlation id, sequence number, sequence size).
package splitter

import (
	"encoding/json"
	"fmt"
	"strconv"

	"academy/routing-patterns-advanced/eip"
)

// Split is generic over the element type. key gives each element a stable
// identity so the derived message id is deterministic: if the splitter
// crashes and runs again, it emits the same ids and downstream dedup works.
func Split[T any](parent eip.Message, items []T, key func(T) string) ([]eip.Message, error) {
	if len(items) == 0 {
		return nil, fmt.Errorf("split %s: no elements", parent.ID)
	}
	corr := parent.Header(eip.HdrCorrelationID)
	if corr == "" {
		corr = parent.ID // the composite message starts the correlation
	}
	out := make([]eip.Message, 0, len(items))
	for i, it := range items {
		body, err := json.Marshal(it)
		if err != nil {
			return nil, fmt.Errorf("split %s item %d: %w", parent.ID, i, err)
		}
		m := eip.Message{
			ID: parent.ID + "/" + key(it),
			Headers: map[string]string{
				eip.HdrCorrelationID: corr,
				eip.HdrSequence:      strconv.Itoa(i + 1),
				eip.HdrSequenceSize:  strconv.Itoa(len(items)),
				eip.HdrTraceparent:   parent.Header(eip.HdrTraceparent),
			},
			Body: body,
		}
		m.Headers[eip.HdrMessageID] = m.ID
		out = append(out, m)
	}
	return out, nil
}

// Order is the worked example: one order, several shipments.
type Order struct {
	ID        string     `json:"id"`
	Shipments []Shipment `json:"shipments"`
}

// Shipment is one element of the composite order.
type Shipment struct {
	ID        string   `json:"id"`
	Warehouse string   `json:"warehouse"`
	SKUs      []string `json:"skus"`
}

// SplitOrder turns an OrderPlaced message into ShipmentRequested messages.
func SplitOrder(m eip.Message) ([]eip.Message, error) {
	var o Order
	if err := json.Unmarshal(m.Body, &o); err != nil {
		return nil, fmt.Errorf("decode order: %w", err)
	}
	if m.ID == "" {
		m.ID = o.ID
	}
	return Split(m, o.Shipments, func(s Shipment) string { return s.ID })
}

The Aggregator is generic over the aggregate value; the store makes it restart-safe:

go
// Package aggregator implements the EIP Aggregator as a stateful, restart-safe
// component: correlation by header, a completeness condition (count of
// distinct parts == sequence size), a timeout with an explicit policy, a
// pluggable aggregation strategy, and a Store that makes every step
// idempotent.
package aggregator

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"academy/routing-patterns-advanced/eip"
)

// Part is one correlated message as the store keeps it.
type Part struct {
	CorrelationID string
	Seq           int
	Size          int
	Body          []byte
}

// Outcome of storing a part.
type Outcome int

const (
	Stored    Outcome = iota // new part, counted
	Duplicate                // same (correlation id, seq) seen before: redelivery
	Late                     // aggregate already closed (completed or timed out)
)

// Result is what the store writes to its outbox when an aggregate closes.
type Result struct {
	Topic string
	Key   string
	Body  []byte
}

// Store persists aggregates. Implementations must make SavePart idempotent
// and Close exactly-once (see PgStore).
type Store interface {
	SavePart(ctx context.Context, p Part, deadline time.Time) (Outcome, error)
	// Close closes the aggregate if it is still open and either complete or
	// force is true, calling build with the parts it holds and writing the
	// result to the outbox in the same transaction. closed reports whether
	// this call did the closing.
	Close(ctx context.Context, id string, force bool,
		build func(parts []Part, complete bool) (Result, error)) (closed bool, err error)
	// Expired lists open aggregates whose deadline is before now.
	Expired(ctx context.Context, now time.Time, limit int) ([]string, error)
}

// TimeoutPolicy decides what an expired aggregate turns into.
type TimeoutPolicy int

const (
	EmitPartial TimeoutPolicy = iota // publish what arrived, flagged partial
	Fail                             // publish a failure listing missing parts
)

// Aggregator is generic over the aggregate value R that Strategy builds.
type Aggregator[R any] struct {
	Store       Store
	Strategy    func(parts []Part) (R, error) // aggregation algorithm
	Timeout     time.Duration                 // per aggregate, from the first part
	OnTimeout   TimeoutPolicy
	OutputTopic string
	Now         func() time.Time
}

// Envelope is the published aggregate.
type Envelope[R any] struct {
	CorrelationID string `json:"correlation_id"`
	Complete      bool   `json:"complete"`
	Received      int    `json:"received"`
	Expected      int    `json:"expected"`
	Missing       []int  `json:"missing,omitempty"`
	Value         *R     `json:"value,omitempty"`
}

// ErrNotCorrelated means the message lacks the headers an aggregator needs;
// route it to an invalid message channel rather than retrying.
var ErrNotCorrelated = errors.New("aggregator: missing correlation headers")

var ErrInvalidPart = errors.New("aggregator: invalid or conflicting sequence metadata")

func validPart(p Part) bool {
	return p.CorrelationID != "" && p.Size > 0 && p.Seq > 0 && p.Seq <= p.Size
}

// Handle stores one part and closes the aggregate if it became complete.
// Safe under redelivery: duplicates and late parts are acknowledged and
// ignored after retrying Close for duplicates, so a crash between SavePart and
// Close is recovered on redelivery. Ack the broker message only on nil error.
func (a *Aggregator[R]) Handle(ctx context.Context, m eip.Message) (Outcome, error) {
	corr := m.Header(eip.HdrCorrelationID)
	seq, ok1 := m.IntHeader(eip.HdrSequence)
	size, ok2 := m.IntHeader(eip.HdrSequenceSize)
	if corr == "" || !ok1 || !ok2 || seq < 1 || seq > size {
		return 0, ErrNotCorrelated
	}
	p := Part{CorrelationID: corr, Seq: seq, Size: size, Body: m.Body}
	out, err := a.Store.SavePart(ctx, p, a.now().Add(a.Timeout))
	if err != nil || out == Late {
		return out, err
	}
	_, err = a.Store.Close(ctx, corr, false, a.build(corr))
	return out, err
}

// Sweep closes expired aggregates according to OnTimeout. Run it from a
// ticker in every instance: Close is exactly-once, so racing sweepers are safe.
func (a *Aggregator[R]) Sweep(ctx context.Context, limit int) (int, error) {
	ids, err := a.Store.Expired(ctx, a.now(), limit)
	if err != nil {
		return 0, err
	}
	n := 0
	for _, id := range ids {
		closed, err := a.Store.Close(ctx, id, true, a.build(id))
		if err != nil {
			return n, fmt.Errorf("sweep %s: %w", id, err)
		}
		if closed {
			n++
		}
	}
	return n, nil
}

func (a *Aggregator[R]) build(id string) func([]Part, bool) (Result, error) {
	return func(parts []Part, complete bool) (Result, error) {
		env := Envelope[R]{CorrelationID: id, Complete: complete, Received: len(parts)}
		if len(parts) > 0 {
			env.Expected = parts[0].Size
		}
		env.Missing = missing(parts, env.Expected)
		topic := a.OutputTopic
		if !complete && a.OnTimeout == Fail {
			topic += ".failed"
		} else {
			if !complete {
				topic += ".partial"
			}
			v, err := a.Strategy(parts)
			if err != nil {
				return Result{}, err
			}
			env.Value = &v
		}
		body, err := json.Marshal(env)
		return Result{Topic: topic, Key: id, Body: body}, err
	}
}

func (a *Aggregator[R]) now() time.Time {
	if a.Now != nil {
		return a.Now()
	}
	return time.Now()
}

func missing(parts []Part, size int) []int {
	seen := make(map[int]bool, len(parts))
	for _, p := range parts {
		seen[p.Seq] = true
	}
	var out []int
	for i := 1; i <= size; i++ {
		if !seen[i] {
			out = append(out, i)
		}
	}
	return out
}
go
package aggregator

import (
	"context"
	"errors"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// Schema for PgStore. The primary key on aggregate_parts is the dedup:
// a redelivered part hits ON CONFLICT DO NOTHING and is not counted twice.
const Schema = `
CREATE TABLE IF NOT EXISTS aggregates (
  correlation_id text PRIMARY KEY,
  expected       int  NOT NULL,
  received       int  NOT NULL DEFAULT 0,
  status         text NOT NULL DEFAULT 'open'
                 CHECK (status IN ('open','complete','partial','failed')),
  deadline       timestamptz NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now(),
  closed_at      timestamptz
);
CREATE INDEX IF NOT EXISTS aggregates_open_deadline
  ON aggregates (deadline) WHERE status = 'open';
CREATE TABLE IF NOT EXISTS aggregate_parts (
  correlation_id text NOT NULL REFERENCES aggregates ON DELETE CASCADE,
  seq            int  NOT NULL,
  body           bytea NOT NULL,
  received_at    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (correlation_id, seq)
);
CREATE TABLE IF NOT EXISTS outbox (
  id         bigserial PRIMARY KEY,
  topic      text  NOT NULL,
  msg_key    text  NOT NULL,
  payload    bytea NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);`

// PgStore keeps aggregate state in PostgreSQL so an aggregator can restart,
// scale out and still close every aggregate exactly once.
type PgStore struct{ Pool *pgxpool.Pool }

// SavePart implements Store in one transaction: create the aggregate row if
// needed, refuse late parts, insert the part idempotently, bump the counter.
func (s PgStore) SavePart(ctx context.Context, p Part, deadline time.Time) (Outcome, error) {
	if !validPart(p) {
		return Stored, ErrInvalidPart
	}
	out := Stored
	err := pgx.BeginFunc(ctx, s.Pool, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx, `
			INSERT INTO aggregates (correlation_id, expected, deadline)
			VALUES ($1, $2, $3) ON CONFLICT (correlation_id) DO NOTHING`,
			p.CorrelationID, p.Size, deadline); err != nil {
			return err
		}
		var status string
		var expected int
		if err := tx.QueryRow(ctx, `
			SELECT status, expected FROM aggregates WHERE correlation_id = $1 FOR UPDATE`,
			p.CorrelationID).Scan(&status, &expected); err != nil {
			return err
		}
		if expected != p.Size {
			return ErrInvalidPart
		}
		if status != "open" {
			out = Late
			return nil
		}
		tag, err := tx.Exec(ctx, `
			INSERT INTO aggregate_parts (correlation_id, seq, body)
			VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
			p.CorrelationID, p.Seq, p.Body)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			out = Duplicate
			return nil
		}
		_, err = tx.Exec(ctx, `
			UPDATE aggregates SET received = received + 1
			WHERE correlation_id = $1`, p.CorrelationID)
		return err
	})
	return out, err
}

// Close implements Store. The row lock plus the status check make closing
// exactly-once; the sweeper path uses SKIP LOCKED so it never queues behind
// a worker that is closing the same aggregate.
func (s PgStore) Close(ctx context.Context, id string, force bool,
	build func([]Part, bool) (Result, error)) (bool, error) {
	closed := false
	lock := "FOR UPDATE"
	if force {
		lock = "FOR UPDATE SKIP LOCKED"
	}
	err := pgx.BeginFunc(ctx, s.Pool, func(tx pgx.Tx) error {
		var expected, received int
		var status string
		err := tx.QueryRow(ctx, `SELECT expected, received, status FROM aggregates
			WHERE correlation_id = $1 `+lock, id).Scan(&expected, &received, &status)
		if errors.Is(err, pgx.ErrNoRows) {
			return nil // locked by someone else (sweeper) or unknown
		}
		if err != nil {
			return err
		}
		complete := received == expected
		if status != "open" || (!complete && !force) {
			return nil
		}
		rows, err := tx.Query(ctx, `SELECT seq, body FROM aggregate_parts
			WHERE correlation_id = $1 ORDER BY seq`, id)
		if err != nil {
			return err
		}
		parts, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Part, error) {
			p := Part{CorrelationID: id, Size: expected}
			err := r.Scan(&p.Seq, &p.Body)
			return p, err
		})
		if err != nil {
			return err
		}
		res, err := build(parts, complete)
		if err != nil {
			return err
		}
		if _, err := tx.Exec(ctx, `INSERT INTO outbox (topic, msg_key, payload)
			VALUES ($1, $2, $3)`, res.Topic, res.Key, res.Body); err != nil {
			return err
		}
		newStatus := "complete"
		if !complete {
			newStatus = "partial"
			if len(res.Topic) > 7 && res.Topic[len(res.Topic)-7:] == ".failed" {
				newStatus = "failed"
			}
		}
		_, err = tx.Exec(ctx, `UPDATE aggregates SET status = $2, closed_at = now()
			WHERE correlation_id = $1`, id, newStatus)
		closed = err == nil
		return err
	})
	return closed && err == nil, err
}

// Expired implements Store using the partial index on open deadlines.
func (s PgStore) Expired(ctx context.Context, now time.Time, limit int) ([]string, error) {
	rows, err := s.Pool.Query(ctx, `SELECT correlation_id FROM aggregates
		WHERE status = 'open' AND deadline < $1 ORDER BY deadline LIMIT $2`, now, limit)
	if err != nil {
		return nil, err
	}
	return pgx.CollectRows(rows, pgx.RowTo[string])
}

The in-memory store and the tests that prove out-of-order parts, duplicates, late parts and both timeout policies:

go
package aggregator

import (
	"context"
	"encoding/json"
	"errors"
	"strconv"
	"testing"
	"time"

	"academy/routing-patterns-advanced/eip"
)

func part(corr string, seq, size int, body string) eip.Message {
	return eip.Message{ID: corr + "/" + strconv.Itoa(seq), Body: []byte(body), Headers: map[string]string{
		eip.HdrCorrelationID: corr, eip.HdrSequence: strconv.Itoa(seq), eip.HdrSequenceSize: strconv.Itoa(size),
	}}
}

func newAgg(store Store, now *time.Time, p TimeoutPolicy) *Aggregator[[]string] {
	return &Aggregator[[]string]{
		Store: store, Timeout: time.Minute, OnTimeout: p, OutputTopic: "order.shipped",
		Now: func() time.Time { return *now },
		Strategy: func(parts []Part) ([]string, error) {
			out := make([]string, len(parts))
			for i, p := range parts {
				out[i] = string(p.Body)
			}
			return out, nil
		},
	}
}

func TestOutOfOrderAndDuplicatesCloseOnce(t *testing.T) {
	ctx, now, s := context.Background(), time.Unix(0, 0), NewMemStore()
	a := newAgg(s, &now, Fail)
	for _, m := range []eip.Message{part("o1", 3, 3, "c"), part("o1", 1, 3, "a"), part("o1", 1, 3, "a"), part("o1", 2, 3, "b"), part("o1", 2, 3, "b")} {
		if _, err := a.Handle(ctx, m); err != nil {
			t.Fatal(err)
		}
	}
	if len(s.Outbox) != 1 || s.Outbox[0].Topic != "order.shipped" {
		t.Fatalf("want one complete result, got %+v", s.Outbox)
	}
	var env Envelope[[]string]
	_ = json.Unmarshal(s.Outbox[0].Body, &env)
	if !env.Complete || len(*env.Value) != 3 || (*env.Value)[0] != "a" {
		t.Fatalf("bad envelope %+v", env)
	}
	if out, _ := a.Handle(ctx, part("o1", 2, 3, "b")); out != Late {
		t.Fatalf("want Late after close, got %v", out)
	}
}

func TestTimeoutPolicies(t *testing.T) {
	for _, tc := range []struct {
		policy TimeoutPolicy
		topic  string
	}{{EmitPartial, "order.shipped.partial"}, {Fail, "order.shipped.failed"}} {
		ctx, now, s := context.Background(), time.Unix(0, 0), NewMemStore()
		a := newAgg(s, &now, tc.policy)
		_, _ = a.Handle(ctx, part("o2", 1, 3, "a"))
		now = now.Add(2 * time.Minute)
		n, err := a.Sweep(ctx, 10)
		if err != nil || n != 1 || s.Outbox[0].Topic != tc.topic {
			t.Fatalf("policy %v: n=%d err=%v outbox=%+v", tc.policy, n, err, s.Outbox)
		}
		var env Envelope[[]string]
		_ = json.Unmarshal(s.Outbox[0].Body, &env)
		if env.Complete || len(env.Missing) != 2 {
			t.Fatalf("want missing [2 3], got %+v", env)
		}
	}
}

type failCloseOnce struct {
	*MemStore
	failed bool
}

func (s *failCloseOnce) Close(ctx context.Context, id string, force bool, build func([]Part, bool) (Result, error)) (bool, error) {
	if !s.failed {
		s.failed = true
		return false, errors.New("temporary close failure")
	}
	return s.MemStore.Close(ctx, id, force, build)
}
func TestRedeliveryRetriesClose(t *testing.T) {
	now := time.Unix(0, 0)
	s := &failCloseOnce{MemStore: NewMemStore()}
	a := newAgg(s, &now, Fail)
	m := part("retry", 1, 1, "done")
	if _, err := a.Handle(context.Background(), m); err == nil {
		t.Fatal("expected close failure")
	}
	if out, err := a.Handle(context.Background(), m); err != nil || out != Duplicate || len(s.Outbox) != 1 {
		t.Fatalf("retry: %v %v outbox=%d", out, err, len(s.Outbox))
	}
}
func TestRejectConflictingSequenceSize(t *testing.T) {
	s := NewMemStore()
	ctx := context.Background()
	now := time.Unix(0, 0)
	if _, err := s.SavePart(ctx, Part{CorrelationID: "a", Seq: 1, Size: 2}, now); err != nil {
		t.Fatal(err)
	}
	for _, p := range []Part{{CorrelationID: "a", Seq: 2, Size: 3}, {CorrelationID: "b", Seq: 0, Size: 2}, {CorrelationID: "b", Seq: 3, Size: 2}} {
		if _, err := s.SavePart(ctx, p, now); !errors.Is(err, ErrInvalidPart) {
			t.Fatalf("accepted %+v: %v", p, err)
		}
	}
}

Resequencer with capacity and gap timeout:

go
// Package resequencer implements the EIP Resequencer as a stream
// resequencer: release messages as soon as the next expected sequence
// number is present, buffer the rest, and bound the buffer in two ways:
// a capacity (memory) and a gap timeout (how long to wait for a hole).
package resequencer

import (
	"errors"
	"sort"
	"time"
)

// ErrBufferFull means the hole is too old or too wide; the caller should
// stop consuming (backpressure) or force a skip with Tick.
// MaxGap bounds the work and memory required to report skipped sequence IDs.
const MaxGap int64 = 100000

var ErrGapTooWide = errors.New("resequencer: sequence gap too wide")

var ErrBufferFull = errors.New("resequencer: buffer full")

// Resequencer is not safe for concurrent use: run one per key (per order,
// per account), which is also what keeps ordering meaningful.
type Resequencer[T any] struct {
	next       int64
	buf        map[int64]T
	capacity   int
	gapTimeout time.Duration
	gapSince   time.Time // when the current hole was first seen
}

// New starts expecting sequence number start.
func New[T any](start int64, capacity int, gapTimeout time.Duration) *Resequencer[T] {
	return &Resequencer[T]{next: start, buf: map[int64]T{}, capacity: capacity, gapTimeout: gapTimeout}
}

// Next reports the sequence number the resequencer is waiting for. Persist
// it (with the buffer) if the resequencer must survive restarts.
func (r *Resequencer[T]) Next() int64 { return r.next }

// Push accepts one message and returns the in-order run it unlocked.
// Duplicates (already released or already buffered) are dropped.
func (r *Resequencer[T]) Push(seq int64, v T, now time.Time) ([]T, error) {
	if seq < r.next {
		return nil, nil // duplicate of a released message
	}
	if seq > r.next && uint64(seq)-uint64(r.next) > uint64(MaxGap) {
		return nil, ErrGapTooWide
	}
	if _, dup := r.buf[seq]; dup {
		return nil, nil
	}
	if seq != r.next && len(r.buf) >= r.capacity {
		return nil, ErrBufferFull
	}
	r.buf[seq] = v
	previous := r.next
	out := r.drain()
	if len(r.buf) > 0 && (r.gapSince.IsZero() || r.next != previous) {
		r.gapSince = now
	}
	return out, nil
}

// Tick skips a hole that has been open longer than the gap timeout. It
// returns the released messages and the sequence numbers given up on, which
// the caller should log, count and possibly send to a dead-letter channel.
func (r *Resequencer[T]) Tick(now time.Time) (released []T, skipped []int64) {
	if len(r.buf) == 0 || now.Sub(r.gapSince) < r.gapTimeout {
		return nil, nil
	}
	keys := make([]int64, 0, len(r.buf))
	for k := range r.buf {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
	for s := r.next; s < keys[0]; s++ {
		skipped = append(skipped, s)
	}
	r.next = keys[0]
	released = r.drain()
	if len(r.buf) > 0 {
		r.gapSince = now
	}
	return released, skipped
}

func (r *Resequencer[T]) drain() []T {
	var out []T
	for {
		v, ok := r.buf[r.next]
		if !ok {
			break
		}
		out = append(out, v)
		delete(r.buf, r.next)
		r.next++
	}
	if len(r.buf) == 0 {
		r.gapSince = time.Time{}
	}
	return out
}

Message Filter, Recipient List and Dynamic Router:

go
// Package filterrouter holds the simple routers of this chapter, in process:
// Message Filter, Recipient List and Dynamic Router (with its control
// channel). Broker-side equivalents live in ../brokers.
package filterrouter

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

	"academy/routing-patterns-advanced/eip"
)

// Handler consumes one message.
type Handler func(ctx context.Context, m eip.Message) error

// Predicate decides whether a message is interesting.
type Predicate func(m eip.Message) bool

// Filter is the EIP Message Filter: one output; non-matching messages are
// discarded (acknowledged and counted, never retried).
func Filter(p Predicate, next Handler, dropped func(eip.Message)) Handler {
	return func(ctx context.Context, m eip.Message) error {
		if !p(m) {
			if dropped != nil {
				dropped(m) // metric: messages_filtered_total
			}
			return nil
		}
		return next(ctx, m)
	}
}

// CreditCheckRecipients is a Recipient List rule from the EIP text: small
// orders go to one agency, large ones to several so results can be compared.
func CreditCheckRecipients(m eip.Message) []string {
	amount, _ := strconv.ParseInt(m.Header("amount-cents"), 10, 64)
	if amount >= 1_000_000 {
		return []string{"credit.experian", "credit.equifax", "credit.transunion"}
	}
	return []string{"credit.experian"}
}

// Sender publishes to one destination.
type Sender func(ctx context.Context, dest string, m eip.Message) error

// SendToAll delivers one copy per recipient. Each copy keeps the same
// message id and gets a recipient header, so a downstream Aggregator can
// count replies and an Idempotent Receiver can dedup retries of one copy.
func SendToAll(ctx context.Context, send Sender, m eip.Message, recipients []string) error {
	for _, r := range recipients {
		c := m.Clone()
		c.Headers["recipient"] = r
		c.Headers[eip.HdrSequenceSize] = strconv.Itoa(len(recipients))
		if err := send(ctx, r, c); err != nil {
			return err // retrying the whole list is safe only with receiver dedup
		}
	}
	return nil
}

// Rule is what a participant announces on the control channel.
type Rule struct {
	Destination string            `json:"destination"`
	Match       map[string]string `json:"match"` // header -> required value
	Priority    int               `json:"priority"`
}

// DynamicRouter self-configures from control messages instead of
// hard-coding every destination.
type DynamicRouter struct {
	mu    sync.RWMutex
	rules map[string]Rule // by destination
}

// NewDynamicRouter returns a router with an empty rule base.
func NewDynamicRouter() *DynamicRouter { return &DynamicRouter{rules: map[string]Rule{}} }

// OnControl consumes the control channel: register or replace a rule; an
// empty Match unregisters the destination.
func (r *DynamicRouter) OnControl(_ context.Context, m eip.Message) error {
	var rule Rule
	if err := json.Unmarshal(m.Body, &rule); err != nil {
		return err
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	if len(rule.Match) == 0 {
		delete(r.rules, rule.Destination)
		return nil
	}
	r.rules[rule.Destination] = rule
	return nil
}

// Route picks the highest-priority matching destination.
func (r *DynamicRouter) Route(m eip.Message) (string, bool) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	best, found := Rule{Priority: -1 << 31}, false
	for _, rule := range r.rules {
		ok := true
		for k, v := range rule.Match {
			if m.Header(k) != v {
				ok = false
				break
			}
		}
		if ok && rule.Priority > best.Priority {
			best, found = rule, true
		}
	}
	return best.Destination, found
}

The Go angle ​

  • golang.org/x/sync/errgroup is the natural Scatter-Gather in one process, with one trap: errgroup.WithContext cancels the shared context on the first error, which is fail-fast, not gather. Use a plain errgroup.Group, a context.WithTimeout for the deadline, SetLimit for concurrency, record errors per recipient and return nil from each function. The package doc also says "A Group should not be reused for different tasks." Create one per request.
  • Generics (Go 1.18+) let one Splitter and one Aggregator serve every element and aggregate type (Split[T], Aggregator[R], Resequencer[T]).
  • pgx gives pgx.BeginFunc for "commit or roll back the whole step", pgx.CollectRows for reading parts, and plain SQL for ON CONFLICT and FOR UPDATE SKIP LOCKED.
  • No Kafka Streams in Go. Kafka Streams is a JVM library. In Go the Aggregator host is a franz-go consumer group plus a database store (this page), or a stream processor such as Apache Flink or ksqlDB run beside the Go services.
  • Keep decisions pure. processmanager.Decide takes state, data and an event and returns the new state and commands; persistence and publishing are a thin shell. That makes the transition table testable without Docker.

Laravel ​

Example: batches as Splitter + Aggregator ​

Laravel's job batching is a ready-made Splitter + Aggregator for work inside one application. Batching runs a group of jobs and exposes lifecycle callbacks. The batch id is the correlation id, the job_batches table is the aggregate state (total_jobs, pending_jobs, failed_jobs), then fires when every job succeeded, catch on the first failure, finally when the batch finished either way. Reading Illuminate\Bus\Batch, recordSuccessfulJob() decrements pendingJobs and runs then callbacks when it reaches zero: it is a count-based Wait for All. It has no completion timeout and it does not collect job results, so the timeout and any result storage are yours to add.

php
<?php

// app/Jobs/ProcessShipment.php — one split part. Batchable gives it
// $this->batch(); the unique key on shipment_events makes a retry harmless.
namespace App\Jobs;

use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

final class ProcessShipment implements ShouldQueue
{
    use Batchable, Queueable;

    public int $tries = 5;

    public function __construct(
        public string $orderId,
        public string $shipmentId,
        public string $warehouse,
    ) {}

    public function backoff(): array
    {
        return [5, 30, 120];
    }

    public function handle(): void
    {
        if ($this->batch()?->cancelled()) {
            return; // another part failed and the batch was cancelled
        }

        DB::transaction(function (): void {
            // Idempotent receiver: (shipment_id, event) is a unique key.
            $inserted = DB::table('shipment_events')->insertOrIgnore([
                'shipment_id' => $this->shipmentId,
                'event' => 'label_created',
                'created_at' => now(),
            ]);

            if ($inserted === 0) {
                return; // already done by an earlier attempt
            }

            DB::table('shipments')
                ->where('id', $this->shipmentId)
                ->update(['status' => 'shipped', 'shipped_at' => now()]);
        });
    }
}
php
<?php

// app/Actions/ShipOrder.php — Bus::batch is a Splitter (one job per shipment)
// plus a count-based "wait for all" Aggregator (then/catch/finally). It has
// no completion timeout and stores no job results: add both yourself.
namespace App\Actions;

use App\Events\OrderShipped;
use App\Jobs\ProcessShipment;
use App\Models\Order;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

final class ShipOrder
{
    public function __invoke(Order $order): string
    {
        $jobs = $order->shipments
            ->map(fn ($s) => new ProcessShipment($order->id, $s->id, $s->warehouse))
            ->all();

        $orderId = $order->id; // callbacks are serialized: never capture $this

        $batch = Bus::batch($jobs)
            ->name("ship-order:{$orderId}")
            ->onQueue('shipments')
            ->allowFailures() // keep going so we can report a partial aggregate
            ->then(function (Batch $batch) use ($orderId): void {
                // Completeness reached: every part succeeded.
                DB::table('orders')->where('id', $orderId)->update(['status' => 'shipped']);
                OrderShipped::dispatch($orderId);
            })
            ->catch(function (Batch $batch, Throwable $e) use ($orderId): void {
                // First failure of any part (fires once per batch).
                Log::warning('shipment part failed', ['order' => $orderId, 'batch' => $batch->id, 'error' => $e->getMessage()]);
            })
            ->finally(function (Batch $batch) use ($orderId): void {
                if ($batch->failedJobs > 0) {
                    // Partial aggregate: some shipments left, some did not.
                    DB::table('orders')->where('id', $orderId)->update(['status' => 'partially_shipped']);
                }
            })
            ->dispatch();

        // Correlation id for dashboards: $batch->progress(), pendingJobs, failedJobs.
        DB::table('orders')->where('id', $orderId)->update(['shipment_batch_id' => $batch->id]);

        return $batch->id;
    }
}

The timeout Laravel batches lack, as a scheduled command:

php
<?php

// app/Console/Commands/ShipmentBatchTimeout.php — the completion timeout
// Laravel batches do not have. Schedule it every minute.
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;

final class ShipmentBatchTimeout extends Command
{
    protected $signature = 'shipments:timeout {--minutes=30}';

    protected $description = 'Cancel shipment batches that did not complete in time';

    public function handle(): int
    {
        $cutoff = now()->subMinutes((int) $this->option('minutes'));

        DB::table('orders')
            ->where('status', 'shipping')
            ->whereNotNull('shipment_batch_id')
            ->where('updated_at', '<', $cutoff)
            ->orderBy('id')
            ->each(function (object $order): void {
                $batch = Bus::findBatch($order->shipment_batch_id);
                if ($batch === null || $batch->finished()) {
                    return;
                }
                $batch->cancel(); // remaining parts see cancelled() and return
                DB::table('orders')->where('id', $order->id)
                    ->update(['status' => 'shipment_timed_out']);
                $this->warn("order {$order->id}: {$batch->pendingJobs} parts missing");
            });

        return self::SUCCESS;
    }
}

Batch callbacks are serialized for later execution: avoid capturing $this. Batched jobs run within transactions; do not issue statements causing implicit commits. All jobs in a batch must use the same connection and queue.

Example: chains as Routing Slip ​

A job chain schedules its remaining jobs sequentially after success and stops when a job fails. In the framework source (Illuminate\Bus\Queueable), the remaining jobs are serialized into the running job's $chained property and dispatchNextJobInChain() shifts the next one off after a success: the itinerary travels inside the message, exactly a Routing Slip.

php
<?php

// app/Actions/StartRefund.php — Bus::chain is a Routing Slip: the remaining
// jobs are serialized into the running job's payload ($chained) and the next
// one is shifted off after each success. The slip is computed per refund.
namespace App\Actions;

use App\Jobs\Refunds\CardReversal;
use App\Jobs\Refunds\ManagerApproval;
use App\Jobs\Refunds\NotifyCustomer;
use App\Jobs\Refunds\RestockGiftWrap;
use App\Jobs\Refunds\StoreCredit;
use App\Jobs\Refunds\ValidateRefund;
use App\Models\Refund;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Throwable;

final class StartRefund
{
    public function __invoke(Refund $refund): void
    {
        $slip = [new ValidateRefund($refund->id)];

        if ($refund->amount_cents > 50_000) {
            $slip[] = new ManagerApproval($refund->id);
        }
        if ($refund->gift_wrapped) {
            $slip[] = new RestockGiftWrap($refund->id);
        }
        $slip[] = $refund->paid_by_card
            ? new CardReversal($refund->id)
            : new StoreCredit($refund->id);
        $slip[] = new NotifyCustomer($refund->id);

        $refundId = $refund->id;

        Bus::chain($slip)
            ->onQueue('refunds')
            ->catch(function (Throwable $e) use ($refundId): void {
                // A step failed after its retries: the rest of the slip is dropped.
                DB::table('refunds')->where('id', $refundId)
                    ->update(['status' => 'failed', 'failure' => $e->getMessage()]);
            })
            ->dispatch();
    }
}

A step can edit the rest of the slip with prependToChain / appendToChain:

php
<?php

// app/Jobs/Refunds/ManagerApproval.php — a step may edit the remaining slip
// at run time (prependToChain / appendToChain), which a classic Routing Slip
// allows only through the slip header.
namespace App\Jobs\Refunds;

use App\Models\Refund;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

final class ManagerApproval implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $refundId) {}

    public function handle(): void
    {
        $refund = Refund::findOrFail($this->refundId);

        if ($refund->amount_cents > 500_000) {
            // Very large refund: insert a finance check right after this step.
            $this->prependToChain(new FinanceSignOff($this->refundId));
        }

        $refund->update(['approved_at' => now()]);
    }
}

Example: Scatter-Gather with Http::pool ​

php
<?php

// app/Shipping/CarrierQuotes.php — in-process Scatter-Gather with Http::pool:
// scatter to three carriers concurrently, gather with a per-request timeout,
// pick the best quote, tolerate a failing carrier.
namespace App\Shipping;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

final class CarrierQuotes
{
    private const CARRIERS = [
        'dhl' => 'https://quotes.dhl.example/v1/rates',
        'ups' => 'https://quotes.ups.example/v1/rates',
        'postnl' => 'https://quotes.postnl.example/v1/rates',
    ];

    /** @return array{best: ?array, quotes: array, errors: array} */
    public function best(int $grams, string $correlationId): array
    {
        $responses = Http::pool(fn (Pool $pool) => array_map(
            fn (string $name, string $url) => $pool->as($name)
                ->timeout(2) // the gather deadline, per carrier
                ->withHeaders(['X-Correlation-Id' => $correlationId])
                ->post($url, ['grams' => $grams]),
            array_keys(self::CARRIERS),
            self::CARRIERS,
        ), concurrency: 3);

        $quotes = [];
        $errors = [];
        foreach ($responses as $name => $response) {
            if ($response instanceof ConnectionException) {
                $errors[$name] = 'timeout or connection error';
            } elseif ($response instanceof Response && $response->successful()) {
                $quotes[] = ['carrier' => $name, 'price_cents' => (int) $response->json('price_cents'), 'days' => (int) $response->json('days')];
            } else {
                $errors[$name] = 'HTTP '.$response->status();
            }
        }

        usort($quotes, fn ($a, $b) => [$a['price_cents'], $a['days']] <=> [$b['price_cents'], $b['days']]);

        return ['best' => $quotes[0] ?? null, 'quotes' => $quotes, 'errors' => $errors];
    }
}

Example: a Process Manager as a state model ​

php
<?php

// app/Fulfilment/FulfilmentProcessManager.php — a Process Manager as a
// persisted state model: dedup the event, lock the process row, decide,
// store the new state and dispatch commands after commit.
namespace App\Fulfilment;

use App\Jobs\Fulfilment\SendCommand;
use Illuminate\Support\Facades\DB;
use RuntimeException;

final class FulfilmentProcessManager
{
    /**
     * Pure transition table: [state, event] => [next state, commands].
     * Join and branch logic lives in decide().
     */
    public function decide(string $state, array $data, array $event): array
    {
        $type = $event['type'];

        return match (true) {
            $state === 'started' && $type === 'OrderPlaced' => ['awaiting_checks', $data, ['payment.authorize', 'stock.reserve']],
            $state === 'awaiting_checks' && $type === 'PaymentAuthorized' && ($event['fraud_score'] ?? 0) >= 80 => ['manual_review', $data, ['review.request']],
            $state === 'awaiting_checks' && $type === 'PaymentAuthorized' => $this->join('awaiting_checks', [...$data, 'payment' => true]),
            $state === 'manual_review' && $type === 'StockReserved' => ['manual_review', [...$data, 'stock' => true], []],
            $state === 'awaiting_checks' && $type === 'StockReserved' => $this->join('awaiting_checks', [...$data, 'stock' => true]),
            in_array($state, ['awaiting_checks', 'manual_review'], true) && in_array($type, ['PaymentDeclined', 'OutOfStock'], true) => ['cancelled', $data, ['stock.release', 'payment.void', 'customer.notify-cancelled']],
            $state === 'manual_review' && $type === 'ReviewDecided' && ! ($event['approved'] ?? false) => ['cancelled', $data, ['stock.release', 'payment.void']],
            $state === 'manual_review' && $type === 'ReviewDecided' => $this->join('awaiting_checks', [...$data, 'payment' => true]),
            $state === 'awaiting_shipments' && $type === 'OrderShipped' => ['completed', $data, ['payment.capture', 'customer.notify-shipped']],
            $state === 'awaiting_shipments' && $type === 'ShipmentAggregateFailed' => ['shipment_review', $data, ['ops.investigate-shipment']],
            default => throw new RuntimeException("Unexpected {$type} in {$state}"),
        };
    }

    private function join(string $state, array $data): array
    {
        if (($data['payment'] ?? false) && ($data['stock'] ?? false)) {
            return ['awaiting_shipments', $data, ['order.split-shipments']];
        }

        return [$state, $data, []];
    }

    public function handle(array $event): void
    {
        DB::transaction(function () use ($event): void {
            $fresh = DB::table('fulfilment_processed_events')->insertOrIgnore([
                'process_id' => $event['process_id'],
                'event_id' => $event['id'],
            ]);
            if ($fresh === 0) {
                return; // duplicate delivery
            }

            if ($event['type'] === 'OrderPlaced') {
                DB::table('fulfilment_processes')->insertOrIgnore([
                    'id' => $event['process_id'], 'state' => 'started', 'data' => '{}', 'version' => 0,
                ]);
            }

            $process = DB::table('fulfilment_processes')
                ->where('id', $event['process_id'])
                ->lockForUpdate()
                ->firstOrFail();

            [$next, $data, $commands] = $this->decide($process->state, json_decode($process->data, true), $event);

            DB::table('fulfilment_processes')->where('id', $process->id)->update([
                'state' => $next,
                'data' => json_encode($data),
                'version' => $process->version + 1,
                'deadline_at' => in_array($next, ['completed', 'cancelled'], true) ? null : now()->addMinutes(30),
            ]);

            foreach ($commands as $topic) {
                // afterCommit: no command leaves if the state change rolls back.
                SendCommand::dispatch($topic, $process->id)->afterCommit();
            }
        });
    }
}

The Laravel angle ​

  • Laravel 13's built-in queue connections are, database, Amazon SQS, Redis, Beanstalkd, sync and null. RabbitMQ needs vladimir-yuldashev/laravel-queue-rabbitmq, Kafka needs mateusjunges/laravel-kafka, and Redis Streams are used through the Redis facade, because the redis queue driver uses lists and sorted sets, not streams (Laravel Queue Internals).
  • Bus::batch = Splitter + Aggregator inside one app; allowFailures() turns "fail on first error" into "collect a partial result"; $this->batch()->add() lets a loader job split further; $batch->cancel() + cancelled() checks are your timeout lever.
  • Bus::chain = Routing Slip; catch is the slip's fault channel; a chain can contain a batch and a batch can contain chains, which composes Routing Slip and Splitter/Aggregator without a Process Manager.
  • A Process Manager is a model with a state column, a processed-events table and lockForUpdate(); never dispatch commands before the state commit. The shown PHP afterCommit() adapter has a crash window between commit and dispatch; use a transactional outbox for durable delivery, as in the Go manager. For compensation, follow Saga Pattern.
  • Across services, batches and chains stop working: they live in one app's queue and database. The same patterns then need broker messages and the persisted Aggregator shown above.

Broker differences ​

RabbitMQ ​

RabbitMQ is the most "router-shaped" of the three: much of the simple-router layer runs inside the broker. A headers exchange is a Message Filter / content router on header values: the binding argument x-match set to all requires every listed header to match, any requires one, and headers starting with x- are ignored unless you use all-with-x or any-with-x. Sender-selected distribution is a broker-native Recipient List: set CC and BCC headers to an array of routing keys and RabbitMQ routes to all of them; RabbitMQ removes BCC before delivering the message. An alternate exchange catches messages no binding matched, so a filter can park instead of silently drop. What RabbitMQ does not have: any state across messages. Aggregator, Resequencer and Process Manager are consumers you write, with their own storage; split parts sent to different queues lose relative order; and per-part publishing should use publisher confirms and mandatory so an unroutable part comes back via basic.return.

go
// Package rabbitmq maps the chapter's patterns onto RabbitMQ (AMQP 0-9-1):
// a headers exchange as Message Filter / content router per warehouse,
// sender-selected distribution (CC header) as a Recipient List, persistent
// split parts carrying correlation headers, and a routing-slip publisher.
package rabbitmq

import (
	"context"
	"fmt"
	"os"

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

	"academy/routing-patterns-advanced/eip"
)

// Topology declares one headers exchange and one queue per warehouse. The
// binding arguments are the filter: x-match=all means every listed header
// must match (headers starting with x- are ignored unless all-with-x).
func Topology(ch *amqp.Channel, warehouses []string) error {
	if err := ch.ExchangeDeclare("shipments.requested", amqp.ExchangeHeaders,
		true, false, false, false, nil); err != nil {
		return err
	}
	for _, w := range warehouses {
		q := "shipments." + w
		if _, err := ch.QueueDeclare(q, true, false, false, false,
			amqp.Table{"x-queue-type": "quorum"}); err != nil {
			return err
		}
		if err := ch.QueueBind(q, "", "shipments.requested", false,
			amqp.Table{"x-match": "all", "warehouse": w}); err != nil {
			return err
		}
	}
	// The aggregator's input: every warehouse replies here.
	_, err := ch.QueueDeclare("shipments.completed", true, false, false, false,
		amqp.Table{"x-queue-type": "quorum"})
	return err
}

func toPublishing(m eip.Message) amqp.Publishing {
	h := amqp.Table{}
	for k, v := range m.Headers {
		h[k] = v
	}
	return amqp.Publishing{
		MessageId:     m.ID,
		CorrelationId: m.Header(eip.HdrCorrelationID),
		DeliveryMode:  amqp.Persistent,
		ContentType:   "application/json",
		Headers:       h,
		Body:          m.Body,
	}
}

// PublishParts publishes split parts to the headers exchange. Use a channel
// in confirm mode (ch.Confirm(false)) and wait for confirms in production.
func PublishParts(ctx context.Context, ch *amqp.Channel, parts []eip.Message, warehouseOf func(eip.Message) string) error {
	for _, p := range parts {
		pub := toPublishing(p)
		pub.Headers["warehouse"] = warehouseOf(p)
		// mandatory=true: an unroutable part (no warehouse queue) comes back
		// via NotifyReturn instead of vanishing.
		if err := ch.PublishWithContext(ctx, "shipments.requested", "", true, false, pub); err != nil {
			return fmt.Errorf("publish %s: %w", p.ID, err)
		}
	}
	return nil
}

// RecipientList publishes ONE message that RabbitMQ copies to several queues
// using sender-selected distribution: the routing key plus the CC list.
func RecipientList(ctx context.Context, ch *amqp.Channel, m eip.Message, queues []string) error {
	if len(queues) == 0 {
		return fmt.Errorf("recipient list for %s is empty", m.ID)
	}
	pub := toPublishing(m)
	cc := make([]interface{}, 0, len(queues)-1)
	for _, q := range queues[1:] {
		cc = append(cc, q)
	}
	pub.Headers["CC"] = cc
	// Default exchange "": each routing key is a queue name.
	return ch.PublishWithContext(ctx, "", queues[0], true, false, pub)
}

// SlipPublisher adapts a channel to routingslip.Publisher: each step is a
// queue, so "next destination" is a routing key on the default exchange.
type SlipPublisher struct{ Ch *amqp.Channel }

// Publish implements routingslip.Publisher.
func (p SlipPublisher) Publish(ctx context.Context, dest string, m eip.Message) error {
	return p.Ch.PublishWithContext(ctx, "", dest, true, false, toPublishing(m))
}

// FromDelivery converts an AMQP delivery into the envelope.
func FromDelivery(d amqp.Delivery) eip.Message {
	m := eip.Message{ID: d.MessageId, Body: d.Body, Headers: map[string]string{}}
	for k, v := range d.Headers {
		if s, ok := v.(string); ok {
			m.Headers[k] = s
		}
	}
	return m
}

// Example wires it up only when AMQP_URL is set, so the file compiles and
// vets without a broker.
func Example(ctx context.Context) error {
	url := os.Getenv("AMQP_URL")
	if url == "" {
		return nil
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		return err
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	if err := ch.Confirm(false); err != nil {
		return err
	}
	if err := Topology(ch, []string{"eu-1", "eu-2", "us-1"}); err != nil {
		return err
	}
	m := eip.Message{ID: "credit-42", Headers: map[string]string{"amount-cents": "2000000"}, Body: []byte(`{}`)}
	return RecipientList(ctx, ch, m, []string{"credit.experian", "credit.equifax", "credit.transunion"})
}

In Laravel, the package publishes jobs to an exchange with a routing key from config; per-message headers such as CC need php-amqplib directly:

php
<?php

// config/queue.php (fragment) — vladimir-yuldashev/laravel-queue-rabbitmq:
// jobs pushed to this connection are published to a topic exchange with a
// routing key, so bindings (not code) decide which queues get them.
return [
    'connections' => [
        'rabbitmq' => [
            'driver' => 'rabbitmq',
            'queue' => env('RABBITMQ_QUEUE', 'default'),
            'connection' => 'default',
            'hosts' => [[
                'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                'port' => env('RABBITMQ_PORT', 5672),
                'user' => env('RABBITMQ_USER', 'guest'),
                'password' => env('RABBITMQ_PASSWORD', 'guest'),
                'vhost' => env('RABBITMQ_VHOST', '/'),
            ]],
            'options' => [
                'queue' => [
                    'exchange' => 'shipments',
                    'exchange_type' => 'topic',
                    'exchange_routing_key' => 'shipments.%s',
                ],
            ],
        ],
    ],
];
php
<?php

// app/Messaging/RabbitRecipientList.php — the Laravel package does not expose
// per-message headers, so this uses php-amqplib (its dependency) directly:
// one publish, RabbitMQ copies it to every queue in routing key + CC.
namespace App\Messaging;

use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

final class RabbitRecipientList
{
    public function __construct(private AMQPChannel $channel) {}

    /** @param list<string> $queues */
    public function send(array $payload, array $queues, string $correlationId): void
    {
        $first = array_shift($queues);

        $message = new AMQPMessage(json_encode($payload), [
            'content_type' => 'application/json',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
            'correlation_id' => $correlationId,
            'application_headers' => new AMQPTable([
                'CC' => $queues, // sender-selected distribution
                'sequence-size' => count($queues) + 1,
            ]),
        ]);

        // Default exchange: routing keys are queue names. mandatory=true.
        $this->channel->basic_publish($message, '', $first, true);
    }
}

Kafka ​

Kafka has no routing in the broker: a record goes to the topic and partition the producer chose, and every consumer group reads everything. Routing patterns live in clients and in Kafka Streams (JVM), which is where Kafka shines for the stateful ones. branch/split() is a content router, filter() a Message Filter, and flatMap a Splitter that emits any number of records per input. groupByKey().aggregate(...) is an Aggregator with a fault-tolerant state store (RocksDB + changelog topic); the aggregation strategy generalizes reduction. windowedBy(...) with a grace period plus suppress(untilWindowCloses) gives a stream-time completeness condition that emits a final window result when time advances; KStream-KStream windowed joins and KTable-KTable joins (including the foreign-key join) gather two related streams. Kafka Connect sits at the edges: the Filter SMT with predicates (KIP-585) filters records in a connector without a stream app. The key rule for hand-written aggregators: use the correlation id as the record key so all parts of one aggregate land in one partition and one consumer; commit offsets only after the store accepted the parts.

go
// Package kafka maps the chapter's patterns onto Kafka with franz-go. Go has
// no Kafka Streams, so the Aggregator host is a consumer group plus the
// PostgreSQL store from ../../aggregator. The key choice is what makes it
// scale: every part of one order uses the order id as record key, so all
// parts land in one partition and one consumer owns that aggregate.
package kafka

import (
	"context"
	"os"

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

	"academy/routing-patterns-advanced/aggregator"
	"academy/routing-patterns-advanced/eip"
)

func toRecord(topic string, m eip.Message) *kgo.Record {
	r := &kgo.Record{Topic: topic, Key: []byte(m.Header(eip.HdrCorrelationID)), Value: m.Body}
	for k, v := range m.Headers {
		r.Headers = append(r.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
	}
	return r
}

func fromRecord(r *kgo.Record) eip.Message {
	m := eip.Message{Body: r.Value, Headers: map[string]string{}}
	for _, h := range r.Headers {
		m.Headers[h.Key] = string(h.Value)
	}
	m.ID = m.Headers[eip.HdrMessageID]
	return m
}

// ProduceParts is the Splitter's output side. With the idempotent producer
// (franz-go default) and acks=all, a retried batch does not duplicate.
func ProduceParts(ctx context.Context, cl *kgo.Client, topic string, parts []eip.Message) error {
	recs := make([]*kgo.Record, len(parts))
	for i, p := range parts {
		recs[i] = toRecord(topic, p)
	}
	return cl.ProduceSync(ctx, recs...).FirstErr()
}

// RunAggregator consumes per-shipment results and feeds the aggregator.
// Offsets are committed only after the store accepted the batch, so a crash
// replays parts; the store's primary key turns replays into Duplicate.
func RunAggregator(ctx context.Context, cl *kgo.Client, agg *aggregator.Aggregator[[]string]) error {
	for {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() || ctx.Err() != nil {
			return ctx.Err()
		}
		var handleErr error
		fetches.EachRecord(func(r *kgo.Record) {
			if handleErr != nil {
				return
			}
			_, handleErr = agg.Handle(ctx, fromRecord(r))
		})
		if handleErr != nil {
			return handleErr // restart from last committed offset
		}
		if err := cl.CommitUncommittedOffsets(ctx); err != nil {
			return err
		}
	}
}

// NewAggregatorClient builds the consumer; returns nil without KAFKA_BROKERS
// so the file compiles and vets without a cluster.
func NewAggregatorClient() (*kgo.Client, error) {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		return nil, nil
	}
	return kgo.NewClient(
		kgo.SeedBrokers(brokers),
		kgo.ConsumerGroup("order-shipment-aggregator"),
		kgo.ConsumeTopics("shipment.completed"),
		kgo.DisableAutoCommit(),
		kgo.RequiredAcks(kgo.AllISRAcks()),
	)
}

With mateusjunges/laravel-kafka, the splitter keys every part by order id and the aggregator is a long-running consumer command:

php
<?php

// app/Messaging/KafkaShipmentSplitter.php — mateusjunges/laravel-kafka.
// Every part uses the order id as Kafka key, so all parts of one order land
// in one partition and one aggregator instance owns the aggregate.
namespace App\Messaging;

use App\Models\Order;
use Junges\Kafka\Facades\Kafka;

final class KafkaShipmentSplitter
{
    public function split(Order $order, string $traceparent): void
    {
        $size = $order->shipments->count();

        foreach ($order->shipments->values() as $i => $shipment) {
            Kafka::publish('broker')
                ->onTopic('shipment.requested')
                ->withKafkaKey($order->id)
                ->withHeaders([
                    'message-id' => "{$order->id}/{$shipment->id}",
                    'correlation-id' => $order->id,
                    'sequence-number' => (string) ($i + 1),
                    'sequence-size' => (string) $size,
                    'traceparent' => $traceparent,
                ])
                ->withBodyKey('shipment_id', $shipment->id)
                ->withBodyKey('warehouse', $shipment->warehouse)
                ->send();
        }
    }
}
php
<?php

// app/Console/Commands/AggregateShipments.php — a long-running consumer that
// feeds the database-backed aggregator (same tables as the Go PgStore).
namespace App\Console\Commands;

use App\Messaging\ShipmentAggregator;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\Consumer;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Facades\Kafka;

final class AggregateShipments extends Command
{
    protected $signature = 'shipments:aggregate';

    protected $description = 'Aggregate shipment.completed parts into OrderShipped';

    public function handle(ShipmentAggregator $aggregator): int
    {
        $consumer = Kafka::consumer(['shipment.completed'], 'order-shipment-aggregator')
            ->withHandler(function (ConsumerMessage $message, Consumer $consumer) use ($aggregator): void {
                $h = $message->getHeaders();
                $aggregator->handle(
                    $h['correlation-id'],
                    (int) $h['sequence-number'],
                    (int) $h['sequence-size'],
                    $message->getBody(),
                );
            })
            ->build();

        $consumer->consume();

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

// app/Messaging/ShipmentAggregator.php — the Aggregator's state in the
// database: parts deduplicated by primary key, completion claimed once under
// a row lock, the result written to an outbox in the same transaction.
namespace App\Messaging;

use Illuminate\Support\Facades\DB;

final class ShipmentAggregator
{
    public function handle(string $correlationId, int $seq, int $size, array $body): void
    {
        if ($correlationId === '' || $size < 1 || $seq < 1 || $seq > $size) {
            throw new \InvalidArgumentException('Invalid aggregate sequence metadata');
        }
        DB::transaction(function () use ($correlationId, $seq, $size, $body): void {
            DB::table('aggregates')->insertOrIgnore([
                'correlation_id' => $correlationId,
                'expected' => $size,
                'received' => 0,
                'status' => 'open',
                'deadline' => now()->addMinutes(30),
            ]);

            $agg = DB::table('aggregates')->where('correlation_id', $correlationId)
                ->lockForUpdate()->first();

            if ((int) $agg->expected !== $size) {
                throw new \InvalidArgumentException('Conflicting aggregate sequence size');
            }
            if ($agg->status !== 'open') {
                return; // late part after completion or timeout
            }

            $new = DB::table('aggregate_parts')->insertOrIgnore([
                'correlation_id' => $correlationId,
                'seq' => $seq,
                'body' => json_encode($body),
            ]);
            if ($new === 0) {
                return; // duplicate part (redelivery)
            }

            $received = $agg->received + 1;
            $update = ['received' => $received];

            if ($received === (int) $agg->expected) {
                $parts = DB::table('aggregate_parts')->where('correlation_id', $correlationId)
                    ->orderBy('seq')->pluck('body')->map(fn ($b) => json_decode($b, true))->all();

                DB::table('outbox')->insert([
                    'topic' => 'order.shipped',
                    'msg_key' => $correlationId,
                    'payload' => json_encode(['order_id' => $correlationId, 'shipments' => $parts]),
                ]);
                $update += ['status' => 'complete', 'closed_at' => now()];
            }

            DB::table('aggregates')->where('correlation_id', $correlationId)->update($update);
        });
    }
}

Redis Streams ​

Redis Streams give you ordered append-only logs with consumer groups (XGROUP CREATE, XREADGROUP ... >, XACK, the pending entries list and XAUTOCLAIM for crashed consumers), and nothing that routes or aggregates. A Splitter is several XADDs in one MULTI/EXEC; a Message Filter is consumer code that XACKs what it skips; a Recipient List is XADD to several streams. For stateful patterns Redis is an excellent state store: a hash per aggregate with HSETNX per part for dedup, and a sorted set as the Resequencer buffer, whose unique members are sorted by numeric score. Use the sequence number as the score, and release the contiguous run with one Lua script so "read head, remove, advance next" is atomic. Persistence depends on Redis AOF/replication settings (Redis); a consumer group with several consumers breaks per-key order, which is exactly when you need the Resequencer.

go
// Package redisstreams maps the chapter's patterns onto Redis: a stream per
// channel with consumer groups for the split parts, and a sorted set as the
// Resequencer buffer (score = sequence number), released by a Lua script so
// "check head, pop, advance next" is atomic.
package redisstreams

import (
	"context"
	"errors"
	"os"
	"strconv"

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

	"academy/routing-patterns-advanced/eip"
)

// PublishParts appends split parts to one stream. MAXLEN ~ caps memory.
func PublishParts(ctx context.Context, rdb *redis.Client, stream string, parts []eip.Message) error {
	pipe := rdb.TxPipeline() // MULTI/EXEC: all parts or none
	for _, p := range parts {
		vals := map[string]any{"body": p.Body, eip.HdrMessageID: p.ID}
		for k, v := range p.Headers {
			vals[k] = v
		}
		pipe.XAdd(ctx, &redis.XAddArgs{Stream: stream, MaxLen: 100_000, Approx: true, Values: vals})
	}
	_, err := pipe.Exec(ctx)
	return err
}

// ReadParts reads new entries for this consumer; ack after the aggregator
// stored them (XACK), so a crash leaves them in the PEL for XAUTOCLAIM.
func ReadParts(ctx context.Context, rdb *redis.Client, stream, group, consumer string) ([]redis.XMessage, error) {
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err()
	if err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
		return nil, err
	}
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 100, Block: 0,
	}).Result()
	if err != nil || len(res) == 0 {
		return nil, err
	}
	return res[0].Messages, nil
}

// Ack acknowledges processed entries.
func Ack(ctx context.Context, rdb *redis.Client, stream, group string, ids ...string) error {
	return rdb.XAck(ctx, stream, group, ids...).Err()
}

// ErrBufferFull mirrors the in-memory resequencer's bound.
var ErrBufferFull = errors.New("resequencer buffer full")

// releaseScript pops the contiguous run starting at "next".
// KEYS[1] = next counter, KEYS[2] = buffer zset. Returns released members.
var releaseScript = redis.NewScript(`
local nxt = tonumber(redis.call('GET', KEYS[1]) or '1')
local out = {}
while true do
  local head = redis.call('ZRANGE', KEYS[2], 0, 0, 'WITHSCORES')
  if #head == 0 or tonumber(head[2]) ~= nxt then break end
  table.insert(out, head[1])
  redis.call('ZREMRANGEBYRANK', KEYS[2], 0, 0)
  nxt = nxt + 1
end
redis.call('SET', KEYS[1], nxt)
return out
`)

// Resequence buffers one message (per key, e.g. per account) and returns
// whatever is now in order. Members must be unique: include the sequence
// number in the payload.
func Resequence(ctx context.Context, rdb *redis.Client, key string, seq int64, payload string, capacity int64) ([]string, error) {
	nextKey, bufKey := "reseq:"+key+":next", "reseq:"+key+":buf"
	next, err := rdb.Get(ctx, nextKey).Int64()
	if errors.Is(err, redis.Nil) {
		next = 1
	} else if err != nil {
		return nil, err
	}
	if seq < next {
		return nil, nil // duplicate of an already released message
	}
	if n, err := rdb.ZCard(ctx, bufKey).Result(); err != nil {
		return nil, err
	} else if n >= capacity && seq != next {
		return nil, ErrBufferFull
	}
	if err := rdb.ZAddNX(ctx, bufKey, redis.Z{Score: float64(seq), Member: payload}).Err(); err != nil {
		return nil, err
	}
	return releaseScript.Run(ctx, rdb, []string{nextKey, bufKey}).StringSlice()
}

// Example runs only with REDIS_ADDR set.
func Example(ctx context.Context) ([]string, error) {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		return nil, nil
	}
	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()
	var out []string
	for _, s := range []int64{2, 3, 1} {
		got, err := Resequence(ctx, rdb, "acct-7", s, "tx-"+strconv.FormatInt(s, 10), 1000)
		if err != nil {
			return nil, err
		}
		out = append(out, got...)
	}
	return out, nil // [tx-1 tx-2 tx-3]
}
php
<?php

// app/Messaging/RedisStreamsResequencer.php — read parts from a stream with
// a consumer group, buffer out-of-order entries in a sorted set (score =
// sequence number) and release the contiguous run with one Lua script.
namespace App\Messaging;

use Illuminate\Support\Facades\Redis;
use RuntimeException;

final class RedisStreamsResequencer
{
    private const RELEASE = <<<'LUA'
local nxt = tonumber(redis.call('GET', KEYS[1]) or '1')
local out = {}
while true do
  local head = redis.call('ZRANGE', KEYS[2], 0, 0, 'WITHSCORES')
  if #head == 0 or tonumber(head[2]) ~= nxt then break end
  table.insert(out, head[1])
  redis.call('ZREMRANGEBYRANK', KEYS[2], 0, 0)
  nxt = nxt + 1
end
redis.call('SET', KEYS[1], nxt)
return out
LUA;

    public function __construct(private int $capacity = 1000) {}

    public function consume(string $stream, string $group, string $consumer): void
    {
        $batches = Redis::xreadgroup($group, $consumer, [$stream => '>'], 100, 5000) ?: [];

        foreach ($batches[$stream] ?? [] as $id => $fields) {
            $released = $this->push($fields['account_id'], (int) $fields['seq'], $fields['seq'].':'.$fields['body']);

            foreach ($released as $member) {
                // Hand in-order entries to the next step here.
            }

            Redis::xack($stream, $group, [$id]); // buffered entries are safe in the zset
        }
    }

    /** @return list<string> */
    public function push(string $key, int $seq, string $member): array
    {
        $nextKey = "reseq:{$key}:next";
        $bufKey = "reseq:{$key}:buf";

        $next = (int) (Redis::get($nextKey) ?? 1);
        if ($seq < $next) {
            return []; // duplicate of a released entry
        }
        if ($seq !== $next && Redis::zcard($bufKey) >= $this->capacity) {
            throw new RuntimeException("resequencer buffer full for {$key}");
        }

        Redis::zadd($bufKey, ['NX'], $seq, $member);

        return Redis::eval(self::RELEASE, 2, $nextKey, $bufKey) ?: [];
    }
}
CapabilityRabbitMQKafkaRedis StreamsNATS JetStreamPulsarSQS/SNS
Message Filter in the brokerBindings, headers exchangeNo (Streams/Connect)NoSubject filtersTopic patternsSNS filter policies
Recipient List nativeCC/BCC headersNoNoNoNoNo
Splitter hostConsumerKafka Streams flatMapConsumerConsumerPulsar FunctionsLambda
Aggregator stateYour DBKafka Streams state storeRedis hash / your DBKV bucket / your DBFunction stateDynamoDB (EIP Loan Broker)
Ordering of partsPer queuePer partition (keyed)Per streamPer subjectPer key (Key_Shared)FIFO queues per group id
Process ManagerYour serviceYour service / StreamsYour serviceYour serviceYour serviceStep Functions

In production systems ​

  • Apache Camel implements the routing chapter almost one to one: an aggregate EIP with completionSize, completionTimeout, completionPredicate, an AggregationRepository for persistent state and optional optimistic locking, and a resequence EIP whose stream mode keeps a backlog with "The default capacity is 1000 elements" and a gap timeout.
  • Kafka Streams is the standard stateful Aggregator and windowed gatherer on Kafka: aggregate with an initializer and an adder, windows with grace, and suppress for one final result per window (Kafka 4.x Streams DSL docs).
  • AWS Step Functions is the EIP authors' own modern Process Manager example: their serverless Loan Broker "employs AWS Step Functions as Process Manager", and its Aggregator uses Lambda and DynamoDB with "a simple completeness condition of waiting for a minimum number of answers".
  • Laravel ships batches (Splitter + Aggregator) and chains (Routing Slip) in the framework, documented in the 13.x queues guide and implemented in Illuminate\Bus\Batch, PendingBatch and Queueable.

Solving the classic problems ​

Order with 3 shipments: Splitter → per-shipment processing → Aggregator → OrderShipped ​

SolutionHowAdvantageCost / limitation
Bus::batch in one Laravel appOne ProcessShipment job per shipment, then publishes OrderShippedNo extra tables or code; progress built inOne app only; no timeout; then runs once per batch but you must still publish reliably
Broker + persisted AggregatorSplitter publishes 3 parts, warehouses reply on shipment.completed, Aggregator closes once and writes to the outboxWorks across services; restart-safe; partial/failed visibleTwo tables + sweeper + outbox relay
Kafka StreamsflatMapValues to split, groupByKey().aggregate() to gather, keyed by order idState store and exactly-once processing come with the libraryJVM; window/grace semantics for timeouts
text
     Splitter              eu-1 / eu-2 / us-1            Aggregator (PgStore)            Outbox relay
1    OrderPlaced(42)  ->   3 x ShipmentRequested
2                          eu-2 done -> ShipmentCompleted(42, seq 2)  -> stored 1/3
3                          eu-1 done -> ShipmentCompleted(42, seq 1)  -> stored 2/3
4                          eu-1 retry (dup)                          -> Duplicate
5                          us-1 done -> ShipmentCompleted(42, seq 3)  -> stored 3/3 -> close -> outbox row
6                                                                                         -> OrderShipped(42)

Go: splitter.SplitOrder → rabbitmq.PublishParts / kafka.ProduceParts → warehouse consumers → aggregator.Aggregator[[]string] with PgStore → outbox relay. Laravel: ShipOrder for the in-app variant, KafkaShipmentSplitter + AggregateShipments + ShipmentAggregator across services. The partial case (one warehouse cannot ship) is a business outcome in the part's body, not a missing part; the strategy turns it into OrderPartiallyShipped.

Price quotes from 3 carriers: Scatter-Gather with best-of ​

SolutionHowAdvantageCost / limitation
In-process (Go errgroup, Laravel Http::pool)Concurrent HTTP calls with a deadlineSimplest; answer in the same requestCarriers must be reachable synchronously
Over a broker, Recipient ListPublish to 3 carrier queues with reply_to + correlation id, Aggregator with Time OutCarriers can be async, slow or batch-basedCaller must wait asynchronously or poll
Auction over pub-subPublish one QuoteRequested event; any carrier adapter may answerNew carriers join without changing the gathererUnknown N: completeness is time-based only

The rules: deadline first, then "Time Out with Override" (stop as soon as a quote beats the threshold), per-carrier errors never fatal, the result says complete=false when somebody did not answer, and a carrier that answers after the deadline is ignored (its reply lands on a closed aggregate and is counted as late). Code: scattergather (Go) and CarrierQuotes (Laravel).

go
// Command scattergather asks three carriers for a price quote in parallel and
// picks the best one. Completeness: wait for all, but never past the deadline
// ("Time Out"), and stop early if a quote beats the override price ("Time Out
// with Override"). One failing carrier must not cancel the others, so errors
// are recorded per carrier and the errgroup functions always return nil.
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"maps"
	"math/rand/v2"
	"slices"
	"sort"
	"time"

	"golang.org/x/sync/errgroup"
)

// Quote is one carrier's reply.
type Quote struct {
	Carrier    string
	PriceCents int64
	Days       int
}

// Carrier is a recipient of the scatter.
type Carrier interface {
	Name() string
	Quote(ctx context.Context, parcelGrams int) (Quote, error)
}

// Gathered is the aggregate the caller gets back.
type Gathered struct {
	Best     *Quote
	Quotes   []Quote
	Errors   map[string]error
	Complete bool // every carrier answered (success or error) before the deadline
}

// ScatterGather is the Recipient List (carriers) plus an Aggregator with a
// best-of strategy.
func ScatterGather(ctx context.Context, carriers []Carrier, grams int,
	deadline time.Duration, overrideCents int64) Gathered {
	ctx, cancel := context.WithTimeout(ctx, deadline)
	defer cancel()

	type reply struct {
		q   Quote
		err error
	}
	replies := make([]reply, len(carriers)) // one slot per goroutine: no mutex
	var g errgroup.Group                    // not WithContext: one failure must not cancel the rest
	g.SetLimit(8)
	for i, c := range carriers {
		g.Go(func() error {
			q, err := c.Quote(ctx, grams)
			replies[i] = reply{q, err}
			if err == nil && q.PriceCents <= overrideCents {
				cancel() // good enough: stop waiting for the others
			}
			return nil
		})
	}
	_ = g.Wait()

	out := Gathered{Errors: map[string]error{}, Complete: true}
	for i, r := range replies {
		switch {
		case r.err != nil:
			out.Errors[carriers[i].Name()] = r.err
			if errors.Is(r.err, context.DeadlineExceeded) {
				out.Complete = false
			}
		default:
			out.Quotes = append(out.Quotes, r.q)
		}
	}
	sort.Slice(out.Quotes, func(i, j int) bool {
		a, b := out.Quotes[i], out.Quotes[j]
		return a.PriceCents < b.PriceCents || (a.PriceCents == b.PriceCents && a.Days < b.Days)
	})
	if len(out.Quotes) > 0 {
		out.Best = &out.Quotes[0]
	}
	return out
}

// fakeCarrier simulates latency and failures so the program runs offline.
type fakeCarrier struct {
	name    string
	latency time.Duration
	price   int64
	fail    bool
}

func (f fakeCarrier) Name() string { return f.name }

func (f fakeCarrier) Quote(ctx context.Context, grams int) (Quote, error) {
	select {
	case <-time.After(f.latency + time.Duration(rand.IntN(5))*time.Millisecond):
	case <-ctx.Done():
		return Quote{}, ctx.Err()
	}
	if f.fail {
		return Quote{}, fmt.Errorf("%s: 503 service unavailable", f.name)
	}
	return Quote{Carrier: f.name, PriceCents: f.price + int64(grams/100), Days: 2}, nil
}

func main() {
	override := flag.Int64("override", 500, "stop early when a quote is at or below this price (cents)")
	flag.Parse()
	carriers := []Carrier{
		fakeCarrier{name: "dhl", latency: 40 * time.Millisecond, price: 1290},
		fakeCarrier{name: "ups", latency: 60 * time.Millisecond, fail: true},
		fakeCarrier{name: "postnl", latency: 900 * time.Millisecond, price: 790},
	}
	res := ScatterGather(context.Background(), carriers, 1200, 300*time.Millisecond, *override)
	fmt.Printf("best=%s %d cents, quotes=%d, complete=%v\n",
		res.Best.Carrier, res.Best.PriceCents, len(res.Quotes), res.Complete)
	for _, name := range slices.Sorted(maps.Keys(res.Errors)) {
		fmt.Printf("error %s: %v\n", name, res.Errors[name])
	}
}

Refund flow as a Routing Slip ​

SolutionHowAdvantageCost / limitation
Bus::chainSlip computed in StartRefund, jobs run in order, catch marks failureNative, testable with Bus::fakeOne app; a failed step drops the rest of the chain
Header slip over a brokerrouting-slip header, routingslip.Wrap around every stepSteps owned by different services; no central coordinatorEach step must be idempotent; no parallelism; no undo
Process ManagerCentral state machineBranching, parallel steps, timersMore moving parts

The slip for a 600 EUR card refund of a gift-wrapped item is [validate, manager-approval, restock-giftwrap, card-reversal, notify-customer]; for a 40 EUR cash refund it is [validate, store-credit, notify-customer]. Every step is idempotent because a broker redelivery carries the same slip, and the slip's on_error channel (refund.failed) is the place a human looks. If refunds ever need "reverse the card and restock in parallel, then notify", switch to a Process Manager.

go
// Package routingslip implements the EIP Routing Slip: the itinerary travels
// in a header, and each step is wrapped by a small router that runs the step,
// pops itself off the slip and forwards the message to the next step.
package routingslip

import (
	"context"
	"encoding/json"
	"fmt"

	"academy/routing-patterns-advanced/eip"
)

// Slip is the itinerary. Done is kept for observability (it is the EIP
// Message History of this message) and for idempotency checks.
type Slip struct {
	Steps    []string `json:"steps"`              // remaining destinations, first is "me"
	Done     []string `json:"done"`               // completed destinations, in order
	OnError  string   `json:"on_error,omitempty"` // fault channel for this message
	Complete string   `json:"complete"`           // where to send the message at the end
}

// Publisher is what a broker adapter provides (see brokers/rabbitmq).
type Publisher interface {
	Publish(ctx context.Context, destination string, m eip.Message) error
}

// Step is one processing unit. It may change the body; it must not touch
// the slip (only the wrapper does).
type Step func(ctx context.Context, m eip.Message) (eip.Message, error)

// Attach computes nothing; the caller decides the steps (the "slip
// computation" component) and Attach writes them to the header.
func Attach(m eip.Message, s Slip) (eip.Message, error) {
	b, err := json.Marshal(s)
	if err != nil {
		return m, err
	}
	m = m.Clone()
	m.Headers[eip.HdrRoutingSlip] = string(b)
	return m, nil
}

// Read decodes the slip from a message.
func Read(m eip.Message) (Slip, error) {
	var s Slip
	err := json.Unmarshal([]byte(m.Header(eip.HdrRoutingSlip)), &s)
	return s, err
}

// Wrap turns a Step into a consumer handler for destination self.
func Wrap(self string, step Step, pub Publisher) func(context.Context, eip.Message) error {
	return func(ctx context.Context, in eip.Message) error {
		s, err := Read(in)
		if err != nil {
			return fmt.Errorf("routing slip: %w", err) // invalid message channel material
		}
		if len(s.Steps) == 0 || s.Steps[0] != self {
			// Misrouted (not my turn): drop it. A broker redelivery of the same
			// message carries the same slip, so the step itself must be
			// idempotent (inbox keyed by message id + step).
			return nil
		}
		out, err := step(ctx, in)
		if err != nil {
			if s.OnError == "" {
				return err // let the broker retry / dead-letter
			}
			fault := in.Clone()
			fault.Headers["slip-failed-step"] = self
			fault.Headers["slip-error"] = err.Error()
			return pub.Publish(ctx, s.OnError, fault)
		}
		s.Done = append(s.Done, self)
		s.Steps = s.Steps[1:]
		next := s.Complete
		if len(s.Steps) > 0 {
			next = s.Steps[0]
		}
		out.Headers = in.Clone().Headers // keep correlation and trace headers
		out, err = Attach(out, s)
		if err != nil {
			return err
		}
		return pub.Publish(ctx, next, out)
	}
}

// RefundSlip is the worked example: the slip is computed per refund.
func RefundSlip(amountCents int64, paidByCard, giftWrapped bool) Slip {
	steps := []string{"refund.validate"}
	if amountCents > 50_000 {
		steps = append(steps, "refund.manager-approval")
	}
	if giftWrapped {
		steps = append(steps, "refund.restock-giftwrap")
	}
	if paidByCard {
		steps = append(steps, "refund.card-reversal")
	} else {
		steps = append(steps, "refund.store-credit")
	}
	steps = append(steps, "refund.notify-customer")
	return Slip{Steps: steps, OnError: "refund.failed", Complete: "refund.completed"}
}

Order fulfilment Process Manager vs Saga: what differs ​

go
// Package processmanager implements the EIP Process Manager for order
// fulfilment: a central unit that keeps per-order state, decides the next
// step from intermediate results (including parallel branches), and emits
// commands. Decide is a pure function; Handle persists state, dedups events
// and writes commands to an outbox in one PostgreSQL transaction.
package processmanager

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// State of one fulfilment process.
type State string

const (
	Started           State = "started"
	AwaitingChecks    State = "awaiting_checks"    // payment auth and stock run in parallel
	ManualReview      State = "manual_review"      // fraud score too high
	AwaitingShipments State = "awaiting_shipments" // splitter fired, aggregator pending
	ShipmentReview    State = "shipment_review"    // operational investigation; no automatic reship
	Completed         State = "completed"
	Cancelled         State = "cancelled"
)

// Event is an incoming reply or business event.
type Event struct {
	ID         string `json:"id"` // dedup key
	ProcessID  string `json:"process_id"`
	Type       string `json:"type"`
	FraudScore int    `json:"fraud_score,omitempty"`
	Approved   bool   `json:"approved,omitempty"`
}

// Command is an outgoing message.
type Command struct {
	Topic     string `json:"topic"`
	ProcessID string `json:"process_id"`
}

// Data is the per-process memory the decisions need.
type Data struct {
	PaymentAuthorized bool `json:"payment_authorized"`
	StockReserved     bool `json:"stock_reserved"`
}

// ErrUnexpected marks an event that is invalid in the current state.
var ErrUnexpected = errors.New("process manager: unexpected event for state")

// Decide is the transition table. It is pure, so it is unit-tested without
// a database, a broker or a clock.
func Decide(s State, d Data, e Event) (State, Data, []Command, error) {
	cmd := func(t string) Command { return Command{Topic: t, ProcessID: e.ProcessID} }
	switch {
	case s == Started && e.Type == "OrderPlaced":
		// Fan out two independent checks: a Routing Slip could not do this.
		return AwaitingChecks, d, []Command{cmd("payment.authorize"), cmd("stock.reserve")}, nil
	case s == AwaitingChecks && e.Type == "PaymentAuthorized":
		if e.FraudScore >= 80 {
			return ManualReview, d, []Command{cmd("review.request")}, nil
		}
		d.PaymentAuthorized = true
	case s == ManualReview && e.Type == "StockReserved":
		d.StockReserved = true
		return ManualReview, d, nil, nil
	case s == AwaitingChecks && e.Type == "StockReserved":
		d.StockReserved = true
	case (s == AwaitingChecks || s == ManualReview) && (e.Type == "PaymentDeclined" || e.Type == "OutOfStock"):
		return Cancelled, d, []Command{cmd("stock.release"), cmd("payment.void"), cmd("customer.notify-cancelled")}, nil
	case s == ManualReview && e.Type == "ReviewDecided":
		if !e.Approved {
			return Cancelled, d, []Command{cmd("stock.release"), cmd("payment.void")}, nil
		}
		d.PaymentAuthorized = true
	case s == AwaitingShipments && e.Type == "OrderShipped": // from the Aggregator
		return Completed, d, []Command{cmd("payment.capture"), cmd("customer.notify-shipped")}, nil
	case s == AwaitingShipments && e.Type == "ShipmentAggregateFailed":
		return ShipmentReview, d, []Command{cmd("ops.investigate-shipment")}, nil
	default:
		return s, d, nil, fmt.Errorf("%w: %s in %s", ErrUnexpected, e.Type, s)
	}
	// Join of the parallel branch: both checks done?
	if s != AwaitingShipments && d.PaymentAuthorized && d.StockReserved {
		return AwaitingShipments, d, []Command{cmd("order.split-shipments")}, nil
	}
	if s == ManualReview { // approved, but stock may still be pending
		return AwaitingChecks, d, nil, nil
	}
	return s, d, nil, nil
}

// Schema for the persisted state machine.
const Schema = `
CREATE TABLE IF NOT EXISTS fulfilment_processes (
  id         text PRIMARY KEY,
  state      text NOT NULL,
  data       jsonb NOT NULL DEFAULT '{}',
  version    int  NOT NULL DEFAULT 0,
  deadline   timestamptz,               -- reminder / timeout for the current state
  updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS fulfilment_processed_events (
  process_id text NOT NULL,
  event_id   text NOT NULL,
  PRIMARY KEY (process_id, event_id)
);`

// Manager persists processes in PostgreSQL.
type Manager struct {
	Pool         *pgxpool.Pool
	StateTimeout time.Duration
}

// Handle applies one event exactly once: dedup row, row lock, decide,
// write state and outbox commands, commit.
func (m Manager) Handle(ctx context.Context, e Event) error {
	return pgx.BeginFunc(ctx, m.Pool, func(tx pgx.Tx) error {
		tag, err := tx.Exec(ctx, `INSERT INTO fulfilment_processed_events (process_id, event_id)
			VALUES ($1, $2) ON CONFLICT DO NOTHING`, e.ProcessID, e.ID)
		if err != nil || tag.RowsAffected() == 0 {
			return err // duplicate delivery: nothing to do
		}
		if e.Type == "OrderPlaced" {
			if _, err := tx.Exec(ctx, `INSERT INTO fulfilment_processes (id, state)
				VALUES ($1, $2) ON CONFLICT DO NOTHING`, e.ProcessID, Started); err != nil {
				return err
			}
		}
		var s State
		var raw []byte
		if err := tx.QueryRow(ctx, `SELECT state, data FROM fulfilment_processes
			WHERE id = $1 FOR UPDATE`, e.ProcessID).Scan(&s, &raw); err != nil {
			return fmt.Errorf("load process %s: %w", e.ProcessID, err)
		}
		var d Data
		if err := json.Unmarshal(raw, &d); err != nil {
			return err
		}
		ns, nd, cmds, err := Decide(s, d, e)
		if err != nil {
			return err // caller routes to an invalid-message / parking queue
		}
		nraw, _ := json.Marshal(nd)
		if _, err := tx.Exec(ctx, `UPDATE fulfilment_processes
			SET state = $2, data = $3, version = version + 1, updated_at = now(),
			    deadline = CASE WHEN $2 IN ('completed','cancelled') THEN NULL ELSE now() + make_interval(secs => $4) END
			WHERE id = $1`, e.ProcessID, ns, nraw, m.StateTimeout.Seconds()); err != nil {
			return err
		}
		for _, c := range cmds {
			payload, _ := json.Marshal(c)
			if _, err := tx.Exec(ctx, `INSERT INTO outbox (topic, msg_key, payload)
				VALUES ($1, $2, $3)`, c.Topic, c.ProcessID, payload); err != nil {
				return err
			}
		}
		return nil
	})
}
QuestionProcess Manager (EIP)Saga (Saga Pattern)
What problem does it solve?Routing: which step next, based on state and intermediate resultsConsistency: a business transaction across services without 2PC
Defining featureCentral state + decisions (hub-and-spoke)Compensatable steps have undo actions; pivot and retryable steps differ
Can it run steps in parallel?Yes (our checks)Yes; define compensation and retry boundaries for each branch
Does it need a central component?Yes, by definitionNo: choreography is a saga without one
What happens on failure?Whatever the transition table says (retry, review, cancel)Run compensations in reverse order
Typical stateCurrent state, data for decisions, deadlineCurrent step, completed steps (to know what to compensate)
RelationshipAn orchestrated saga is usually implemented as a process managerA process manager becomes a saga when you add compensations

In the fulfilment example, the cancelled transitions send stock.release and payment.void: those are compensations, so this particular process manager is also an orchestrated saga. The parts that make it a process manager, not "just" a saga, are the fraud branch to manual_review, the parallel join of payment and stock, and the use of a Splitter and an Aggregator for shipments.

The Go aggregator retries Close after both a stored and a duplicate part: storage may have committed before a crash interrupted closing. Both stores reject conflicting sequence sizes and out-of-range positions. The in-memory Resequencer also bounds forward distance with MaxGap, preventing one distant sequence number from generating an enormous skipped list; each newly exposed hole receives a fresh deadline.

Shipment aggregation failure enters shipment_review, distinct from fraud manual_review. Operations must reconcile carrier effects before defining an explicit recovery transition; ReviewDecided cannot dispatch shipments again from that state. A StockReserved reply received during fraud review is retained without starting shipment.

Choosing ​

SituationPatternExtra techniqueReason
Consumer only wants a subsetMessage Filter (broker side if possible)Count dropsDo not pay network and CPU for unwanted messages
Destinations come and goDynamic RouterControl channel, TTL on rulesRouter does not redeploy for each new participant
Recipients depend on the messageRecipient ListRabbitMQ CC; same message id per copyOne decision, N copies, receivers dedup
One message contains independent itemsSplitterDeterministic part ids, correlation headersParallel processing, per-item retries
Need one result from N related messagesAggregatorPK dedup, row lock, timeout policy, outboxExactly one result despite duplicates and crashes
Order broken by parallel routesAvoid with keys; else ResequencerCapacity + gap timeout, skip reportingOrder without unbounded memory
Items need different handlers, then one answerComposed Message ProcessorContent-based routing of partsReuse three proven patterns
Ask many, answer fastScatter-GatherDeadline, override threshold, per-recipient errorsBounded latency, partial answers allowed
Steps known up front, linear, vary per messageRouting SlipIdempotent steps, on_error channelNo central coordinator
Branches, joins, waits, human stepsProcess ManagerPersisted state machine, deadlinesOne place that knows "where is order 42"
Steps must be undone on failureSaga (often built as a Process Manager)Compensations, pivotConsistency without 2PC
Many legacy systems, one routing teamMessage Broker (EIP)Stateless, replicated hubCentral control; watch the bottleneck

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

Monolith: one process, one database ​

All of these patterns exist inside one Laravel or Go application, and that is the right place to start. A Scatter-Gather is Http::pool or an errgroup; a Splitter + Aggregator is Bus::batch with then; a Routing Slip is Bus::chain; a Process Manager is a model with a state column. The state lives in the same database as the business data, so "close the aggregate and mark the order shipped" is one transaction. Example: an e-shop monolith ships each order through ShipOrder (one job per shipment), then sets orders.status = shipped, and a scheduled shipments:timeout cancels batches older than 30 minutes.

Modular monolith and multiple databases ​

Modules (Orders, Warehouse, Billing) own their tables and talk through in-process events or queued jobs. The Splitter belongs to Orders, the per-shipment work to Warehouse, the Aggregator back in Orders. The rule that matters: the Aggregator's tables belong to the module that consumes the aggregate, and other modules only send parts with the correlation headers, never write into those tables. A batch spanning modules still works because they share one queue and one database, but treat batch callbacks as a cross-module contract. Example: Warehouse jobs dispatch ShipmentCompleted events; an Orders listener feeds ShipmentAggregator, which writes OrderShipped to the Orders outbox.

Microservices: what survives the boundary ​

Batches and chains do not cross services. What does: messages with correlation headers, a persisted Aggregator in the service that owns the result, an outbox in every service that emits, and an inbox in every service that consumes. Example flow for one order:

text
1    order-service: OrderPlaced -> fulfilment PM (state started -> awaiting_checks), outbox: payment.authorize, stock.reserve
2    payment-service -> PaymentAuthorized(fraud 10)      stock-service -> StockReserved
3    PM: join -> awaiting_shipments, outbox: order.split-shipments
4    order-service Splitter -> 3 x ShipmentRequested (key = order id) -> warehouse-eu-1, eu-2, us-1
5    warehouses -> ShipmentCompleted x3 -> Aggregator (order-service DB) -> outbox OrderShipped
6    PM: OrderShipped -> completed, outbox: payment.capture, customer.notify-shipped

Each arrow is at-least-once, so every hop dedups (Idempotent Consumers). The broader trade-offs are in Service Communication, Domain Events vs Integration Events and Designing for Failure & Reliable Messaging.

Distributed data: partitions, replicas and many aggregator instances ​

At scale the hard question is: where does the state of one aggregate live, and who may touch it?

ApproachHow one aggregate stays consistentBreaks when
Key affinity (Kafka partition = correlation id)Only one consumer sees an aggregate's partsParts produced with a different key; rebalance without state hand-off (Kafka Streams handles this with changelog restore)
Shared database with row locksAny instance may handle any part; the row lock serialisesHot aggregates (thousands of parts) contend on one row
Redis as stateLua scripts for atomic check-and-closeFailover with async replication can lose the last writes (Replication & Failover)
Kafka Streams state storesLocal RocksDB + changelog topic per partitionLong restore after losing a node; standby replicas help

Read replicas are useless for an Aggregator's decisions: reading "received = 2" from a lagging replica while the primary already has 3 makes the aggregate look incomplete forever. All completeness checks go to the primary. Across regions, keep each aggregate in one home region (route parts there by key) rather than merging state.

Scaling path: 1×, 10×, 100× ​

LoadDesign
1× (hundreds of orders/day)Laravel batches and chains, or one Go service with an in-process scatter-gather; state in the main database
10× (tens of thousands/day, several services)Broker messages with correlation headers; persisted Aggregator with PK dedup and sweeper; outbox; a hand-rolled Process Manager for the one complex flow
100× (millions/day, many teams)Kafka with correlation id as key; Kafka Streams or Flink for aggregation and windows; a workflow engine (Temporal, Step Functions) for process managers; partitioned aggregate tables and retention jobs; dashboards on completeness and stuck instances

Lab ​

The Go part runs offline. The broker steps need RabbitMQ, Kafka and Redis; following the cost rule they are written as commands with expected, not run output.

  1. Run the unit tests (expected, not run):
bash
cd docs/snippets/messaging/routing-patterns-advanced/go
go vet ./... && go test ./...
# ok  academy/routing-patterns-advanced/aggregator
# ok  academy/routing-patterns-advanced/processmanager
# ok  academy/routing-patterns-advanced/resequencer
# ok  academy/routing-patterns-advanced/routingslip
  1. Scatter-Gather with a failing and a slow carrier (expected, not run):
bash
go run ./scattergather
# best=dhl 1302 cents, quotes=1, complete=false
# error postnl: context deadline exceeded
# error ups: ups: 503 service unavailable

Raise the override so DHL's price counts as "good enough" (expected, not run): the gather stops as soon as DHL answers at about 40 ms, the other two calls are cancelled, and the result counts as complete because nobody hit the deadline:

bash
go run ./scattergather -override 1400
# best=dhl 1302 cents, quotes=1, complete=true
# error postnl: context canceled
# error ups: context canceled
  1. Aggregator in PostgreSQL, duplicates and late parts (expected, not run):
bash
# first apply the DDL from aggregator.Schema (pgstore.go)
psql "$DATABASE_URL" <<'SQL'
INSERT INTO aggregates (correlation_id, expected, deadline) VALUES ('42', 3, now() + interval '30 min');
INSERT INTO aggregate_parts VALUES ('42', 1, 'a') ON CONFLICT DO NOTHING;  -- INSERT 0 1
INSERT INTO aggregate_parts VALUES ('42', 1, 'a') ON CONFLICT DO NOTHING;  -- INSERT 0 0  (duplicate)
SELECT count(*) FROM aggregate_parts WHERE correlation_id = '42';          -- 1
SQL
  1. RabbitMQ Recipient List with CC (expected, not run):
bash
rabbitmqadmin declare queue name=credit.experian durable=true
rabbitmqadmin declare queue name=credit.equifax durable=true
rabbitmqadmin publish routing_key=credit.experian payload='{}' \
  properties='{"headers":{"CC":["credit.equifax"]}}'
rabbitmqadmin list queues name messages
# credit.equifax  1
# credit.experian 1
  1. Redis sorted-set Resequencer (expected, not run):
bash
redis-cli ZADD reseq:acct-7:buf NX 2 "2:tx-2"
redis-cli ZADD reseq:acct-7:buf NX 3 "3:tx-3"
redis-cli ZRANGE reseq:acct-7:buf 0 -1 WITHSCORES   # 2:tx-2 2, 3:tx-3 3 (waiting for 1)
redis-cli ZADD reseq:acct-7:buf NX 1 "1:tx-1"
# run the release script from redisstreams.go with KEYS reseq:acct-7:next reseq:acct-7:buf
# -> 1:tx-1, 2:tx-2, 3:tx-3 ; GET reseq:acct-7:next -> 4
  1. Laravel batch as Splitter + Aggregator (expected, not run):
bash
php artisan make:queue-batches-table && php artisan migrate
php artisan tinker --execute='(new App\Actions\ShipOrder)(App\Models\Order::first());'
php artisan queue:work --queue=shipments --stop-when-empty
# 3 x ProcessShipment ... DONE ; then-callback: orders.status = shipped

Common misconceptions ​

BeliefReality
"The Aggregator publishes when the counter reaches N."It publishes when N distinct parts are stored, decided under a lock, exactly once; a counter per delivery double-counts redeliveries
"An in-memory Aggregator is fine, the broker redelivers."Parts were acked when stored in memory; after a restart they are gone and the aggregate never completes
"No timeout needed, every part eventually arrives."One absent or late part can hold the entire aggregate open. Every wait needs a deadline and a policy
"A partial result is just a smaller result."It must say complete=false and list what is missing, or consumers treat it as complete
"Kafka keeps order, so no Resequencer ever."Only within a partition; parallel routes, retries and multi-consumer Redis groups reorder
"A Resequencer can wait forever for a hole."Bound it by capacity and gap timeout, and report what it skipped
"errgroup.WithContext is the Scatter-Gather primitive."It cancels everyone on the first error; use a plain Group, a timeout context and per-recipient errors
"Routing Slip and Process Manager are interchangeable."A slip is linear and fixed at the start; branching, joining or parallel steps need a Process Manager
"A Process Manager is a Saga."A Process Manager routes; a Saga compensates. An orchestrated saga is usually built as a process manager, not the other way round
"Bus::batch has a timeout."It is count-based Wait for All; add a scheduled timeout and cancel() yourself
"A Recipient List is fan-out."Fan-out is decided by subscribers; a Recipient List is computed per message by the sender's router
"The EIP Message Broker means RabbitMQ."It is the hub-and-spoke architecture pattern; RabbitMQ is one tool to build it
"Read replicas can serve the completeness check."A lagging replica makes aggregates look incomplete; decide on the primary

Cheat sheet ​

TopicRemember
Aggregator design itemsCorrelation, completeness condition, aggregation algorithm, timeout policy, state store
Split headerscorrelation-id, sequence-number (1-based), sequence-size, deterministic message-id, traceparent
Dedup inside statePK (correlation id, seq) + ON CONFLICT DO NOTHING
Exactly-once closeSELECT ... FOR UPDATE, check status = 'open', write outbox, update status, commit
SweeperEvery instance; FOR UPDATE SKIP LOCKED; partial or failed by policy
Completeness strategiesWait for All, Time Out, First Best, Time Out with Override, External Event
Resequencer boundsCapacity + maximum forward gap (MaxGap) + gap timeout; drop seq < next; report skips
Scatter-Gather in Goerrgroup.Group (not WithContext) + context.WithTimeout + SetLimit
Scatter-Gather in LaravelHttp::pool + as() + timeout(); ConnectionException per entry
Laravel Splitter + AggregatorBus::batch, then / catch / finally, allowFailures, job_batches
Laravel Routing SlipBus::chain, catch, prependToChain / appendToChain
RabbitMQHeaders exchange x-match = filter; CC/BCC = recipient list; no state
KafkaKey = correlation id; Streams flatMap, aggregate, windowedBy + grace + suppress
Redis StreamsXREADGROUP/XACK for parts; sorted set + Lua for resequencing
Process Manager vs SagaRouting hub with state vs compensating transactions

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 — Name the three design items Hohpe & Woolf list for an Aggregator and the two you must add in production. Good to know ​

Answer

Answer: Correlation, completeness condition, aggregation algorithm. In production add where the state is persisted (and how duplicates are rejected) and what happens at the timeout (emit partial or fail).

2 — Why must the Splitter derive part ids from the element instead of generating random UUIDs? Important ​

Answer

Answer: If the Splitter crashes after emitting some parts and the composite message is redelivered, it emits all parts again. Deterministic ids (42/s1) make the second copies recognisable as duplicates; random ids make them new parts.

3 — Two aggregator instances process the last two parts of order 42 at the same moment. What prevents two OrderShipped events? Important ​

Answer

Answer: Closing happens in one transaction that locks the aggregate row (FOR UPDATE), checks status = 'open', writes the outbox row and sets the status. The second transaction waits for the lock, then sees the status is no longer open and does nothing.

4 — A part arrives after the aggregate timed out and was published as failed. What should happen? Important ​

Answer

Answer: Store nothing, acknowledge the message and count it as late. Re-opening would break "one result per aggregate"; if late parts matter, route them to a reconciliation channel.

5 — Why is errgroup.WithContext a poor fit for Scatter-Gather? Important ​

Answer

Answer: Its derived context is cancelled when the first function returns a non-nil error, so one failing recipient cancels all other in-flight requests. Scatter-Gather wants independent recipients bounded by a deadline.

6 — When does a Resequencer give up on a missing sequence number, and what must it do when it does? Important ​

Answer

Answer: When the gap timeout expires (or the buffer hits capacity and you choose to skip rather than apply backpressure). It must release the buffered run and report the skipped numbers (metric, log, DLQ or reconciliation).

7 — Which RabbitMQ feature implements a Recipient List without N publishes, and what does BCC add? Good to know ​

Answer

Answer: Sender-selected distribution: the CC and BCC headers carry extra routing keys. BCC is removed from the message before delivery, so recipients do not see each other.

8 — Why is the correlation id also the Kafka record key in the shipment example? Important ​

Answer

Answer: A stable partition mapping places related records in one partition with one active group consumer. This preserves append order, not business sequence after parallel processing. Rebalances still require recoverable state and ownership handoff; external effects require deduplication.

9 — What makes Laravel's Bus::chain a Routing Slip, and what does it lack compared to a Process Manager? Important ​

Answer

Answer: The remaining jobs are serialized into the running job ($chained) and the next is dispatched after success: the itinerary travels with the message. It cannot branch on results (beyond prepend/append), run steps in parallel or wait for external events with deadlines.

10 — In the fulfilment example, which features make it a Process Manager, and which make it a Saga too? Must-know ​

Answer

Answer: Process Manager: central persisted state, the parallel payment/stock join, the fraud branch to manual review, and orchestrating a Splitter and an Aggregator. Saga: the stock.release and payment.void compensations on cancellation.

Glossary ​

TermMeaning
Message FilterRouter with one output that discards non-matching messages
Selective ConsumerEndpoint-side filtering, as opposed to a filter in the messaging system
Content-Based RouterRoutes each message to one channel by content (Routing Topologies)
Dynamic RouterRouter whose rules are registered by participants over a control channel
Control channelSeparate channel carrying configuration messages, not business data
Recipient ListRouter that computes recipients per message and sends a copy to each
Sender-selected distributionRabbitMQ feature routing one message by its routing key plus CC/BCC header keys
SplitterTurns one composite message into one message per element
AggregatorStateful filter that combines related messages into one
Correlation IdentifierValue tying related messages (parts, replies) to one group
Completeness conditionRule deciding when an aggregate is ready to publish
Aggregation algorithm / strategyHow parts become the result (merge, best-of, sum)
Wait for All / Time Out / First Best / Time Out with Override / External EventThe EIP completeness strategies
Partial aggregateResult published at timeout with fewer parts, flagged incomplete
Late partPart arriving after its aggregate closed
SweeperPeriodic job closing expired aggregates
ResequencerStateful filter that reorders messages by sequence number
Gap timeoutMaximum time a Resequencer waits for a missing sequence number
Batch vs stream resequencingApache Camel's modes: sort a collected batch, or release on gap detection
Composed Message ProcessorSplitter + router + Aggregator for per-item processing
Scatter-GatherBroadcast a request, aggregate the replies into one
AuctionScatter-Gather over pub-sub where the number of replies is unknown
Routing SlipItinerary attached to the message; each step forwards to the next
Message HistoryRecord of the steps a message passed (our slip's done list)
Process ManagerCentral unit keeping per-instance state and choosing the next step
Trigger messageMessage that creates a Process Manager instance
Hub-and-spokeTopology where all traffic passes through one central component
Message Broker (EIP)Architectural hub that routes between many applications
SagaSequence of local transactions with compensations (Saga Pattern)
CompensationBusiness action that semantically undoes an earlier step
OutboxTable written in the same transaction as state, relayed to the broker
Idempotent receiverConsumer that handles duplicates without side effects
Headers exchange / x-matchRabbitMQ exchange matching on headers; all, any, all-with-x, any-with-x
Alternate exchangeRabbitMQ exchange receiving messages no binding matched
flatMapKafka Streams operator turning one record into zero or more
aggregate / KGroupedStream / KTableKafka Streams stateful aggregation by key and its table result
Grace period / suppressKafka Streams bound on lateness / emit only the final window result
Foreign-key joinKafka Streams KTable-KTable join on a field other than the key
Filter SMTKafka Connect single message transform that drops records (KIP-585)
Consumer group (Redis)XGROUP/XREADGROUP/XACK delivery with a pending entries list
Sorted setRedis type ordering unique members by score; our resequencer buffer
Bus::batch / then / catch / finally / allowFailuresLaravel batching API and callbacks
job_batchesLaravel table holding batch state and counters
Bus::chain / prependToChain / appendToChainLaravel chaining API and runtime slip edits
Http::poolLaravel concurrent HTTP requests, an in-process scatter
errgroup / SetLimitGo package for goroutine groups with error propagation / concurrency cap
FOR UPDATE SKIP LOCKEDPostgreSQL row lock that skips rows locked by others
traceparentW3C trace-context header carried through every part

References ​

Built by Morteza Negahi