Patterncore
Command Message
Also called Command Message pattern, command, command message.
A command message is a message that asks one receiver to do something, such as to reserve stock or to charge a card. It is a normal message whose body names an operation and gives its arguments.
- Family
- integration
- Intent
- Ask another program to run an operation by sending a message that names the operation and carries its arguments, so that the call gets the benefits of messaging in place of a remote procedure call.
- Also called
- command
Intent
Use a message to call an operation in another program. The book asks: "How can messaging be used to invoke a procedure in another application?"12 The answer: "Use a Command Message to reliably invoke a procedure in another application."1 The message names the operation and carries its arguments, and the receiver runs the operation.
Problem
A shop must reserve stock in the warehouse program for each order. The easy way is a remote procedure call: the shop calls reserveStock over the network and waits. But then the shop stops when the warehouse is down or slow, and the call is lost when the network fails.
The forces are these. The shop needs a specific action, not only a notice: the warehouse must reserve the stock. The shop and the warehouse should not need to run at the same time. And the request must not be lost, also when the warehouse is down for an hour.
Solution
Put the request in a message. The book says that there is no special message type for commands: a Command Message is a normal message that contains a command.1 In Jakarta Messaging, it can be any message type, for example an ObjectMessage, "a message that contains a serializable Java object",3 or a text message with the command in XML.1
shop --- ReserveStock {sku: A1, qty: 2} ---> [ stock.commands ] ---> warehouse
a name and the arguments point-to-point runs reserve_stock
The participants are the sender, the command message, a channel and the receiver that owns the operation. A command message has three usual parts:
- The name of the command. It tells the receiver which operation to run. NServiceBus and MassTransit advise a verb and a noun, in the "tell" style, such as
SubmitOrder.45 - The arguments. The data that the operation needs.
- Headers for the conversation. A message id, and, if the sender wants an answer, a reply channel.
One owner. A command asks for an action, so one receiver must do it. NServiceBus says: "Typically, a command should only be consumed by a single consumer."4 It also says that a command should be sent to its logical owner, and it throws an exception when a program tries to publish a command.4 A command on a Publish-Subscribe Channel runs once for each subscriber, so a card is charged once for each copy. Send commands on a Point-to-Point Channel.
Command, document and event. The book gives three kinds of message intent. A Command Message asks the receiver to run a function, a Document Message carries a data structure, and an Event Message tells the receivers that something changed in the sender.6 NServiceBus puts the difference between commands and events in its table: a command is "Used to make a request to perform an action", and an event is "Used to communicate that an action has been performed".4
A reply. A command can need an answer. In the Request-Reply pattern, the request is usually a Command Message, and the reply is a Document Message with a result or an exception; the request gives the channel for the reply.6 The program below sends three commands to a stock service on a queue, each with an id and a reply channel. A thread of the service runs the commands, and it puts a reply with a result or an error on the reply channel.
import json
import queue
import threading
channels = {"stock.commands": queue.Queue(), "shop.replies": queue.Queue()}
stock = {"A1": 5}
def reserve_stock(sku, qty):
if sku not in stock:
raise KeyError(f"unknown sku {sku}")
if stock[sku] < qty:
raise ValueError(f"not enough stock, {stock[sku]} left")
stock[sku] -= qty
return {"sku": sku, "left": stock[sku]}
HANDLERS = {"ReserveStock": reserve_stock}
def receiver():
while (raw := channels["stock.commands"].get()) is not None:
cmd = json.loads(raw)
reply = {"in_reply_to": cmd["id"]}
try:
reply["result"] = HANDLERS[cmd["command"]](**cmd["args"])
except (KeyError, ValueError) as e:
reply["error"] = f"{type(e).__name__}: {e.args[0]}"
channels[cmd["reply_to"]].put(json.dumps(reply))
t = threading.Thread(target=receiver)
t.start()
commands = [
{"id": "c1", "command": "ReserveStock", "args": {"sku": "A1", "qty": 2}},
{"id": "c2", "command": "ReserveStock", "args": {"sku": "Z9", "qty": 1}},
{"id": "c3", "command": "ReserveStock", "args": {"sku": "A1", "qty": 9}},
]
for cmd in commands:
cmd["reply_to"] = "shop.replies"
channels["stock.commands"].put(json.dumps(cmd))
print("sent", cmd["id"], cmd["command"], cmd["args"])
channels["stock.commands"].put(None)
t.join()
while not channels["shop.replies"].empty():
reply = json.loads(channels["shop.replies"].get())
print("reply to", reply["in_reply_to"], reply.get("result") or reply.get("error"))
sent c1 ReserveStock {'sku': 'A1', 'qty': 2}
sent c2 ReserveStock {'sku': 'Z9', 'qty': 1}
sent c3 ReserveStock {'sku': 'A1', 'qty': 9}
reply to c1 {'sku': 'A1', 'left': 3}
reply to c2 KeyError: unknown sku Z9
reply to c3 ValueError: not enough stock, 3 left
The sender does not wait for each reply. It sends the three commands, and it matches the replies to the commands by the field in_reply_to.
Example
Each example file sends three command messages on a channel in memory: two ReserveStock commands and one ChargeCard command. Each message is only bytes on the channel. The receiver reads the bytes, finds the name of the command, and runs the handler for it. The second reservation asks for more stock than there is, and the handler answers so.
The examples use the serialization of the standard library: json in Python, encoding/json in Go, System.Text.Json in C#, and the Java serialization in Java, which is the form that the book names for an ObjectMessage.1 With Java serialization, the receiver must check the classes that it reads: the Java documentation warns that "Deserialization of untrusted data is inherently dangerous and should be avoided."7 The Java example sets a filter that accepts only its own classes. In C#, the attribute JsonPolymorphic and one JsonDerivedType for each command read the name of the command from a property of the JSON; the documentation calls this property a type discriminator.8
import json
from collections import deque
channel = deque() # the channel carries bytes; it does not know what is in them
def send(command, **args):
channel.append(json.dumps({"command": command, **args}).encode())
stock = {"A1": 5}
def reserve_stock(sku, qty):
if stock[sku] < qty:
return f"reserve {qty} of {sku}: not enough stock, {stock[sku]} left"
stock[sku] -= qty
return f"reserve {qty} of {sku}: {stock[sku]} left"
def charge_card(order, cents):
return f"charge {cents} cents for order {order}: done"
HANDLERS = {"ReserveStock": reserve_stock, "ChargeCard": charge_card}
send("ReserveStock", sku="A1", qty=2)
send("ChargeCard", order=42, cents=1999)
send("ReserveStock", sku="A1", qty=9)
while channel:
args = json.loads(channel.popleft())
command = args.pop("command")
print(HANDLERS[command](**args))
reserve 2 of A1: 3 left
charge 1999 cents for order 42: done
reserve 9 of A1: not enough stock, 3 left
- Verdict: stdlib.
jsonturns each command into bytes and back, and a dict from the name of a command to a function is the dispatcher. - The channel holds bytes, as a broker does. It cannot see the command, so any program that can read JSON can send to the receiver or read from the channel.
HANDLERS[command]raisesKeyErrorfor an unknown command. A receiver on a broker would catch it and move the message to an invalid message channel.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
public class Main {
sealed interface Command extends Serializable permits ReserveStock, ChargeCard {}
record ReserveStock(String sku, int qty) implements Command {}
record ChargeCard(int order, int cents) implements Command {}
static final Map<String, Integer> stock = new HashMap<>(Map.of("A1", 5));
static byte[] encode(Command c) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(c);
}
return bytes.toByteArray();
}
static Command decode(byte[] raw) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw))) {
// Accept only the command classes; reject every other class in the stream.
in.setObjectInputFilter(ObjectInputFilter.Config.createFilter("Main$*;java.lang.*;!*"));
return (Command) in.readObject();
}
}
static String handle(Command c) {
if (c instanceof ReserveStock r) {
int left = stock.get(r.sku());
if (left < r.qty()) {
return "reserve " + r.qty() + " of " + r.sku() + ": not enough stock, " + left + " left";
}
stock.put(r.sku(), left - r.qty());
return "reserve " + r.qty() + " of " + r.sku() + ": " + (left - r.qty()) + " left";
}
ChargeCard ch = (ChargeCard) c;
return "charge " + ch.cents() + " cents for order " + ch.order() + ": done";
}
public static void main(String[] args) throws Exception {
Queue<byte[]> channel = new ArrayDeque<>(); // the channel carries bytes
channel.add(encode(new ReserveStock("A1", 2)));
channel.add(encode(new ChargeCard(42, 1999)));
channel.add(encode(new ReserveStock("A1", 9)));
while (!channel.isEmpty()) {
System.out.println(handle(decode(channel.poll())));
}
}
}
reserve 2 of A1: 3 left
charge 1999 cents for order 42: done
reserve 9 of A1: not enough stock, 3 left
- Verdict: stdlib. Java serialization turns a record into bytes and back; this is the body of a Jakarta Messaging
ObjectMessage. - The sealed interface
Commandlists the commands, andinstanceofwith a pattern picks the handler. setObjectInputFilterwith the patternMain$*;java.lang.*;!*accepts only the classes of the program and ofjava.lang, and rejects all other classes. Without a filter, the bytes of a message can make the receiver create objects of any serializable class on its class path.
using System.Text.Json;
using System.Text.Json.Serialization;
var stock = new Dictionary<string, int> { ["A1"] = 5 };
var channel = new Queue<byte[]>(); // the channel carries bytes
void Send(Command c) => channel.Enqueue(JsonSerializer.SerializeToUtf8Bytes(c));
Send(new ReserveStock("A1", 2));
Send(new ChargeCard(42, 1999));
Send(new ReserveStock("A1", 9));
while (channel.TryDequeue(out var raw))
{
var command = JsonSerializer.Deserialize<Command>(raw);
Console.WriteLine(command switch
{
ReserveStock r when stock[r.Sku] < r.Qty =>
$"reserve {r.Qty} of {r.Sku}: not enough stock, {stock[r.Sku]} left",
ReserveStock r => $"reserve {r.Qty} of {r.Sku}: {stock[r.Sku] -= r.Qty} left",
ChargeCard c => $"charge {c.Cents} cents for order {c.Order}: done",
_ => "invalid message",
});
}
// The "command" property of the JSON names the command.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "command")]
[JsonDerivedType(typeof(ReserveStock), "ReserveStock")]
[JsonDerivedType(typeof(ChargeCard), "ChargeCard")]
abstract record Command;
record ReserveStock(string Sku, int Qty) : Command;
record ChargeCard(int Order, int Cents) : Command;
reserve 2 of A1: 3 left
charge 1999 cents for order 42: done
reserve 9 of A1: not enough stock, 3 left
- Verdict: stdlib.
System.Text.Jsonwrites each command as JSON with a propertycommandthat names its type, and reads it back as the right record. - The
switchexpression on the type of the record is the dispatcher. A JSON body with an unknown name incommandmakesDeserializethrow, so the receiver does not run it. - The records are immutable, so a handler cannot change a command after it arrives.
package main
import (
"encoding/json"
"fmt"
)
// envelope is the form of each command message: the name of the command and its arguments.
type envelope struct {
Command string `json:"command"`
Args json.RawMessage `json:"args"`
}
type reserveStock struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
type chargeCard struct {
Order int `json:"order"`
Cents int `json:"cents"`
}
var stock = map[string]int{"A1": 5}
func handle(raw []byte) (string, error) {
var env envelope
if err := json.Unmarshal(raw, &env); err != nil {
return "", err
}
switch env.Command {
case "ReserveStock":
var c reserveStock
if err := json.Unmarshal(env.Args, &c); err != nil {
return "", err
}
if stock[c.SKU] < c.Qty {
return fmt.Sprintf("reserve %d of %s: not enough stock, %d left", c.Qty, c.SKU, stock[c.SKU]), nil
}
stock[c.SKU] -= c.Qty
return fmt.Sprintf("reserve %d of %s: %d left", c.Qty, c.SKU, stock[c.SKU]), nil
case "ChargeCard":
var c chargeCard
if err := json.Unmarshal(env.Args, &c); err != nil {
return "", err
}
return fmt.Sprintf("charge %d cents for order %d: done", c.Cents, c.Order), nil
}
return "", fmt.Errorf("unknown command %q", env.Command)
}
func encode(command string, args any) []byte {
a, err := json.Marshal(args)
if err != nil {
panic(err)
}
raw, err := json.Marshal(envelope{Command: command, Args: a})
if err != nil {
panic(err)
}
return raw
}
func main() {
channel := make(chan []byte, 3) // the channel carries bytes
channel <- encode("ReserveStock", reserveStock{SKU: "A1", Qty: 2})
channel <- encode("ChargeCard", chargeCard{Order: 42, Cents: 1999})
channel <- encode("ReserveStock", reserveStock{SKU: "A1", Qty: 9})
close(channel)
for raw := range channel {
out, err := handle(raw)
if err != nil {
fmt.Println("invalid message:", err)
continue
}
fmt.Println(out)
}
}
reserve 2 of A1: 3 left
charge 1999 cents for order 42: done
reserve 9 of A1: not enough stock, 3 left
- Verdict: stdlib.
encoding/jsonencodes an envelope with the name of the command and its arguments, andjson.RawMessagekeeps the arguments as bytes until the receiver knows their type. - The
switchonenv.Commandis the dispatcher. An unknown name gives an error, and the loop reports it as an invalid message. - The channel has a buffer of 3, so
maincan send the three commands before it reads them, in one goroutine.
Consequences
Benefits.
- The sender does not wait for the receiver. The command waits in the channel when the receiver is down or busy.
- Reliable calls. With Guaranteed Delivery, a command is not lost when a program or the network fails.
- Load is shared. Many copies of the receiver can read one queue of commands, and each command goes to one of them.
Liabilities.
- No answer at once. A sender that needs the result must use a reply channel and match the replies, as in the program above.
- Duplicates. With at-least-once delivery, a command can arrive twice. A command such as
ChargeCardmust carry an id, and the receiver must find the second copy. - The sender knows the receiver. A command names an operation of one service, so the sender depends on that service and its contract. An event does not have this dependency.
- Old commands. A command that waits a long time in a queue can be out of date when it runs. A message expiration, or a check of the state before the work, prevents an old command from doing harm.
- Commands that always fail. A command that the receiver cannot run goes back to the queue again and again; send it to a Dead Letter Channel after a limit.
When not to use it
When many programs must react. If the sender only reports a fact, such as an order that was placed, send an Event Message on a Publish-Subscribe Channel. The sender then does not need to know who reacts.
When the sender must have the answer before it can go on. A user who waits for a price needs it in a fraction of a second. A direct call is simpler than a command and a reply channel.
For data that the receiver only stores. A message that only carries a data structure, with no operation, is a Document Message.6
Variants and related patterns
Document Message and Event Message. The two other kinds of message intent.6
Request-Reply. A command as the request and a document as the reply.6
Message Bus. The common command set of a Message Bus is a set of command messages that all the programs understand.
The Command pattern. In object-oriented design, the Command pattern makes a request into an object. A command message is a similar idea between programs, but the request is data in a message, not an object in memory, so it can wait in a queue and cross a network.
Known uses
- NServiceBus: ICommand.cs at 1.0.0 of NServiceBus.MessageInterfaces is the "Marker interface to indicate that a class is a command message."9 NServiceBus uses it to route commands and to refuse to publish them.4
- MassTransit: commands that are sent to a queue and consumed by one consumer.5
- Jakarta Messaging: any message type can carry a command, for example an
ObjectMessageor aTextMessage.13
References
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Command Message (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 5, Message Construction, Command Message and Request-Reply
- Jakarta Messaging 3.1 specification, 3.11 Jakarta Messaging message body
- Particular Software, NServiceBus documentation, Messages, events, and commands, Commands; Commands vs Events
- MassTransit documentation, Messages, Message Names; Commands
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Message Construction, Message intent; Request-Reply
- Java SE 21 API, Class ObjectInputStream, class description, the warning on untrusted data
- .NET documentation, How to serialize properties of derived classes with System.Text.Json, Polymorphic type discriminators
- NServiceBus.MessageInterfaces 1.0.0 source, ICommand.cs, interface ICommand, lines 3 to 8
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 3P6MZR Edit this page History Report an error Markdown