← Wiki

Recipient List in Mule: notifying only the systems the order involves

  • 10 min read
On this page

Code

When a new order comes in, some systems need to know about it and others do not: billing always, stock only if there is a physical item, digital delivery only if there is a digital item, customs only if the physical item leaves the country. Sending the same message to a list of recipients computed from it is the Recipient List’s problem. Mule 4 has no component by that name; the pattern is built from a DataWeave expression that computes the list and a For Each that delivers to each recipient.

The problem

In the series scenario, order ORD-3401 goes to the United States with a printed book and an e-book. It has to reach billing, stock, digital delivery and customs. The next order, with only e-books, to Brazil, has to reach billing and digital delivery, and no one else. The list changes with every order. Sending to everyone and letting each system discard what is not its own forces every recipient to know everyone’s rules; writing a fixed path per combination of rules does not scale. And when stock is down, billing and customs still need to receive the order.

The pattern in the book

The book asks how to route a message to a dynamically specified list of recipients. The solution is to define a channel for each recipient and use a Recipient List that inspects the incoming message, determines the list of desired recipients and forwards the message to all the channels associated with them (Recipient List).

The book describes the logic in two parts, even though an implementation usually merges them: the first computes the list; the second walks the list and sends a copy of the message to each recipient. Like the Content-Based Router, the Recipient List generally does not change the content of the message (Recipient List). The difference from the Content-Based Router is the number of outputs: the router picks one destination; the Recipient List picks as many as needed.

The diagram redraws the book’s sketch (CC BY 4.0) in the order scenario:

Order ORD-3401, bound for the US, with a physical and a digital item, enters the Recipient List, which computes the list and delivers the message to four channels: the Billing channel, the Stock channel, the Digital delivery channel and the Customs channel.

In Mule

The book’s two parts become two components. The list is a value computed by a Transform; the delivery is a For Each over that list. For Each splits the collection into elements and processes them one by one with the components inside the scope, and does not change the payload: what comes out is what went in (For Each Scope). Each recipient’s address lives in configuration (eip.recipientList.paths.<recipient>), and the HTTP Request reads it by name. Because the list is data, a new rule or a new recipient changes the expression and the configuration, not the design of the flow.

For Each is also the book’s Splitter, and it was Mule that put the two roles in the same scope. Here it splits the list of recipients, not the order: the whole order goes unchanged to each one.

The POST /eip/orders/notifications endpoint passes to the Transform that computes vRecipients, and the For Each goes through each recipient inside a Try. On ok, the recipient is DELIVERED; on on-error-continue (dashed line), it is FAILED with the errorType. Both paths reach the response 200 deliveries with allDelivered.

Mule’s Scatter-Gather also sends one message to several destinations, but its routes are fixed in the XML and all of them always run (Scatter-Gather Router): there is no list computed per message. In the book, the Scatter-Gather is a Recipient List (or a publish-subscribe channel) followed by an Aggregator that joins the responses (Scatter-Gather). Mule joined the two halves in a single component; this page covers the first half on its own, for when nobody needs to combine responses.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Recipient List. The Scatter Gather Router it does map has the fixed routes described above, which is why this page builds the list with a Transform and delivers it with a For Each.

The example

The Transform computes the list from the order:

<ee:set-variable variableName="vRecipients"><![CDATA[%dw 2.0
output application/java
var physical = not isEmpty(vars.vOrder.items filter ($.'type' == "PHYSICAL"))
var digital = not isEmpty(vars.vOrder.items filter ($.'type' == "DIGITAL"))
var international = upper(vars.vOrder.country) != upper(p('eip.orders.homeCountry'))
---
["invoicing"]
	++ (if (physical) ["warehouse"] else [])
	++ (if (digital) ["digitalDelivery"] else [])
	++ (if (physical and international) ["customs"] else [])]]></ee:set-variable>

In the repository: src/main/mule/eip/recipient-list/recipient-list.xml

The home country is BR, in config/app.yaml. For Each walks the list and delivers the order to each recipient, each delivery inside its own Try:

<foreach doc:name="For Each Recipient" collection="#[vars.vRecipients]">
	<set-variable doc:name="SET vRecipient" variableName="vRecipient" value="#[payload]" />
	<try doc:name="Try Deliver To Recipient">
		<http:request doc:name="POST Order To Recipient" config-ref="eip-self-http-request-config" method="POST" path="#[p('eip.recipientList.paths.' ++ vars.vRecipient)]">
			<http:body><![CDATA[#[output application/json --- vars.vOrder]]]></http:body>
		</http:request>
		<set-variable doc:name="SET vDeliveries" variableName="vDeliveries" value="#[output application/java --- vars.vDeliveries ++ [{ recipient: vars.vRecipient, status: 'DELIVERED' }]]" />
		<error-handler>
			<on-error-continue doc:name="On Error Continue (recipient failed)" type="ANY" logException="false">
				...
				<set-variable doc:name="SET vDeliveries" variableName="vDeliveries" value="#[output application/java --- vars.vDeliveries ++ [{ recipient: vars.vRecipient, status: 'FAILED', errorType: error.errorType.namespace ++ ':' ++ error.errorType.identifier }]]" />
			</on-error-continue>
		</error-handler>
	</try>
</foreach>

vDeliveries works because, in For Each, a variable changed while processing one element stays visible in the next element and after the scope (For Each Scope). The response lists the recipients, the result of each delivery and allDelivered.

The recipients are simulated in the same application, in recipient-list-recipients.xml: one endpoint per recipient, which stores the order in an inbox queried by GET /eip/orders/{orderId}/notifications. To simulate a recipient that is down, stock answers 503 to any order whose orderId starts with ORD-WAREHOUSE-DOWN.

Why 200 with a partial failure. When a recipient fails, the endpoint answers 200 with allDelivered: false. Each notification stands on its own: the ones delivered are done, and the ones that failed show up in the response for a retry. Scatter-Gather makes a different choice, explained on its page.

Caveats

  • For Each stops at the first error. The documentation says that, if an element of the collection throws an exception, For Each stops processing the collection and calls error handling (For Each Scope). Without the Try, stock being down would prevent the digital delivery, which comes later in the list. The MuleSoft knowledge base has an article just for this, how to keep processing after an error inside a For Each; its solution, written with the Mule 3 term (exception strategy), is to put the content of the For Each in a private flow with its own error handling, which in Mule 4 is that flow’s error handler (How to continue processing after an error occurs inside a foreach). The example’s per-delivery Try has the same effect without an extra flow.
  • There is no way to retry only the one that failed. A retry of the request sends the order to all the recipients again. The recipients need to be idempotent: the simulated ones are, because each inbox entry is stored under the key <recipient>|<orderId> and a repeat overwrites it. A real recipient that is not idempotent needs an Idempotent Receiver in front of it.
  • on-error-continue with type="ANY" hides everything. The example’s Try records the error type of each failure (HTTP:SERVICE_UNAVAILABLE when the recipient answers 503) and logs it as WARN. Without that record, the response would say only that something failed.
  • Delivery in sequence. For Each delivers to one recipient after another; the total time is the sum of the calls. Parallel For Each would deliver to all of them at the same time; the Splitter page shows the difference between the two scopes.
  • The item with no type. An item that is neither PHYSICAL nor DIGITAL fits no rule. The example refuses it with 400 before computing the list, so that no order goes out with an incomplete list.

When not to use it

If every order always goes to the same recipients, the list is not dynamic and the pattern becomes ceremony: a fixed sequence of calls, or a publish-subscribe channel where each system subscribes to what interests it, solves it with less code. Publish-subscribe also takes away from the sender the knowledge of who receives, which in the Recipient List sits entirely in the expression. The Recipient List makes sense when the sender needs to control who receives, order by order. And when the recipients’ responses need to be combined into a decision, the right pattern is Scatter-Gather.

Running the example and the tests

git clone https://github.com/brunosouzas/mulesoft-patterns-examples.git
cd mulesoft-patterns-examples
mvn clean test

The project needs Java 17, Maven 3.9+ and the Mule 4.9 runtime. MUnit runs on the Enterprise runtime, so Maven needs access to MuleSoft’s Enterprise repository (credentials in ~/.m2/settings.xml).

The recipient-list-test-suite.xml suite pins the behavior down, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
rl-domestic-physical-order-goes-to-invoicing-and-warehouse A domestic order with only physical items goes to billing and stock, and no one else
rl-international-mixed-order-goes-to-every-recipient An international order with physical and digital items goes to all four recipients
rl-international-digital-order-needs-no-customs An international order with only digital items goes to billing and digital delivery, with no stock and no customs
rl-failed-recipient-does-not-stop-the-others With stock answering 503, its delivery is FAILED with HTTP:SERVICE_UNAVAILABLE, the digital delivery after it is made, and allDelivered is false
rl-unknown-recipient-returns-404 The simulated endpoint answers 404 to a recipient that is not in the configuration
rl-recipient-rejects-order-without-id A known recipient answers 400 to a body without orderId
rl-item-without-type-returns-400 An item without a valid type cannot be routed and the order gets 400

The failure test checks the three results in list order and the three calls to the HTTP Request:

<munit-tools:assert-that doc:name="Statuses" expression="#[vars.response.deliveries map $.status]" is="#[MunitTools::equalTo(['DELIVERED', 'FAILED', 'DELIVERED'])]" />
<munit-tools:assert-that doc:name="Failure recorded with its error type" expression="#[vars.response.deliveries[1].errorType]" is="#[MunitTools::equalTo('HTTP:SERVICE_UNAVAILABLE')]" />
<munit-tools:assert-that doc:name="Failed recipient named" expression="#[vars.response.deliveries[1].recipient]" is="#[MunitTools::equalTo('warehouse')]" />
<munit-tools:assert-that doc:name="Not all delivered" expression="#[vars.response.allDelivered]" is="#[MunitTools::equalTo(false)]" />
<munit-tools:assert-that doc:name="Received by the others only" expression="#[payload.receivedBy]" is="#[MunitTools::equalTo(['digitalDelivery', 'invoicing'])]" />

In the repository: src/test/munit/eip/recipient-list-test-suite.xml

To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Recipient List entries in requests.http:

### EIP recipient list — an international order with physical and digital items goes to all four recipients
POST {{base}}/eip/orders/notifications
Content-Type: application/json

{ "orderId": "ORD-3401", "country": "US", "items": [ { "sku": "SKU-BOOK", "quantity": 1, "unitPrice": 30, "type": "PHYSICAL" }, { "sku": "SKU-EBOOK", "quantity": 1, "unitPrice": 9, "type": "DIGITAL" } ] }

###
GET {{base}}/eip/orders/ORD-3401/notifications

In the repository: requests.http

Swap the orderId for one that starts with ORD-WAREHOUSE-DOWN to see the partial failure, or the country for BR to see customs drop off the list. The other patterns are in the integration patterns catalog in Mule and, by component name, in the index by component.

Code for this page