← Wiki

Aggregator in Mule: issuing the invoice when all the order items have arrived

  • 11 min read
On this page

Code

In the series’ order scenario, stock confirms the items of an order one by one, each confirmation in its own request, and the invoice can go out only when all the items have arrived. Combining separate messages that belong to the same whole is the Aggregator’s problem. In Mule 4, the group-based aggregator of the Aggregators module solves it, and this page uses it in an example that runs, with MUnit tests.

The problem

An order with three items becomes three messages: stock picks the book, then the mug, then the e-book, and confirms each one when it finishes. The confirmations arrive in different requests, in any order, mixed with those of other orders. Billing needs one invoice per order, with all the lines and the total. Something has to keep what has already arrived, recognize which order each item belongs to and notice the moment the order became complete. And if an item never arrives, something has to decide how long to wait.

The pattern in the book

The book asks how to combine the results of individual but related messages so they can be processed as a whole. The answer is a stateful filter, the Aggregator, which collects and stores messages until it has received a complete set of related messages and then publishes a single message distilled from them (Aggregator).

To design an Aggregator, the book asks for three definitions: correlation (which messages belong to the same set), the completeness condition (when to publish the result) and the aggregation algorithm (how to combine the messages into one). Among the completeness strategies, “Wait for All” waits for every response and, if they do not arrive within a deadline, the Aggregator has to treat the case as an error. The book warns that this strategy may also be the slowest and the most brittle: a message that is missing or late blocks the whole set. The Aggregator can know how many messages to expect, for example, because each one carries the total count (Aggregator). That is what the example does.

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

Three items arrive at the Aggregator: Item SKU-BOOK of order 42, Item SKU-MUG of order 43 and Item SKU-MUG of order 42. The Aggregator stores by order and, when order 42 is complete, delivers the Invoice of order 42, one message.

In Mule

The Aggregators module has three scopes: by size, by time and by group. An aggregator scope collects values until a condition is met and then runs a chain of components with the list of the aggregated elements as the payload (Aggregators Module 1.1). The group-based aggregator separates elements into groups by groupId and completes each group when it reaches groupSize (Aggregators Module Reference). The book’s three questions become three parameters:

Book Group-based aggregator In the example
Correlation groupId (default #[correlationId]) #[payload.orderId]
Completeness groupSize (default #[itemSequenceInfo.sequenceSize]), plus timeout #[payload.itemCount], 5 s
Aggregation the aggregation-complete route, which receives the list of items builds the invoice

The default for groupSize assumes the sequence information that For Each creates when it splits the message; items that arrive on their own do not carry it. The default for groupId, #[correlationId], also works across requests, as long as the sender propagates the same ID in all of them (the Correlation Identifier pattern); the example uses orderId, which already travels in the body.

Items that arrive in separate requests carry no sequence information. The reference says that, when it exists, the elements are sorted by sequenceNumber before release (Aggregators Module Reference). Without it, the invoice comes out in arrival order.

The aggregator lets the message through: whatever comes after it receives the same data that went in, and only the variables set in the aggregation routes leave the scope (Aggregators Module 1.1). A variable is how the endpoint knows whether the item closed the invoice.

POST /eip/invoices/items goes to the group-based-aggregator (groupId: orderId, groupSize: itemCount). For each item, it goes to incremental-aggregation, which counts the items received, and then to 202 WAITING. With the group complete, it goes to aggregation-complete, which calls sf-issue-invoice, and then to 201 with the invoice. On timeout, in a dashed line, it goes to the aggregator-listener, which saves the INCOMPLETE invoice. With GROUP_COMPLETED or GROUP_TIMED_OUT, it goes to 409 REJECTED.

The same job of joining results shows up in two other Mule components, and it was Mule that joined them, not the book. Parallel For Each processes the items of a collection and, when all routes finish, aggregates the results into a collection (Parallel For Each Scope): it is a Splitter with an Aggregator built in. Scatter-Gather sends the same message to several routes and combines the responses: it is the book’s Scatter-Gather, which is already a Recipient List plus an Aggregator. The Aggregators module is the case where the messages arrive separately, at different moments, and no scope saw them leave together.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule maps the Aggregator to the Aggregators module, the same one this page uses.

The example

The POST /eip/invoices/items endpoint receives one item at a time, with the order’s orderId and itemCount:

<aggregators:group-based-aggregator doc:name="Aggregate Items By orderId" name="invoice-items-by-order-aggregator"
	groupId="#[payload.orderId]" groupSize="#[payload.itemCount]"
	timeout="${eip.invoice.groupTimeoutSeconds}" timeoutUnit="SECONDS"
	evictionTime="${eip.invoice.groupEvictionMinutes}" evictionTimeUnit="MINUTES"
	objectStore="eip-invoice-aggregation-store">
	<aggregators:content><![CDATA[#[output application/java --- { sku: payload.sku, quantity: payload.quantity, unitPrice: payload.unitPrice, itemCount: payload.itemCount }]]]></aggregators:content>
	<aggregators:incremental-aggregation>
		<set-variable doc:name="SET vReceivedItems" variableName="vReceivedItems" value="#[sizeOf(payload)]" />
	</aggregators:incremental-aggregation>
	<aggregators:aggregation-complete>
		<flow-ref doc:name="Refer to sf-issue-invoice" name="sf-issue-invoice" />
	</aggregators:aggregation-complete>
</aggregators:group-based-aggregator>

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

The content uses output application/java because everything the aggregator stores goes into an object store and has to be serializable (Aggregators Module Reference); storing the request’s JSON stream would not work. The aggregation-complete route receives the list of items and builds the invoice:

<ee:set-variable variableName="vInvoice"><![CDATA[%dw 2.0
output application/java
var lines = payload map { sku: $.sku, quantity: $.quantity, unitPrice: $.unitPrice, lineTotal: $.quantity * $.unitPrice }
---
{
	invoiceId: "INV-" ++ uuid(),
	orderId: vars.vOrderId,
	status: "ISSUED",
	lines: lines,
	total: sum(lines map $.lineTotal),
	issuedAt: now() as String
}]]></ee:set-variable>

After the scope, a Choice answers 201 with the invoice when vars.vInvoice exists and 202 (WAITING, with receivedItems and expectedItems) when the order is still waiting for items.

The order that never completes goes to a separate flow. With includeTimedOutGroups="true", the aggregator-listener also receives the groups released by the timeout, without marking them as complete (Aggregators Module Reference). In the example, these groups arrive with attributes.isAggregationComplete equal to false, and the flow stores the invoice as INCOMPLETE with the items that arrived:

<aggregators:aggregator-listener doc:name="On Group Released By invoice-items-by-order-aggregator" aggregatorName="invoice-items-by-order-aggregator" includeTimedOutGroups="true" />
<choice doc:name="Check Group Timed Out">
	<when expression="#[not attributes.isAggregationComplete]">
		<os:store doc:name="Store Incomplete Invoice" key="#[attributes.aggregationId]" objectStore="eip-invoices-store">

The listener runs in its own flow: it does not see the variables of the request that touched the group last, only the aggregated items and the attributes.

To see the pattern end to end, aggregator-client.xml plays the role of stock: it receives the whole order at POST /eip/invoices/orders, splits the items in a For Each and sends each one over HTTP to the aggregator, with the itemCount calculated from the order.

Caveats

  • Several workers on CloudHub. The module’s troubleshooting page says aggregators do not work with several workers and a persistent object store, because CloudHub has no cluster (Troubleshooting Aggregators Module). The consequence that follows from it: items of an order that land on different workers end up in different groups, and none of them completes. The example uses in-memory stores so each test starts clean, and the XML notes that, in production and always in a cluster, the aggregator needs a persistent, shared object store. According to the troubleshooting page, that combination works only where there is a cluster, which leaves out CloudHub with several workers.
  • The example’s timeout is for demonstration. Five seconds let the test watch the group expire. In production, the timeout has to cover the real interval between the first and the last item of the order; without a timeout, the default is to wait forever (-1) (Aggregators Module Reference).
  • A late item is rejected only until eviction. A completed or expired group is remembered for evictionTime (default: 180 seconds); in that interval, a new item for it throws AGGREGATORS:GROUP_COMPLETED or AGGREGATORS:GROUP_TIMED_OUT. After eviction, the same groupId creates a new group (Aggregators Module Reference). The example remembers the group for 60 minutes; after that, a late item would open a new order that never completes.
  • groupSize is taken from the first item. All messages of a group should have the same size; if they do not, only the first resolved size counts, and the module logs a warning (Aggregators Module Reference). A null itemCount throws AGGREGATORS:NO_GROUP_SIZE (Troubleshooting Aggregators Module); the example validates the field first and answers 400.
  • The aggregator does not remove duplicates. The same item sent twice counts twice toward itemCount, and the order closes without one of the items. When the sender may repeat the message, an Idempotent Receiver before the aggregator solves it.
  • Large payloads. The documentation does not recommend aggregators for large payloads: the state sits in the object store and is queried every second, which increases the store’s load and affects performance (Aggregators Module Reference). The example stores only four fields per item.

When not to use it

If the parts are born in the same flow, the module is added complexity. A MuleSoft knowledge base article builds the combination of For Each with Async and a group-based aggregator to call a flow in parallel for each element of a collection and respond after all the calls finish; the article itself notes that, from Mule 4.3.0, Parallel For Each replaces For Each with Async with the same result (Make a parallel async call in Mule 4 and aggregate the results). Parallel For Each returns the collection of results with no object store, no group timeout and no eviction (Splitter). The same goes for calling fixed systems in parallel and combining the responses: there, the way is Scatter-Gather. The Aggregators module pays off when the parts arrive from outside, in separate requests or messages.

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, with Aggregators module 1.1.5. MUnit runs on the Enterprise runtime, so Maven needs access to MuleSoft’s Enterprise repository (credentials in ~/.m2/settings.xml).

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

Test What it proves
agg-split-order-is-aggregated-back-into-one-invoice The client splits an order of three items; the items get 202, 202 and 201, and the invoice has the three lines and a total of 81.5
agg-interleaved-items-are-grouped-by-order-id Items of two orders arriving interleaved are grouped by orderId; each invoice has only its own lines
agg-item-after-the-invoice-is-rejected-with-409 An item for an order already invoiced throws AGGREGATORS:GROUP_COMPLETED (409) and does not change the invoice
agg-incomplete-order-times-out-and-is-recorded-incomplete The order missing its last item expires, the listener stores the invoice as INCOMPLETE and the late item gets 409 (GROUP_TIMED_OUT)
agg-item-without-item-count-returns-400 An item without itemCount does not say when the order completes and gets 400
agg-invoice-of-unknown-order-returns-404 GET /eip/invoices/{orderId} answers 404 for an order with no invoice
agg-client-order-without-items-returns-400 The client refuses an order without items and sends nothing to the aggregator

The timeout test waits for the group to expire (5 seconds, checked by the module once per second), so the suite takes about 9 seconds.

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

### EIP aggregator — the client splits the order and posts its items one by one; the last one gets the invoice
POST {{base}}/eip/invoices/orders
Content-Type: application/json

{ "orderId": "ORD-3301", "items": [ { "sku": "SKU-BOOK", "quantity": 2, "unitPrice": 30 }, { "sku": "SKU-MUG", "quantity": 1, "unitPrice": 12.5 } ] }

###
GET {{base}}/eip/invoices/ORD-3301

### One item of a two-item order: 202, and after 5 seconds the invoice is INCOMPLETE
POST {{base}}/eip/invoices/items
Content-Type: application/json

{ "orderId": "ORD-3302", "itemCount": 2, "sku": "SKU-BOOK", "quantity": 1, "unitPrice": 30 }

###
GET {{base}}/eip/invoices/ORD-3302

In the repository: requests.http

The third request shows the path of the incomplete order: the GET right after answers 404, and the same GET five seconds later returns the INCOMPLETE invoice. The other patterns, with the Mule component that implements each, are in the integration patterns catalog in Mule and, by component name, in the index by component.

Code for this page