Patterncore
Content-Based Router
Also called Content-Based Router pattern, content-based routing, CBR, choice router.
A content-based router reads each message on one channel and sends it to another channel that it chooses from the content, such as the type of an item. The sender then needs to know only one channel.
- Family
- integration
- Intent
- Send each message to the right receiver for its content, by a router that reads one input channel, tests rules on each message, and puts the message on the channel of the first rule that matches.
- Also called
- content-based routing, CBR
Intent
Send each message to the receiver that can handle its content. The book asks: "How do we handle a situation where the implementation of a single logical function (e.g., inventory check) is spread across multiple physical systems?"12 The answer: "Use a Content-Based Router to route each message to the correct recipient based on message content."1
Problem
A shop sells widgets and gadgets. One warehouse program keeps the stock of widgets, and another one keeps the stock of gadgets. For the shop, an inventory check is one function, but the work is in two systems. If the shop chooses the system for each order, it must know all the systems and change when a third one comes.
The forces are these. The sender should send to one channel and not know the systems behind it. Each message must go to exactly one system, the one that owns its item. And a message that no system can handle must not be lost.
Solution
Put a router between the sender and the systems. The router reads each message on its input channel, looks at the data in the message, and puts the message on the output channel of the right system.1 The book says that the router lets the producer send all its messages to one channel, and so the producer is not coupled to the channels of the destinations.3
+--> [ inventory.widgets ] ---> widget system
shop ---> [ orders ] ---> content-based ---+--> [ inventory.gadgets ] ---> gadget system
router +--> [ invalid ] ---> a person looks
The participants are the input channel, the router with its rules, the output channels and the receivers. A rule can test that a field exists or that it has a given value.1
One rule for each channel, in order. Apache Camel calls the pattern the Choice EIP, which "allows you to route messages to the correct destination based on the contents of the message exchanges."4 A route lists when clauses with a predicate and a destination, and an otherwise clause.4 The class ChoiceProcessor tests the predicates in order and sends the message to the first one that matches.5 So the order of the rules is a part of the routing, as the program below shows. It routes the same four orders with two orders of the rules.
orders = [
{"id": 1, "shipping": "express", "total": 5000},
{"id": 2, "shipping": "normal", "total": 5000},
{"id": 3, "shipping": "normal", "total": 20},
{"id": 4, "total": 20}, # a message with no shipping field
]
express = ("orders.express", lambda o: o["shipping"] == "express")
large = ("orders.large", lambda o: o["total"] >= 1000)
normal = ("orders.normal", lambda o: True)
def route(order, rules):
"""Return the channel of the first rule that matches."""
try:
for channel, test in rules:
if test(order):
return channel
except KeyError as missing:
return f"orders.invalid (no field {missing})"
return "orders.invalid (no rule matched)"
for name, rules in [("express first", [express, large, normal]), ("large first", [large, express, normal])]:
print(name + ":")
for order in orders:
print(f" order {order['id']} -> {route(order, rules)}")
express first:
order 1 -> orders.express
order 2 -> orders.large
order 3 -> orders.normal
order 4 -> orders.invalid (no field 'shipping')
large first:
order 1 -> orders.large
order 2 -> orders.large
order 3 -> orders.normal
order 4 -> orders.invalid (no field 'shipping')
Order 1 is an express order and also a large order. With the express rule first, it goes to orders.express. With the large rule first, it goes to orders.large. Order 4 has no shipping field, and the router sends it to an invalid channel, not to a normal channel by accident.
A default. A message that matches no rule needs a place. In Camel, when no when matches and there is no otherwise, the comment in the code says: "when no filter matches and there is no otherwise, then just continue".5 The message goes on with no routing, so an unknown type can pass with no error. A default rule to an invalid channel or a Dead Letter Channel makes the case visible.
Maintenance. The book warns that the router can become a place of frequent change, because it must know all the destinations. In larger systems, the rules can be in a configurable rules engine.1
Example
Each example file routes four orders by the type field. Widgets go to inventory.widgets, gadgets go to inventory.gadgets, and the order for a gizmo goes to invalid, because no system owns it. Python and Go use a map from the type to the channel, Java uses a list of rules with a predicate and the first match wins, and C# uses a switch expression with a default arm.
import json
# The router reads one input channel and writes to the channel of the system for each item type.
channels = {"inventory.widgets": [], "inventory.gadgets": [], "invalid": []}
routes = {"widget": "inventory.widgets", "gadget": "inventory.gadgets"}
def route(raw):
order = json.loads(raw)
channel = routes.get(order.get("type"), "invalid") # an unknown type is not lost
channels[channel].append(order["id"])
incoming = [
{"id": "o1", "type": "widget", "qty": 3},
{"id": "o2", "type": "gadget", "qty": 1},
{"id": "o3", "type": "gizmo", "qty": 2},
{"id": "o4", "type": "widget", "qty": 1},
]
for order in incoming:
route(json.dumps(order).encode())
for name, ids in channels.items():
print(f"{name}: {' '.join(ids)}")
inventory.widgets: o1 o4
inventory.gadgets: o2
invalid: o3
- Verdict: idiom. A dict from the item type to the name of a channel is the rule table, and the second argument of
routes.getis the default rule. order.getgivesNonefor a message with no type field, so such a message also goes to the invalid channel and does not raise an error.- With a broker, the router is a consumer of the input queue and a producer for the output queues.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
public class Main {
record Order(String id, String type, int qty) {}
record Rule(Predicate<Order> test, String channel) {}
// The router reads one input channel and writes to the channel of the system for each item type.
static final List<Rule> RULES = List.of(
new Rule(o -> o.type().equals("widget"), "inventory.widgets"),
new Rule(o -> o.type().equals("gadget"), "inventory.gadgets"));
static final Map<String, List<String>> CHANNELS = new LinkedHashMap<>();
static void route(Order o) {
var channel = "invalid"; // an unknown type is not lost
for (var rule : RULES) {
if (rule.test().test(o)) {
channel = rule.channel();
break; // the first rule that matches wins
}
}
CHANNELS.get(channel).add(o.id());
}
public static void main(String[] args) {
for (var name : List.of("inventory.widgets", "inventory.gadgets", "invalid")) {
CHANNELS.put(name, new ArrayList<>());
}
var incoming = List.of(new Order("o1", "widget", 3), new Order("o2", "gadget", 1),
new Order("o3", "gizmo", 2), new Order("o4", "widget", 1));
for (var o : incoming) {
route(o);
}
CHANNELS.forEach((name, ids) -> System.out.println(name + ": " + String.join(" ", ids)));
}
}
inventory.widgets: o1 o4
inventory.gadgets: o2
invalid: o3
- Verdict: idiom. A list of rules, each a
Predicateand a channel, is the router; the loop stops at the first rule that matches, as the Choice EIP of Apache Camel does. - The variable
channelstarts with the name of the invalid channel, so a message that matches no rule goes there. - A
LinkedHashMapkeeps the order in which the channels were added, so the output has a fixed order.
using System.Text.Json;
// The router reads one input channel and writes to the channel of the system for each item type.
var channels = new Dictionary<string, List<string>>
{
["inventory.widgets"] = [],
["inventory.gadgets"] = [],
["invalid"] = [],
};
Order[] incoming = [new("o1", "widget", 3), new("o2", "gadget", 1), new("o3", "gizmo", 2), new("o4", "widget", 1)];
foreach (var o in incoming)
{
Route(JsonSerializer.SerializeToUtf8Bytes(o));
}
foreach (var (name, ids) in channels)
{
Console.WriteLine($"{name}: {string.Join(" ", ids)}");
}
void Route(byte[] raw)
{
var o = JsonSerializer.Deserialize<Order>(raw)!;
var channel = o.Type switch
{
"widget" => "inventory.widgets",
"gadget" => "inventory.gadgets",
_ => "invalid", // an unknown type is not lost
};
channels[channel].Add(o.Id);
}
record Order(string Id, string Type, int Qty);
inventory.widgets: o1 o4
inventory.gadgets: o2
invalid: o3
- Verdict: idiom. A
switchexpression on the item type is the rule table, and the discard arm_is the default rule. - The compiler warns when a
switchexpression has no arm for some values, which helps to keep a default. System.Text.Jsonturns each order into bytes and back, as on a broker.
package main
import (
"encoding/json"
"fmt"
"strings"
)
type order struct {
ID string `json:"id"`
Type string `json:"type"`
Qty int `json:"qty"`
}
// The router reads one input channel and writes to the channel of the system for each item type.
var routes = map[string]string{"widget": "inventory.widgets", "gadget": "inventory.gadgets"}
var names = []string{"inventory.widgets", "inventory.gadgets", "invalid"}
var channels = map[string][]string{}
func route(raw []byte) {
var o order
if err := json.Unmarshal(raw, &o); err != nil {
channels["invalid"] = append(channels["invalid"], string(raw))
return
}
channel, ok := routes[o.Type]
if !ok {
channel = "invalid" // an unknown type is not lost
}
channels[channel] = append(channels[channel], o.ID)
}
func main() {
incoming := []order{{"o1", "widget", 3}, {"o2", "gadget", 1}, {"o3", "gizmo", 2}, {"o4", "widget", 1}}
for _, o := range incoming {
raw, err := json.Marshal(o)
if err != nil {
panic(err)
}
route(raw)
}
for _, name := range names {
fmt.Printf("%s: %s\n", name, strings.Join(channels[name], " "))
}
}
inventory.widgets: o1 o4
inventory.gadgets: o2
invalid: o3
- Verdict: idiom. A
map[string]stringfrom the item type to the channel is the rule table, and the formchannel, ok := routes[o.Type]finds the case with no rule. - A message that is not valid JSON also goes to the invalid channel, with its raw bytes, so a person can read it.
- The slice
namesgives a fixed order for the output, because the order of a Go map is not defined.
Consequences
Benefits.
- One channel for the sender. The sender does not know how many systems there are, or which one owns which items.3
- Each message goes once. The router chooses one channel, so no system gets a message that it must ignore.
- Rules in one place. A change of the owner of an item type is a change of one rule.
Liabilities.
- The router knows all destinations. A new system means a change to the router.3
- The router reads the content. It must parse the message, so it depends on the format of the data. A change of a field name can send messages to the wrong place.
- Order of the rules. When two rules can match one message, the first one wins, and a change of the order changes the routing.
- One more step. Each message goes through the router, which adds a hop and a part that can fail.
When not to use it
When each receiver can decide alone. The book gives an alternative: a Publish-Subscribe Channel with one message filter for each receiver. The router routes predictively and depends on all the destinations; the filters filter reactively, and no part knows all the destinations.3 Amazon SNS uses this form: by default, "an Amazon SNS topic subscriber receives every message that's published to the topic", and a filter policy on a subscription selects a subset.6
When the sender already knows the receiver. If the sender has the information and the destinations do not change, it can send to the right channel itself.
When a message must go to many receivers. A content-based router chooses one channel. The book uses a recipient list for more than one.3
Variants and related patterns
Message Filter. A special form of the router with one output: a message that does not match is discarded.3
Dynamic Router. A router whose rules change at run time, by control messages.3
Recipient List. A router that can send one message to more than one channel.3
Chain of Responsibility. In object-oriented design, the Chain of Responsibility pattern gives a request to a list of handlers in order; the rules of a router also run in order, but the router, not the handler, chooses the destination.
Known uses
- Apache Camel: the process method of ChoiceProcessor at 4.14.0 finds "the first matching filter", runs its processor, and else runs
otherwise.5 The EIP site shows the same router in the Camel Java DSL, withchoice,whenandotherwise.1 - Amazon SNS: filter policies on the subscriptions act on the message attributes or on the body.6
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Content-Based Router (problem and solution under CC BY), problem and solution statements; pattern text; Example, Apache Camel
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 7, Message Routing, Content-Based Router
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Message Routing, Simple Routers
- Apache Camel 4.14.0 documentation source, Choice EIP, introduction; Example
- Apache Camel 4.14.0 source, ChoiceProcessor.java, method process, lines 60 to 100
- Amazon SNS Developer Guide, Amazon SNS message filtering, introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag KC8BRN Edit this page History Report an error Markdown