Appearance
2. Aggregates and commands
An aggregate is one thing your business makes decisions about: a customer, an order. It has a state, built from its events, and commands that ask it to change. A command handler looks at the state and either returns new events or rejects the command. Nothing else changes state: the events are the truth, and the kernel stores them forever.
Aggregates belong to a domain, here shop: one area of the business, and in code one object that holds everything of it, its aggregates, read models and reactors, its event versions and which fields go to the vault. Types are unique within a domain and named shop.Register elsewhere. A domain writes only its own events and learns about other domains through listeners; Domains explains the rules and a code layout for when it grows.
The domain
Start domain.ts (or domain.py, src/domain.rs) with the domain and the customer:
ts
export const shopDomain = domain("shop");py
shop_domain = domain("shop")rs
let shop_domain = domain("shop");ts
type Customer = { registered: boolean; passwordHash?: string; salt?: string };
export const customerAggregate = shopDomain.aggregate<Customer>("customer", { registered: false })
.apply("CustomerRegistered", (s) => { s.registered = true; })
.command("Register", (s, data: { email: string; name: string }) => {
if (s.registered) throw new Rejected("Customer already registered", "exists");
if (!/^[^@\s]+@[^@\s]+$/.test(data.email ?? "")) throw new Rejected("Invalid email", "invalid");
return [{ type: "CustomerRegistered", data: { email: data.email, name: data.name } }];
});py
customer_aggregate = shop_domain.aggregate("customer", {"registered": False})
@customer_aggregate.apply("CustomerRegistered")
def _(state, data):
state["registered"] = True
@customer_aggregate.command("Register")
def _(state, data):
if state["registered"]:
raise Rejected("Customer already registered", "exists")
if not re.match(r"^[^@\s]+@[^@\s]+$", data.get("email") or ""):
raise Rejected("Invalid email", "invalid")
return [{"type": "CustomerRegistered", "data": {"email": data["email"], "name": data["name"]}}]rs
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct Customer {
registered: bool,
password_hash: Option<String>,
salt: Option<String>,
}
#[derive(Deserialize)]
struct Register {
email: Option<String>,
name: Option<String>,
}
fn customer(shop_domain: &Domain) -> Aggregate<Customer> {
let customer_aggregate = shop_domain.aggregate("customer", Customer::default());
customer_aggregate.apply("CustomerRegistered", |s, _: Value, _evt, _ctx| {
s.registered = true
});
customer_aggregate.command("Register", |s, data: Register, _cmd, _ctx| {
if s.registered {
return Err(Rejected::new("Customer already registered").code("exists"));
}
let email = data.email.unwrap_or_default();
let valid = email.split_once('@').is_some_and(|(user, host)| {
!user.is_empty()
&& !host.is_empty()
&& !email.contains(char::is_whitespace)
&& !host.contains('@')
});
if !valid {
return Err(Rejected::new("Invalid email").code("invalid"));
}
Ok(vec![NewEvent::new(
"CustomerRegistered",
json!({ "email": email, "name": data.name }),
)])
});
customer_aggregate
}apply turns an event's data into the next state; command decides. Rejected carries a message and a code (exists, invalid) your callers can act on.
Add the order:
ts
type Order = { status: "none" | "draft" | "submitted" | "confirmed" | "paid" | "shipped" | "cancelled"; items: number };
export const orderAggregate = shopDomain.aggregate<Order>("order", { status: "none", items: 0 })
.apply("OrderPlaced", () => ({ status: "draft", items: 0 }))
.apply("ItemAdded", (s, data: { qty: number }) => { s.items += data.qty; })
.apply("OrderSubmitted", (s) => { s.status = "submitted"; })
.apply("OrderConfirmed", (s) => { s.status = "confirmed"; })
.command("Place", (s, data: { customerId: string }) => {
if (s.status !== "none") throw new Rejected("Order already exists", "exists");
return [{ type: "OrderPlaced", data: { customerId: data.customerId } }];
})
.command("AddItem", (s, data: { sku: string; qty: number }) => {
if (s.status !== "draft") throw new Rejected(`Cannot add items to a ${s.status} order`, "invalid_state");
if (!(data.qty > 0)) throw new Rejected("Quantity must be positive", "invalid");
return [{ type: "ItemAdded", data: { sku: data.sku, qty: data.qty } }];
})
.command("Submit", (s) => {
if (s.status !== "draft" || s.items === 0) throw new Rejected(`Cannot submit a ${s.status} order with ${s.items} items`, "invalid_state");
return [{ type: "OrderSubmitted" }];
});py
order_aggregate = shop_domain.aggregate("order", {"status": "none", "items": 0})
@order_aggregate.apply("OrderPlaced")
def _(state, data):
return {"status": "draft", "items": 0}
@order_aggregate.apply("ItemAdded")
def _(state, data):
state["items"] += data["qty"]
@order_aggregate.apply("OrderSubmitted")
def _(state, data):
state["status"] = "submitted"
@order_aggregate.apply("OrderConfirmed")
def _(state, data):
state["status"] = "confirmed"
@order_aggregate.command("Place")
def _(state, data):
if state["status"] != "none":
raise Rejected("Order already exists", "exists")
return [{"type": "OrderPlaced", "data": {"customerId": data["customerId"]}}]
@order_aggregate.command("AddItem")
def _(state, data):
if state["status"] != "draft":
raise Rejected(f"Cannot add items to a {state['status']} order", "invalid_state")
if not data.get("qty", 0) > 0:
raise Rejected("Quantity must be positive", "invalid")
return [{"type": "ItemAdded", "data": {"sku": data["sku"], "qty": data["qty"]}}]
@order_aggregate.command("Submit")
def _(state, data):
if state["status"] != "draft" or state["items"] == 0:
raise Rejected(f"Cannot submit a {state['status']} order with {state['items']} items", "invalid_state")
return [{"type": "OrderSubmitted"}]rs
#[derive(Clone, Serialize, Deserialize)]
pub struct Order {
/// none, draft, submitted, confirmed, paid, shipped or cancelled.
status: String,
items: i64,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Place {
customer_id: String,
}
#[derive(Serialize, Deserialize)]
struct AddItem {
sku: String,
qty: Option<i64>,
}
fn order(shop_domain: &Domain) -> Aggregate<Order> {
let order_aggregate = shop_domain.aggregate(
"order",
Order {
status: "none".into(),
items: 0,
},
);
order_aggregate.apply("OrderPlaced", |s, _: Value, _evt, _ctx| {
*s = Order {
status: "draft".into(),
items: 0,
}
});
order_aggregate.apply("ItemAdded", |s, data: AddItem, _evt, _ctx| {
s.items += data.qty.unwrap_or(0)
});
order_aggregate.apply("OrderSubmitted", |s, _: Value, _evt, _ctx| {
s.status = "submitted".into()
});
order_aggregate.apply("OrderConfirmed", |s, _: Value, _evt, _ctx| {
s.status = "confirmed".into()
});
order_aggregate.command("Place", |s, data: Place, _cmd, _ctx| {
if s.status != "none" {
return Err(Rejected::new("Order already exists").code("exists"));
}
Ok(vec![NewEvent::new("OrderPlaced", data)])
});
order_aggregate.command("AddItem", |s, data: AddItem, _cmd, _ctx| {
if s.status != "draft" {
let message = format!("Cannot add items to a {} order", s.status);
return Err(Rejected::new(message).code("invalid_state"));
}
if data.qty.is_none_or(|qty| qty <= 0) {
return Err(Rejected::new("Quantity must be positive").code("invalid"));
}
Ok(vec![NewEvent::new("ItemAdded", data)])
});
order_aggregate.command("Submit", |s, _: Value, _cmd, _ctx| {
if s.status != "draft" || s.items == 0 {
let message = format!("Cannot submit a {} order with {} items", s.status, s.items);
return Err(Rejected::new(message).code("invalid_state"));
}
Ok(vec![NewEvent::new("OrderSubmitted", ())])
});
order_aggregate
}Handlers must be deterministic and free of side effects: the kernel may run a command again (after a crash, or when another command changed the aggregate in between), and it must decide the same way.
The worker
A worker runs the commands of its aggregates. It connects, tells the kernel which command types it handles, and waits:
ts
const kernable = new Kernable();
await kernable.worker(customerAggregate, orderAggregate).run();py
k = Kernable()
k.worker(customer_aggregate, order_aggregate).run()rs
let kernable = Kernable::new(Options::default())?;
kernable
.worker(&shop.customer_aggregate)
.aggregate(&shop.order_aggregate)
.run()
.await;sh
node worker.tssh
.venv/bin/python worker.pysh
cargo run -q --bin workerYou can start more workers; the kernel spreads the commands over them and never runs two commands of one aggregate at a time.
Send commands
ts
const send = (aggregateType: string, aggregateId: string, type: string, data?: object, id?: string) =>
kernable.submit({ domain: "shop", aggregateType, aggregateId, type, data, id });
show("register", await send("customer", "c1", "Register", { email: "ann@example.com", name: "Ann" }));
show("register again", await send("customer", "c1", "Register", { email: "ann@example.com", name: "Ann" }));
show("place", await send("order", "o1", "Place", { customerId: "c1" }));
show("add apples", await send("order", "o1", "AddItem", { sku: "apple", qty: 2 }, "add-1"));
show("same command again", await send("order", "o1", "AddItem", { sku: "apple", qty: 2 }, "add-1"));
show("submit", await send("order", "o1", "Submit"));
show("add after submit", await send("order", "o1", "AddItem", { sku: "pear", qty: 1 }));py
def send(aggregate_type, aggregate_id, type, data=None, id=None):
return k.submit("shop", aggregate_type, aggregate_id, type, data, id=id)
show("register", send("customer", "c1", "Register", {"email": "ann@example.com", "name": "Ann"}))
show("register again", send("customer", "c1", "Register", {"email": "ann@example.com", "name": "Ann"}))
show("place", send("order", "o1", "Place", {"customerId": "c1"}))
show("add apples", send("order", "o1", "AddItem", {"sku": "apple", "qty": 2}, "add-1"))
show("same command again", send("order", "o1", "AddItem", {"sku": "apple", "qty": 2}, "add-1"))
show("submit", send("order", "o1", "Submit"))
show("add after submit", send("order", "o1", "AddItem", {"sku": "pear", "qty": 1}))rs
let send = |aggregate_type, aggregate_id, command_type, data: Value| {
kernable.submit(Submit::new("shop", aggregate_type, aggregate_id, command_type).data(data))
};
let ann = json!({ "email": "ann@example.com", "name": "Ann" });
show(
"register",
send("customer", "c1", "Register", ann.clone()).await?,
);
show(
"register again",
send("customer", "c1", "Register", ann).await?,
);
show(
"place",
send("order", "o1", "Place", json!({ "customerId": "c1" })).await?,
);
let apples = Submit::new("shop", "order", "o1", "AddItem")
.data(json!({ "sku": "apple", "qty": 2 }))
.id("add-1");
show("add apples", kernable.submit(apples.clone()).await?);
show("same command again", kernable.submit(apples).await?);
show("submit", send("order", "o1", "Submit", Value::Null).await?);
show(
"add after submit",
send("order", "o1", "AddItem", json!({ "sku": "pear", "qty": 1 })).await?,
);text
register: committed, version 1
register again: exists (Customer already registered)
place: committed, version 1
add apples: committed, version 2
same command again: committed, version 2
submit: committed, version 3
add after submit: invalid_state (Cannot add items to a submitted order)text
register: committed, version 1
register again: exists (Customer already registered)
place: committed, version 1
add apples: committed, version 2
same command again: committed, version 2
submit: committed, version 3
add after submit: invalid_state (Cannot add items to a submitted order)text
register: committed, version 1
register again: exists (Customer already registered)
place: committed, version 1
add apples: committed, version 2
same command again: committed, version 2
submit: committed, version 3
add after submit: invalid_state (Cannot add items to a submitted order)What happened:
- Each committed command reports the aggregate's new version: one per event.
register againandadd after submitwere rejected by the handlers. A rejected command is stored as rejected, like a committed one.same command againused the same command ID (add-1) and got the original outcome back: the item was added once. Give a command a fixed ID when you might send it twice, for example when retrying after a timeout.
Next: 3. Read models and queries.
