← Wiki

Content-Based Router in Mule: sending each order to its handler

  • 9 min read
On this page

Code

A new order can go to one of three places: manual review, when the amount is high; international fulfillment, when the destination is another country; or domestic fulfillment. The content of the order decides, and in Mule 4 the component that applies the decision is Choice.

The problem

In the series’ order scenario (order → payment → inventory → invoice), each incoming order needs different handling. An order of 5,000 is checked by a person before it continues. An order to Portugal needs a customs declaration. An order of 120 to Brazil goes straight through. That makes three destinations for a single input, and the sender does not know, and should not need to know, which one serves their order.

The pattern in the book

The book starts from a logical function, such as checking inventory, that is spread across several physical systems, each able to handle only some items. The pattern’s question is how to deal with that situation. The answer is a Content-Based Router: it examines the content of each message and routes it to the right recipient, on a different channel, according to the data the message carries. The criterion can be whether a field exists, the value of a field, and so on. The book warns that the routing function should be easy to maintain, because the router tends to be a frequent maintenance point, and that in more sophisticated scenarios it can turn into a configurable rules engine (Content-Based Router).

One input, one destination per message

The diagram, redrawn from the official sketch (CC BY 4.0), answers: where does each message that enters the router go?

The Order enters the Content-Based Router, which picks one of three paths by content: a high amount goes to Manual review, another country goes to International fulfillment and all the rest go to Domestic fulfillment.

Each message leaves by one path only. That is what sets the router apart from the Recipient List, which delivers the same message to several recipients.

In Mule

In Mule 4, the Content-Based Router is Choice. The documentation describes the component as a router that sends the message through the flow according to a set of DataWeave expressions that evaluate its content, each expression tied to a route. Only one route runs: the first whose expression is true; the following ones are not even evaluated. If none is true, the default route runs, the <otherwise> (Choice Router). The <otherwise> can be left out: the test cbr-without-otherwise-unmatched-order-comes-back-unchanged, below, runs a Choice without it.

In the book, each destination is a channel. In the example, each destination is a sub-flow called by flow-ref inside the route; in a distributed system, the route would publish to an Anypoint MQ queue. The pattern is the same: the decision lives in the router, and the destinations do not know about each other.

The routing flow

The diagram answers: which route does each order take, and in what order are the rules tested?

The POST /eip/orders/route endpoint passes to the decision Readable order?. If not, it answers 400: APP:BAD_REQUEST. If yes, it goes to the Choice: 1. amount >= 1000 goes to sf-route-order-to-review (MANUAL_REVIEW); 2. country != BR goes to sf-route-order-to-international-fulfilment (INTERNATIONAL_FULFILMENT); otherwise goes to sf-route-order-to-domestic-fulfilment (DOMESTIC_FULFILMENT).

The same component is the Message Filter

Choice also implements another pattern from the book, the Message Filter: a router with a single output that discards the message that does not qualify. It was Mule, not the book, that put the two patterns in one component. The Message Filter page shows what changes when Choice is used to discard, and the trap that comes with it.

In the MuleSoft documentation

The page Enterprise Integration Patterns Using Mule in the documentation maps the Content-Based Router to the Choice Router, the same component as this page.

The example

The POST /eip/orders/route endpoint receives { orderId, country, amount, items }. Before routing, a first Choice rejects with 400 an order the rules cannot read. Then comes the router:

<choice doc:name="Route Order By Content">
	<when expression="#[payload.amount &gt;= (p('eip.router.reviewThreshold') as Number)]">
		<flow-ref doc:name="Refer to sf-route-order-to-review" name="sf-route-order-to-review" />
	</when>
	<when expression="#[upper(payload.country) != upper(p('eip.orders.homeCountry'))]">
		<flow-ref doc:name="Refer to sf-route-order-to-international-fulfilment" name="sf-route-order-to-international-fulfilment" />
	</when>
	<otherwise>
		<flow-ref doc:name="Refer to sf-route-order-to-domestic-fulfilment" name="sf-route-order-to-domestic-fulfilment" />
	</otherwise>
</choice>

In the repository: src/main/mule/eip/content-based-router/content-based-router.xml

Three decisions are in this block.

The order of the rules is part of the routing. An order of 5,000 to the United States meets the first two rules. Because Choice runs only the first true one, it goes to manual review, and international fulfillment never sees it. If the two when elements were swapped, the same order would go on to fulfillment without anyone reviewing it.

The otherwise makes the router total. Every valid order goes somewhere. Without it, an order that no rule catches passes through the Choice unchanged, and the caller gets its own request back.

The rules’ data stays in configuration. The review threshold and the home country come from app.yaml, not from the XML, and can change per environment:

  orders:
    homeCountry: "BR"
  # Content-based router: orders at or above the threshold go to manual review; orders shipped outside
  # the home country go to international fulfilment; the rest to domestic fulfilment.
  router:
    reviewThreshold: "1000"

In the repository: src/main/resources/config/app.yaml

Each destination builds the response with the chosen destination. The review one, for example, returns routedTo: "MANUAL_REVIEW", the reason and the threshold that applied. The suite proves the ordering rule by checking which sub-flows were called:

<munit-tools:assert-that doc:name="Routed to MANUAL_REVIEW" expression="#[payload.routedTo]" is="#[MunitTools::equalTo('MANUAL_REVIEW')]" />
<munit-tools:assert-that doc:name="Response names the order" expression="#[payload.orderId]" is="#[MunitTools::equalTo('ORD-CBR-BOTH')]" />
<munit-tools:verify-call doc:name="Called: sf-route-order-to-review" processor="flow-ref" times="1">
	<munit-tools:with-attributes>
		<munit-tools:with-attribute attributeName="name" whereValue="sf-route-order-to-review" />
	</munit-tools:with-attributes>
</munit-tools:verify-call>
<munit-tools:verify-call doc:name="Not called: sf-route-order-to-international-fulfilment" processor="flow-ref" times="0">
	<munit-tools:with-attributes>
		<munit-tools:with-attribute attributeName="name" whereValue="sf-route-order-to-international-fulfilment" />
	</munit-tools:with-attributes>
</munit-tools:verify-call>

In the repository: src/test/munit/eip/content-based-router-test-suite.xml

Caveats

The more general rule hiding the ones after it. Choice stops at the first true expression (Choice Router). A 2014 answer on Stack Overflow recalls the same behavior: Choice stops evaluating at the first true route (Stack Overflow: Pros and Cons of using Choice Router in Mule). In practice, the more specific rule goes before the more general one, and a test pins the order down, like cbr-first-matching-rule-wins-high-value-international-goes-to-review.

The field’s type decides the comparison. In a Stack Overflow question from 2018, still using Mule 3 syntax, the author says the expression of a when on the code field did not behave as he expected; one of the answers assumes, from a comment of his, that the code arrived as text, and points out that 100 != '100' (Stack Overflow: Choice Router Expression Mule). In DataWeave 2, in Mule 4, the trap remains: == compares without converting types, and only ~= tries to convert one value to the other’s type (DataWeave Operators). The example on this page converts the threshold with as Number and rejects with 400, before the router, an order whose amount is not a number.

A missing field cannot become a route. Without the country field, the comparison with the home country says nothing useful, and the order would land in a destination by accident. That is why validation comes first: the test cbr-order-without-country-returns-400 shows the order without a country refused without reaching any destination.

Without an otherwise, the order passes with no destination. Mule accepts a Choice with no otherwise, and nothing warns that an order was not routed. The test cbr-without-otherwise-unmatched-order-comes-back-unchanged uses a copy of the router without an otherwise: a domestic order of 120 meets no rule, no destination is called and the payload leaves the same as it came in.

The router grows. The book already warns that it becomes a frequent maintenance point (Content-Based Router). When the set of destinations keeps growing, looking the destination up in configuration instead of adding a when per case keeps the Choice the size it is; the OCP example in the same repository does this for payment methods (src/main/mule/solid/ocp).

When not to use it

When every order follows the same path and only one field changes, a router is extra complexity: the difference fits in a DataWeave expression inside the Transform. When the same message has to go to several destinations at once, the pattern is a different one: the Recipient List, or the Scatter-Gather when the replies have to come back together. And when the message only needs to be discarded or not, it is the Message Filter.

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.

What each test in the suite proves:

Test What it proves
cbr-domestic-order-goes-to-domestic-fulfilment An order to the home country, below the threshold, goes to domestic fulfillment
cbr-international-order-goes-to-international-fulfilment An order to another country goes to international fulfillment, with a customs declaration
cbr-order-at-the-threshold-goes-to-review An order whose amount equals the threshold goes to manual review
cbr-first-matching-rule-wins-high-value-international-goes-to-review An order that meets two rules goes only to the first; international fulfillment is not called
cbr-order-without-country-returns-400 An order without a country is refused with 400 and reaches no destination
cbr-without-otherwise-unmatched-order-comes-back-unchanged Without an otherwise, the order that no rule catches comes back unchanged

To call the endpoint, run the application in Anypoint Studio (port 8081) and open requests.http in VS Code (REST Client) or IntelliJ. The three Content-Based Router entries send a domestic order, an international one and a high-value international one, which goes to review:

### EIP content-based router — domestic, international and review (the first matching rule wins: this one goes to review)
POST {{base}}/eip/orders/route
Content-Type: application/json

{ "orderId": "ORD-3001", "country": "BR", "amount": 120, "items": [ { "sku": "SKU-BOOK", "quantity": 1, "unitPrice": 120 } ] }

In the repository: requests.http

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.

Code for this page