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

Queries and middleware ​

Every read goes through the kernel ​

A read model's state is private to its process. Every other process reads it with a query, sent to the kernel like a command:

  • it is signed, and the key's grant must allow it (query to ask, answer to answer);
  • it passes the middleware chain, exactly like a command;
  • the kernel routes it to a read model that answers its type, in order with that read model's events: the answer reflects every event the read model was sent before the query.

There are no shortcuts, also not inside one process. A shortcut would be the one place where authorization does not apply.

If several read models answer the same type, the kernel spreads queries over them: that is how a read model scales.

Designing queries ​

  • One query type per question: GetCart, ListOpenOrders, GetRevenue. A read model may answer several; each type is answered by read models that keep the data for it.
  • Unknown is a rejection. Throw Rejected with a code (not_found): the client gets it as a result, not as an error.
  • After a committed submit, ask with minPosition, the position of its events: the answer waits until the read model has them. After a settled submit, it is not needed.
  • A listener cannot ask its own read model: the answer would wait behind the event it is handling. The kernel refuses it at once; ask another read model, or keep what you need in the listener itself.
  • No read model connected? The query waits up to --query-timeout-ms (default 5 s) for one, then fails: run read models next to the clients that need them, or several of them.
  • A query about one aggregate says so. GetOrder { id: "o-17" } is about order o-17, but only your code knows that id names an order. Declare it once on the query, static target = { aggregateType: "order", field: "id" } on a query class, or shopDomain.query("GetOrder").target("order", "id") for a query given by name. The SDK then sends the aggregate with the query, signed, and a middleware sees it as check.target, the same as a command's aggregate. That is what lets a rule say "only the order's owner may read it".

Middleware ​

A middleware is a listener that checks commands and queries before the kernel accepts or routes them (or after, see below). It builds its knowledge from events, like a read model, and answers each check from it.

It checks file and cache requests too, before they run, under their own types: <domain>.PutData, .GetData, .DeleteData, .SetCache, .GetCache and .DeleteCache. A middleware that covers shop.* or * gets them; one that covers AddItem does not. It sees who asks (the request context), the tenant, the domain and the key, never the file or the value itself. A refusal reaches the client as PERMISSION_DENIED, with the middleware's code.

  • Registered in code. A listener declares the types it checks and its order; its key needs a grant for check on those types. Negative orders are reserved for kernable's kits: they need a grant of reserved_order. If its service has a membership, it must list the listener as a middleware (membership).
  • A chain. Middlewares run by order, then by name; the first rejection refuses the request. A refused command is never stored.
  • Fails closed. The kernel keeps the registration. While a middleware is away, also right after a kernel restart, every request it covers is refused with UNAVAILABLE. Only a membership of its service that no longer lists it as a middleware, or kernable listeners remove, unregisters it.
  • Never stale. After a reconnect, a middleware is asked only once it has processed every event committed before; checks travel in order with its events.
  • Checks only. A middleware decides; it cannot change a request, because the request is signed.

A whole middleware: it learns who is a customer from events, and refuses shop requests of anyone else.

ts
export const identityDomain = domain("identity");
const known = new Set<string>();
const blocked = new Set<string>();

// A read model that is also a middleware: it learns from events, and decides on every shop request.
export const rbacReadmodel = identityDomain.readModel("rbac")
  .on("CustomerRegistered", (_data, evt) => void known.add(evt.aggregateId))
  .on("CustomerBlocked", (_data, evt) => void blocked.add(evt.aggregateId))
  .middleware({ types: ["shop.*"], order: 0 }, (check) => {
    const who = check.request.senderIdentity;
    if (!who) throw new Rejected("who are you?", "unauthenticated");
    if (!known.has(who)) throw new Rejected(`${who} is no customer`, "unknown_customer");
    if (blocked.has(who)) throw new Rejected(`${who} is blocked`, "blocked");
  });
python
identity_domain = domain("identity")
rbac_readmodel = identity_domain.read_model("rbac")
known, blocked = set(), set()

@rbac_readmodel.on("CustomerRegistered")
def _(data, evt):
    known.add(evt.aggregate_id)

@rbac_readmodel.on("CustomerBlocked")
def _(data, evt):
    blocked.add(evt.aggregate_id)

@rbac_readmodel.middleware(["shop.*"], order=0)
def _(check):
    who = check.request.sender_identity
    if not who:
        raise Rejected("who are you?", "unauthenticated")
    if who not in known:
        raise Rejected(f"{who} is no customer", "unknown_customer")
    if who in blocked:
        raise Rejected(f"{who} is blocked", "blocked")
rust
let identity_domain = domain("identity");
let known = Arc::new(Mutex::new(HashSet::new()));
let blocked = Arc::new(Mutex::new(HashSet::new()));
let (k, b) = (Arc::clone(&known), Arc::clone(&blocked));
let rbac_readmodel = identity_domain
    .read_model("rbac")
    .on("CustomerRegistered", move |_: Value, evt, _ctx| {
        k.lock().unwrap().insert(evt.aggregate_id);
        async { Ok(()) }
    })
    .on("CustomerBlocked", move |_: Value, evt, _ctx| {
        b.lock().unwrap().insert(evt.aggregate_id);
        async { Ok(()) }
    });
let (k, b) = (Arc::clone(&known), Arc::clone(&blocked));
rbac_readmodel.middleware(MiddlewareOptions::new(&["shop.*"]), move |check| {
    let who = check.request.sender_identity.clone();
    let refusal = if who.is_empty() {
        Some(Rejected::new("who are you?").code("unauthenticated"))
    } else if !k.lock().unwrap().contains(&who) {
        Some(Rejected::new(format!("{who} is no customer")).code("unknown_customer"))
    } else if b.lock().unwrap().contains(&who) {
        Some(Rejected::new(format!("{who} is blocked")).code("blocked"))
    } else {
        None
    };
    async move { refusal.map_or(Ok(()), |r| Err(r.into())) }
});

Run it like any read model; its key needs listen for the identity events and check for shop.*.

What middleware is for ​

MiddlewareRunsDecides on
authorization (rbac)beforethe sender, and who owns what, from events
tenant isolationbeforesenderTenant against the request's tenant, for commands, queries, files and cache values
quota, rate limitbeforecounts from events, per sender or per aggregate
maintenance mode, feature flagbeforea switch, kept as an event
privacy filterafter a querythe answer against the asker
audit of refusalsafter a commandrejections, which never become events

What it costs ​

Every request a middleware covers waits for it: one round trip per middleware in the chain, in order. So keep the decision in memory, from what the middleware learned from events, with no calls to databases or other services. A middleware that does not answer within --middleware-timeout-ms (default 5 s) refuses the request; the kernel's metrics (kernable_middleware_seconds, passed and rejected counts) show what the chain costs. Cover only the types that need a check: shop.* rather than *.

Middleware after a request ​

A middleware can also run after a request (when: "after"); a listener has at most one before and one after. After a request, the handler gets the request and what came of it:

RequestOutcomeWhat the middleware can do
query, answeredthe responserefuse it: the client gets the rejection instead. Fails closed, like before.
query, rejectedcode and messageobserve
commandcommitted with its events, or rejected (also by a middleware before)observe

Observing is best effort: the kernel tells the middleware once the command completes, also for wait: "accepted" and for commands that finish after a kernel restart, but nobody waits for it, and what happens while it is away is missed. For anything that must not be missed, use a reactor: events are delivered at least once. Middleware after a request gets no vault values, and like before it changes nothing.

Typical uses: an audit trail of refused requests, which never become events; keeping a query from returning data the asker must not see.

The request context ​

Every command and query carries a signed request context. The kernel stores it with every event the command causes, and middleware decides on it. follow() gives a follow-up command the context of the event that caused it.

FieldMeans
senderIdentitythe person or system the request is for: who middleware checks
senderTenant, senderAccount, senderSessionthe sender's tenant, account and session, as your application defines them
onBehalfOfact as this identity of the target tenant; the sender stays the real principal
correlationIdshared by everything one original request causes; defaults to the command ID
causationIdthe command that caused this one (follow() sets it)
traceIdyour tracing system's ID
expectedVersionreject the command (version_mismatch) unless the aggregate is still at this version
bypassAuthorizationprivileged: only keys granted privileged for it may set it; what it means, middleware decides
attributesfree key-value pairs for business data, never for security decisions