Scatter-Gather in Mule: checking price, stock and fraud for the order in parallel
- 10 min read
On this page
Code
Before accepting an order, three services need to weigh in: pricing calculates the total, stock says whether all the items are available and fraud gives the customer a risk score. The three questions are independent, and the decision needs all three answers. Sending one message to several recipients and joining the responses into one is the Scatter-Gather’s problem. In Mule 4, the component has the same name as the pattern.
The problem
Calling the three services in sequence adds the three response times to the customer’s wait. Calling them in parallel requires something to fire the three calls, wait for all three to finish and combine the responses into a decision: REJECTED if stock is short, REVIEW if the customer is high risk, ACCEPTED otherwise. And that something has to know what to do when the fraud service is down and the other two have answered.
The pattern in the book
The book asks how to maintain the overall flow of a message when it has to be sent to several recipients, each of which may reply. The solution is a Scatter-Gather that broadcasts the message to several recipients and re-aggregates the responses into a single message (Scatter-Gather).
The book builds the Scatter-Gather from two other patterns. The way out can go two ways: by distribution, with a Recipient List, where the Scatter-Gather controls the list of recipients but has to know each one’s channel; or by auction, with a publish-subscribe channel, where a single channel is enough but control over who receives is lost. The way back is always an Aggregator, which collects the responses and distills them into a single response (Scatter-Gather). Each of these patterns has its own page in this series; here they appear together because the book combines them.
The diagram redraws the book’s sketch (CC BY 4.0) in the order scenario, in the distribution variant:
In Mule
Mule’s Scatter-Gather receives an event, sends a reference to it to each route, runs the routes in parallel, each on its own thread, and moves on only when all of them finish: the next event combines the events returned by each route (Scatter-Gather Router). The book’s two halves are in the same scope; Mule joined them, not the book. Two differences matter:
- The routes are fixed in the XML. The book’s own site, when citing the Mule component, notes that it configures a predefined number of paths, so it does not broadcast to an unknown number of recipients, and that knowing all the recipients makes the Aggregator’s “Wait for All” completeness natural (Scatter-Gather). When the list changes with each message, the way out is a Recipient List with For Each.
- The aggregation is fixed. The result is an object with one key per route,
{0: messageFromRoute0, 1: messageFromRoute1, …}, each holding the route’s whole message, payload and attributes (Scatter-Gather Router). Combining the responses into a decision is left to a Transform after the scope.
When the responses arrive separately, with no scope that fired them together, the way back is the Aggregator of the Aggregators module.
In the MuleSoft documentation
The documentation page Enterprise Integration Patterns Using Mule maps the Scatter-Gather to the Scatter Gather Router, the same component this page uses.
The example
Each route calls a simulated service in the same application, with the whole order:
<scatter-gather doc:name="Run Pricing Stock And Fraud Checks" timeout="${eip.scatterGather.timeoutMillis}" maxConcurrency="3">
<route>
<http:request doc:name="Call Pricing Service" config-ref="eip-self-http-request-config" method="POST" path="/eip/services/pricing">
<http:body><![CDATA[#[output application/json --- vars.vOrder]]]></http:body>
</http:request>
</route>
<route>
<http:request doc:name="Call Stock Service" config-ref="eip-self-http-request-config" method="POST" path="/eip/services/stock">
<http:body><![CDATA[#[output application/json --- vars.vOrder]]]></http:body>
</http:request>
</route>
<route>
<http:request doc:name="Call Fraud Service" config-ref="eip-self-http-request-config" method="POST" path="/eip/services/fraud">
<http:body><![CDATA[#[output application/json --- vars.vOrder]]]></http:body>
</http:request>
</route>
</scatter-gather>
In the repository: src/main/mule/eip/scatter-gather/scatter-gather.xml
The timeout comes from eip.scatterGather.timeoutMillis (10000, in config/app.yaml). The following Transform reads each response by the route’s position and decides:
var pricing = payload["0"].payload
var stock = payload["1"].payload
var fraud = payload["2"].payload
---
{
orderId: vars.vOrder.orderId,
decision: if (not stock.available) "REJECTED" else if (fraud.risk == "HIGH_RISK") "REVIEW" else "ACCEPTED",
total: pricing.total,
stock: { available: stock.available, unavailableSkus: stock.unavailableSkus },
fraud: { score: fraud.score, risk: fraud.risk }
}
The services are in scatter-gather-services.xml, with synthetic data: stock has zero units of SKU-POSTER, and fraud gives a score of 80 (HIGH_RISK) to customers whose id starts with CUS-NEW.
When a route fails. If a route fails, the Scatter-Gather waits for the others to finish and then throws MULE:COMPOSITE_ROUTING; the flow does not continue after the scope and goes to error handling. The error carries the events of the routes that succeeded, along with the errors of the ones that failed (Scatter-Gather Router). The book’s site describes the same behavior in the Mule component: the route’s error rises to the Scatter-Gather, which signals the error and passes on the results the routes managed to deliver (Scatter-Gather). The example uses this to answer 503 with what it already knows, instead of an empty 500:
var checkNames = { "0": "pricing", "1": "stock", "2": "fraud" }
var results = error.errorMessage.payload.results default {}
var failures = error.errorMessage.payload.failures default {}
---
{
orderId: vars.vOrder.orderId,
decision: "INCOMPLETE",
completedChecks: results mapObject ((message, route) -> { (checkNames[route as String]): message.payload }),
failedChecks: failures mapObject ((failure, route) -> {
(checkNames[route as String]): {
// Only the error type: the description can carry internal details (the requester's URL, for one),
// so it is logged above and never sent to the caller.
errorType: failure.errorType.namespace ++ ":" ++ failure.errorType.identifier
}
})
}
The 503 is the example’s choice: the decision to accept the order cannot be made without all three responses. The Recipient List makes a different choice, explained on its page.
Caveats
- Partial responses are not lost, but they are in the error. A Stack Overflow question starts from an interview in which the candidate answered that, if a route fails, the Scatter-Gather gives no output at all, and that to make use of the successful routes you needed a Try with
on-error-continue(Error Handling in Scatter-Gather (Mule 4)). The documentation shows both paths: a Try withon-error-continueinside the route makes the route finish successfully and the scope carry on; without it,MULE:COMPOSITE_ROUTINGbringsresultsandfailuresby route key (Scatter-Gather Router). The example uses the second, because the decision needs to know the fraud check did not happen. - The
timeoutis in milliseconds. A MuleSoft knowledge base article covers an application that loggedTimeout while processing route/part: '0'and could return 500 to the client: thetimeoutwas set to5, and the value is in milliseconds. The same article warns that, withmaxConcurrency="1", the routes run in sequence and the timeout applies per route (Timeout while processing Scatter-Gather). A route that exceeds the deadline throwsMULE:TIMEOUT, handled like any other route error insideMULE:COMPOSITE_ROUTING(Scatter-Gather Router). The example’s suite does not exercise the timeout. - Streams that cannot be repeated. The Scatter-Gather works with repeatable streams and does not process non-repeatable streams, which can be read only once (Scatter-Gather Router). On the MuleSoft forum, a Mule 3 case shows the symptom: the HTTP request body, a stream, was consumed by one route and missing in the other, with the error
Cannot copy message with a stream payload(Scatter-gather issue “Cannot copy message with a stream payload”). In Mule 4 streams are repeatable by default, and the case comes back only when a component before the scope uses thenon-repeatable-streamstrategy. The example stores the order invars.vOrderas a Java object before the scope, and each route builds its own body from it. - Variables set in more than one route become a list. Every route starts with the same variables; a variable changed in one route keeps only that route’s value, but a variable changed in several routes becomes a list with the values of all of them (Scatter-Gather Router). Reading the responses from each route’s payload, as the example does, avoids that surprise.
- The route key is the position. The result uses
"0","1","2". Inserting a route in the middle changes the key of the ones after it; the example keeps the position-to-name translation in thecheckNamesof the error handling.
When not to use it
If the list of recipients changes with each message, fixed routes will not do: a Recipient List with For Each computes the list and, if there are responses to combine, a Transform after the scope does the aggregation. If nobody needs the responses, as in a notice to several systems, parallelism and aggregation are added complexity, and a publish-subscribe decouples better. And if the calls depend on one another (price depends on stock, say), they are not parallel: a sequence of calls is the right design.
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 scatter-gather-test-suite.xml suite pins the behavior down, observed on Mule 4.9.17 with MUnit 3.7.1:
| Test | What it proves |
|---|---|
sg-all-checks-pass-order-is-accepted |
The three checks pass and the order is accepted, with the total coming from the pricing service |
sg-out-of-stock-order-is-rejected |
Stock reports a missing item and the order is rejected |
sg-high-risk-customer-goes-to-review |
The fraud service gives HIGH_RISK to a new customer and the order goes to review |
sg-failed-route-raises-composite-routing-with-the-other-results |
With the fraud route failing, the others finish, MULE:COMPOSITE_ROUTING carries their results and the failure, and the endpoint answers 503 with the partial result |
sg-order-without-customer-returns-400 |
An order without customerId gets 400 and no check runs |
The failure test simulates the fraud service being down with a mock that returns HTTP:SERVICE_UNAVAILABLE and checks what is left:
<munit-tools:assert-that doc:name="503" expression="#[vars.httpStatus as Number]" is="#[MunitTools::equalTo(503)]" />
<munit-tools:assert-that doc:name="INCOMPLETE" expression="#[payload.decision]" is="#[MunitTools::equalTo('INCOMPLETE')]" />
<munit-tools:assert-that doc:name="Completed checks" expression="#[keysOf(payload.completedChecks) map ($ as String) orderBy $]" is="#[MunitTools::equalTo(['pricing', 'stock'])]" />
<munit-tools:assert-that doc:name="Pricing result kept" expression="#[payload.completedChecks.pricing.total]" is="#[MunitTools::equalTo(72.5)]" />
<munit-tools:assert-that doc:name="Stock result kept" expression="#[payload.completedChecks.stock.available]" is="#[MunitTools::equalTo(true)]" />
<munit-tools:assert-that doc:name="Failed checks" expression="#[keysOf(payload.failedChecks) map ($ as String)]" is="#[MunitTools::equalTo(['fraud'])]" />
<munit-tools:assert-that doc:name="Failure error type" expression="#[payload.failedChecks.fraud.errorType]" is="#[MunitTools::equalTo('HTTP:SERVICE_UNAVAILABLE')]" />
<munit-tools:assert-that doc:name="No error description in the response" expression="#[payload.failedChecks.fraud.description default null]" is="#[MunitTools::nullValue()]" />
In the repository: src/test/munit/eip/scatter-gather-test-suite.xml
To call the endpoint, run the application in Anypoint Studio (port 8081) and use the Scatter-Gather entry in requests.http:
### EIP scatter-gather — pricing, stock and fraud checks in parallel (a CUS-NEW... customer goes to REVIEW)
POST {{base}}/eip/orders/checks
Content-Type: application/json
{ "orderId": "ORD-3501", "customerId": "CUS-100", "items": [ { "sku": "SKU-BOOK", "quantity": 2, "unitPrice": 30 }, { "sku": "SKU-MUG", "quantity": 1, "unitPrice": 12.5 } ] }
In the repository: requests.http
Swap the customerId for one that starts with CUS-NEW to see REVIEW, or include a SKU-POSTER to see REJECTED. The other patterns are in the integration patterns catalog in Mule and, by component name, in the index by component.