Appearance
Getting started
In this guide you run a kernel, write business logic and a read model in TypeScript, Python, Rust or Go, in the same language or two different ones, and see that a request reads its own writes. Then you run both as one app.
You need Node.js ≥ 22.18, Python ≥ 3.10, Rust (stable) or Go ≥ 1.26 for the steps you write in them.
1. Install the kernel
sh
curl -fsSL https://kernable.com/install.sh | shThe script installs the kernel on macOS and Linux; on Windows, run it and all the steps below in WSL, with the Linux commands.
It installs kernable into ~/.local/bin; if that is not on your PATH yet, the script says so and how to add it. kernable start runs the kernel, the other commands create keys and grants and verify a log (kernable alone lists them).
2. Start a kernel
sh
mkdir kernable-demo
cd kernable-demo
kernable start --devThe kernel keeps its events in kernable.db in this directory and listens on http://127.0.0.1:7233, for this machine only. --dev also creates the keys this guide uses, among them app.key, which may do everything here. Keys and grants below explains what that means.
--dev also turns on the kernel's UI: open http://127.0.0.1:7234 in a browser. It stays empty until the next steps connect something; then it shows them live.
Leave the kernel running and continue in a second terminal. One kernel per address: if kernable start says 127.0.0.1:7233 is in use, a kernel from an earlier try still runs; stop it first (Ctrl-C in its terminal).
3. Business logic
A shopping cart: commands add items and check it out; events record what happened, and the cart's state is rebuilt from them. Pick TypeScript, Python, Rust or Go; the tabs switch together.
1. Register the aggregate with its initial state:
ts
const shopDomain = domain("shop");
const cartAggregate = shopDomain.aggregate("cart", { items: 0, checkedOut: false });python
shop_domain = domain("shop")
cart_aggregate = shop_domain.aggregate("cart", {"items": 0, "checked_out": False})rust
#[derive(Clone, Default, Serialize, Deserialize)]
struct Cart {
items: u32,
checked_out: bool,
}
let shop_domain = domain("shop");
let cart_aggregate = shop_domain.aggregate("cart", Cart::default());go
type Cart struct {
Items int `json:"items"`
CheckedOut bool `json:"checkedOut"`
}
var shopDomain = kernable.NewDomain("shop")
var cartAggregate = kernable.NewAggregate(shopDomain, "cart", Cart{})2. Apply events to the state:
ts
cartAggregate.apply("ItemAdded", (state, data: { qty: number }) => { state.items += data.qty; });
cartAggregate.apply("CheckedOut", (state) => { state.checkedOut = true; });python
@cart_aggregate.apply("ItemAdded")
def _(state, data):
state["items"] += data["qty"]
@cart_aggregate.apply("CheckedOut")
def _(state, data):
state["checked_out"] = Truerust
#[derive(Serialize, Deserialize)]
struct Item {
sku: String,
qty: u32,
}
cart_aggregate.apply("ItemAdded", |state, data: Item, _evt, _ctx| {
state.items += data.qty
});
cart_aggregate.apply("CheckedOut", |state, _: Value, _evt, _ctx| {
state.checked_out = true
});go
kernable.Apply(cartAggregate, "ItemAdded", func(_ *kernable.ApplyContext, s *Cart, d AddItem) { s.Items += d.Qty })
kernable.Apply(cartAggregate, "CheckedOut", func(_ *kernable.ApplyContext, s *Cart, _ struct{}) { s.CheckedOut = true })3. Decide commands: return events, or reject with Rejected:
ts
cartAggregate.command("AddItem", (state, data: { sku: string; qty: number }) => {
if (state.checkedOut) throw new Rejected("Cart is checked out");
return [{ type: "ItemAdded", data }];
});
cartAggregate.command("CheckOut", (state, _data, _cmd, ctx) => {
if (state.items === 0) throw new Rejected("Cart is empty");
if (state.checkedOut) throw new Rejected("Cart is checked out");
// ctx.now() and ctx.id() stay the same if the command runs again.
return [{ type: "CheckedOut", data: { at: ctx.now().toISOString(), orderId: ctx.id() } }];
});python
@cart_aggregate.command("AddItem")
def _(state, data):
if state["checked_out"]:
raise Rejected("Cart is checked out")
return [{"type": "ItemAdded", "data": data}]
@cart_aggregate.command("CheckOut")
def _(state, data, cmd, ctx):
if state["items"] == 0:
raise Rejected("Cart is empty")
if state["checked_out"]:
raise Rejected("Cart is checked out")
# ctx.now() and ctx.id() stay the same if the command runs again.
return [{"type": "CheckedOut", "data": {"at": ctx.now().isoformat(), "orderId": ctx.id()}}]rust
cart_aggregate.command("AddItem", |state, data: Item, _cmd, _ctx| {
if state.checked_out {
return Err(Rejected::new("Cart is checked out"));
}
Ok(vec![NewEvent::new("ItemAdded", data)])
});
cart_aggregate.command("CheckOut", |state, _: Value, _cmd, ctx| {
if state.items == 0 {
return Err(Rejected::new("Cart is empty"));
}
if state.checked_out {
return Err(Rejected::new("Cart is checked out"));
}
// ctx.now() and ctx.id() stay the same if the command runs again.
Ok(vec![NewEvent::new(
"CheckedOut",
json!({ "at": ctx.now().to_string(), "orderId": ctx.id() }),
)])
});go
kernable.Handle(cartAggregate, "AddItem", func(_ *kernable.CommandContext, s Cart, d AddItem) ([]kernable.NewEvent, error) {
if s.CheckedOut {
return nil, kernable.Reject("", "Cart is checked out")
}
return kernable.Events(kernable.Event("ItemAdded", d)), nil
})
kernable.Handle(cartAggregate, "CheckOut", func(ctx *kernable.CommandContext, s Cart, _ struct{}) ([]kernable.NewEvent, error) {
if s.Items == 0 {
return nil, kernable.Reject("", "Cart is empty")
}
if s.CheckedOut {
return nil, kernable.Reject("", "Cart is checked out")
}
// ctx.Now() and ctx.ID() stay the same if the command runs again.
return kernable.Events(kernable.Event("CheckedOut", map[string]string{"at": ctx.Now().UTC().Format(time.RFC3339Nano), "orderId": ctx.ID()})), nil
})4. Run a worker that executes the cart's commands:
ts
const kernable = new Kernable({ key: "app.key" });
await kernable.worker(cartAggregate).run();python
k = Kernable(key="app.key")
k.worker(cart_aggregate).run()rust
let kernable = Kernable::new("app.key")?;
kernable.worker(&cart_aggregate).run().await;go
client, err := kernable.New(kernable.Options{Key: "app.key"})
if err != nil {
log.Fatal(err)
}
log.Fatal(client.Worker(cartAggregate).Run(context.Background()))In a second terminal, in kernable-demo, set up a project, save the whole file and run it. Leave it running; it prints where it connected and what it runs:
text
12:04:10 worker connected to http://127.0.0.1:7233 · key app (69212a19f36f…) · runs shop.AddItem, shop.CheckOutsh
npm init -y
npm pkg set type=module
npm install @kernable/sdk
# save cart.ts, then (Node ≥ 22.18 runs TypeScript directly):
node cart.tssh
python3 -m venv py
py/bin/pip install kernable-sdk
# save cart.py, then:
py/bin/python cart.pysh
cargo init --name demo
cargo add kernable-sdk serde_json
cargo add serde --features derive
cargo add tokio --features macros,rt-multi-thread
# save src/bin/cart.rs, then:
cargo run --bin cartsh
go mod init demo
go get github.com/kernable/kernable/sdks/go
# save cart/main.go, then:
go run ./cartThe whole file
ts
import { Kernable, Rejected, domain } from "@kernable/sdk";
const shopDomain = domain("shop");
const cartAggregate = shopDomain.aggregate("cart", { items: 0, checkedOut: false });
cartAggregate.apply("ItemAdded", (state, data: { qty: number }) => { state.items += data.qty; });
cartAggregate.apply("CheckedOut", (state) => { state.checkedOut = true; });
cartAggregate.command("AddItem", (state, data: { sku: string; qty: number }) => {
if (state.checkedOut) throw new Rejected("Cart is checked out");
return [{ type: "ItemAdded", data }];
});
cartAggregate.command("CheckOut", (state, _data, _cmd, ctx) => {
if (state.items === 0) throw new Rejected("Cart is empty");
if (state.checkedOut) throw new Rejected("Cart is checked out");
// ctx.now() and ctx.id() stay the same if the command runs again.
return [{ type: "CheckedOut", data: { at: ctx.now().toISOString(), orderId: ctx.id() } }];
});
const kernable = new Kernable({ key: "app.key" });
await kernable.worker(cartAggregate).run();python
from kernable import Kernable, Rejected, domain
shop_domain = domain("shop")
cart_aggregate = shop_domain.aggregate("cart", {"items": 0, "checked_out": False})
@cart_aggregate.apply("ItemAdded")
def _(state, data):
state["items"] += data["qty"]
@cart_aggregate.apply("CheckedOut")
def _(state, data):
state["checked_out"] = True
@cart_aggregate.command("AddItem")
def _(state, data):
if state["checked_out"]:
raise Rejected("Cart is checked out")
return [{"type": "ItemAdded", "data": data}]
@cart_aggregate.command("CheckOut")
def _(state, data, cmd, ctx):
if state["items"] == 0:
raise Rejected("Cart is empty")
if state["checked_out"]:
raise Rejected("Cart is checked out")
# ctx.now() and ctx.id() stay the same if the command runs again.
return [{"type": "CheckedOut", "data": {"at": ctx.now().isoformat(), "orderId": ctx.id()}}]
k = Kernable(key="app.key")
k.worker(cart_aggregate).run()rust
use kernable::{BoxError, Kernable, NewEvent, Rejected, domain};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
#[tokio::main]
async fn main() -> Result<(), BoxError> {
#[derive(Clone, Default, Serialize, Deserialize)]
struct Cart {
items: u32,
checked_out: bool,
}
let shop_domain = domain("shop");
let cart_aggregate = shop_domain.aggregate("cart", Cart::default());
#[derive(Serialize, Deserialize)]
struct Item {
sku: String,
qty: u32,
}
cart_aggregate.apply("ItemAdded", |state, data: Item, _evt, _ctx| {
state.items += data.qty
});
cart_aggregate.apply("CheckedOut", |state, _: Value, _evt, _ctx| {
state.checked_out = true
});
cart_aggregate.command("AddItem", |state, data: Item, _cmd, _ctx| {
if state.checked_out {
return Err(Rejected::new("Cart is checked out"));
}
Ok(vec![NewEvent::new("ItemAdded", data)])
});
cart_aggregate.command("CheckOut", |state, _: Value, _cmd, ctx| {
if state.items == 0 {
return Err(Rejected::new("Cart is empty"));
}
if state.checked_out {
return Err(Rejected::new("Cart is checked out"));
}
// ctx.now() and ctx.id() stay the same if the command runs again.
Ok(vec![NewEvent::new(
"CheckedOut",
json!({ "at": ctx.now().to_string(), "orderId": ctx.id() }),
)])
});
let kernable = Kernable::new("app.key")?;
kernable.worker(&cart_aggregate).run().await;
Ok(())
}go
package main
import (
"context"
"log"
"time"
kernable "github.com/kernable/kernable/sdks/go"
)
type Cart struct {
Items int `json:"items"`
CheckedOut bool `json:"checkedOut"`
}
var shopDomain = kernable.NewDomain("shop")
var cartAggregate = kernable.NewAggregate(shopDomain, "cart", Cart{})
type AddItem struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
func main() {
kernable.Apply(cartAggregate, "ItemAdded", func(_ *kernable.ApplyContext, s *Cart, d AddItem) { s.Items += d.Qty })
kernable.Apply(cartAggregate, "CheckedOut", func(_ *kernable.ApplyContext, s *Cart, _ struct{}) { s.CheckedOut = true })
kernable.Handle(cartAggregate, "AddItem", func(_ *kernable.CommandContext, s Cart, d AddItem) ([]kernable.NewEvent, error) {
if s.CheckedOut {
return nil, kernable.Reject("", "Cart is checked out")
}
return kernable.Events(kernable.Event("ItemAdded", d)), nil
})
kernable.Handle(cartAggregate, "CheckOut", func(ctx *kernable.CommandContext, s Cart, _ struct{}) ([]kernable.NewEvent, error) {
if s.Items == 0 {
return nil, kernable.Reject("", "Cart is empty")
}
if s.CheckedOut {
return nil, kernable.Reject("", "Cart is checked out")
}
// ctx.Now() and ctx.ID() stay the same if the command runs again.
return kernable.Events(kernable.Event("CheckedOut", map[string]string{"at": ctx.Now().UTC().Format(time.RFC3339Nano), "orderId": ctx.ID()})), nil
})
client, err := kernable.New(kernable.Options{Key: "app.key"})
if err != nil {
log.Fatal(err)
}
log.Fatal(client.Worker(cartAggregate).Run(context.Background()))
}More on aggregates and their handlers: Event sourcing.
4. A read model
A read model is a listener: it builds its own view from the events and answers queries from it. Queries always go through the kernel, so signatures and grants apply to every read. The read model doesn't have to be in the worker's language: pick any tab, independent of step 3.
1. Register the read model on the domain, like the aggregate: its event and query types are then the domain's (ItemAdded, GetCart); another domain's would be qualified (billing.InvoicePaid). It keeps its rows in memory and reads every event again when it starts; with a store (sqlite:carts.db) it would keep them in a file and continue where it left off:
ts
const shopDomain = domain("shop");
const cartsReadmodel = shopDomain.readModel("carts");
const rows = new Map<string, { items: number; order?: string }>();python
rows = {}
shop_domain = domain("shop")
carts_readmodel = shop_domain.read_model("carts")rust
#[derive(Clone, Default, Serialize)]
struct Row {
items: u32,
#[serde(skip_serializing_if = "Option::is_none")]
order: Option<String>,
}
let rows = Arc::new(Mutex::new(HashMap::<String, Row>::new()));
let shop_domain = domain("shop");
let carts_readmodel = shop_domain.read_model("carts");go
type Row struct {
Items int `json:"items"`
Order string `json:"order,omitempty"`
}
var shopDomain = kernable.NewDomain("shop")
var cartsReadModel = shopDomain.ReadModel("carts")
var rows = map[string]*Row{}2. Handle events and update the rows:
ts
cartsReadmodel.on("ItemAdded", (data: { qty: number }, evt) => {
const row = rows.get(evt.aggregateId) ?? { items: 0 };
row.items += data.qty;
rows.set(evt.aggregateId, row);
});
cartsReadmodel.on("CheckedOut", (data: { orderId: string }, evt) => {
rows.get(evt.aggregateId)!.order = data.orderId;
});python
@carts_readmodel.on("ItemAdded")
def _(data, evt):
rows.setdefault(evt.aggregate_id, {"items": 0})["items"] += data["qty"]
@carts_readmodel.on("CheckedOut")
def _(data, evt):
rows[evt.aggregate_id]["order"] = data["orderId"]rust
#[derive(Deserialize)]
struct ItemAdded {
qty: u32,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CheckedOut {
order_id: String,
}
let r = Arc::clone(&rows);
carts_readmodel.on("ItemAdded", move |data: ItemAdded, evt, _ctx| {
r.lock().unwrap().entry(evt.aggregate_id).or_default().items += data.qty;
async { Ok(()) }
});
let r = Arc::clone(&rows);
carts_readmodel.on("CheckedOut", move |data: CheckedOut, evt, _ctx| {
r.lock().unwrap().entry(evt.aggregate_id).or_default().order = Some(data.order_id);
async { Ok(()) }
});go
kernable.On(cartsReadModel, "ItemAdded", func(ctx *kernable.ListenerContext, d struct{ Qty int }) error {
row, ok := rows[ctx.Event.AggregateID]
if !ok {
row = &Row{}
rows[ctx.Event.AggregateID] = row
}
row.Items += d.Qty
return nil
})
kernable.On(cartsReadModel, "CheckedOut", func(ctx *kernable.ListenerContext, d struct{ OrderID string }) error {
rows[ctx.Event.AggregateID].Order = d.OrderID
return nil
})3. Answer queries from the rows:
ts
cartsReadmodel.query("GetCart", (data: { id: string }) => {
const row = rows.get(data.id);
if (!row) throw new Rejected("no such cart", "not_found");
return row;
});python
@carts_readmodel.query("GetCart")
def _(data):
if data["id"] not in rows:
raise Rejected("no such cart", "not_found")
return rows[data["id"]]rust
#[derive(Deserialize)]
struct GetCart {
id: String,
}
let r = Arc::clone(&rows);
carts_readmodel.query("GetCart", move |data: GetCart, _qry, _ctx| {
let row = r.lock().unwrap().get(&data.id).cloned();
async move { Ok(row.ok_or_else(|| Rejected::new("no such cart").code("not_found"))?) }
});go
kernable.Answer(cartsReadModel, "GetCart", func(_ *kernable.QueryContext, d struct{ ID string }) (*Row, error) {
row, ok := rows[d.ID]
if !ok {
return nil, kernable.Reject("not_found", "no such cart")
}
return row, nil
})4. Run it through the connection, as the worker runs the aggregate. Read models run before reactors (order 0 and 10), so reactors can query them:
ts
const kernable = new Kernable({ key: "app.key" });
await kernable.listener(cartsReadmodel).run();python
k = Kernable(key="app.key")
k.listener(carts_readmodel).run()rust
let kernable = Kernable::new("app.key")?;
kernable.listener(&carts_readmodel).run().await;go
client, err := kernable.New(kernable.Options{Key: "app.key"})
if err != nil {
log.Fatal(err)
}
log.Fatal(client.Listener(cartsReadModel).Run(context.Background()))In a third terminal, in kernable-demo, set up the language as in step 3 if it is new to you, save the whole file and run it. It prints where it starts and what it reads and answers:
text
12:04:31 listener carts connected to http://127.0.0.1:7233 · key app (69212a19f36f…) · from 0 · reads shop.ItemAdded, shop.CheckedOut · answers shop.GetCartsh
node carts.tssh
py/bin/python carts.pysh
cargo run --bin carts # saved as src/bin/carts.rssh
go run ./carts # saved as carts/main.goThe whole file
ts
import { Kernable, Rejected, domain } from "@kernable/sdk";
const shopDomain = domain("shop");
const cartsReadmodel = shopDomain.readModel("carts");
const rows = new Map<string, { items: number; order?: string }>();
cartsReadmodel.on("ItemAdded", (data: { qty: number }, evt) => {
const row = rows.get(evt.aggregateId) ?? { items: 0 };
row.items += data.qty;
rows.set(evt.aggregateId, row);
});
cartsReadmodel.on("CheckedOut", (data: { orderId: string }, evt) => {
rows.get(evt.aggregateId)!.order = data.orderId;
});
cartsReadmodel.query("GetCart", (data: { id: string }) => {
const row = rows.get(data.id);
if (!row) throw new Rejected("no such cart", "not_found");
return row;
});
const kernable = new Kernable({ key: "app.key" });
await kernable.listener(cartsReadmodel).run();python
from kernable import Kernable, Rejected, domain
rows = {}
shop_domain = domain("shop")
carts_readmodel = shop_domain.read_model("carts")
@carts_readmodel.on("ItemAdded")
def _(data, evt):
rows.setdefault(evt.aggregate_id, {"items": 0})["items"] += data["qty"]
@carts_readmodel.on("CheckedOut")
def _(data, evt):
rows[evt.aggregate_id]["order"] = data["orderId"]
@carts_readmodel.query("GetCart")
def _(data):
if data["id"] not in rows:
raise Rejected("no such cart", "not_found")
return rows[data["id"]]
k = Kernable(key="app.key")
k.listener(carts_readmodel).run()rust
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use kernable::{BoxError, Kernable, Rejected, domain};
use serde::{Deserialize, Serialize};
#[tokio::main]
async fn main() -> Result<(), BoxError> {
#[derive(Clone, Default, Serialize)]
struct Row {
items: u32,
#[serde(skip_serializing_if = "Option::is_none")]
order: Option<String>,
}
let rows = Arc::new(Mutex::new(HashMap::<String, Row>::new()));
let shop_domain = domain("shop");
let carts_readmodel = shop_domain.read_model("carts");
#[derive(Deserialize)]
struct ItemAdded {
qty: u32,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CheckedOut {
order_id: String,
}
let r = Arc::clone(&rows);
carts_readmodel.on("ItemAdded", move |data: ItemAdded, evt, _ctx| {
r.lock().unwrap().entry(evt.aggregate_id).or_default().items += data.qty;
async { Ok(()) }
});
let r = Arc::clone(&rows);
carts_readmodel.on("CheckedOut", move |data: CheckedOut, evt, _ctx| {
r.lock().unwrap().entry(evt.aggregate_id).or_default().order = Some(data.order_id);
async { Ok(()) }
});
#[derive(Deserialize)]
struct GetCart {
id: String,
}
let r = Arc::clone(&rows);
carts_readmodel.query("GetCart", move |data: GetCart, _qry, _ctx| {
let row = r.lock().unwrap().get(&data.id).cloned();
async move { Ok(row.ok_or_else(|| Rejected::new("no such cart").code("not_found"))?) }
});
let kernable = Kernable::new("app.key")?;
kernable.listener(&carts_readmodel).run().await;
Ok(())
}go
package main
import (
"context"
"log"
kernable "github.com/kernable/kernable/sdks/go"
)
type Row struct {
Items int `json:"items"`
Order string `json:"order,omitempty"`
}
var shopDomain = kernable.NewDomain("shop")
var cartsReadModel = shopDomain.ReadModel("carts")
var rows = map[string]*Row{}
func main() {
kernable.On(cartsReadModel, "ItemAdded", func(ctx *kernable.ListenerContext, d struct{ Qty int }) error {
row, ok := rows[ctx.Event.AggregateID]
if !ok {
row = &Row{}
rows[ctx.Event.AggregateID] = row
}
row.Items += d.Qty
return nil
})
kernable.On(cartsReadModel, "CheckedOut", func(ctx *kernable.ListenerContext, d struct{ OrderID string }) error {
rows[ctx.Event.AggregateID].Order = d.OrderID
return nil
})
kernable.Answer(cartsReadModel, "GetCart", func(_ *kernable.QueryContext, d struct{ ID string }) (*Row, error) {
row, ok := rows[d.ID]
if !ok {
return nil, kernable.Reject("not_found", "no such cart")
}
return row, nil
})
client, err := kernable.New(kernable.Options{Key: "app.key"})
if err != nil {
log.Fatal(err)
}
log.Fatal(client.Listener(cartsReadModel).Run(context.Background()))
}5. Submit and read your own writes
A client submits commands and asks the read model. A command names the aggregate it goes to by domain, aggregate type and ID: shop, cart, c1. The comments show the output; the order ID will differ.
ts
import { Kernable } from "@kernable/sdk";
const kernable = new Kernable({ key: "app.key" });
const cartC1 = { domain: "shop", aggregateType: "cart", aggregateId: "c1" };
await kernable.submit({ ...cartC1, type: "AddItem", data: { sku: "apple", qty: 2 } });
// submit returned only after every listener processed the event: no polling needed.
let cart = await kernable.query({ domain: "shop", type: "GetCart", data: { id: "c1" } });
console.log(cart);
// { items: 2 }
await kernable.submit({ ...cartC1, type: "CheckOut" });
cart = await kernable.query({ domain: "shop", type: "GetCart", data: { id: "c1" } });
console.log(cart);
// { items: 2, order: '0b9c5e1a-6f3d-8a42-9c1e-5d7f2b8e4a10' }
const outcome = await kernable.submit({ ...cartC1, type: "AddItem", data: { sku: "pear", qty: 1 } });
console.log(outcome);
// { committed: false, code: 'rejected', message: 'Cart is checked out' }python
from kernable import Kernable
k = Kernable(key="app.key")
cart_c1 = dict(domain="shop", aggregate_type="cart", aggregate_id="c1")
k.submit(**cart_c1, type="AddItem", data={"sku": "apple", "qty": 2})
# submit returned only after every listener processed the event: no polling needed.
cart = k.query(domain="shop", type="GetCart", data={"id": "c1"})
print(cart)
# {'items': 2}
k.submit(**cart_c1, type="CheckOut")
cart = k.query(domain="shop", type="GetCart", data={"id": "c1"})
print(cart)
# {'items': 2, 'order': '0b9c5e1a-6f3d-8a42-9c1e-5d7f2b8e4a10'}
outcome = k.submit(**cart_c1, type="AddItem", data={"sku": "pear", "qty": 1})
print(outcome)
# Outcome(committed=False, events=[], code='rejected', message='Cart is checked out', key='', requirement=None)rust
use kernable::{BoxError, Kernable, Query, Submit};
use serde_json::{Value, json};
#[tokio::main]
async fn main() -> Result<(), BoxError> {
let kernable = Kernable::new("app.key")?;
let get_cart_c1 = Query::new("shop", "GetCart").data(json!({ "id": "c1" }));
let add_apples =
Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "sku": "apple", "qty": 2 }));
kernable.submit(add_apples).await?;
// submit returned only after every listener processed the event: no polling needed.
let cart: Value = kernable.query(get_cart_c1.clone()).await?;
println!("{cart}");
// {"items":2}
kernable
.submit(Submit::new("shop", "cart", "c1", "CheckOut"))
.await?;
let cart: Value = kernable.query(get_cart_c1).await?;
println!("{cart}");
// {"items":2,"order":"0b9c5e1a-6f3d-8a42-9c1e-5d7f2b8e4a10"}
let add_pears =
Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "sku": "pear", "qty": 1 }));
let outcome = kernable.submit(add_pears).await?;
println!("{outcome:?}");
// Rejected(Rejected { code: "rejected", message: "Cart is checked out", key: None, requirement: None })
Ok(())
}go
package main
import (
"context"
"fmt"
"log"
kernable "github.com/kernable/kernable/sdks/go"
)
func main() {
client, err := kernable.New(kernable.Options{Key: "app.key"})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
cartC1 := kernable.Command{Domain: "shop", AggregateType: "cart", AggregateID: "c1"}
command := func(commandType string, data any) kernable.Outcome {
c := cartC1
c.Type, c.Data = commandType, data
outcome, err := client.Submit(ctx, c)
if err != nil {
log.Fatal(err)
}
return outcome
}
getCart := func() string {
cart, err := client.Query(ctx, kernable.Query{Domain: "shop", Type: "GetCart", Data: map[string]string{"id": "c1"}})
if err != nil {
log.Fatal(err)
}
return string(cart)
}
command("AddItem", map[string]any{"sku": "apple", "qty": 2})
// Submit returned only after every listener processed the event: no polling needed.
fmt.Println(getCart())
// {"items":2}
command("CheckOut", nil)
fmt.Println(getCart())
// {"items":2,"order":"0b9c5e1a-6f3d-8a42-9c1e-5d7f2b8e4a10"}
outcome := command("AddItem", map[string]any{"sku": "pear", "qty": 1})
fmt.Printf("committed: %v, %s: %s\n", outcome.Committed, outcome.Code, outcome.Message)
// committed: false, rejected: Cart is checked out
}In a fourth terminal, in kernable-demo, save the file and run it:
sh
node submit.tssh
py/bin/python submit.pysh
cargo run --bin submit # saved as src/bin/submit.rssh
go run ./submit # saved as submit/main.goNow look at it in the UI, http://127.0.0.1:7234:
- Overview: Healthy, and the commands and events so far.
- Explore › Domains: the
shopdomain with the cart, its commands and the events it writes (ItemAdded,CheckedOut), read by the carts read model, which answersGetCart; green dots show both connected and up to date. - Operations: the worker and the read model, each with its key, since when, and how far behind.
- Search
c1: the cart and its events in order, each with the command that caused it and who sent it.
6. One app
The worker and the read model ran as two processes. When they belong together, run them as one app: it runs everything defined on its domains and tells the kernel what the service consists of, so the kernel knows what to wait for (see Remove a listener, middleware or aggregate). In one file with the aggregate and the read model, replace both run blocks with:
ts
await new Kernable({ key: "app.key" })
.app({ service: "shop", version: "1.0.0", domains: [shopDomain] })
.run();python
Kernable(key="app.key").app(service="shop", version="1.0.0", domains=[shop_domain]).run()rust
use kernable::App;
let kernable = Kernable::new("app.key")?;
let app = kernable.app(App::new().service("shop").version("1.0.0").domain(&shop_domain))?;
app.run().await?;go
client, err := kernable.New(kernable.Options{Key: "app.key"})
if err != nil {
log.Fatal(err)
}
app, err := client.App(kernable.AppOptions{Service: "shop", Version: "1.0.0", Domains: []*kernable.Domain{shopDomain}})
if err != nil {
log.Fatal(err)
}
log.Fatal(app.Run(context.Background()))It prints one overview once everything is connected:
text
kernable · shop 1.0.0
kernel http://127.0.0.1:7233 · key app (69212a19f36f…)
membership applied: 1 worker, 1 listener
worker cart runs AddItem, CheckOut
listener carts from 0 · reads ItemAdded, CheckedOut
answers GetCart
ready in 12 msKeys and grants
Every process signs what it sends with its own Ed25519 key, so the kernel and kernable verify know who sent every command and event. A signature proves who sent a message, but anyone can make a key. So the kernel trusts one root key, and the root key grants each key what it may do: which commands it may submit or run, which events it may read, which queries it may ask or answer.
kernable start --dev made a root key, app.key and a grant that lets app do everything; the SDKs send app.grant with every request signed by app.key. In production, every service gets its own key and only the grant it needs, and the root key stays offline:
sh
kernable keys new root && kernable keys new kernel && kernable keys new orders
kernable grant root.key orders.pub 'run=shop.*' 'listen=shop.*' # writes orders.grant
kernable start --root root.pubPart 8 of the shop tutorial sets this up for a whole application; Trust explains the model.
Where to go next
- Build a shop builds an application step by step, in TypeScript, Python, Rust and Go: commands, read models, reactors, an HTTP API with sign-in, operations and a business process. Every part runs as written in the tests (
make check), in each language and mixed, and with each process killed once. - The reference covers every kernel flag, the CLI (also
kernable certs newfor mutual TLS), the SDKs, metrics, the protocol and the exact signed byte layouts, with test vectors to write an SDK for another language. - Rules worth knowing:
- Command handlers must be deterministic. Use
ctx.now()andctx.id(). - Reactors submit with a fixed command ID, so a redelivered event is harmless. Their submits settle on the listeners before them (the read models), not on themselves: a listener handles one event at a time and never waits for itself. The kernel refuses at once what would wait for the sending listener, such as a query to its own read model.
- A domain only writes its own events. It reacts to other domains through listeners.
- Personal data and secrets go to the vault, never into the signed log: mark the fields on the domain (
personal,secret) and erase a person with an erasing event (erases); seeEventSchemaandCommandSchemain the TypeScript SDK. - Events are never changed. To change an event's payload, raise its version and add an upcast from the old one:
shopDomain.event("ItemAdded", 2).upcast(1, (d) => ({ ...d, count: d.qty })). Listeners in other processes and languages need the same definition (use(shopDomain)); a listener that meets an unknown version stops until it is updated.
- Command handlers must be deterministic. Use
