Skip to content

3. Read models and queries ​

Aggregates decide; they do not answer questions like "what is in order o1?". That is the job of read models: listeners that receive events in order and keep a view of them, shaped for the questions you ask.

Read models are defined on the domain, like aggregates, and run through the connection with listener, like an aggregate with worker. A read model's state is private. Everything else reads it through queries, which go through the kernel like commands do: they are signed, allowed by the sender's grant, and checked by middleware (part 6).

The read models ​

Create read-models.ts (or read_models.py, src/bin/read_models.rs, read-models/main.go) with the customers:

ts
type CustomerRow = { id: string; email: string; name: string };
const customers = new Map<string, CustomerRow>();

const customersReadmodel = shopDomain.readModel("customers")
  .on("CustomerRegistered", (data: { email: string; name: string }, evt) => {
    customers.set(evt.aggregateId, { id: evt.aggregateId, email: data.email, name: data.name });
  })
  .query("GetCustomer", (data: { id: string }) => {
    const row = customers.get(data.id);
    if (!row) throw new Rejected(`No customer ${data.id}`, "not_found");
    return row;
  });
py
customers: dict[str, dict] = {}
customers_readmodel = shop_domain.read_model("customers")


@customers_readmodel.on("CustomerRegistered")
def _(data, evt):
    customers[evt.aggregate_id] = {"id": evt.aggregate_id, "email": data["email"], "name": data["name"]}


@customers_readmodel.query("GetCustomer")
def _(data):
    if data["id"] not in customers:
        raise Rejected(f"No customer {data['id']}", "not_found")
    return customers[data["id"]]
rs
#[derive(Clone, Serialize, Deserialize)]
struct CustomerRow {
    id: String,
    email: String,
    name: String,
}
#[derive(Deserialize)]
struct Registered {
    email: String,
    name: String,
}
let customers = Arc::new(Mutex::new(HashMap::<String, CustomerRow>::new()));

let rows = Arc::clone(&customers);
let customers_readmodel = shop_domain.read_model("customers").on(
    "CustomerRegistered",
    move |data: Registered, evt, _ctx| {
        let Registered { email, name } = data;
        let id = evt.aggregate_id;
        rows.lock()
            .unwrap()
            .insert(id.clone(), CustomerRow { id, email, name });
        async { Ok(()) }
    },
);
let rows = Arc::clone(&customers);
customers_readmodel.query("GetCustomer", move |data: Id, _qry, _ctx| {
    let row = rows.lock().unwrap().get(&data.id).cloned();
    async move {
        Ok(row.ok_or_else(|| {
            Rejected::new(format!("No customer {}", data.id)).code("not_found")
        })?)
    }
});
go
type CustomerRow struct {
	ID    string  `json:"id"`
	Email *string `json:"email"`
	Name  *string `json:"name"`
}

var customers = map[string]CustomerRow{}

var customersReadModel = shop.Domain.ReadModel("customers")

func init() {
	kernable.On(customersReadModel, "CustomerRegistered", func(ctx *kernable.ListenerContext, d struct{ Email, Name *string }) error {
		customers[ctx.Event.AggregateID] = CustomerRow{ID: ctx.Event.AggregateID, Email: d.Email, Name: d.Name}
		return nil
	})
	kernable.Answer(customersReadModel, "GetCustomer", func(_ *kernable.QueryContext, d byID) (CustomerRow, error) {
		row, ok := customers[d.ID]
		if !ok {
			return row, kernable.Reject("not_found", "No customer "+d.ID)
		}
		return row, nil
	})
}

and the orders:

ts
type OrderRow = { id: string; customerId: string; status: string; items: Record<string, number>; confirmedTo?: string | null; cancelled?: string };
const orders = new Map<string, OrderRow>();

const ordersReadmodel = shopDomain.readModel("orders")
  .on("OrderPlaced", (data: { customerId: string }, evt) => {
    orders.set(evt.aggregateId, { id: evt.aggregateId, customerId: data.customerId, status: "draft", items: {} });
  })
  .on("ItemAdded", (data: { sku: string; qty: number }, evt) => {
    const items = orders.get(evt.aggregateId)!.items;
    items[data.sku] = (items[data.sku] ?? 0) + data.qty;
  })
  .on("OrderSubmitted", (_data, evt) => void (orders.get(evt.aggregateId)!.status = "submitted"))
  .query("GetOrder", (data: { id: string }) => {
    const row = orders.get(data.id);
    if (!row) throw new Rejected(`No order ${data.id}`, "not_found");
    return row;
  });
py
orders: dict[str, dict] = {}
orders_readmodel = shop_domain.read_model("orders")


@orders_readmodel.on("OrderPlaced")
def _(data, evt):
    orders[evt.aggregate_id] = {"id": evt.aggregate_id, "customerId": data["customerId"], "status": "draft",
                              "items": {}}


@orders_readmodel.on("ItemAdded")
def _(data, evt):
    items = orders[evt.aggregate_id]["items"]
    items[data["sku"]] = items.get(data["sku"], 0) + data["qty"]


@orders_readmodel.on("OrderSubmitted")
def _(data, evt):
    orders[evt.aggregate_id]["status"] = "submitted"


@orders_readmodel.query("GetOrder")
def _(data):
    if data["id"] not in orders:
        raise Rejected(f"No order {data['id']}", "not_found")
    return orders[data["id"]]
rs
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct OrderRow {
    id: String,
    customer_id: String,
    status: String,
    items: serde_json::Map<String, serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    confirmed_to: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cancelled: Option<String>,
}
let orders = Arc::new(Mutex::new(HashMap::<String, OrderRow>::new()));

let rows = Arc::clone(&orders);
let orders_readmodel =
    shop_domain
        .read_model("orders")
        .on("OrderPlaced", move |data: Value, evt, _ctx| {
            let customer_id = data["customerId"].as_str().unwrap_or_default().to_owned();
            let id = evt.aggregate_id;
            let row = OrderRow {
                id: id.clone(),
                customer_id,
                status: "draft".into(),
                items: Default::default(),
                confirmed_to: None,
                cancelled: None,
            };
            rows.lock().unwrap().insert(id, row);
            async { Ok(()) }
        });
let rows = Arc::clone(&orders);
orders_readmodel.on("ItemAdded", move |data: Value, evt, _ctx| {
    let (sku, qty) = (
        data["sku"].as_str().unwrap_or_default(),
        data["qty"].as_i64().unwrap_or(0),
    );
    let mut rows = rows.lock().unwrap();
    let items = &mut rows.get_mut(&evt.aggregate_id).expect("placed").items;
    let count = items.get(sku).and_then(|n| n.as_i64()).unwrap_or(0) + qty;
    items.insert(sku.to_owned(), count.into());
    async { Ok(()) }
});
let rows = Arc::clone(&orders);
orders_readmodel.on("OrderSubmitted", move |_: Value, evt, _ctx| {
    rows.lock()
        .unwrap()
        .get_mut(&evt.aggregate_id)
        .expect("placed")
        .status = "submitted".into();
    async { Ok(()) }
});
let rows = Arc::clone(&orders);
orders_readmodel.query("GetOrder", move |data: Id, _qry, _ctx| {
    let row = rows.lock().unwrap().get(&data.id).cloned();
    async move {
        Ok(row
            .ok_or_else(|| Rejected::new(format!("No order {}", data.id)).code("not_found"))?)
    }
});
go
type OrderRow struct {
	ID          string         `json:"id"`
	CustomerID  string         `json:"customerId"`
	Status      string         `json:"status"`
	Items       map[string]int `json:"items"`
	ConfirmedTo *string        `json:"confirmedTo,omitempty"`
	Cancelled   string         `json:"cancelled,omitempty"`
}

var orders = map[string]*OrderRow{}

var ordersReadModel = shop.Domain.ReadModel("orders")

func init() {
	kernable.On(ordersReadModel, "OrderPlaced", func(ctx *kernable.ListenerContext, d shop.Place) error {
		orders[ctx.Event.AggregateID] = &OrderRow{ID: ctx.Event.AggregateID, CustomerID: d.CustomerID, Status: "draft", Items: map[string]int{}}
		return nil
	})
	kernable.On(ordersReadModel, "ItemAdded", func(ctx *kernable.ListenerContext, d shop.Item) error {
		orders[ctx.Event.AggregateID].Items[d.SKU] += d.Qty
		return nil
	})
	kernable.On(ordersReadModel, "OrderSubmitted", func(ctx *kernable.ListenerContext, _ struct{}) error {
		orders[ctx.Event.AggregateID].Status = "submitted"
		return nil
	})
	kernable.Answer(ordersReadModel, "GetOrder", func(_ *kernable.QueryContext, d byID) (*OrderRow, error) {
		row, ok := orders[d.ID]
		if !ok {
			return nil, kernable.Reject("not_found", "No order "+d.ID)
		}
		return row, nil
	})
}

and run both:

ts
const kernable = new Kernable();
await Promise.all([kernable.listener(customersReadmodel).run(), kernable.listener(ordersReadmodel).run()]);
py
threading.Thread(target=k.listener(customers_readmodel).run, daemon=True).start()
k.listener(orders_readmodel).run()
rs
let kernable = Kernable::new(Options::default())?;
let customers_readmodel = kernable.listener(&customers_readmodel);
let orders_readmodel = kernable.listener(&orders_readmodel);
tokio::join!(customers_readmodel.run(), orders_readmodel.run());
go
func main() {
	client, err := kernable.New(kernable.Options{})
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	go func() { log.Fatal(client.Listener(customersReadModel).Run(ctx)) }()
	log.Fatal(client.Listener(ordersReadModel).Run(ctx))
}

A read model is rebuilt from the first event every time it starts; part 8 shows how to keep it in a file instead. Start it next to the worker (node read-models.ts, .venv/bin/python read_models.py, cargo run -q --bin read_models or go run ./read-models).

Read your own writes ​

ts
const getOrder = (id: string) => kernable.query({ domain: "shop", type: "GetOrder", data: { id } });

await send("customer", "c1", "Register", { email: "ann@example.com", name: "Ann" });
await send("order", "o1", "Place", { customerId: "c1" });
await send("order", "o1", "AddItem", { sku: "apple", qty: 2 });
// The submit returned after the read model processed the event: the query sees it.
console.log(await getOrder("o1"));
console.log(await kernable.query({ domain: "shop", type: "GetCustomer", data: { id: "c1" } }));
await getOrder("o9").catch((err) => console.log(`${err.code}: ${err.message}`));
py
def get_order(id):
    return k.query("shop", "GetOrder", {"id": id})


send("customer", "c1", "Register", {"email": "ann@example.com", "name": "Ann"})
send("order", "o1", "Place", {"customerId": "c1"})
send("order", "o1", "AddItem", {"sku": "apple", "qty": 2})
# The submit returned after the read model processed the event: the query sees it.
print(get_order("o1"))
print(k.query("shop", "GetCustomer", {"id": "c1"}))
try:
    get_order("o9")
except Rejected as err:
    print(f"{err.code}: {err}")
rs
let get_order = |id: &str| {
    kernable.query::<Value>(Query::new("shop", "GetOrder").data(json!({ "id": id })))
};

send(
    "customer",
    "c1",
    "Register",
    json!({ "email": "ann@example.com", "name": "Ann" }),
)
.await?;
send("order", "o1", "Place", json!({ "customerId": "c1" })).await?;
send(
    "order",
    "o1",
    "AddItem",
    json!({ "sku": "apple", "qty": 2 }),
)
.await?;
// The submit returned after the read model processed the event: the query sees it.
println!("{}", get_order("o1").await?);
let customer: Value = kernable
    .query(Query::new("shop", "GetCustomer").data(json!({ "id": "c1" })))
    .await?;
println!("{customer}");
if let Err(Error::Rejected(r)) = get_order("o9").await {
    println!("{}: {}", r.code, r.message);
}
go
query := func(queryType, id string) {
	answer, err := client.Query(ctx, kernable.Query{Domain: "shop", Type: queryType, Data: m{"id": id}})
	var rejected *kernable.Rejected
	switch {
	case errors.As(err, &rejected):
		fmt.Printf("%s: %s\n", rejected.Code, rejected.Message)
	case err != nil:
		log.Fatal(err)
	default:
		fmt.Println(string(answer))
	}
}

send("customer", "c1", "Register", m{"email": "ann@example.com", "name": "Ann"})
send("order", "o1", "Place", m{"customerId": "c1"})
send("order", "o1", "AddItem", m{"sku": "apple", "qty": 2})
// The submit returned after the read model processed the event: the query sees it.
query("GetOrder", "o1")
query("GetCustomer", "c1")
query("GetOrder", "o9")
text
{ id: 'o1', customerId: 'c1', status: 'draft', items: { apple: 2 } }
{ id: 'c1', email: 'ann@example.com', name: 'Ann' }
not_found: No order o9
text
{'id': 'o1', 'customerId': 'c1', 'status': 'draft', 'items': {'apple': 2}}
{'id': 'c1', 'email': 'ann@example.com', 'name': 'Ann'}
not_found: No order o9
text
{"id":"o1","customerId":"c1","status":"draft","items":{"apple":2}}
{"id":"c1","email":"ann@example.com","name":"Ann"}
not_found: No order o9
text
{"id":"o1","customerId":"c1","status":"draft","items":{"apple":2}}
{"id":"c1","email":"ann@example.com","name":"Ann"}
not_found: No order o9

The query right after AddItem already shows the apples. By default a submit settles: it returns only after every listener has processed the command's events. There is no polling and no "eventually". If you do not need that, submit with wait: "committed" and it returns once the events are stored.

Next: 4. A reactor.