← Wiki

Splitter in Mule: checking stock for each item in the order

  • 10 min read
On this page

Code

An order arrives with several items, and stock has to check each one. In the book, the pattern that breaks a message into parts is the Splitter; in Mule 4 there are two scopes, For Each and Parallel For Each, which split the same way but return different things.

The problem

In the series’ order scenario (order → payment → inventory → invoice), order ORD-3201 has three items: book (2), poster (1) and mug (3). The stock check is per item: the book may be in stock, the poster may be at zero. The whole order is a single message, but the work is done item by item, and the response has to say which items are available.

The pattern in the book

The book asks how to process a message that contains several elements, each of which may need different processing. Its own example is an order, where each item may be handled by a different inventory system. The answer is the Splitter: it breaks the composite message into a series of individual messages, each with the data for one item, and publishes one message per element, or per subset of elements, of the original message (Splitter).

One message in, one per item out

The diagram, redrawn from the official sketch (CC BY 4.0), answers one question: what comes out of the Splitter when an order with three items goes in?

The Order, with the list book, poster and mug, enters the Splitter, which divides it into three separate messages: Item book, Item poster and Item mug.

In the book, putting the results back together is another pattern, the Aggregator.

In Mule

Mule 4 splits with two scopes.

For Each splits the payload into elements and processes them one by one. Inside the scope, the payload is the element; the collection field says what to split when the collection is not the payload itself, and counter holds the position. For Each does not change the payload: after the scope, the payload is the same as on the way in. Variables created or changed inside it remain valid afterward (For Each Scope). It is only the Splitter.

Parallel For Each splits the collection and processes the parts at the same time, in separate routes, up to the limit set by maxConcurrency (by default, all routes in parallel). When they all finish, it aggregates the results in the same order they had before the split, and the flow continues. Variables changed inside the routes do not leave the scope: after it, the variables are the same as before (Parallel For Each Scope).

The same component is also the Aggregator

Parallel For Each implements two patterns from the book: it splits, like the Splitter, and it joins the results, like the Aggregator. It was Mule, not the book, that put the two in one scope. The Aggregator page covers the pattern for when the parts arrive separately, in different requests for example, and have to be grouped by order.

The example’s two flows

The diagram answers: what does each scope hand to the next processor?

Two groups, one per endpoint. In POST /eip/stock/availability/for-each: vItemResults = empty, For Each item, one at a time, sf-check-item-availability with vItemResults += result, and afterwards the payload is the original order, with the results in vars.vItemResults. In POST /eip/stock/availability/parallel-for-each: vOrderId = payload.orderId, Parallel For Each with maxConcurrency=4, sf-check-item-availability per route, and afterwards the payload is the list of messages, in item order, read with payload map $.payload.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule maps the Splitter to For Each, Parallel For Each and Batch. This page sticks to the first two because the example needs each item’s result in the same request: Batch was built to process data sets larger than memory asynchronously, and the Batch Job does not return the processed records to the components outside it (Batch Processing).

The example

Both endpoints receive { orderId, items: [ { sku, quantity } ] } and call the same sub-flow, sf-check-item-availability, once per item. The check is simulated, with fixed stock per SKU; the one for SKU-BOOK takes 300 ms on purpose, and each result carries checkedAt, the moment it finished.

For Each: the result goes into a variable

<set-variable doc:name="SET vItemResults" variableName="vItemResults" value="#[[]]" />
<foreach doc:name="For Each Order Item" collection="#[payload.items]">
	<flow-ref doc:name="Refer to sf-check-item-availability" name="sf-check-item-availability" />
	<set-variable doc:name="SET vItemResults" variableName="vItemResults" value="#[output application/java --- vars.vItemResults ++ [payload ++ { position: vars.counter }]]" />
	<set-variable doc:name="SET vLastCheckedSku" variableName="vLastCheckedSku" value="#[payload.sku]" />
</foreach>

In the repository: src/main/mule/eip/splitter/splitter.xml

Since For Each returns the original order, anyone who wants to keep each item’s result accumulates it in a variable, and vars.counter gives the position. After the scope, the response reads payload.orderId from the order that came back, and the items from vars.vItemResults. The variable vLastCheckedSku, created inside the scope, still exists outside it, with the last value.

Parallel For Each: the result is the payload

<!-- After the scope the payload is the list of results, so the orderId is kept here. -->
<set-variable doc:name="SET vOrderId" variableName="vOrderId" value="#[payload.orderId]" />
<parallel-foreach doc:name="Parallel For Each Order Item" collection="#[payload.items]" maxConcurrency="4">
	<flow-ref doc:name="Refer to sf-check-item-availability" name="sf-check-item-availability" />
	<!-- Set inside a route: not visible after the scope. -->
	<set-variable doc:name="SET vLastCheckedSku" variableName="vLastCheckedSku" value="#[payload.sku]" />
</parallel-foreach>

Here it works the other way around. After the scope, the payload is no longer the order: it is the list of messages each route produced, one per item. The orderId is saved in a variable beforehand, and the response pulls the results out with payload map $.payload. The variable vLastCheckedSku, created in a route, does not exist after the scope.

The suite proves both differences and the order. In the test splitter-parallel-for-each-returns-the-route-messages-in-input-order, the book finishes after the mug but comes back first, because the order is that of the items on input, not of arrival:

<munit-tools:assert-that doc:name="Items in input order" expression="#[payload.items map $.sku]" is="#[MunitTools::equalTo(['SKU-BOOK', 'SKU-POSTER', 'SKU-MUG'])]" />
<munit-tools:assert-that doc:name="Availability per item" expression="#[payload.items map $.available]" is="#[MunitTools::equalTo([true, false, true])]" />
<munit-tools:assert-that doc:name="Not all available" expression="#[payload.allAvailable]" is="#[MunitTools::equalTo(false)]" />
<munit-tools:assert-that doc:name="SKU-BOOK finished after SKU-MUG" expression="#[(payload.items[0].checkedAt as DateTime) &gt; (payload.items[2].checkedAt as DateTime)]" is="#[MunitTools::equalTo(true)]" />
<munit-tools:assert-that doc:name="Variable set inside a route is not visible after" expression="#[payload.lastCheckedSku]" is="#[MunitTools::nullValue()]" />

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

Caveats

A variable filled inside Parallel For Each comes out empty. A 2022 Stack Overflow question describes a flow that accumulated the results of a Parallel For Each in a variable initialized with [], and the variable was still empty after the scope. The answer points out that variable changes inside the scope are not visible outside it and that the result is already in the payload, in the list of messages, and shows payload map $.payload (Stack Overflow: Mule 4 - Can’t combine results from parallel for_each loop into a single json). It is the For Each pattern carried into the wrong scope; the test with vLastCheckedSku shows the same effect.

The order disappears from the payload after Parallel For Each. The test splitter-parallel-for-each-payload-is-a-list-of-messages looks at the payload right after the scope: it is three messages, with no orderId, and the first item’s result is in payload[0].payload. Whatever is needed from the original order goes into a variable before the scope.

A large collection in Parallel For Each. The scope holds the result of all routes in a list until it finishes, which can cause an out-of-memory error with many entries; for large payloads, the documentation points to Batch Processing (Parallel For Each Scope). Without maxConcurrency, all routes run at the same time; the example limits it to 4.

An item with an error. In For Each, an error on one element stops the processing of the collection and calls error handling; in Parallel For Each, the other routes finish first, and only then does error handling receive a composite routing error, MULE:COMPOSITE_ROUTING, with the results and the failures of each route (For Each Scope, Parallel For Each Scope). With For Each, the items after the one that failed are not checked; with Parallel For Each, all of them are, and the response has to decide what to do with a partial check. The example has no item that fails: the Scatter-Gather page shows how to handle MULE:COMPOSITE_ROUTING.

When not to use it

When the per-item work is only transforming data, with no calls, a DataWeave expression with map does the same with no scope at all, and returns the finished list. When the collection is large or comes from a file or a query with thousands of records, the case is Batch, not For Each. And, as a recommendation, Parallel For Each pays off when each item waits on I/O, such as an HTTP call or a query. The example shows why: only the book’s check waits (300 ms simulated), and it is the only one the parallelism overlaps with the others; with in-memory checks only, parallelism saves no time and still returns a list of messages instead of the results.

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 example runs with nothing external.

Test What it proves
splitter-for-each-checks-every-item-and-keeps-the-original-payload For Each checks every item in order; after the scope, the payload is the original order and the variable created inside is still visible
splitter-parallel-for-each-returns-the-route-messages-in-input-order Parallel For Each returns the results in item order, even with the book finishing after the mug; the variable created in a route is null afterward
splitter-parallel-for-each-payload-is-a-list-of-messages Right after Parallel For Each, the payload is one message per item, without the order’s orderId
splitter-order-without-items-returns-400 An order without items is refused with 400 and nothing is split

To compare through the API, run the application in Anypoint Studio (port 8081) and send the same order to both endpoints from requests.http, in VS Code (REST Client) or IntelliJ:

### EIP splitter — the same order with For Each and with Parallel For Each
POST {{base}}/eip/stock/availability/for-each
Content-Type: application/json

{ "orderId": "ORD-3201", "items": [ { "sku": "SKU-BOOK", "quantity": 2 }, { "sku": "SKU-POSTER", "quantity": 1 }, { "sku": "SKU-MUG", "quantity": 3 } ] }

In the repository: requests.http

The two responses carry the same items and allAvailable: false, because of the poster. What changes is the splitter field, the position that only For Each adds, and lastCheckedSku, filled in with For Each and null with Parallel For Each.

The other patterns, with the Mule component that implements each, are in the integration patterns catalog in Mule; the reverse path, from component to patterns, is in the index by component.

Code for this page