Previewkernable is not released yet: these docs describe work in progress, and things may change before 1.0.Not released yet.Request early access →
Skip to content

Getting started ​

In this guide you run a kernel, write business logic and a read model in TypeScript, Python or Rust, in the same language or two different ones, and see that a request reads its own writes. Then you run the reference application.

You need Node.js ≥ 22.18 (step 5 submits from TypeScript), and Python ≥ 3.10 or Rust (stable) for the steps you write in them.

1. Install the kernel ​

Not released yet

kernable is in private preview: the install scripts and the SDK packages (@kernable/sdk on npm, kernable-sdk on PyPI and crates.io) are not public yet, so the commands below do not work for everyone yet. Request early access to get the binaries and the SDKs.

sh
curl -fsSL https://kernable.com/install.sh | sh
powershell
irm https://kernable.com/install.ps1 | iex

This puts kernable on your PATH: 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 --dev

The 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.

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 or Rust; 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());

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"] = True
rust
#[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
});

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");
  // 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")
    # 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"));
    }
    // 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() }),
    )])
});

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;

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.CheckOut
sh
npm init -y
npm pkg set type=module
npm install @kernable/sdk
# save cart.ts, then (Node ≥ 22.18 runs TypeScript directly):
node cart.ts
sh
python3 -m venv py                # Windows: python -m venv py
py/bin/pip install kernable-sdk       # Windows: py\Scripts\pip install kernable-sdk
# save cart.py, then:
py/bin/python cart.py             # Windows: py\Scripts\python cart.py
sh
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 cart
The 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");
  // 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")
    # 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"));
        }
        // 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(())
}

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");

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(()) }
});

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"))?) }
});

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;

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.GetCart
sh
node carts.ts
sh
py/bin/python carts.py            # Windows: py\Scripts\python carts.py
sh
cargo run --bin carts             # saved as src/bin/carts.rs
The 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(())
}

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(())
}

In a fourth terminal, in kernable-demo, save the file and run it:

sh
node submit.ts
sh
py/bin/python submit.py           # Windows: py\Scripts\python submit.py
sh
cargo run --bin submit            # saved as src/bin/submit.rs

Now look at it in the UI, http://127.0.0.1:7234:

  • Overview: Healthy, and the commands and events so far.
  • Explore › Domains: the shop domain with the cart, its commands and the events it writes (ItemAdded, CheckedOut), read by the carts read model, which answers GetCart; 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?;

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 ms

7. The reference application ​

examples/shop is a two-domain shop. The identity domain is written in Python, the orders domain and the HTTP API in TypeScript. A reactor confirms orders using the other domain's read model. Its acceptance tests run everything over TCP with mutual TLS and kill each process once:

sh
make check            # all tests, including examples/shop/shop.test.ts

Keys 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.pub

Part 8 of the shop tutorial sets this up for a whole application; Trust explains the model.

Where to go next ​

  • The reference covers every kernel flag, the CLI (also kernable certs new for 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() and ctx.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); see EventSchema and CommandSchema in 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.