Message Filter in Mule: reserving stock only for paid orders
- 10 min read
On this page
- The problem
- The pattern in the book
- One output, and the discard
- In Mule
- The filter flow
- The same component is the Content-Based Router
- In the MuleSoft documentation
- The example
- Before: the protected work after the Choice
- After: the work inside the route that lets the order through
- Caveats
- When not to use it
- Running the example and the tests
Code
Inventory receives events for every order, but it should reserve items only for the ones that were paid. An order with a declined payment has to be discarded before the reservation. In the book that is a Message Filter; Mule 4 no longer has a filter component, and the work falls to Choice or to the Validation module.
The problem
In the series’ order scenario (order → payment → inventory → invoice), inventory is notified of each order with { orderId, status, items }. The status can be PAID, PAYMENT_DECLINED (payment refused) or PAYMENT_REVIEW (payment still under review). Only PAID matters to inventory. Reserving items for an order nobody paid ties up another customer’s stock, and the error does not show up for the sender of the event.
The pattern in the book
The book asks how a component avoids receiving messages it is not interested in. The answer is a special kind of Message Router, the Message Filter, which removes unwanted messages from a channel according to a set of criteria. It has a single output channel: the message that meets the criterion continues through it; the one that does not is discarded (Message Filter).
One output, and the discard
The diagram, redrawn from the official sketch (CC BY 4.0), answers: what happens to the message that does not meet the criterion?
The difference from the Content-Based Router is in the output: the router chooses one of several destinations; the filter has a single destination, and the message that does not qualify goes nowhere.
In Mule
Mule 3 had filters, and when a filter blocked the message the flow ended there, silently. Mule 4 no longer uses filters: the migration documentation says to use the Validation module, which makes the flow fail when the condition is not met, with a VALIDATION error that the flow’s error handling has to account for to build the response (Migrating Filters).
So there are two ways to filter in Mule 4:
- Validation with an error. A validator from the Validation module, such as
validation:is-true, or araise-error. The flow stops at the filter’s point. The migration documentation’s example handles the error withon-error-propagateand answers 400 (Migrating Filters); when the discard is not an error for the business, as on this page, the choice is anon-error-continuethat answers 200. The cost is using an error for a normal outcome: every discarded message goes through the error handling. - Choice. One route for the message that passes, and the discarded message on the other route or on none. Choice runs the first route whose expression is true (Choice Router), and after that the flow continues at the next processor. This is what the example uses, and it is where the trap lives.
The filter flow
The diagram answers: where does the reservation sit, so that the discarded order does not reach it?
The same component is the Content-Based Router
Choice is also the book’s Content-Based Router, with one route per destination. It was Mule, not the book, that put the two patterns in one component. In the book, the filter is a router with a single output, and the discard is part of the pattern. In Choice there is no discard: there is a route that ends, and the flow carries on.
In the MuleSoft documentation
The page Enterprise Integration Patterns Using Mule in the documentation maps the Message Filter to the Validation module, the first of the two ways above. The example uses Choice because the unpaid order is a normal business outcome, and with a validator every discard would go through the error handling.
The example
The repository has two versions of the same endpoint, one with the bug and one with the fix. Both validate the event, apply the filter and answer { orderId, result }. The reservation is simulated, and each one becomes an entry in a statement that GET /eip/stock/{orderId}/reservations counts.
Before: the protected work after the Choice
<choice doc:name="Discard Orders Not Paid">
<when expression="#[payload.status != 'PAID']">
<logger doc:name="WARN: Log discarded order" level="WARN" message="#['Discarded order ' ++ payload.orderId ++ ' with status ' ++ payload.status ++ ', correlationId=' ++ correlationId]" />
<set-variable doc:name="SET vFilterResult" variableName="vFilterResult" value="DISCARDED" />
</when>
<otherwise>
<set-variable doc:name="SET vFilterResult" variableName="vFilterResult" value="RESERVED" />
</otherwise>
</choice>
<!-- The defect: this runs after the Choice for every order, including the ones it "discarded". -->
<flow-ref doc:name="Refer to sf-reserve-stock-for-order" name="sf-reserve-stock-for-order" />
In the repository: src/main/mule/eip/message-filter/message-filter-before.xml
Choice sees that the order is not paid, logs the discard and marks the result DISCARDED. When the route ends, the flow moves on to the reservation, which runs for every order. The sender of the event gets DISCARDED, and the warehouse holds stock for an order nobody paid. The test filter-before-unpaid-order-is-reported-discarded-but-stock-is-reserved sends a PAYMENT_DECLINED order and checks both things:
<munit-tools:assert-that doc:name="Caller is told DISCARDED" expression="#[vars.response.result]" is="#[MunitTools::equalTo('DISCARDED')]" />
<munit-tools:assert-that doc:name="Reservations: 1" expression="#[payload.reservations]" is="#[MunitTools::equalTo(1)]" />
In the repository: src/test/munit/eip/message-filter-test-suite.xml
For a paid order the defect does not show: the test filter-before-paid-order-is-reserved shows a single reservation, as expected. That is why this bug passes a test that uses only the happy path.
After: the work inside the route that lets the order through
<choice doc:name="Pass Only Paid Orders">
<when expression="#[payload.status == 'PAID']">
<flow-ref doc:name="Refer to sf-reserve-stock-for-order" name="sf-reserve-stock-for-order" />
<set-variable doc:name="SET vFilterResult" variableName="vFilterResult" value="RESERVED" />
</when>
<otherwise>
<logger doc:name="WARN: Log discarded order" level="WARN" message="#['Discarded order ' ++ payload.orderId ++ ' with status ' ++ payload.status ++ ', correlationId=' ++ correlationId]" />
<set-variable doc:name="SET vFilterResult" variableName="vFilterResult" value="DISCARDED" />
</otherwise>
</choice>
In the repository: src/main/mule/eip/message-filter/message-filter-after.xml
The reservation moved inside the paid order’s route, and after the Choice only the response assembly is left, which applies to both cases. The response is 200 in both: for the sender of the event, a discarded order is a normal outcome, not an error. With validation by error, the same rule would be written with validation:is-true and an on-error-continue that answers DISCARDED.
Caveats
Choice does not end the flow. That is the defect in the “before”, and it has shown up in public questions since Mule 3. In 2013, on Stack Overflow, a filter inside a route of a Choice, inside a For Each, blocked the message and processing continued after the end of the Choice, with a slightly different payload; the accepted answer attributes this to the For Each, which restores the original message after it runs, and suggests a filter that throws an error to stop execution (Stack Overflow: mule filter not stopping flow processing, picks up after choice end tag). On the MuleSoft forum, in 2015, someone asks how to stop the flow when the Choice condition fails, without throwing an error; one of the answers suggests putting the components that depend on the condition in another flow, called by flow-ref inside the route, and leaving only a log on the other one (MuleSoft forum: How to stop a mule flow from processing?). That is the fix in the “after”. Both cases are from Mule 3, but in Mule 4, with no filter component, the effect is the same: every processor after the Choice runs for any message, discarded or not. The rule: nothing that depends on the filter goes after the Choice.
A migrated Mule 3 filter becomes an error. Anyone who migrates a filter to the Validation module trades the silent end for the VALIDATION error. Without handling that error, the caller gets a failure instead of a discard; the documentation’s example stores a variable in the error handling and answers 400 with it (Migrating Filters). If the discard is normal for the business, as here, the handling has to say so in the response.
The discard has to leave a trace. In the book, the discarded message simply disappears (Message Filter). In an order system, an order that vanishes without a record becomes a support ticket with no answer. The example logs each discard at WARN with the orderId, the status and the correlationId, and returns DISCARDED to the sender.
Validate before filtering. An event with no items is not an unpaid order: it is a malformed event. The example refuses it with 400 before the filter (filter-request-without-items-returns-400), so that a sender’s mistake is not counted as a discard.
When not to use it
When the sender can send only what matters, filtering at the receiver is extra work: a queue or a topic just for paid orders solves it at the source. When the message that does not qualify has to go to another destination, and not vanish, the pattern is the Content-Based Router. And when the whole message qualifies but part of it does not, the case is a transformation, not a filter: a Transform with DataWeave’s filter removes the items without discarding the order.
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 the MuleSoft Enterprise repository (credentials in ~/.m2/settings.xml). The example runs without anything external; the reservations statement lives in an in-memory object store.
| Test | What it proves |
|---|---|
filter-before-unpaid-order-is-reported-discarded-but-stock-is-reserved |
Before: the declined order gets DISCARDED and still has a reservation |
filter-before-paid-order-is-reserved |
Before: the paid order has a reservation; the defect does not show for it |
filter-after-unpaid-order-is-discarded-and-nothing-is-reserved |
After: the declined order is discarded inside the Choice and has no reservation |
filter-after-order-in-review-is-discarded |
After: the PAYMENT_REVIEW order does not pass either |
filter-after-paid-order-is-reserved |
After: the paid order passes and has one reservation |
filter-request-without-items-returns-400 |
An event with no items is refused with 400 before the filter |
To see it through the API, run the application in Anypoint Studio (port 8081) and use requests.http in VS Code (REST Client) or IntelliJ: send the declined order to the “before” endpoint and query its reservations, then do the same with the “after” endpoint.
### EIP message filter — a declined order: "before" answers DISCARDED but reserves stock anyway
POST {{base}}/eip/stock/before/reservations
Content-Type: application/json
{ "orderId": "ORD-3101", "status": "PAYMENT_DECLINED", "items": [ { "sku": "SKU-BOOK", "quantity": 2 } ] }
###
GET {{base}}/eip/stock/ORD-3101/reservations
In the repository: requests.http
The GET shows reservations: 1 for ORD-3101; repeating with the “after” endpoint and ORD-3102, it shows zero.
The other patterns, with the Mule component that implements each one, are in the catalog of integration patterns in Mule; the reverse path, from the component to the patterns, is in the index by component.