Skip to content

Business processes ​

A business process is a flow across commands, events and queries: a confirmed order is paid within 3 days and shipped, else cancelled. Without help, such a flow ends up spread over reactors, scheduled commands and a read model that remembers where each order stands, and nobody can see it. In kernable you define it once, in code next to your domain; the kernel runs it, keeps every step in the log, and its UI shows the diagram, where each case stands, and statistics.

A process is optional, and it builds on the other pieces: it sends ordinary commands to your aggregates and waits for the events they write; it never changes your data itself. "When X, do Y" is a reactor; a process is for flows that wait, have deadlines, and whose cases you want to see (Do you need a process?). An example below follows an account's onboarding from start to end.

A process ​

The shop's fulfilment, from part 10 of the tutorial:

ts
// How long a customer has to pay; PAY_WITHIN=10s to try it.
const payWithin = (process.env.PAY_WITHIN ?? "3d") as Duration;

export const fulfilment = shopDomain.process("fulfilment")
  .start("OrderConfirmed", { key: "aggregateId", data: { orderId: "aggregateId" } })
  .wait("paid", "OrderPaid", { key: "aggregateId", timeout: payWithin, onTimeout: "cancel" })
  .command("ship", "order.Ship", { aggregate: "case.orderId", next: "shipped" })
  .command("cancel", "order.Cancel", { aggregate: "case.orderId", data: { reason: value("unpaid") } })
  .end("unpaid")
  .end("shipped");
py
# How long a customer has to pay; PAY_WITHIN=10s to try it.
pay_within = os.environ.get("PAY_WITHIN", "3d")

fulfilment = (
    shop_domain.process("fulfilment")
    .start("OrderConfirmed", key="aggregate_id", data={"order_id": "aggregate_id"})
    .wait("paid", "OrderPaid", key="aggregate_id", timeout=pay_within, on_timeout="cancel")
    .command("ship", "order.Ship", aggregate="case.order_id", next="shipped")
    .command("cancel", "order.Cancel", aggregate="case.order_id", data={"reason": value("unpaid")})
    .end("unpaid")
    .end("shipped")
)
rs
fn process(shop_domain: &Domain) -> Process {
    // How long a customer has to pay; PAY_WITHIN=10s to try it.
    let pay_within = std::env::var("PAY_WITHIN").unwrap_or_else(|_| "3d".into());

    shop_domain
        .process("fulfilment")
        .start_named(
            "OrderConfirmed",
            Start::key("aggregate_id").data([("order_id", "aggregate_id")]),
        )
        .wait_named(
            "paid",
            "OrderPaid",
            Wait::key("aggregate_id").timeout(&pay_within, "cancel"),
        )
        .command_named(
            "ship",
            "order.Ship",
            Send::aggregate("case.order_id").next("shipped"),
        )
        .command_named(
            "cancel",
            "order.Cancel",
            Send::aggregate("case.order_id").data([("reason", value("unpaid"))]),
        )
        .end("unpaid")
        .end("shipped")
}
go
// How long a customer has to pay; PAY_WITHIN=10s to try it.
var payWithin = cmp(os.Getenv("PAY_WITHIN"), "3d")

var Fulfilment = Domain.Process("fulfilment").
	Start("OrderConfirmed", kernable.StartOptions{Key: "aggregateId", Data: kernable.Mapping{"orderId": "aggregateId"}}).
	Wait("paid", "OrderPaid", kernable.WaitStep{Key: "aggregateId", Timeout: payWithin, OnTimeout: "cancel"}).
	Command("ship", "order.Ship", kernable.CommandStep{Aggregate: "case.orderId", Next: "shipped"}).
	Command("cancel", "order.Cancel", kernable.CommandStep{Aggregate: "case.orderId", Data: kernable.Mapping{"reason": kernable.Value("unpaid")}}).
	End("unpaid").
	End("shipped")

The SDK turns this into a model, plain JSON, and the kernel runs it. One engine, in the kernel, runs the processes of every language; your processes only define and register them.

StepDoesOptions
start(Event, …)starts a case when the event commitskey: where the case's key is; data: the case's data from the event
command(name, Command, …)sends the commandaggregate, data, rejected (code → step), next
wait(name, Event, …)waits for an event of this casekey, data (merged into the case's data), timeout with onTimeout, next
timer(name, …)waits for a timeafter (a duration) or at (a field of the case holding a time in ms), next
decide(name, …)picks a path by the case's datawhen with then, or a list of them; otherwise
query(name, Query, …)asks a read model; its answer picks the pathdata, answer, paths, into, otherwise
end(name)ends the case
cancelOn(Event, …)ends a running case at once when the event comes, at any step (not a step itself)key, end: an end step
  • Steps run in the order written, unless a step names next. Step names are required: the UI, the statistics and new versions know a step by its name.
  • References say where a value comes from: aggregateId and data.<field> of the event being handled (in start and wait), case.<field> of the case's data, and in a query step answer or answer.<field>. Python and Rust write fields in their own style (case.order_id); the SDK converts them. Go writes them as on the wire (case.orderId). A literal is value(…).
  • Conditions (decide) are small expressions on the case's data: references, numbers, strings, true, false, null, == != < <= > >=, and, or, not and parentheses: case.total > 1000 and not case.trusted. Anything more is a query to a read model you write.
  • Durations are 30s, 15m, 12h or 3d.
  • Names: an event or query without a domain is of the process's domain; a command is aggregate.Command (order.Ship) or domain.aggregate.Command. Classes work too; in Rust the typed steps take the type (command::<Ship>) and start_named, wait_named, command_named and query_named take a name.

No other logic runs in the kernel: what a step does is a command, and what decides is the case's data or a read model's answer.

How a case runs ​

  • It starts when its start event commits: one case per key (here the order). While a case for a key runs, another start event for that key is ignored; after it ended, the next one starts a new case. Cases are numbered per key: o1#1, then o1#2.
  • A command step sends its command and waits for the outcome. Its ID is fixed by the case and the step, so a crash or a failover never sends it twice. Committed, the case goes on. Rejected, it goes to the step rejected names for that code; any other rejection stops the case as an incident.
  • A wait completes with the first event of its type whose key is the case's. An event that comes before the case reaches its wait (a fast payment, a slow confirmation) is kept for the case and counts when it gets there.
  • A cancelling event (cancelOn) of the case's key ends it at once at the end step named, whatever step it is at: its timer is withdrawn, a command or query it still awaits is ignored when it comes, an incident ends with it. Events the case's own commands caused (their correlation is the case) do not cancel it, so a step that closes the account does not cut its own case short.
  • A timeout or a timer is a scheduled command of the case, cancelled when the awaited event comes first. It survives restarts, failover and moves like any other.
  • A query step asks with the position of the event that moved the case, so the read model has seen it (reading your own writes). While no read model answers (one reconnecting after a restart, say), it asks again every second, for up to 30 s, before the case stops as an incident query_failed.
  • Tenants: a case lives in the tenant of the event that started it, and its commands, queries and waits stay in that tenant. With partitions, each partition runs the cases of its own tenants, and a tenant's running cases move with it. An event a case kept early for a later wait does not move with it: the case waits on the target for that event again (or its timeout), and the kernel logs a warning naming the case.

Cases in the log ​

Each case is an aggregate of its own: domain process, type the process's name, ID the case's. Its events say what happened, in order:

EventWhen
ProcessStartedthe case started: the version, the key, the case's data, the event that started it
StepReachedthe case reached a step
CommandSenta command step sent its command (with its ID)
StepCompleteda step completed: how (committed, event, timeout, answer, a rejection code, skipped), and the step next
TimerSet, TimerFireda timeout or a timer was set, and fell due
EventKeptan event a later wait of the case may need came early
IncidentRaised, IncidentResolvedthe case stopped, and an operator resolved it
CaseCancelledan event named in cancelOn ended the case: the step it was at, the event and its position, the end
ProcessEndedthe case ended, at which end

The kernel writes and signs them itself; kernable verify refuses case events signed by any other key. Because they are ordinary events, backups, the standby, exports and the UI's Explore cover cases like everything else, and you can read them like any other events.

As whom a process acts ​

The engine's commands and queries carry the request context senderIdentity: "process:shop.fulfilment", with the case in correlationId (shop.fulfilment/o1#1) and the process and case attributes. Your middleware decides on them as on any sender: in the tutorial, the guard lets process:shop.fulfilment send Ship and Cancel. With the kit, each process gets an identity and an API key of its own, with permissions through groups like a service.

Registering, versions and removing ​

kernable.app({ domains }) registers the processes of its domains once its workers are connected; kernable.registerProcess(fulfilment) does it on its own, for example in a deploy script. The key needs a grant process for the process, and submit for each command, query for each query and listen for each event its model names: a process never does more than the key that registered it. The kernel checks the model when it is registered (every step reachable, every target a step, every condition well-formed, every command type known), so a typo fails the deploy and names the step, not a case later.

  • Versions: registering the same model again changes nothing. A changed one becomes the next version: new cases start on it, running cases finish on the version they started with.
  • Removing: a process the service's membership no longer lists, or one removed with kernable processes remove, starts no new cases; its running cases finish. Registering it again makes it active.

Incidents ​

When a case cannot go on, it stops as an incident: a rejection with no path for its code, a query that fails or has no path for its answer, a missing field the step needs, or decisions that loop (the codes). Nothing is lost: the case waits at its step. Fix the cause, then resolve it, signed with an operator's key granted process for the process:

sh
kernable processes retry  <addr> <key> shop.fulfilment o1#1   # run the step again
kernable processes skip   <addr> <key> shop.fulfilment o1#1   # go on to the step's next step
kernable processes cancel <addr> <key> shop.fulfilment o1#1   # end the case

The resolution is an event of the case (IncidentResolved, with the key that signed it).

Watching processes ​

  • The UI's Processes draw each version as a diagram (left to right, or top to bottom when it is long), each path as wide as the cases that took it, with the cases at each step now, incidents in red, and the conditions of its decisions; show outcomes over time and how long open cases have waited; list the cases and tell one, at its own address, as a story linked to the aggregates it touched, with its incident and the commands that resolve it first; over the last hour, day or week (Monitor kernable). Explore's Catalog lists every process with what it starts on, waits for, sends and asks, and its open cases and incidents.
  • Metrics: kernable_process_cases by process and state, kernable_process_incidents and kernable_process_step_seconds per step (Metrics).
  • The command line: kernable processes list, show, cases and case read the store, also with the kernel stopped (CLI).

An example: onboarding an account ​

The onboarding: a KYC check that a person approves or rejects, the account activated, the email address confirmed, with deadlines and reminders. Each part does one job:

PartDoes
Aggregate accounttakes Open, RequestKyc, DecideKyc, Activate, SendVerification, ConfirmEmail, Close, and writes AccountOpened, KycRequested, KycDecided, AccountActivated, …
Reactor kyc-provideron KycRequested, calls the KYC provider; its result (a webhook) comes back into your API
Your back officea reviewer approves or rejects: it sends DecideKyc { approved }
Reactor maileron VerificationSent, sends the email with the confirmation link
Your APIthe user clicks the link: it sends ConfirmEmail
Process accounts.onboardingsays what comes next: sends the commands, waits for the events, keeps the deadlines

The process, defined next to the domain:

ts
export const onboarding = accounts.process("onboarding")
  .start("AccountOpened", { key: "aggregateId", data: { accountId: "aggregateId" } })
  .command("request-kyc", "account.RequestKyc", { aggregate: "case.accountId" })
  // A person decides: the process waits for the event their command writes.
  .wait("kyc", "KycDecided", { key: "aggregateId", data: { approved: "data.approved" }, timeout: "3d", onTimeout: "kyc-overdue" })
  .decide("kyc-result", { when: "case.approved == true", then: "activate", otherwise: "reject" })
  .command("activate", "account.Activate", { aggregate: "case.accountId" })
  .command("verify-email", "account.SendVerification", { aggregate: "case.accountId" })
  .wait("email", "EmailConfirmed", { key: "aggregateId", timeout: "2d", onTimeout: "remind", next: "onboarded" })
  .command("remind", "account.SendVerification", { aggregate: "case.accountId" })
  .wait("email-late", "EmailConfirmed", { key: "aggregateId", timeout: "7d", onTimeout: "abandoned", next: "onboarded" })
  .command("kyc-overdue", "account.EscalateKyc", { aggregate: "case.accountId", next: "kyc" })
  .command("reject", "account.Close", { aggregate: "case.accountId", next: "rejected" })
  .end("onboarded")
  .end("rejected")
  .end("abandoned")
  .end("closed")
  // The customer closes the account during onboarding: the case ends at once.
  .cancelOn("AccountClosed", { key: "aggregateId", end: "closed" });
python
onboarding = (
    accounts.process("onboarding")
    .start("AccountOpened", key="aggregate_id", data={"account_id": "aggregate_id"})
    .command("request-kyc", "account.RequestKyc", aggregate="case.account_id")
    # A person decides: the process waits for the event their command writes.
    .wait("kyc", "KycDecided", key="aggregate_id", data={"approved": "data.approved"}, timeout="3d", on_timeout="kyc-overdue")
    .decide("kyc-result", when="case.approved == true", then="activate", otherwise="reject")
    .command("activate", "account.Activate", aggregate="case.account_id")
    .command("verify-email", "account.SendVerification", aggregate="case.account_id")
    .wait("email", "EmailConfirmed", key="aggregate_id", timeout="2d", on_timeout="remind", next="onboarded")
    .command("remind", "account.SendVerification", aggregate="case.account_id")
    .wait("email-late", "EmailConfirmed", key="aggregate_id", timeout="7d", on_timeout="abandoned", next="onboarded")
    .command("kyc-overdue", "account.EscalateKyc", aggregate="case.account_id", next="kyc")
    .command("reject", "account.Close", aggregate="case.account_id", next="rejected")
    .end("onboarded")
    .end("rejected")
    .end("abandoned")
    .end("closed")
    # The customer closes the account during onboarding: the case ends at once.
    .cancel_on("AccountClosed", key="aggregate_id", end="closed")
)
rust
let onboarding = accounts
    .process("onboarding")
    .start_named("AccountOpened", Start::key("aggregate_id").data([("account_id", "aggregate_id")]))
    .command_named("request-kyc", "account.RequestKyc", Send::aggregate("case.account_id"))
    // A person decides: the process waits for the event their command writes.
    .wait_named("kyc", "KycDecided", Wait::key("aggregate_id").data([("approved", "data.approved")]).timeout("3d", "kyc-overdue"))
    .decide("kyc-result", Decide::when("case.approved == true", "activate").otherwise("reject"))
    .command_named("activate", "account.Activate", Send::aggregate("case.account_id"))
    .command_named("verify-email", "account.SendVerification", Send::aggregate("case.account_id"))
    .wait_named("email", "EmailConfirmed", Wait::key("aggregate_id").timeout("2d", "remind").next("onboarded"))
    .command_named("remind", "account.SendVerification", Send::aggregate("case.account_id"))
    .wait_named("email-late", "EmailConfirmed", Wait::key("aggregate_id").timeout("7d", "abandoned").next("onboarded"))
    .command_named("kyc-overdue", "account.EscalateKyc", Send::aggregate("case.account_id").next("kyc"))
    .command_named("reject", "account.Close", Send::aggregate("case.account_id").next("rejected"))
    .end("onboarded")
    .end("rejected")
    .end("abandoned")
    .end("closed")
    // The customer closes the account during onboarding: the case ends at once.
    .cancel_on_named("AccountClosed", "aggregate_id", "closed");

One account, from start to end. Each line is a command (──Name──▶) or an event (▶ Name):

Your API      ──Open──────────────▶ account a-17  ▶ AccountOpened
Kernel        AccountOpened starts the case a-17#1
Process       ──RequestKyc────────▶ account a-17  ▶ KycRequested
Reactor       KycRequested: calls the KYC provider
Back office   ──DecideKyc─────────▶ account a-17  ▶ KycDecided { approved: true }
Process       the wait "kyc" completes; decides; ──Activate──▶ account a-17  ▶ AccountActivated
Process       ──SendVerification──▶ account a-17  ▶ VerificationSent
Reactor       VerificationSent: sends the email
Your API      the user clicks the link; ──ConfirmEmail──▶ account a-17  ▶ EmailConfirmed
Process       the wait "email" completes: the case ends at "onboarded"

The process never writes AccountActivated itself and never changes the account: it asks, and the account decides. Its own notes, where each case stands, are events of the case (domain process), which the UI reads (Cases in the log).

When something else happens meanwhile ​

A case reacts only to the events it waits for at its current step, with its key. Everything else in the log goes past it. Three situations:

  • The awaited event comes early. The user confirms the email before the case reaches the step email. The kernel keeps the event for the case; when the case gets there, the wait completes at once.
  • An event the process does not care about. Support changes the account's address. The case goes on as before.
  • An event that should stop the case. The customer closes the account during onboarding. Name it with cancelOn: the case ends at once at the end step you give (closed), whatever step it is at. Its timer is withdrawn, a command it still awaits is ignored, and an incident ends with it. Without cancelOn, the case would notice only at its next command, which the closed account refuses; give that rejection a path (rejected: { closed: "closed" }), or the case stops as an incident.

Events the case's own commands caused do not cancel it: the step reject sends Close, the account writes AccountClosed, and the case still ends at rejected, where it was going.

What a process does not do ​

  • Talk to the outside. Calls to other services, emails and webhooks belong in reactors and your API; their results come back as commands. So the log stays the record of what happened, and a case can be replayed.
  • Write your events or change your data. Only aggregates do, through commands.
  • Give people a task list. Approving a KYC check is your back office's screen; the process waits for the command it sends. A read model, or the cases waiting at kyc, give that screen its list.
  • Move running cases to a new version. A changed process is a new version; running cases finish on theirs (Versions).

The tutorial's part 10 builds a process in the shop.

Not yet ​

Processes are edited in code only; the UI shows them. There are no human tasks ("wait for a person's decision" is a wait for the event their command writes), and running cases are not moved to a new version.