Decision
Every command is decided once. An aggregate decides the ones that concern it alone. A decision decides one that involves several aggregate instances: it reads them, decides against all of their states together, and records events on them. Every event commits, or none does.
In the example bank, a transfer is a decision: it debits one account and credits another in one step.
A rule that spans two instances
Section titled “A rule that spans two instances”An aggregate instance decides alone. It sees its own state and nothing else, so an account can refuse an overdraft but can’t know whether the account it pays exists.
Without a decision, a rule about two instances becomes a conversation between them: a policy or a saga sends one command, waits for its event, and sends the next. In between, only half of it has happened, so each side needs a state for “pending” and a way to undo.
A decision has no in-between. Use one when the rule should be answered at once and should never be half done.
Declare the command
Section titled “Declare the command”A command’s input names every instance it involves. A transfer involves two accounts, so it has a from and a to.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { AccountId } from "./Account.id.ts";
export class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { balance: Schema.Int,}) {}
export class TransferSent extends Domain.Event("TransferSent", { to: AccountId, amount: Schema.Int,}) {}
export class TransferReceived extends Domain.Event("TransferReceived", { from: AccountId, amount: Schema.Int,}) {}
export class TransferMoney extends Domain.Command("TransferMoney", { input: { from: AccountId, to: AccountId, amount: Schema.Int }, events: [TransferSent, TransferReceived], rejects: [InsufficientFunds],}) {}Everything else about the command is the same: its events, its rejections, its reply and its middleware.
Let the aggregate fold the events
Section titled “Let the aggregate fold the events”A decision keeps no state. Each event it records lands on one aggregate instance, which folds it with its own evolve.
List those events in the aggregate’s events, and give evolve a handler for each.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { AccountId } from "./Account.id.ts";import { DepositMoney, MoneyDeposited } from "./DepositMoney.command.ts";import { TransferReceived, TransferSent } from "./TransferMoney.command.ts";
export class Account extends Domain.Aggregate("Account", { id: AccountId, state: Schema.Struct({ balance: Schema.Int }), initial: { balance: 0 }, commands: [DepositMoney], keyOf: (cmd) => cmd.accountId, events: [TransferSent, TransferReceived], decide: { DepositMoney: (_, cmd) => [new MoneyDeposited({ amount: cmd.amount })], }, evolve: { MoneyDeposited: (account, e) => ({ balance: account.balance + e.amount }), TransferSent: (account, e) => ({ balance: account.balance - e.amount }), TransferReceived: (account, e) => ({ balance: account.balance + e.amount }), },}) {}The account still decides its own commands. DepositMoney goes to one account, so it stays there.
Decide against every instance
Section titled “Decide against every instance”A decision takes the command it implements, the aggregates it reads, which instances of them a command names, and how it decides.
import * as Domain from "@alchemy.run/domain";import { Account } from "./Account.aggregate.ts";import { InsufficientFunds, TransferMoney, TransferReceived, TransferSent,} from "./TransferMoney.command.ts";
export class Transfer extends Domain.Decision(TransferMoney, { reads: { from: Account, to: Account }, keyOf: (cmd) => ({ from: cmd.from, to: cmd.to }), decide: ({ from, to }, cmd) => cmd.amount > from.state.balance ? new InsufficientFunds({ balance: from.state.balance }) : [ from.record(new TransferSent({ to: to.id, amount: cmd.amount })), to.record(new TransferReceived({ from: from.id, amount: cmd.amount })), ],}) {}reads names the aggregates, each under a key. It is a plain value, so the model knows which aggregates a decision touches before any command arrives.
keyOf gives the id of the instance behind each key. It depends only on the command, so the same command always involves the same instances.
decide receives each instance under its key, with its id, its state and its version. It returns one of the command’s rejections, or the events to record.
Record each event on one instance
Section titled “Record each event on one instance”An event is recorded on an instance with that instance’s record. from.record(...) puts TransferSent in the sending account’s history, and to.record(...) puts TransferReceived in the receiving account’s.
record takes only events the instance folds. Recording a TransferSent on a Customer is a type error.
An empty array accepts the command and records nothing, as it does in an aggregate.
Add it to the model
Section titled “Add it to the model”List the decision next to the aggregates it reads.
import * as Domain from "@alchemy.run/domain";import { Account } from "./Account/Account.aggregate.ts";import { Transfer } from "./Account/Transfer.decision.ts";
export class Bank extends Domain.Model("Bank", { aggregates: [Account], decisions: [Transfer],}) {}Every command has one implementation: an aggregate or a decision. A second one is a type error on its entry in the model, and building the model’s Layer fails with ImplementedTwice.
A decision that reads an aggregate the model leaves out is a type error on its entry too, and building the Layer fails with UnknownRead.
Send it
Section titled “Send it”The decision’s class is a service tag. yield* it for its client, and send the command with no id beside it.
import * as Effect from "effect/Effect";import { AccountId } from "./Account.id.ts";import { Transfer } from "./Transfer.decision.ts";import { TransferMoney } from "./TransferMoney.command.ts";
export const payRent = Effect.gen(function* () { const transfer = yield* Transfer; return yield* transfer.send( new TransferMoney({ from: AccountId.make("a-1"), to: AccountId.make("a-2"), amount: 900, }), );});send succeeds once every event is committed. It fails with one of the command’s rejections, and then nothing was recorded on either account.
Pass a commandId as you would to an aggregate. A command sent again under the same id returns its first receipt and records nothing new.
Read what it committed
Section titled “Read what it committed”The receipt lists every stream the decision read, with its version after the commit.
import * as Effect from "effect/Effect";import { Account } from "./Account.aggregate.ts";import { AccountId } from "./Account.id.ts";import { AccountSummary } from "./AccountSummary.view.ts";import { Transfer } from "./Transfer.decision.ts";import { TransferMoney } from "./TransferMoney.command.ts";
export const payRentAndRead = Effect.gen(function* () { const transfer = yield* Transfer; const summaries = yield* AccountSummary; const receipt = yield* transfer.send( new TransferMoney({ from: AccountId.make("a-1"), to: AccountId.make("a-2"), amount: 900, }), ); return yield* summaries.get(Account.ref("a-2"), { atLeast: receipt.commits[1] });});commits is in stream order, so Account/a-1 comes before Account/a-2. Each entry is what a view takes as atLeast, to wait until it has applied that write.
Reply to the caller
Section titled “Reply to the caller”A command that declares a reply gets it from the decision.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { AccountId } from "./Account.id.ts";
export class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { balance: Schema.Int,}) {}
export class TransferSent extends Domain.Event("TransferSent", { to: AccountId, amount: Schema.Int,}) {}
export class TransferReceived extends Domain.Event("TransferReceived", { from: AccountId, amount: Schema.Int,}) {}
export class TransferMoney extends Domain.Command("TransferMoney", { input: { from: AccountId, to: AccountId, amount: Schema.Int }, events: [TransferSent, TransferReceived], rejects: [InsufficientFunds], reply: { balance: Schema.Int },}) {}The decision’s reply receives each instance’s state after the events, under the same keys as reads.
import * as Domain from "@alchemy.run/domain";import { Account } from "./Account.aggregate.ts";import { InsufficientFunds, TransferMoney, TransferReceived, TransferSent,} from "./TransferMoney.command.ts";
export class Transfer extends Domain.Decision(TransferMoney, { reads: { from: Account, to: Account }, keyOf: (cmd) => ({ from: cmd.from, to: cmd.to }), decide: ({ from, to }, cmd) => cmd.amount > from.state.balance ? new InsufficientFunds({ balance: from.state.balance }) : [ from.record(new TransferSent({ to: to.id, amount: cmd.amount })), to.record(new TransferReceived({ from: from.id, amount: cmd.amount })), ], reply: ({ from }) => ({ balance: from.balance }),}) {}A command with a reply whose decision has none is a type error.
Authorize in decide
Section titled “Authorize in decide”decide can be an Effect.fn that reads what the command’s middleware provides, and fails with a rejection. Here the command requires a session.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { Session } from "../Session.middleware.ts";import { AccountId } from "./Account.id.ts";
export class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { balance: Schema.Int,}) {}
export class NotACustomer extends Domain.Rejection("NotACustomer") {}
export class TransferSent extends Domain.Event("TransferSent", { to: AccountId, amount: Schema.Int,}) {}
export class TransferReceived extends Domain.Event("TransferReceived", { from: AccountId, amount: Schema.Int,}) {}
export class TransferMoney extends Domain.Command("TransferMoney", { middleware: [Session], input: { from: AccountId, to: AccountId, amount: Schema.Int }, events: [TransferSent, TransferReceived], rejects: [InsufficientFunds, NotACustomer],}) {}The session provides the current actor, and decide reads it.
import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import { CurrentActor } from "../CurrentActor.context.ts";import { Account } from "./Account.aggregate.ts";import { InsufficientFunds, NotACustomer, TransferMoney, TransferReceived, TransferSent,} from "./TransferMoney.command.ts";
export class Transfer extends Domain.Decision(TransferMoney, { reads: { from: Account, to: Account }, keyOf: (cmd) => ({ from: cmd.from, to: cmd.to }), decide: Effect.fn(function* ({ from, to }, cmd) { const actor = yield* CurrentActor; if (actor._tag !== "Customer") return yield* new NotACustomer(); if (cmd.amount > from.state.balance) { return yield* new InsufficientFunds({ balance: from.state.balance }); } return [ from.record(new TransferSent({ to: to.id, amount: cmd.amount })), to.record(new TransferReceived({ from: from.id, amount: cmd.amount })), ]; }),}) {}It may read only what the middleware provides, as an aggregate’s decide may. A decision that needs an external system belongs in a saga.
Serve it through an Api
Section titled “Serve it through an Api”An Api lists the command by name, like any other.
import * as Domain from "@alchemy.run/domain";import { Bank } from "./Bank.model.ts";
export class CustomerApi extends Domain.Api("CustomerApi", { model: Bank, commands: ["DepositMoney", "TransferMoney"],}) {}Its client method takes the input, like any command’s: bank.TransferMoney({ from, to, amount: 900 }). The same holds over plain HTTP, the CLI and MCP.
How it commits
Section titled “How it commits”In memory, a decision holds the instances it reads, decides, and records before it lets go.
On Cloudflare, Rivet and Effect Cluster, each instance is an object with storage of its own, so no single write can cover two of them. One of the instances runs the commit instead: the first one the command reads, in the order of their streams. Call it the primary.
Whoever sends the command makes one call, to the primary. The primary does the rest.
The primary reads its own state and asks the others for theirs, then runs decide. A rejection ends it there, with nothing stored.
Otherwise it writes the whole decision to its own storage: its events, and what each other instance is to record. From then on, finishing the decision needs nothing but that storage.
Each other instance is prepared in turn. It checks that nothing changed since it was read, and holds its events without recording them. While it holds them, its own commands wait.
Then the primary commits, in one write of its own: its events, the receipt, and the fact that it committed. That write is the moment the decision happens. The others are told next, and each records what it held.
When something stops midway
Section titled “When something stops midway”The sender can hang up, and an object can be restarted, at any step. A decision still ends one way on every instance, because its outcome is written in one place, the primary’s storage, in one write.
Everything else can be done twice without harm. Preparing an instance that is already prepared changes nothing, and so does telling an instance an outcome it already has. So recovery is the same steps, run again.
The primary keeps a wake-up for as long as it holds a decision. If whatever was running the commit is gone, the primary wakes a couple of seconds later, reads the decision from its storage, and carries on from step 3. A command that reaches it first does the same before it runs.
So a sender that hangs up doesn’t cancel a decision that was already held: it commits without it. Send the command again with the same command id and you get the receipt of what happened.
The primary gives a decision up for one reason: another instance couldn’t be prepared. It had changed, another decision held it, or it couldn’t be reached. The primary writes that down first, then tells the instances it had prepared to let go. The command is then decided again from the start, against the new states.
After the commit, the primary keeps telling an instance that hasn’t answered until it does. An instance that is holding events and hears nothing also asks the primary, before its next command and on a wake-up of its own.
What it costs
Section titled “What it costs”A decision makes a few calls per instance, where an aggregate’s command makes one. A decision that reads one instance still goes through the same steps.
While an instance holds a decision’s events, its own commands wait: a few milliseconds, or about two seconds when whatever was running the commit stopped.
If the primary’s object can’t be reached at all, the instances it prepared stay held until it can. A command to one of them fails after about 13 seconds of waiting, and succeeds once the primary is back.
An instance that many decisions read becomes the place they queue. Two transfers out of the same account run one after the other, as two withdrawals do. A decision that keeps losing that race for about 20 seconds fails, and nothing of it is recorded.
Read as many instances as the command names
Section titled “Read as many instances as the command names”A key can stand for several instances of its aggregate. Return an array of ids for it, and decide receives an array.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { AccountId } from "./Account.aggregate.ts";import { InsufficientFunds, TransferReceived, TransferSent } from "./TransferMoney.command.ts";
export class PayOut extends Domain.Command("PayOut", { input: { from: AccountId, to: Schema.Array(AccountId), amount: Schema.Int }, events: [TransferSent, TransferReceived], rejects: [InsufficientFunds],}) {}to is one key in reads, and keyOf returns the whole list for it.
import * as Domain from "@alchemy.run/domain";import { Account } from "./Account.aggregate.ts";import { PayOut } from "./PayOut.command.ts";import { InsufficientFunds, TransferReceived, TransferSent } from "./TransferMoney.command.ts";
export class Payout extends Domain.Decision(PayOut, { reads: { from: Account, to: Account }, keyOf: (cmd) => ({ from: cmd.from, to: cmd.to }), decide: ({ from, to }, cmd) => cmd.amount * to.length > from.state.balance ? new InsufficientFunds({ balance: from.state.balance }) : to.flatMap((account) => [ from.record(new TransferSent({ to: account.id, amount: cmd.amount })), account.record(new TransferReceived({ from: from.id, amount: cmd.amount })), ]),}) {}Every account is paid, or none is. An instance named twice is read once.
Say what it must keep
Section titled “Say what it must keep”A decision can state rules about the step it takes. Each entry of transitions is given the states it read, before and after, with the command and the events, and returns true while the rule holds.
export class Transfer extends Domain.Decision(TransferMoney, { reads: { from: Account, to: Account }, keyOf: (cmd) => ({ from: cmd.from, to: cmd.to }), transitions: { MoneyIsConserved: ({ before, after }) => after.from.balance + after.to.balance === before.from.balance + before.to.balance, },Nothing runs a transition when a command arrives. It’s a claim about decide, and verification proves it for every pair of states and every input, along with each account’s own rules.
What it can’t do yet
Section titled “What it can’t do yet”A command a decision implements can’t be scheduled, and it has no predict for optimistic updates. Send it when it’s due, and show its result when the receipt arrives.
Decision, saga or policy?
Section titled “Decision, saga or policy?”A decision is one rule, answered at once, over instances in the same model. It can’t wait, and it can’t call an external system.
A saga is a process that takes time: it waits for an approval or a timer, calls a payment provider, and undoes earlier steps when a later one fails.
A policy reacts after the fact: an event was recorded, so something else should happen.
Moving money between two accounts of your own bank is a decision. Moving it to another bank is a saga.
Test it
Section titled “Test it”A story sends a decision’s command with Story.when, and asserts what each instance recorded with Story.then.
import { it } from "@effect/vitest";import { Story } from "@alchemy.run/domain/Story";import { Account } from "../src/Account/Account.aggregate.ts";import { AccountId } from "../src/Account/Account.id.ts";import { MoneyDeposited } from "../src/Account/DepositMoney.command.ts";import { Transfer } from "../src/Account/Transfer.decision.ts";import { InsufficientFunds, TransferMoney, TransferReceived, TransferSent,} from "../src/Account/TransferMoney.command.ts";import { Bank } from "../src/Bank.model.ts";
const story = Story.make(Bank);const a1 = AccountId.make("a-1");const a2 = AccountId.make("a-2");
it.effect("a transfer is recorded on both accounts", () => story( Story.given(Account.ref("a-1"), new MoneyDeposited({ amount: 1000 })), Story.when(new TransferMoney({ from: a1, to: a2, amount: 900 })), Story.then(Account.ref("a-1"), new TransferSent({ to: a2, amount: 900 })), Story.then(Account.ref("a-2"), new TransferReceived({ from: a1, amount: 900 })), ),);
it.effect("an overdraft is refused, and neither account changes", () => story( Story.given(Account.ref("a-1"), new MoneyDeposited({ amount: 100 })), Story.when(new TransferMoney({ from: a1, to: a2, amount: 900 })), Story.rejected(new InsufficientFunds({ balance: 100 })), Story.then(Account.ref("a-1")), Story.then(Account.ref("a-2")), ),);Story.given puts history on any instance the decision reads, so a test starts from the states that matter.
Next, View: how the model answers reads.