Appearance
Order and consistency
kernable gives you a strict order where it matters and parallelism where it does not.
The rules across aggregates, unique keys and conditions, are below.
What is consistent, and from when
| Consistent | How | |
|---|---|---|
| Within one aggregate | always | one command at a time, committed on the version it was decided on |
| A read after a settled submit | from the moment the submit returns | every listener that counts has processed the events |
A read after a committed submit | from the given position on | ask with minPosition, or the read model may not have it yet |
| Unique keys and required facts | at every commit | the kernel checks them atomically with the commit (unique keys and conditions) |
| Across aggregates | step by step | a reactor turns one aggregate's event into the next command (rules across aggregates); each step is consistent in itself |
| Across domains and tenants | in one global order | every listener sees the same sequence of positions |
Commands
- One at a time per aggregate. The kernel queues commands per aggregate in submission order and leases one at a time to a worker. Commands of different aggregates run in parallel, on as many workers as you start.
- Optimistic commit. A worker's events are committed only on the version they were based on. If the aggregate changed in between, the kernel runs the command again with the new history.
- Idempotent by ID. A command ID is stored with the command. Submitting the same ID again returns the original outcome instead of running it twice: give retried commands a fixed ID.
expected_versionin the request context rejects a command unless the aggregate is still at the version the client saw.
Listeners
Events have a global position. Every listener receives them in that order, one at a time, and acknowledges what it has processed.
There is one order for everything: all domains and all tenants share the global position. A read model that reads shop and billing events sees them interleaved exactly as they were committed (a projection across domains).
- Lower orders first. A listener gets an event only once every listener with a lower order has acknowledged it. Read models default to 0 and reactors to 10, so a reactor's queries always see the event it reacts to. Listeners of the same order run in parallel.
- At least once. After a crash a listener gets the events after its last acknowledgement again. Handlers must be idempotent: reactors submit with fixed command IDs, read models overwrite rather than add. A read model with a store writes data and position together and takes effect exactly once.
Who counts
Not every listener holds the others back. Those that count decide when higher orders get an event, when a submit settles, and when the kernel is ready (/ready):
| Listener | Counts | Why |
|---|---|---|
| registered, in a service without a membership, or without a service | yes | the simple rule: everything registered counts |
| listed in its service's membership | yes, also before it ever connected | the service consists of it (memberships) |
| registered, but not listed in its service's membership | no (dynamic) | it runs, keeps its position, nobody waits for it |
live (live: true) | no | never registered: starts at the newest event, forgotten when it disconnects |
A middleware counts like a listener and fails closed besides: while it is away, what it checks is refused.
A listener that runs as several instances (one per machine, Run a listener on several machines) counts once: it is through an event once one instance has processed it, and caught up once one instance has, so an instance that is gone or rebuilding holds nothing back. A query goes to an instance that has reached its min_position.
When a listener is slow or stuck
A listener that counts and does not acknowledge holds things up, on purpose, rather than letting a reader see an incomplete state:
- Settling submits wait up to
--settle-timeout-ms(default 5 s), then throwNotSettled. The command is committed; only the guarantee that every read model shows it is missing. Retrying with the same command ID returns the same outcome. - Higher orders wait behind it: reactors do not get events the read models before them have not processed.
- The kernel is not ready (
/readyanswers 503 and names the listener), and its UI shows the listener as behind, with how many events. - A listener that is away, not slow, is the same case: it counts until its service's membership no longer lists it, or it is removed (Remove a listener).
Settling: reading your own writes
By default submit settles: it returns once every listener has processed the command's events. The next query, from anyone, sees the change. No polling, no "eventually".
wait | returns when | use it for |
|---|---|---|
settled (default) | every listener processed the events | APIs that read right after writing |
committed | the events are stored | throughput, or when you do not read back |
accepted (enqueue) | the command is stored in the queue | fire and forget; resubmit the ID to get the outcome |
A query can also wait on its own: minPosition answers only after the read model has processed that position.
A settled submit includes the reactions it caused. A reactor (order 10) acknowledges an event only after its handler finished, including the follow-up command it submitted and awaited. So when the original submit settles, the follow-up is committed too, and the read models already show its events. Only reactions the reactor starts without waiting for them come later.
A listener never waits for itself
A listener handles one event at a time, so a request from inside its handler must not wait for that listener. The SDKs name the listener in such requests, and the kernel adapts:
- a settling submit from a listener waits only for listeners of a lower order: a reactor still reads its writes in the read models;
- a query from a listener goes to another read model, or is refused at once instead of timing out;
- a middleware cannot send what it checks itself.
Unique keys and conditions
An aggregate decides alone, on its own history (Event sourcing). Two kinds of rules still reach across aggregates, and the kernel checks both when a command commits:
- Uniqueness. Every fund has its own ISIN, and no two open funds of a tenant share a name. Each fund decides alone, so two funds launched at the same moment with the same ID would both commit.
- A condition on another aggregate. An investor account opens only while its fund is open. A check against a read model before the submit leaves a gap: the fund can be wound up between the check and the commit.
An aggregate declares unique keys and facts, both computed from its own state, and a command declares the facts it requires of other aggregates. Handlers and events do not change.
Unique keys
A unique key is a name and a function of the state that returns the value the aggregate holds:
ts
export const fundsDomain = domain("funds");
type Fund = { status: "none" | "open" | "wound_up"; isin?: string; name?: string };
export const fundAggregate = fundsDomain.aggregate<Fund>("fund", { status: "none" })
.apply("FundLaunched", (_s, data: { isin: string; name: string }) => ({ status: "open", ...data }))
.apply("FundWoundUp", (s) => { s.status = "wound_up"; })
.command("Launch", (s, data: { isin: string; name: string }) => {
if (s.status !== "none") throw new Rejected("Fund already exists", "exists");
return [{ type: "FundLaunched", data: { isin: data.isin, name: data.name } }];
})
.command("WindUp", (s) => {
if (s.status !== "open") throw new Rejected(`Cannot wind up a ${s.status} fund`, "invalid_state");
return [{ type: "FundWoundUp" }];
})
// One ISIN per fund in all tenants, kept after winding up.
.unique("isin", (s) => s.isin?.trim().toUpperCase(), { scope: "global" })
// One name per open fund in each tenant: winding up frees it.
.unique("name", (s) => (s.status === "open" ? s.name?.trim().toLowerCase() : null))
.fact("open", (s) => s.status === "open");python
from kernable import Rejected, Requirement, domain
funds_domain = domain("funds")
fund_aggregate = funds_domain.aggregate("fund", {"status": "none"})
@fund_aggregate.apply("FundLaunched")
def _(state, data):
return {"status": "open", **data}
@fund_aggregate.apply("FundWoundUp")
def _(state, data):
state["status"] = "wound_up"
@fund_aggregate.command("Launch")
def _(state, data):
if state["status"] != "none":
raise Rejected("Fund already exists", "exists")
return [{"type": "FundLaunched", "data": {"isin": data["isin"], "name": data["name"]}}]
@fund_aggregate.command("WindUp")
def _(state, data):
if state["status"] != "open":
raise Rejected(f"Cannot wind up a {state['status']} fund", "invalid_state")
return [{"type": "FundWoundUp"}]
# One ISIN per fund in all tenants, kept after winding up.
fund_aggregate.unique("isin", lambda s: s["isin"].strip().upper() if "isin" in s else None, scope="global")
# One name per open fund in each tenant: winding up frees it.
fund_aggregate.unique("name", lambda s: s["name"].strip().lower() if s["status"] == "open" else None)
fund_aggregate.fact("open", lambda s: s["status"] == "open")rust
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Fund {
status: String, // "", "open" or "wound_up"
isin: Option<String>,
name: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Launch {
isin: String,
name: String,
}
fn fund(funds_domain: &Domain) -> Aggregate<Fund> {
let fund_aggregate = funds_domain.aggregate("fund", Fund::default());
fund_aggregate.apply("FundLaunched", |s, data: Launch, _evt, _ctx| {
s.status = "open".into();
s.isin = Some(data.isin);
s.name = Some(data.name);
});
fund_aggregate.apply("FundWoundUp", |s, _: Value, _evt, _ctx| {
s.status = "wound_up".into()
});
fund_aggregate.command("Launch", |s, data: Launch, _cmd, _ctx| {
if !s.status.is_empty() {
return Err(Rejected::new("Fund already exists").code("exists"));
}
Ok(vec![NewEvent::new(
"FundLaunched",
json!({ "isin": data.isin, "name": data.name }),
)])
});
fund_aggregate.command("WindUp", |s, _: Value, _cmd, _ctx| {
if s.status != "open" {
return Err(Rejected::new("Cannot wind up this fund").code("invalid_state"));
}
Ok(vec![NewEvent::new("FundWoundUp", json!({}))])
});
// One ISIN per fund in all tenants, kept after winding up.
fund_aggregate.unique(
"isin",
|s| s.isin.as_ref().map(|id| id.trim().to_uppercase()),
Unique::global(),
);
// One name per open fund in each tenant: winding up frees it.
fund_aggregate.unique(
"name",
|s| {
s.name
.as_ref()
.filter(|_| s.status == "open")
.map(|n| n.trim().to_lowercase())
},
Unique::tenant(),
);
fund_aggregate.fact("open", |s| s.status == "open");
fund_aggregate
}After every command, also one without events, the worker computes the keys from the new state and sends the full set. The kernel compares it with what the aggregate holds and stores the difference with the commit. So an aggregate always holds exactly what its state yields:
| The function returns | The aggregate holds |
|---|---|
| a string | that value |
| a list of strings | each value once |
null, undefined, None | nothing |
- Freeing cannot be forgotten. A changed value frees the old one in the same commit; a value that becomes null frees it. There is no separate step to release a key.
- Scope.
tenant(the default) makes a value unique within the command's tenant; another tenant may hold the same value.globalmakes it unique across tenants, also when they live on different partitions: the control partition reserves each new global key before it is committed. A personal global key is unique within its partition only. - Per aggregate type. A key belongs to its domain, aggregate type and name:
isinoffunds.fundnever collides with aisinof another aggregate type. - Normalising is yours. The kernel compares the SHA-256 of the value's UTF-8 bytes, so
LU0001andlu0001are two values. Trim, lowercase or format the value in the function. - Deterministic, like
apply: the function sees only the state. If it throws, the command is rejected as for a handler error (handler_error).
Facts and requirements
A fact is a name and a function of the state that says whether the aggregate holds it: the fund above holds open while its status is open. A command declares the facts other aggregates must hold for it to commit:
ts
type Account = { status: "none" | "open"; fundId?: string };
export const accountAggregate = fundsDomain.aggregate<Account>("account", { status: "none" })
.apply("AccountOpened", (_s, data: { fundId: string }) => ({ status: "open", fundId: data.fundId }))
.command(
"OpenAccount",
(s, data: { fundId: string }) => {
if (s.status !== "none") throw new Rejected("Account already exists", "exists");
return [{ type: "AccountOpened", data: { fundId: data.fundId } }];
},
// Commits only while the fund is open, checked by the kernel at commit.
{ requires: (data) => [{ domain: "funds", aggregateType: "fund", aggregateId: data.fundId, fact: "open" }] },
);python
account_aggregate = funds_domain.aggregate("account", {"status": "none"})
@account_aggregate.apply("AccountOpened")
def _(state, data):
return {"status": "open", "fundId": data["fundId"]}
# Commits only while the fund is open, checked by the kernel at commit.
@account_aggregate.command("OpenAccount",
requires=lambda data, state: [Requirement("funds", "fund", data["fundId"], "open")])
def _(state, data):
if state["status"] != "none":
raise Rejected("Account already exists", "exists")
return [{"type": "AccountOpened", "data": {"fundId": data["fundId"]}}]rust
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Account {
fund_id: Option<String>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenAccount {
fund_id: String,
}
fn account(funds_domain: &Domain) -> Aggregate<Account> {
let account_aggregate = funds_domain.aggregate("account", Account::default());
account_aggregate.apply("AccountOpened", |s, data: OpenAccount, _evt, _ctx| {
s.fund_id = Some(data.fund_id)
});
account_aggregate.command("OpenAccount", |s, data: OpenAccount, _cmd, _ctx| {
if s.fund_id.is_some() {
return Err(Rejected::new("Account already exists").code("exists"));
}
Ok(vec![NewEvent::new(
"AccountOpened",
json!({ "fundId": data.fund_id }),
)])
});
// Commits only while the fund is open, checked by the kernel at commit.
account_aggregate.requires("OpenAccount", |_s, data: OpenAccount| {
[Requirement::new("funds", "fund", &data.fund_id, "open")]
});
account_aggregate
}- From the data and the state before the command. The requirement function gets both; a command that requires a fact of its own aggregate sees what the aggregate holds before it.
- Same tenant. A requirement names a domain, an aggregate type, an aggregate ID and a fact, always in the command's tenant. The domain may be another one.
- At commit. The kernel checks what the named aggregate holds at the moment the command commits. If the fund was wound up a moment before, the account is rejected with
requirement_missing. - No lock. A requirement does not hold the fund open afterwards: winding it up later still commits. Blocking a change while other aggregates refer to it is not covered.
By a key, or absent
A requirement can name its aggregate by a unique key of its type instead of its ID: the fund whose isin is FND-lyra. The kernel finds the aggregate that holds the key when the command commits, always in the command's tenant: a global key held in another tenant names no aggregate here, so a requirement never sees another tenant's facts. No aggregate holds it: then none holds the fact either. So a command needs no lookup of the ID first, and the check stays atomic. A requirement can also be absent: the aggregate must not hold the fact. An aggregate without events, or a key nobody holds, holds no fact, so "the vehicle is gone or wound up" is the fact open absent. Without a domain, a requirement is of the command's own domain.
ts
requires: (data) => [
// By the fund's ISIN, normalised as its key function does.
{ domain: "funds", aggregateType: "fund", key: "isin", value: data.fundIsin.toLowerCase(), fact: "open" },
// Only while the vehicle (own domain) is not wound up, or does not exist.
{ aggregateType: "vehicle", aggregateId: data.vehicleId, fact: "woundUp", absent: true },
],python
requires=lambda data, state: [
Requirement.by_key("fund", "isin", data["fundIsin"].lower(), "open", domain="funds"),
Requirement.of("vehicle", data["vehicleId"], "woundUp", absent=True),
]rust
.requires("OpenAccount", |_, d: Open| [
Requirement::by_key("funds", "fund", "isin", &d.fund_isin.to_lowercase(), "open"),
Requirement::of("vehicle", &d.vehicle_id, "woundUp").absent(),
])- The value as the key has it. The kernel compares the SHA-256 of the value: normalise it exactly as the aggregate type's key function does (
toLowerCaseabove), or nobody holds it. - Not personal keys. A personal key lives in the vault and cannot name an aggregate.
- Never the value. A rejection names the key (
funds.fund with key isin does not hold open), never its value;requirement.keysays which, andrequirement.valueis empty.
Personal keys
A key built from personal data, such as an email, names its subject:
ts
type Investor = { investorId?: string; email?: string };
export const investorAggregate = fundsDomain.aggregate<Investor>("investor", {})
.apply("InvestorRegistered", (_s, data: { investorId: string; email: string }) => ({ ...data }))
.command("RegisterInvestor", (s, data: { email: string }, cmd) => {
if (s.investorId) throw new Rejected("Investor already registered", "exists");
return [{ type: "InvestorRegistered", data: { investorId: cmd.aggregateId, email: data.email } }];
})
// A personal key: kept in the vault, freed when the investor is erased.
.unique("email", (s) => s.email?.trim().toLowerCase(), { personal: (s) => s.investorId });
fundsDomain.command("RegisterInvestor").personal(["email"], (_d, id) => id);
fundsDomain.event("InvestorRegistered", 1).personal(["email"], (_d, id) => id);python
investor_aggregate = funds_domain.aggregate("investor", {})
@investor_aggregate.apply("InvestorRegistered")
def _(state, data):
return dict(data)
@investor_aggregate.command("RegisterInvestor")
def _(state, data, cmd):
if "investorId" in state:
raise Rejected("Investor already registered", "exists")
return [{"type": "InvestorRegistered", "data": {"investorId": cmd.aggregate_id, "email": data["email"]}}]
# A personal key: kept in the vault, freed when the investor is erased.
investor_aggregate.unique("email", lambda s: s["email"].strip().lower() if s.get("email") else None,
personal=lambda s: s.get("investorId"))
funds_domain.command("RegisterInvestor").personal(["email"], lambda d, investor_id: investor_id)
funds_domain.event("InvestorRegistered", 1).personal(["email"], lambda d, investor_id: investor_id)rust
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Investor {
investor_id: Option<String>,
email: Option<String>,
}
#[derive(Deserialize)]
struct RegisterInvestor {
email: String,
}
fn investor(funds_domain: &Domain) -> Aggregate<Investor> {
let investor_aggregate = funds_domain.aggregate("investor", Investor::default());
investor_aggregate.apply("InvestorRegistered", |s, data: Investor, _evt, _ctx| {
*s = data
});
investor_aggregate.command(
"RegisterInvestor",
|s, data: RegisterInvestor, cmd, _ctx| {
if s.investor_id.is_some() {
return Err(Rejected::new("Investor already registered").code("exists"));
}
Ok(vec![NewEvent::new(
"InvestorRegistered",
json!({ "investorId": cmd.aggregate_id, "email": data.email }),
)])
},
);
// A personal key: kept in the vault, freed when the investor is erased.
investor_aggregate.unique(
"email",
|s| s.email.as_ref().map(|e| e.trim().to_lowercase()),
Unique::tenant().personal(|s: &Investor| s.investor_id.clone()),
);
let aggregate = |_: &Value, id: &str| id.to_owned();
funds_domain
.command("RegisterInvestor")
.personal(&["email"], aggregate);
funds_domain
.event("InvestorRegistered", 1)
.personal(&["email"], aggregate);
investor_aggregate
}- Kept in the vault. The kernel keeps a personal key in the vault, as a value of its subject, never in the store. The kernel needs a vault (every kernel has one,
--vault-store); without one, the command is rejected withno_vault. - Erasing the subject frees it. After an erasure another aggregate can take the value, and neither the log nor the store keeps a trace of it.
- No subject, no key. A personal key whose subject is empty or null is not held.
- The worker must see the value. Declare the field personal on the command and the event, as above, and grant the worker's key
vault_read: without it the state holdsnull, and the aggregate holds no key.
What the kernel guarantees
The kernel checks keys and requirements while it commits, under the lock that orders commits:
- Never two holders. Two aggregates never hold the same key at the same time. Of two commands racing for one value, exactly one commits; the other is rejected with
unique_taken. - Atomic. The keys and facts an aggregate holds change with its events, in the same commit. A rejected command writes nothing, and is stored as rejected like any other (Errors).
- Never the value. A rejection names the key or the fact, not the value, and not the aggregate that holds it.
- Read from the store. The store files every key by its identity and every aggregate's keys and facts with its stream; a commit looks up what it needs there and the kernel keeps what recently used aggregates hold in memory. So startup and memory do not grow with the number of aggregates, and the kernel never runs your fold code.
| Code | Message | Means |
|---|---|---|
unique_taken | funds.fund key isin is taken | Another aggregate holds a key the command would leave its aggregate with. |
requirement_missing | funds.fund f1 does not hold open, funds.fund with key isin does not hold open, funds.vehicle v1 holds woundUp | An aggregate the command requires does not hold the fact, or holds one it must not. |
invalid_index | says which limit | Too many keys, facts or requirements, or a malformed name: a bug in the aggregate's definition. |
A rejection also names what failed as data, so you need not parse the message: key is the name of the taken key (isin), requirement the requirement that does not hold (domain, aggregate type, ID, fact). In TypeScript and Python they are outcome.key and outcome.requirement, in Rust Rejected::key and Rejected::requirement. Only the kernel sets them, and they are stored with the rejection, so the same command ID gets them back.
- One reason at a time. The kernel checks the requirements first, in the order
requiresreturns them, then the keys. The rejection names the first requirement that does not hold, or else one taken key. Fix that one and submit again: another requirement or key may fail next.
Workers send keys and facts signed over kernable.v1.index (Signatures).
Aggregates from before a key
An aggregate that had events before a key or fact was declared holds nothing of it until its next command. reindex runs a command on each of them now:
ts
const outcomes = await kernable.reindex({ domain: "funds", aggregateType: "fund", aggregateIds: ["f1", "f2"] });
for (const [id, outcome] of outcomes) if (!outcome.committed) console.log(id, outcome.code, outcome.message);python
outcomes = k.reindex("funds", "fund", ["f1", "f2"])
for id, outcome in outcomes.items():
if not outcome.committed:
print(id, outcome.code, outcome.message)rust
let outcomes = kernable.reindex(Reindex::new("funds", "fund", ["f1", "f2"])).await?;
for (id, outcome) in outcomes {
if let Outcome::Rejected(r) = outcome {
println!("{id}: {} {}", r.code, r.message);
}
}- A built-in command. Every aggregate type with keys or facts handles
_reindex_<aggregateType>(here_reindex_fund). It produces no events; the worker sends the set of the current state, and the kernel stores it. Command types starting with_reindex_are reserved for it. - Grants. The worker registers the command, so its key needs
runforfunds._reindex_fund, whichrun=funds.*covers; the client's key needssubmitfor it (Keys per service). - An ID without events holds nothing, and its reindex commits.
- Duplicates from before. If two existing funds share a ISIN, the first to run a command takes the key. The second is rejected with
unique_taken, for every command, until a command changes its value or makes it null. Find duplicates with a read model before you declare a key.
Limits
| Per result (the full set of one aggregate) | At most |
|---|---|
| unique key values | 64 |
| facts | 64 |
| requirements | 64 |
| a key's or fact's name | 128 bytes, not empty, no dots |
The SDKs refuse a name that breaks the rule when the key or fact is declared. A result over a limit is rejected with invalid_index.
What a worker learns
A rejection tells the worker's command something about other aggregates:
- Facts of its tenant. A requirement may name any aggregate of the command's tenant, also in another domain, so a worker learns whether that aggregate holds a fact.
- Values of other tenants. A global key rejects a value another tenant holds, so a worker learns that the value exists somewhere. It never learns where. Use
tenantscope unless the value must be unique across tenants. - The store holds hashes. The kernel never gets a value, only its SHA-256, and files a key under a hash of tenant (unless global), domain, aggregate type, name and that SHA-256. A short value, such as an email, can still be guessed from its hash by whoever reads the store: keep keys built from personal data personal.
Testing
index(state) returns the keys and facts an aggregate holds in a state, without a kernel: fundAggregate.index(state) in TypeScript, fund_aggregate.index(state) in Python, fund_aggregate.index(&state)? in Rust. Use it next to handle (Test your domain). That two aggregates cannot hold one key is the kernel's job: test it against a real kernel.
