Patterncore
Message Bus
Also called Message Bus pattern, messaging bus, service bus, integration bus.
A message bus is a shared messaging infrastructure with a common data model and command set, so that many programs can work together and a program can join or leave without changes to the others.
- Family
- integration
- Intent
- Connect many programs through one shared set of channels, message formats and commands, so that each program needs only one connection, to the bus, and programs can be added or removed without changes to the others.
- Also called
- service bus, integration bus
Intent
Give many programs one shared way to talk. The book asks: "What is an architecture that enables separate applications to work together, but in a decoupled fashion such that applications can be easily added or removed without affecting the others?"12 A Message Bus is the answer: one messaging infrastructure, one data model and one set of commands that all the programs use.
Problem
A company has a shop, a billing program, a warehouse program and a report program. Each one has its own data format. At first, the shop calls billing and the warehouse directly, with a translation for each pair. Then the report program must also see the orders, and the shop must change again.
The forces are these. With a direct connection for each pair, the number of connections grows with the square of the number of programs: 4 programs that each talk to all the others need 12 one-way translations. A change of one format breaks each program that talks to it. And the programs are often old or bought, so they cannot all change to one format.
Solution
"Structure the connecting middleware between these applications as a Message Bus that enables them to work together using messaging."1 The book names the parts of the bus, by analogy with the bus of a computer:1
- A common infrastructure. A messaging system carries the messages between the programs, often with routers or Publish-Subscribe Channels.
- Adapters. Each program connects to the bus through an adapter that translates between the format of the program and the format of the bus.
- A common data model. The messages on the bus use one format that all the programs agree on.
- A common command set. The bus has a set of commands that all the participants understand; see Command Message.
shop ------- adapter --+ +-- adapter ------- billing
"order 42 total 19.99" | | charge 1999 cents
+---[ bus: OrderPlaced ]---+
| order=42 |
analytics -- adapter --+ amount_cents=1999 +-- adapter ------- warehouse
(added later) SHIP|42
The common data model is a pattern of its own, the Canonical Data Model: "design a Canonical Data Model that is independent from any specific application. Require each application to produce and consume messages in this common format."3 With it, a new program needs only its translation to and from the common format, and the number of programs that are already on the bus does not matter.3 For 4 programs, this is 4 adapters in place of 12 translations.
The common command set lets the bus check the messages. The program below gives the bus three commands, each with its fields. The bus sends a valid command to the channel of the command, and it puts a message with an unknown command name or with the wrong fields on an invalid message channel, with the sender and the reason.
# The bus knows a common command set: the name and the fields of each command.
COMMANDS = {
"ReserveStock": {"order", "sku", "qty"},
"ChargeCard": {"order", "cents"},
"ShipOrder": {"order", "address"},
}
channels = {name: [] for name in COMMANDS} # one channel for each command
invalid = [] # the Invalid Message Channel of the bus
def subscribe(command, handler):
channels[command].append(handler)
def send(sender, msg):
name = msg.get("command")
fields = set(msg) - {"command"}
if name not in COMMANDS:
invalid.append((sender, msg, "unknown command"))
elif fields != COMMANDS[name]:
missing = ", ".join(sorted(COMMANDS[name] - fields)) or "none"
extra = ", ".join(sorted(fields - COMMANDS[name])) or "none"
invalid.append((sender, msg, f"missing {missing}; extra {extra}"))
else:
for handler in channels[name]:
handler(msg)
subscribe("ReserveStock", lambda m: print(f"warehouse: reserve {m['qty']} x {m['sku']} for {m['order']}"))
subscribe("ChargeCard", lambda m: print(f"billing: charge {m['cents']} cents for {m['order']}"))
subscribe("ShipOrder", lambda m: print(f"shipping: ship {m['order']} to {m['address']}"))
send("shop", {"command": "ReserveStock", "order": 42, "sku": "A1", "qty": 2})
send("shop", {"command": "ChargeCard", "order": 42, "cents": 1999})
send("mobile-app", {"command": "ChargeCard", "order": 43, "amount": 5.0})
send("partner", {"command": "ReserveStok", "order": 44, "sku": "B7", "qty": 1})
send("shop", {"command": "ShipOrder", "order": 42, "address": "Hue"})
for sender, msg, why in invalid:
print(f"invalid from {sender}: {msg['command']}: {why}")
warehouse: reserve 2 x A1 for 42
billing: charge 1999 cents for 42
shipping: ship 42 to Hue
invalid from mobile-app: ChargeCard: missing cents; extra amount
invalid from partner: ReserveStok: unknown command
The command from mobile-app has a field amount in place of cents, and the command from partner has a wrong name. Without the common command set, billing would get a message that it cannot read, and the warehouse would never see the reservation.
Example
Each example file makes a small bus in memory with one message type, OrderPlaced, in a common format: an order number and an amount in cents. The shop writes its orders as text, such as order 42 total 19.99, and its adapter translates the text to the common message. Billing and the warehouse read the common message, and the warehouse adapter writes the format of the warehouse, SHIP|42. Then an analytics program joins the bus. It needs only a subscription to OrderPlaced, and the shop, billing and the warehouse do not change.
The examples use the maps, lists and records of the standard library in place of a broker.
# The canonical message of the bus: a dict with a type and the shared fields.
subscribers = {}
def subscribe(msg_type, handler):
subscribers.setdefault(msg_type, []).append(handler)
def publish(msg):
print(f"bus: {msg['type']} order={msg['order']} amount_cents={msg['amount_cents']}")
for handler in subscribers.get(msg["type"], []):
handler(msg)
# Each adapter translates between the canonical message and the format of one program.
def shop_adapter(line): # the shop writes "order 42 total 19.99"
print("shop sends:", line)
_, order, _, total = line.split()
units, cents = total.split(".")
publish({"type": "OrderPlaced", "order": int(order), "amount_cents": int(units) * 100 + int(cents)})
def billing_adapter(msg):
print(f"billing: charge {msg['amount_cents']} cents for order {msg['order']}")
def warehouse_adapter(msg): # the warehouse reads "SHIP|42"
print(f"warehouse: SHIP|{msg['order']}")
orders_seen = 0
def analytics_adapter(msg):
global orders_seen
orders_seen += 1
print(f"analytics: order {msg['order']} counted, total orders {orders_seen}")
subscribe("OrderPlaced", billing_adapter)
subscribe("OrderPlaced", warehouse_adapter)
shop_adapter("order 42 total 19.99")
print("analytics joins the bus")
subscribe("OrderPlaced", analytics_adapter)
shop_adapter("order 43 total 5.00")
shop sends: order 42 total 19.99
bus: OrderPlaced order=42 amount_cents=1999
billing: charge 1999 cents for order 42
warehouse: SHIP|42
analytics joins the bus
shop sends: order 43 total 5.00
bus: OrderPlaced order=43 amount_cents=500
billing: charge 500 cents for order 43
warehouse: SHIP|43
analytics: order 43 counted, total orders 1
- Verdict: idiom. Python has no message bus. A dict from a message type to a list of handlers is the bus, and a dict with the shared fields is the common message.
- Each adapter knows two formats: the format of its program and the common format. No adapter knows another program.
- The shop reads the amount as text and makes cents from the two parts, so no binary floating point number is on the bus.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class Main {
// The canonical message of the bus.
record Message(String type, int order, int amountCents) {}
static final Map<String, List<Consumer<Message>>> subscribers = new HashMap<>();
static void subscribe(String type, Consumer<Message> handler) {
subscribers.computeIfAbsent(type, k -> new ArrayList<>()).add(handler);
}
static void publish(Message m) {
System.out.println("bus: " + m.type() + " order=" + m.order() + " amount_cents=" + m.amountCents());
for (Consumer<Message> h : subscribers.getOrDefault(m.type(), List.of())) {
h.accept(m);
}
}
// The adapter of the shop reads "order 42 total 19.99".
static void shopAdapter(String line) {
System.out.println("shop sends: " + line);
String[] f = line.split(" ");
String[] total = f[3].split("\\.");
int cents = Integer.parseInt(total[0]) * 100 + Integer.parseInt(total[1]);
publish(new Message("OrderPlaced", Integer.parseInt(f[1]), cents));
}
public static void main(String[] args) {
subscribe("OrderPlaced", m -> System.out.println(
"billing: charge " + m.amountCents() + " cents for order " + m.order()));
subscribe("OrderPlaced", m -> System.out.println("warehouse: SHIP|" + m.order()));
shopAdapter("order 42 total 19.99");
System.out.println("analytics joins the bus");
int[] seen = {0};
subscribe("OrderPlaced", m -> {
seen[0]++;
System.out.println("analytics: order " + m.order() + " counted, total orders " + seen[0]);
});
shopAdapter("order 43 total 5.00");
}
}
shop sends: order 42 total 19.99
bus: OrderPlaced order=42 amount_cents=1999
billing: charge 1999 cents for order 42
warehouse: SHIP|42
analytics joins the bus
shop sends: order 43 total 5.00
bus: OrderPlaced order=43 amount_cents=500
billing: charge 500 cents for order 43
warehouse: SHIP|43
analytics: order 43 counted, total orders 1
- Verdict: idiom. Java has no message bus in the standard library. A
Mapfrom a message type to a list ofConsumerobjects is the bus, and the recordMessageis the common data model. seenis an array of oneint, because a lambda can only use local variables that do not change; the array does not change, only its element.- With a broker, each program runs in its own process, and a Jakarta Messaging topic for each message type gives the same structure.
var bus = new Bus();
bus.Subscribe("OrderPlaced", m => Console.WriteLine($"billing: charge {m.AmountCents} cents for order {m.Order}"));
bus.Subscribe("OrderPlaced", m => Console.WriteLine($"warehouse: SHIP|{m.Order}"));
ShopAdapter(bus, "order 42 total 19.99");
Console.WriteLine("analytics joins the bus");
int seen = 0;
bus.Subscribe("OrderPlaced", m =>
{
seen++;
Console.WriteLine($"analytics: order {m.Order} counted, total orders {seen}");
});
ShopAdapter(bus, "order 43 total 5.00");
// The adapter of the shop reads "order 42 total 19.99".
static void ShopAdapter(Bus bus, string line)
{
Console.WriteLine($"shop sends: {line}");
var f = line.Split(' ');
var total = f[3].Split('.');
int cents = int.Parse(total[0]) * 100 + int.Parse(total[1]);
bus.Publish(new Message("OrderPlaced", int.Parse(f[1]), cents));
}
// The canonical message of the bus.
record Message(string Type, int Order, int AmountCents);
sealed class Bus
{
private readonly Dictionary<string, List<Action<Message>>> subscribers = new();
public void Subscribe(string type, Action<Message> handler)
{
if (!subscribers.TryGetValue(type, out var list))
{
subscribers[type] = list = new List<Action<Message>>();
}
list.Add(handler);
}
public void Publish(Message m)
{
Console.WriteLine($"bus: {m.Type} order={m.Order} amount_cents={m.AmountCents}");
foreach (var h in subscribers.GetValueOrDefault(m.Type, new List<Action<Message>>()))
{
h(m);
}
}
}
shop sends: order 42 total 19.99
bus: OrderPlaced order=42 amount_cents=1999
billing: charge 1999 cents for order 42
warehouse: SHIP|42
analytics joins the bus
shop sends: order 43 total 5.00
bus: OrderPlaced order=43 amount_cents=500
billing: charge 500 cents for order 43
warehouse: SHIP|43
analytics: order 43 counted, total orders 1
- Verdict: idiom. .NET has no message bus in the base library. A
Dictionaryfrom a message type to a list ofAction<Message>is the bus, and the recordMessageis the common data model. - The lambda of analytics changes the local variable
seen; C# lambdas can change the variables that they capture. - Libraries such as MassTransit give a bus over a broker, with
Publishfor events andSendfor commands.
package main
import (
"fmt"
"strconv"
"strings"
)
// message is the canonical message of the bus.
type message struct {
Type string
Order int
AmountCents int
}
type bus struct {
subscribers map[string][]func(message)
}
func (b *bus) subscribe(msgType string, h func(message)) {
b.subscribers[msgType] = append(b.subscribers[msgType], h)
}
func (b *bus) publish(m message) {
fmt.Printf("bus: %s order=%d amount_cents=%d\n", m.Type, m.Order, m.AmountCents)
for _, h := range b.subscribers[m.Type] {
h(m)
}
}
// shopAdapter reads the format of the shop, "order 42 total 19.99".
func shopAdapter(b *bus, line string) error {
f := strings.Fields(line)
order, err := strconv.Atoi(f[1])
if err != nil {
return err
}
units, cents, _ := strings.Cut(f[3], ".")
u, err := strconv.Atoi(units)
if err != nil {
return err
}
c, err := strconv.Atoi(cents)
if err != nil {
return err
}
b.publish(message{Type: "OrderPlaced", Order: order, AmountCents: u*100 + c})
return nil
}
func main() {
b := &bus{subscribers: map[string][]func(message){}}
b.subscribe("OrderPlaced", func(m message) {
fmt.Printf("billing: charge %d cents for order %d\n", m.AmountCents, m.Order)
})
b.subscribe("OrderPlaced", func(m message) {
fmt.Printf("warehouse: SHIP|%d\n", m.Order)
})
send := func(line string) {
fmt.Println("shop sends:", line)
if err := shopAdapter(b, line); err != nil {
fmt.Println("shop adapter:", err)
}
}
send("order 42 total 19.99")
fmt.Println("analytics joins the bus")
seen := 0
b.subscribe("OrderPlaced", func(m message) {
seen++
fmt.Printf("analytics: order %d counted, total orders %d\n", m.Order, seen)
})
send("order 43 total 5.00")
}
shop sends: order 42 total 19.99
bus: OrderPlaced order=42 amount_cents=1999
billing: charge 1999 cents for order 42
warehouse: SHIP|42
analytics joins the bus
shop sends: order 43 total 5.00
bus: OrderPlaced order=43 amount_cents=500
billing: charge 500 cents for order 43
warehouse: SHIP|43
analytics: order 43 counted, total orders 1
- Verdict: idiom. Go has no message bus. A map from a message type to a slice of functions is the bus, and the struct
messageis the common data model. - A struct for the common message lets the compiler check each adapter against the model. A change of a field breaks the build of each adapter that uses it.
shopAdapterreturns an error for text that it cannot read. On a real bus, it would send that text to an invalid message channel.
Consequences
Benefits.
- Few connections. Each program has one adapter to the bus, not one connection to each other program.
- Programs join and leave. A new program subscribes to the messages that it needs, and the others do not change, as the examples show.
- One place for rules. The bus can check the messages against the common model and the command set, and it can watch and log all the traffic.
Liabilities.
- The common model is hard to agree on. All the programs must agree on the meaning of each field, and each change of the model is a change for all the adapters.
- Two translations. A message is translated from the sender format to the common format and again to the receiver format. Each translation costs time and can lose detail.
- A central dependency. When the bus is down, no program can talk to another. The bus must be as reliable as the most important program on it.
- Logic moves into the bus. A bus that also routes, transforms and runs business rules becomes a large program of its own, and a team that is not the owner of the programs must change it for each new need.
When not to use it
For two or three programs that will stay the same. A direct channel between them is simpler than a common model and a set of adapters.
Inside one program. The objects of one program share a language and a process; use an Event Aggregator or the Observer pattern in place of a bus.
When the programs cannot agree on a model. A bus with a common model that nobody follows is a set of point-to-point translations with more parts. Use a Mediator pattern or explicit translations for each pair.
Variants and related patterns
Canonical Data Model. The common format of the bus.3
Message Channel. The bus is a set of Message Channels with the same infrastructure and formats.
Command Message. The common commands of the bus are Command Messages.
Service bus libraries. Some libraries use the name for a programming model over a broker. In MassTransit, the IBus interface is a publish endpoint and gives send endpoints,4 and its documentation says that a command should typically go to a single consumer, and that events are published, for example through IBus.5
D-Bus. The name is also used for a bus for communication between programs on one computer. "D-Bus is a message bus system, a simple way for applications to talk to one another."6 It has a system daemon for events of the system, and a daemon for each user login session.6
Known uses
- MassTransit: IBus.cs at v8.5.5 defines the bus as "a logical element that includes a local endpoint and zero or more receive endpoints".4
- D-Bus: a system daemon and a daemon for each user login session.6
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Message Bus (problem and solution under CC BY), problem and solution statements; pattern text
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 4, Messaging Channels, Message Bus; Chapter 8, Message Transformation, Canonical Data Model
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Canonical Data Model (problem and solution under CC BY), problem and solution statements
- MassTransit 8.5.5 source, IBus.cs, interface IBus, lines 6 to 20
- MassTransit documentation, Messages, Commands; Events
- freedesktop.org, D-Bus, What is D-Bus?
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 VFFEC5 Edit this page History Report an error Markdown