Separating Reads from Writes
In this pack:
sizing,
notation,
rule strictness.
Overview
A change and a read ask for different things: a change protects a rule
and answers little, while a read serves a screen and answers a shape
that screen can show. This skill keeps the two apart at the level of the
use case, serves a screen from a plain read query while that is enough,
and gives a slow read or one over many tables a read model of its own.
The read model is a store of rows shaped for a screen, kept current by a
projection of the domain events, safe to receive an event twice and able
to rebuild itself, and it tells its readers how current it is. Event
sourcing is kept for an aggregate whose past states must be rebuilt and
whose events can be kept readable, and a second store only for reads the
write store cannot serve.
When to use
- A screen needs data shaped unlike the domain model, such as a row
joining several aggregates.
- Reads slow down writes, or a screen's query joins many aggregates on
every refresh.
- You are weighing a read model, a projection or event sourcing.
- A screen must say how current the figures it shows are.
- You are deciding whether reads need a second store.
- An aggregate's past states must be rebuilt exactly.
When not to use
- A screen shows a few fields of one aggregate and its query is plain:
a read query is enough, as
layering the system rule 6 says.
- The question is how a domain event is recorded, published or
delivered: that is
publishing domain events.
- The question is keeping one aggregate's history of transitions for a
report: that is
modeling lifecycles rule 6.
- The module has no business rules and only moves data between a screen
and a store.
Core rules
Rule. Keep a change and a read apart at the level of the use case: a
use case that changes the clinic's state answers no more than what it
created, such as the new appointment's identity, and a read changes
nothing. Command and query separation, the split
encapsulating state and
behaviour
rule 4 makes inside one object, here covers a whole use case, so each
side can take the shape and the store it needs.
Default. Serve each screen from a read query shaped for it, over
the same store the domain writes, and go no further while that query
stays plain and fast. This is the light form that
layering the system rule 6 and
designing repositories rule 6
already give; a query count that grows with the rows a screen shows is
the finding taming persistence
rule 6 checks.
The exception is a read whose query joins many aggregates or slows
the writes down: rule 3 gives it a read model of its own.
Rule. Build a separate read model as a projection: a handler of the
domain events that updates read rows shaped for one screen after each
change commits, safe to receive an event twice, and able to rebuild
its rows from scratch from the stored events or the write store.
Publishing domain events, rules 3 and 5, gives the handler the
after-commit moment and the repeated-delivery safety it needs; where
an event must not be lost, that skill's outbox keeps it until a relay
has sent it. Nothing writes the read rows but the projection: a wrong
row is fixed by fixing the write side or the projection and
rebuilding.
Rule. Tell the reader that a read model lags: a screen fed by a
projection shows the state as of the last event it handled, so it
says when it was last brought up to date, and a use case that must
show its own change at once answers from the write side or from what
the change returned.
Judgement. Store an aggregate as the list of its events, event
sourcing, only when the business needs that history as the record of
truth, such as an auditor rebuilding any past state of a care plan,
and the team can keep every stored event readable for as long as it
is kept; otherwise store the current state and keep the history the
business asks for, as
modeling lifecycles rule 6
does. What tips the balance is whether a past state must be rebuilt
exactly, against the cost of keeping stored events readable for ever,
a contract with future code under
crossing system boundaries
rule 6.
Judgement. Give the read side a store of its own only when the reads
need what the write store cannot give, such as a search across free
text or a load the writes must not feel; keep one store while one
serves both. What tips the balance is the cost of running and
keeping a second store current against the read load and the shapes
the screens need.
Pattern
Before, TodayBoard serves reception's board of the day's appointments
with their status by asking the clinic's database for a join on every
refresh. After, a projection keeps read rows shaped for the board, and
TodayBoard reads only those rows.
Before:
class TodayBoard
- database: ClinicDatabase
+ new(database: ClinicDatabase)
+ rowsFor(date: Date): List<TodayBoardRow>
return database.appointmentsJoined(date)
ClinicDatabase is the inverting dependencies skill's type.
database.appointmentsJoined(date) is taken to run one query joining
appointments, patients, clinicians and rooms on every read, against the
tables booking writes.
After:
class TodayBoardProjection
- updates: TodayBoardUpdates
- handled: HandledEvents
+ new(updates: TodayBoardUpdates, handled: HandledEvents)
+ handle(id: EventId, event: AppointmentCancelled): void
if handled.contains(id) then
return
else
updates.markCancelled(event.appointment())
handled.add(id)
return
interface TodayBoardUpdates
+ markCancelled(appointment: AppointmentId): void
interface TodayBoardRows
+ forDate(date: Date): List<TodayBoardRow>
class TodayBoard
- rows: TodayBoardRows
+ new(rows: TodayBoardRows)
+ rowsFor(date: Date): List<TodayBoardRow>
return rows.forDate(date)
The read side holds only the read port and the projection only the
write port, as
designing interfaces rule 2 asks,
and one adapter may implement both. AppointmentCancelled, EventId
and HandledEvents are the publishing domain events skill's, and the
handler form handle(id, event) is that skill's. TodayBoardRow is
taken to be a plain row shaped for the board. The projection records
only what the event states, that this appointment was cancelled, and
never marks its slot free, because that skill's ReleaseSlot frees the
slot later, in its own transaction. HandledEvents is per handler: the
projection holds its own, never ReleaseSlot's, so the two never share
one. What is stored is one row marked cancelled and the event's
identity, in the read tables of the clinic's database, in the
projection's own transaction after the cancellation commits. The
handler for the event that booking records, which adds a row, is left
out of the fence. The fence also leaves out how the board reports when
it was last brought up to date, which rule 4 requires of the screen.
TodayBoardProjection's constructor sets updates and handled before
handle reads them, and TodayBoard's sets rows before rowsFor
reads it. For a new event, handle sends updates.markCancelled once,
marking the appointment's one row, and sends add once; for a repeated
one, it returns before either. No other step runs twice, and the fence
uses only keywords the notation defines.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A screen's query that joins many aggregates' tables on every refresh.
- A use case that changes state and also returns a screen's worth of
data.
- Read rows written by anything other than their projection.
- A screen fed by a projection that never says how current it is.
- A proposal to store every aggregate as events, with no aggregate whose
past states must be rebuilt.
- A projection that cannot be rebuilt from scratch.
Common mistakes
- Building a separate read model for a screen a plain read query serves.
- Editing read rows by hand to fix a wrong figure.
- Reading a projection to decide a change, where the write side holds
the current state.
- Adopting event sourcing for the whole system at once.
- Changing a stored event's shape with no plan for the events already
stored.
Related skills
Further reading
- Projections
- Event sourcing
1---2name: oo-separating-reads-from-writes3description: Use when screens need data shaped unlike the model, when reads slow down writes, or when weighing read models, projections or event sourcing.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-separating-reads-from-writes7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Separating Reads from Writes1213**In this pack:**14[sizing](../oo-design/SKILL.md#how-much-design-a-task-warrants),15[notation](../oo-design/references/notation.md),16[rule strictness](../oo-design/SKILL.md#how-strictly-a-rule-is-meant).1718## Overview1920A change and a read ask for different things: a change protects a rule21and answers little, while a read serves a screen and answers a shape22that screen can show. This skill keeps the two apart at the level of the23use case, serves a screen from a plain read query while that is enough,24and gives a slow read or one over many tables a read model of its own.25The read model is a store of rows shaped for a screen, kept current by a26projection of the domain events, safe to receive an event twice and able27to rebuild itself, and it tells its readers how current it is. Event28sourcing is kept for an aggregate whose past states must be rebuilt and29whose events can be kept readable, and a second store only for reads the30write store cannot serve.3132## When to use3334- A screen needs data shaped unlike the domain model, such as a row35 joining several aggregates.36- Reads slow down writes, or a screen's query joins many aggregates on37 every refresh.38- You are weighing a read model, a projection or event sourcing.39- A screen must say how current the figures it shows are.40- You are deciding whether reads need a second store.41- An aggregate's past states must be rebuilt exactly.4243## When not to use4445- A screen shows a few fields of one aggregate and its query is plain:46 a read query is enough, as47 [layering the system](../oo-layering-the-system/SKILL.md) rule 6 says.48- The question is how a domain event is recorded, published or49 delivered: that is50 [publishing domain events](../oo-publishing-domain-events/SKILL.md).51- The question is keeping one aggregate's history of transitions for a52 report: that is53 [modeling lifecycles](../oo-modeling-lifecycles/SKILL.md) rule 6.54- The module has no business rules and only moves data between a screen55 and a store.5657## Core rules58591. Rule. **Keep a change and a read apart at the level of the use case: a60 use case that changes the clinic's state answers no more than what it61 created, such as the new appointment's identity, and a read changes62 nothing.** Command and query separation, the split63 [encapsulating state and64 behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md)65 rule 4 makes inside one object, here covers a whole use case, so each66 side can take the shape and the store it needs.67682. Default. **Serve each screen from a read query shaped for it, over69 the same store the domain writes, and go no further while that query70 stays plain and fast.** This is the light form that71 [layering the system](../oo-layering-the-system/SKILL.md) rule 6 and72 [designing repositories](../oo-designing-repositories/SKILL.md) rule 673 already give; a query count that grows with the rows a screen shows is74 the finding [taming persistence](../oo-taming-persistence/SKILL.md)75 rule 6 checks.7677 The exception is a read whose query joins many aggregates or slows78 the writes down: rule 3 gives it a read model of its own.79803. Rule. **Build a separate read model as a projection: a handler of the81 domain events that updates read rows shaped for one screen after each82 change commits, safe to receive an event twice, and able to rebuild83 its rows from scratch from the stored events or the write store.**84 Publishing domain events, rules 3 and 5, gives the handler the85 after-commit moment and the repeated-delivery safety it needs; where86 an event must not be lost, that skill's outbox keeps it until a relay87 has sent it. Nothing writes the read rows but the projection: a wrong88 row is fixed by fixing the write side or the projection and89 rebuilding.90914. Rule. **Tell the reader that a read model lags: a screen fed by a92 projection shows the state as of the last event it handled, so it93 says when it was last brought up to date, and a use case that must94 show its own change at once answers from the write side or from what95 the change returned.**96975. Judgement. **Store an aggregate as the list of its events, event98 sourcing, only when the business needs that history as the record of99 truth, such as an auditor rebuilding any past state of a care plan,100 and the team can keep every stored event readable for as long as it101 is kept; otherwise store the current state and keep the history the102 business asks for, as103 [modeling lifecycles](../oo-modeling-lifecycles/SKILL.md) rule 6104 does.** What tips the balance is whether a past state must be rebuilt105 exactly, against the cost of keeping stored events readable for ever,106 a contract with future code under107 [crossing system boundaries](../oo-crossing-system-boundaries/SKILL.md)108 rule 6.1091106. Judgement. **Give the read side a store of its own only when the reads111 need what the write store cannot give, such as a search across free112 text or a load the writes must not feel; keep one store while one113 serves both.** What tips the balance is the cost of running and114 keeping a second store current against the read load and the shapes115 the screens need.116117## Pattern118119Before, `TodayBoard` serves reception's board of the day's appointments120with their status by asking the clinic's database for a join on every121refresh. After, a projection keeps read rows shaped for the board, and122`TodayBoard` reads only those rows.123124Before:125126```text127class TodayBoard128 - database: ClinicDatabase129 + new(database: ClinicDatabase)130 + rowsFor(date: Date): List<TodayBoardRow>131 return database.appointmentsJoined(date)132```133134`ClinicDatabase` is the inverting dependencies skill's type.135`database.appointmentsJoined(date)` is taken to run one query joining136appointments, patients, clinicians and rooms on every read, against the137tables booking writes.138139After:140141```text142class TodayBoardProjection143 - updates: TodayBoardUpdates144 - handled: HandledEvents145 + new(updates: TodayBoardUpdates, handled: HandledEvents)146 + handle(id: EventId, event: AppointmentCancelled): void147 if handled.contains(id) then148 return149 else150 updates.markCancelled(event.appointment())151 handled.add(id)152 return153154interface TodayBoardUpdates155 + markCancelled(appointment: AppointmentId): void156157interface TodayBoardRows158 + forDate(date: Date): List<TodayBoardRow>159160class TodayBoard161 - rows: TodayBoardRows162 + new(rows: TodayBoardRows)163 + rowsFor(date: Date): List<TodayBoardRow>164 return rows.forDate(date)165```166167The read side holds only the read port and the projection only the168write port, as169[designing interfaces](../oo-designing-interfaces/SKILL.md) rule 2 asks,170and one adapter may implement both. `AppointmentCancelled`, `EventId`171and `HandledEvents` are the publishing domain events skill's, and the172handler form `handle(id, event)` is that skill's. `TodayBoardRow` is173taken to be a plain row shaped for the board. The projection records174only what the event states, that this appointment was cancelled, and175never marks its slot free, because that skill's `ReleaseSlot` frees the176slot later, in its own transaction. `HandledEvents` is per handler: the177projection holds its own, never `ReleaseSlot`'s, so the two never share178one. What is stored is one row marked cancelled and the event's179identity, in the read tables of the clinic's database, in the180projection's own transaction after the cancellation commits. The181handler for the event that booking records, which adds a row, is left182out of the fence. The fence also leaves out how the board reports when183it was last brought up to date, which rule 4 requires of the screen.184185`TodayBoardProjection`'s constructor sets `updates` and `handled` before186`handle` reads them, and `TodayBoard`'s sets `rows` before `rowsFor`187reads it. For a new event, `handle` sends `updates.markCancelled` once,188marking the appointment's one row, and sends `add` once; for a repeated189one, it returns before either. No other step runs twice, and the fence190uses only keywords the notation defines.191192## Red flags193194Places to look, not verdicts. A red flag becomes a finding only with195evidence: a measurement, a reproducible bug, or a failing test.196197- A screen's query that joins many aggregates' tables on every refresh.198- A use case that changes state and also returns a screen's worth of199 data.200- Read rows written by anything other than their projection.201- A screen fed by a projection that never says how current it is.202- A proposal to store every aggregate as events, with no aggregate whose203 past states must be rebuilt.204- A projection that cannot be rebuilt from scratch.205206## Common mistakes207208- Building a separate read model for a screen a plain read query serves.209- Editing read rows by hand to fix a wrong figure.210- Reading a projection to decide a change, where the write side holds211 the current state.212- Adopting event sourcing for the whole system at once.213- Changing a stored event's shape with no plan for the events already214 stored.215216## Related skills217218- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule219 labels.220- [oo-publishing-domain-events](../oo-publishing-domain-events/SKILL.md)221 records and publishes the events a projection handles.222- [oo-layering-the-system](../oo-layering-the-system/SKILL.md) lets a223 read with no decision take a read query.224- [oo-designing-repositories](../oo-designing-repositories/SKILL.md)225 gives the read query its shape and the domain its ports.226- [oo-modeling-lifecycles](../oo-modeling-lifecycles/SKILL.md) keeps a227 history of transitions inside the aggregate.228- [oo-crossing-system-boundaries](../oo-crossing-system-boundaries/SKILL.md)229 treats a stored event as a contract with future code.230231## Further reading232233- [Projections](references/projections.md)234- [Event sourcing](references/event-sourcing.md)