The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 369 lines 20.7 KB
Raw
1 ---
2 title: Domain Model
3 description: What a domain model contains, how it processes every command, and how you declare, run and use one.
4 ---
5
6 import DAG from "../../../components/DAG.astro";
7
8 A `Domain.Model` is one bounded context running as a whole. It holds the context's aggregates, the views built from their events, and the policies that act on them, and it guarantees how commands and events move between them.
9
10 The concept pages that follow read as a manual, one building block per chapter, in the order a command meets them. This first chapter is the map. It describes what every model contains and what happens to every command, with the bank from the [tutorial](/domain/tutorial/part-1) as the example throughout, then shows how to declare, run and call a model.
11
12 If the words aggregate, view and policy are new, read [What is Domain-Driven Design?](/domain/what-is-ddd) first.
13
14 ## A model is a bounded context
15
16 A business is too big for one model. The words its people use change meaning from one department to the next: to the bank's tellers, an "account" holds money; to its identity team, an "account" is a login. A single model that tries to serve both meanings ends up with a vague `Account` that serves neither.
17
18 So DDD draws boundaries. Inside a **bounded context**, every word means exactly one thing, and the model is written in those words. In the example bank, the banking context knows accounts, deposits, withdrawals and transfers. It doesn't know about login sessions, password resets or support tickets; those belong to other contexts, with models of their own.
19
20 A good boundary passes two tests. Every name inside it has one meaning, so a conversation with the business turns straight into code. And the rules inside it can be enforced without asking another context's permission, so the model can decide on its own. When a word starts needing a qualifier, like "billing account" versus "login account", you've found the edge of a context.
21
22 A `Domain.Model` is how you write one bounded context down. Everything in this manual lives inside one.
23
24 ## What a model contains
25
26 Every model has the same shape. Commands enter on the left and are decided by aggregates. Aggregates record events. Events flow to three kinds of consumer: views, which the model stores and serves; projections, which write a store you own or a stream; and policies, which send further commands.
27
28 <DAG
29 nodes={[
30 { id: "commands", label: "Commands", type: "requests", layer: 0, kind: "command" },
31 { id: "aggregates", label: "Aggregates", type: "decide", layer: 1, kind: "aggregate" },
32 { id: "events", label: "Events", type: "the record", layer: 2, kind: "event" },
33 { id: "views", label: "Views", type: "answer reads", layer: 3, kind: "view" },
34 { id: "projections", label: "Projections", type: "write stores", layer: 3, kind: "projection" },
35 { id: "policies", label: "Policies", type: "act next", layer: 3, kind: "policy" },
36 ]}
37 edges={[
38 { from: "commands", to: "aggregates" },
39 { from: "aggregates", to: "events" },
40 { from: "events", to: "views", dashed: true },
41 { from: "events", to: "projections", dashed: true },
42 { from: "events", to: "policies", dashed: true },
43 { from: "policies", to: "commands" },
44 ]}
45 caption="Solid edges happen within one command. Dashed edges are delivered after it commits."
46 />
47
48 A model declares which aggregates, views, policies, projections and streams it contains. The commands and events come with them, since each aggregate declares the commands it handles and the events it records. The example bank's model contains two aggregates, two views and one policy:
49
50 ```typescript title="src/Bank.model.ts"
51 export class Bank extends Domain.Model("Bank", {
52 aggregates: [Account, Customer],
53 views: [AccountSummary, Statement],
54 policies: [MainAccountProvisioning],
55 }) {}
56 ```
57
58 ## Each command goes to one instance
59
60 An aggregate type has many instances, one per id, and every command names the id of the instance it's for. The model routes the command to that instance and no other.
61
62 Each instance handles one command at a time. Commands for the same instance queue, and each is decided against the state the previous one left. Commands for different instances run independently. This is what makes an instance a consistency boundary: nothing else changes its state while it decides.
63
64 <DAG
65 nodes={[
66 { id: "c1", label: "command", type: "for id 1", layer: 0, kind: "command" },
67 { id: "c2", label: "command", type: "for id 1", layer: 0, kind: "command" },
68 { id: "c3", label: "command", type: "for id 2", layer: 0, kind: "command" },
69 { id: "i1", label: "instance 1", type: "one at a time", layer: 1, kind: "aggregate" },
70 { id: "i2", label: "instance 2", type: "one at a time", layer: 1, kind: "aggregate" },
71 ]}
72 edges={[
73 { from: "c1", to: "i1" },
74 { from: "c2", to: "i1" },
75 { from: "c3", to: "i2" },
76 ]}
77 />
78
79 In the bank, a deposit names the account it's for, so two deposits into `a-1` queue while a deposit into `a-2` runs alongside them:
80
81 ```typescript title="src/depositAndRead.ts"
82 const receipt = yield* accounts.send(accountId, new DepositMoney({ amount: 100 }));
83 ```
84
85 ## The aggregate decides, and everything commits at once
86
87 The instance runs the aggregate's `decide` handler for the command against its current state. A rejection ends the command: nothing is recorded, and the caller gets the rejection as a typed error. Otherwise, `decide` returns events, and each is applied to the state with `evolve`.
88
89 Then the instance commits, in one atomic write: the events, appended to its stream with sequence numbers; its new state and version; the reply; and a delivery for every view and policy that consumes the events. Either all of it is stored or none of it is, so a crash can never leave events without their deliveries, or state that disagrees with its events.
90
91 <DAG
92 nodes={[
93 { id: "decide", label: "decide", type: "accepted", layer: 0 },
94 { id: "commit", label: "one atomic write", layer: 1, tone: "accent" },
95 { id: "events", label: "events", type: "appended", layer: 2, kind: "event" },
96 { id: "state", label: "state", type: "new version", layer: 2 },
97 { id: "receipt", label: "receipt", type: "with the reply", layer: 2 },
98 { id: "deliveries", label: "deliveries", type: "views, policies", layer: 2 },
99 ]}
100 edges={[
101 { from: "decide", to: "commit" },
102 { from: "commit", to: "events" },
103 { from: "commit", to: "state" },
104 { from: "commit", to: "receipt" },
105 { from: "commit", to: "deliveries" },
106 ]}
107 />
108
109 The caller gets a receipt with the stream and version the command committed at, the events, and the reply. The receipt is also stored under the command's id. If the same command arrives again, after a retry over a flaky connection, the instance returns the stored receipt instead of deciding twice.
110
111 For a deposit into an open account, `decide` returns one `MoneyDeposited` event carrying the new balance:
112
113 ```typescript title="src/Account.aggregate.ts"
114 DepositMoney: (s, cmd) =>
115 s._tag !== "Open"
116 ? new NotOpen()
117 : [new MoneyDeposited({ amount: cmd.amount, balanceAfter: s.balance + cmd.amount })],
118 ```
119
120 ## Consumers catch up
121
122 After the commit, the deliveries are sent. Every view, projection and policy receives every event it consumes, at least once, and in the order its source instance recorded them, even if something restarts in between. Views and projections drop events they've already accepted; policies make repeats harmless (see [Policy](/domain/policy#make-it-safe-to-run-twice)).
123
124 Because this happens after the commit, views are eventually consistent: for a moment, the aggregate has the new state and a view doesn't yet. A reader who needs to see their own change passes the command's receipt, and the view waits until it has applied that version.
125
126 In the bank, one `MoneyDeposited` reaches both views that read accounts:
127
128 <DAG
129 nodes={[
130 { id: "event", label: "MoneyDeposited", type: "Account a-1", kind: "event" },
131 { id: "summary", label: "AccountSummary", type: "balance", kind: "view" },
132 { id: "statement", label: "Statement", type: "a new line", kind: "view" },
133 ]}
134 edges={[
135 { from: "event", to: "summary", dashed: true },
136 { from: "event", to: "statement", dashed: true },
137 ]}
138 />
139
140 And a client that has just deposited reads the summary at that receipt, so it sees the new balance:
141
142 ```typescript title="src/depositAndRead.ts"
143 return yield* summaries.query(Account.ref(accountId), { atLeast: receipt });
144 ```
145
146 ## Consumers added later receive the history
147
148 Add a view or a projection to a model that already has events, and it receives those events first. You deploy, and it builds itself from the history, with no command and no script to run.
149
150 Each key of the new consumer pulls the history from every instance that feeds it and applies those events in the order they were recorded, by timestamp. A summary per account sees its account's events in order, and a single dashboard fed by every account sees all of them in order, as if it had been there from the start. Events recorded while it catches up wait their turn, then arrive live.
151
152 Policies never receive history. They act on new events only, so adding a policy never acts on the past again.
153
154 ## Change a view: bump its version
155
156 A view's state is derived, so it can always be computed again. Whenever you change what a view computes (its `evolve`, `emit`, `keyOf`, `state`, or the events and sources it reads), bump its `version`:
157
158 ```typescript title="src/AccountSummary.view.ts"
159 import * as Domain from "@alchemy.run/domain";
160 import * as Schema from "effect/Schema";
161 import { Account } from "./Account.aggregate.ts";
162
163 export class AccountSummary extends Domain.View("AccountSummary", {
164 from: [Account],
165 key: Account,
166 state: Schema.Struct({ net: Schema.Number }),
167 initial: { net: 0 },
168 evolve: {
169 MoneyDeposited: (v, e) => ({ net: v.net + e.amount }),
170 MoneyWithdrawn: (v, e) => ({ net: v.net - e.amount }),
171 },
172 version: 1,
173 }) {}
174 ```
175
176 On the next deploy every key is computed again from the history, with the new code, and so is every view and projection that reads this one. You don't choose how: the deploy picks the cheapest way that is correct.
177
178 A view keyed by the one aggregate it reads, like this summary per account, is rebuilt in place. It keeps its storage, and the deploy waits for nothing. The first time a key is touched after the deploy, it reads its own account's events again before it answers, so even events it never received before (here, withdrawals) count. A view or projection that reads it gets each key's new rows, never a key still being rebuilt. On Cloudflare, an object busy during the deploy keeps its old code until it is idle; until then the Worker computes that key's answers itself, from its account's events.
179
180 Any other view, such as one fed by many accounts through `keyOf`, is rebuilt from the history: it starts over in new storage and receives every event again, and the deploy waits for it, the same way it does for a new view.
181
182 Only ever increase a version. To undo a change, change the code back and bump again. Bump it too when you add back a view you removed earlier: its stored state stopped following the history while it was gone.
183
184 ## Fill a view lazily
185
186 A view keyed by the one aggregate it reads can skip the backfill when it is added, too. List it as lazy on the model's Layer:
187
188 ```typescript title="src/Bank.live.ts"
189 import * as Layer from "effect/Layer";
190 import { Bank } from "./Bank.model.ts";
191
192 export const BankLive = Bank.layer(Layer.empty, { lazy: ["AccountSummary"] });
193 ```
194
195 A deploy that adds it waits for nothing. Each key reads its own account's history the first time it's read, or when that account next changes, and every answer it gives covers the whole history. Keys nobody reads are never built.
196
197 A view fed by many instances, like a total across every account, can't be lazy: one key doesn't know which instances feed it. The model fails to build if you try.
198
199 ## Know when the history has arrived
200
201 Until a new or rebuilt view has received the history, its answers cover only part of it. `history` says whether it's complete:
202
203 ```typescript title="src/summaryStatus.ts"
204 const { complete } = yield* summaries.history;
205 ```
206
207 A screen can show "catching up" until `complete` is true, or hold its reads until then. A projection's `Progress` service has the same `history`.
208
209 On Cloudflare the deploy itself waits until the history is complete. See [History at scale](/domain/backfill) for how long that takes and what it costs.
210
211 ## Order and partitions
212
213 Every consumer works the same way underneath. At commit, each event is routed to a key of each consumer that wants it: by default its source instance, or whatever the consumer's `key` and `keyOf` say. Each key has an ordered input log, and its inputs are handled one at a time, or a batch at a time for a projection. Keys run in parallel.
214
215 That gives a precise guarantee. Within a key, events from one source arrive in that source's order. Between keys, and between different sources feeding one key, there is no order: an account can be a day ahead of the customer that owns it. The model is distributed on purpose, so design consumers to correlate by id, use the envelope's `at` for business time, and let an aggregate decide whenever the order between two facts matters.
216
217 ## Choose a consumer
218
219 All three consumers receive the same events. They differ in what they do with them.
220
221 A [view](/domain/view) folds events into state that the model stores and serves: `get`, `watch`, `events`, with `validate` and read-your-own-write. Reach for it first when clients need to read something.
222
223 A [projection](/domain/projection) writes events into a store you own, such as a database or a search index, or into a [stream](/domain/stream) the model serves. It never sends commands, so it can always be replayed.
224
225 A [policy](/domain/policy) is a business rule. It acts on each new event once, through commands and external systems, and never replays.
226
227 ## Declare the model
228
229 A model lists what runs together. It can start as a single aggregate.
230
231 ```typescript
232 // src/Bank.model.ts
233 import * as Domain from "@alchemy.run/domain";
234 import { Account } from "./Account.aggregate.ts";
235
236 export class Bank extends Domain.Model("Bank", {
237 aggregates: [Account],
238 }) {}
239 ```
240
241 Adding a view to `views` is enough for the model to deliver the events it reads. You never wire an event to a view by hand.
242
243 ```typescript
244 // src/Bank.model.ts
245 import * as Domain from "@alchemy.run/domain";
246 import { Account } from "./Account.aggregate.ts";
247 import { AccountSummary } from "./AccountSummary.view.ts";
248
249 export class Bank extends Domain.Model("Bank", {
250 aggregates: [Account],
251 views: [AccountSummary],
252 }) {}
253 ```
254
255 A policy is declared in one place and implemented in another, because its implementation usually needs things from outside the model, like a client for another aggregate or a payment provider. The declaration goes in `policies`; the implementation is a Layer you keep beside it.
256
257 ```typescript
258 // src/Bank.model.ts
259 import * as Domain from "@alchemy.run/domain";
260 import { Account } from "./Account.aggregate.ts";
261 import { AccountSummary } from "./AccountSummary.view.ts";
262 import { Customer } from "./Customer.aggregate.ts";
263 import {
264 MainAccountProvisioning,
265 MainAccountProvisioningLive,
266 } from "./MainAccountProvisioning.policy.ts";
267
268 export class Bank extends Domain.Model("Bank", {
269 aggregates: [Account, Customer],
270 views: [AccountSummary],
271 policies: [MainAccountProvisioning],
272 }) {}
273
274 export const BankHandlers = MainAccountProvisioningLive;
275 ```
276
277 ## Check the declaration
278
279 Some mistakes in a declaration only show when the model is hosted: a view that reads a source keyed by another aggregate without `keyOf`, a view with `state` but no `initial`, a policy that waits for an event no source emits, a stream with two writers. Building the model's Layer fails on the first one. `Domain.verify` finds all of them without hosting anything, so one unit test covers the whole model:
280
281 ```typescript
282 // packages/domain/test/Bank.model.test.ts
283 import * as Domain from "@alchemy.run/domain";
284 import { expect, it } from "@effect/vitest";
285 import { Bank } from "../src/Bank.model.ts";
286
287 it("the model is well defined", () => {
288 expect(Domain.verify(Bank)).toEqual([]);
289 });
290 ```
291
292 Each problem is a `Domain.DefinitionError`. Its `reason` is a tagged error that says which problem it is, such as `MissingKeyOf` or `TwoWriters`, with the names involved as fields, and its message names the block and the fix. Mistakes that depend on what a handler returns, like `decide` returning an event its command doesn't declare, still fail when the handler runs.
293
294 ## Run it
295
296 A declaration doesn't run anything. `Bank.layer(BankHandlers)` turns it into a Layer that hosts the model, and a platform underneath decides where its state lives.
297
298 ```typescript
299 // src/BankInMemory.ts
300 import * as Domain from "@alchemy.run/domain";
301 import * as Layer from "effect/Layer";
302 import { Bank, BankHandlers } from "./Bank.model.ts";
303
304 export const BankInMemory = Bank.layer(BankHandlers).pipe(Layer.provide(Domain.InMemory));
305 ```
306
307 `Domain.InMemory` keeps everything in memory, which is what tests want. Swap it for another platform and the model runs there unchanged; every platform keeps the guarantees above. See [Hosting](/domain/cloudflare).
308
309 ## Call it from your code
310
311 Inside the hosted model, each aggregate and view is a service. `yield* Account` gives you a client for every account, and `send` takes the target id and the command.
312
313 ```typescript
314 // src/depositAndRead.ts
315 import * as Effect from "effect/Effect";
316 import { Account } from "./Account.aggregate.ts";
317 import { AccountId } from "./Account.id.ts";
318 import { AccountSummary } from "./AccountSummary.view.ts";
319 import { DepositMoney } from "./DepositMoney.command.ts";
320
321 export const depositAndRead = Effect.gen(function* () {
322 const accounts = yield* Account;
323 const summaries = yield* AccountSummary;
324 const accountId = AccountId.make("a-1");
325 const receipt = yield* accounts.send(accountId, new DepositMoney({ amount: 100 }));
326 return yield* summaries.query(Account.ref(accountId), { atLeast: receipt });
327 });
328 ```
329
330 Passing the receipt as `atLeast` is the read-your-own-write from earlier: `query` waits until the summary has applied the deposit.
331
332 Clients outside the model, a browser or another service, reach it through an [Api](/domain/api) instead, which decides what each kind of client may send and read.
333
334 ## Keep one language per model
335
336 A model is one bounded context, so every name in it means one thing. When two parts of the business use a word differently, give each its own model. One model never sends commands to another model's aggregates directly; it calls that model's Api.
337
338 That rule keeps each model free to change. A support tool built on another model's Api depends on the commands and reads that model chose to publish, not on how its aggregates store their state today. The model can split an aggregate, rename a state or add a view without the support tool noticing.
339
340 <DAG
341 nodes={[
342 { id: "support", label: "Support", type: "Domain.Model", layer: 0 },
343 { id: "api", label: "BankApi", type: "Domain.Api", kind: "api", layer: 1 },
344 { id: "bank", label: "Bank", type: "Domain.Model", layer: 2, tone: "accent" },
345 ]}
346 edges={[
347 { from: "support", to: "api" },
348 { from: "api", to: "bank" },
349 ]}
350 />
351
352 ## Give each model its own data
353
354 Each model owns its data. Two models can use the same aggregate definition, and each still gets its own instances:
355
356 ```typescript
357 class Billing extends Domain.Model("Billing", { aggregates: [Account], views: [Ledger] }) {}
358 class Audit extends Domain.Model("Audit", { aggregates: [Account], views: [Owners] }) {}
359 ```
360
361 Account `a-1` in Billing and account `a-1` in Audit are different instances, with their own events. `Ledger` only hears Billing's accounts, and `Owners` only hears Audit's. Every platform keeps them apart, even on the same Worker; see [Cloudflare: Host several models in one Worker](/domain/cloudflare#host-several-models-in-one-worker). Give every model its own name: hosting two models with the same name on one platform fails.
362
363 ## Read the rest of the manual
364
365 The chapters that follow take each building block in turn, in the order a command meets them.
366
367 A [Command](/domain/command) asks for a change, and an [Event](/domain/event) records one. An [Aggregate](/domain/aggregate) sits between them, deciding each command against the rules it protects. On the query side, a [View](/domain/view) answers a question from events, a [Projection](/domain/projection) feeds a store you own, and a [Stream](/domain/stream) keeps an ordered log a client can follow. A [Policy](/domain/policy) applies the business's standing rules about what to do next, and a [Saga](/domain/saga) carries out a process that takes several steps. An [External System](/domain/external-system) is how the model talks to the world outside it, and an [Api](/domain/api) is what the model publishes to its clients. Finally, a [Story](/domain/story) states each rule as an example you can run.
368
369 Next, [Command](/domain/command): how a change is asked for.