Publishing Domain Events
In this pack:
sizing,
notation,
rule strictness.
Overview
One change often sets other parts of the clinic in motion. A cancelled
appointment frees a slot for the waiting list and calls for a letter; a
completed visit calls for an invoice. This skill names such a change as
a past-tense event, records it inside the aggregate that makes the
change, publishes it only after the transaction commits, and runs each
reaction as its own handler in a transaction of its own. An event that
must not be lost is stored with the change in an outbox, and every
handler is safe to receive it twice. Where the caller needs the
reaction's outcome to finish, the skill keeps a direct message instead.
When to use
- A letter, a notice, an invoice or another part must follow a change
once it is saved.
- One use case grows a step for each new reaction to the same change.
- A message leaves before the transaction commits, so a rollback leaves
a letter about a change that never happened.
- A reaction may fail while the change must stay saved.
- An event must reach another process, or must not be lost when one
stops.
- A handler runs twice for one event and changes something twice.
When not to use
- The reaction must be true at the same moment as the change, by a rule
that covers both objects: those objects belong in one aggregate
(designing aggregates, rule 1).
- The caller needs the reaction's outcome to finish, such as booking,
which reserves the slot before the appointment exists.
- The question is storing an aggregate as the list of its past events,
or building read-only views from events: that is
separating reads from writes.
- The question is the shape or the version of a message that another
organisation's system reads.
Core rules
Rule. Name a domain event for a change in the clinic that other
parts react to, in the past tense and in the staff's words, and make
it a value that carries the identities and the facts its handlers
need. A cancellation becomes AppointmentCancelled, which holds
the appointment, the slot, the patient and the reason. An event is
not a command: SendCancellationLetter asks for an action, while the
event says what happened. Nor is it a copy of the whole aggregate,
which would tie every handler to the aggregate's fields. The words
come from speaking the domain language, not from a database column.
Rule. Record the event inside the aggregate method that makes the
change, and let the aggregate hand out the events it has recorded.
A domain object never calls a handler, a message bus or a broker.
Appointment.cancel records AppointmentCancelled in the branch
that changes the status, so the event exists exactly when the change
happens, and a test of cancel reads the recorded events with
nothing else running.
Rule. Publish an event only after the transaction that recorded it
commits, and run each handler's change in a transaction of its own.
A handler that runs before the commit can act on a change that then
rolls back, such as a letter about a cancellation that never
happened; a handler that joins the first transaction changes two
aggregates in it. This is the later step of designing aggregates,
rule 4: until the handler runs, the other aggregate is behind, and
the reply to the user says what has happened, not what will.
Default. When an event must reach another process, or must not be
lost, store it in an outbox: the transaction that stores the change
also stores the event, in the same database, and a relay outside that
transaction sends each stored event and then marks it sent.
The exception is an event whose loss costs nothing, such as a hint
that a screen may refresh: it may be sent after the commit with no
outbox.
Rule. Make each handler safe to receive the same event twice:
before it changes anything, it checks whether it has already handled
that event, by the identity the outbox gave the event or by the state
of what it changes. A relay that stops after sending and before
marking sends the event again, so delivery is at least once, never
exactly once.
Judgement. Choose an event when the change is complete without its
reactions and the reactions vary or belong to other modules; choose a
direct message when the caller needs the outcome to finish its own
work. Cancelling an appointment is complete before the letter goes
out, so the letter is a handler; booking needs the slot reserved
before the appointment exists, so it sends the slot a message inside
one transaction, the exception of designing aggregates, rule 4. What
tips the balance is whether the use case is done while the reaction
has not yet run, and how many parts react: one reaction in the same
module that must happen at once stays a direct message, because an
event makes the flow harder to follow.
Pattern
Before, CancelAppointment changes the appointment, releases its slot,
stores both and sends the letter inside one transaction. After, the
appointment records what happened, the use case stores the event with
the change, and each handler runs after the commit in a transaction of
its own.
Before:
class CancelAppointment
- appointments: Appointments
- slots: Slots
- letters: Letters
+ new(appointments: Appointments, slots: Slots, letters: Letters)
+ run(id: AppointmentId, reason: CancellationReason): void
appointment := appointments.find(id)
appointment.cancel(reason)
slot := slots.find(appointment.slot())
slot.release(appointment.patient())
letters.sendCancellation(id, reason)
slots.save(slot)
appointments.save(appointment)
return
The Before's Appointment is the After's class without events and
recordedEvents. CancelAppointment carries the name the assigning
responsibilities skill gives this use case; that fence passes the whole
appointment and shows the delegation, while this one takes the appointment's
identity and the ports it calls, because it opens the transaction and stores the
change. CancelAppointment.run changes two aggregates in one transaction:
appointments.save stores the changed appointment under its AppointmentId and
slots.save stores the changed slot under its SlotId, both in the clinic's
database, in the transaction run opens, and the letter goes out before either
is stored. Every new reaction edits run. Appointments.find raises
AppointmentNotFound when no appointment has that identity, and Slots.find
raises SlotNotFound when no slot has that identity. Letters.sendCancellation
is taken to send one letter and change nothing in the aggregates. Letters is
the clinic's port for a posted letter; it is not the aggregates reference's
Notices, which sends a patient a message.
After:
interface DomainEvent
value AppointmentCancelled implements DomainEvent
- appointment: AppointmentId
- slot: SlotId
- patient: PatientId
- reason: CancellationReason
+ new(appointment: AppointmentId, slot: SlotId, patient: PatientId,
reason: CancellationReason)
+ appointment(): AppointmentId
return appointment
+ slot(): SlotId
return slot
+ patient(): PatientId
return patient
+ reason(): CancellationReason
return reason
class Appointment
- id: AppointmentId
- slot: SlotId
- patient: PatientId
- status: AppointmentStatus
- events: List<DomainEvent>
- new(id: AppointmentId, slot: SlotId, patient: PatientId,
status: AppointmentStatus)
events := new List<DomainEvent>()
+ id(): AppointmentId
return id
+ slot(): SlotId
return slot
+ patient(): PatientId
return patient
+ cancel(reason: CancellationReason): void
raises AppointmentNotCancellable
if status = Scheduled then
status := Cancelled
events.add(new AppointmentCancelled(id, slot, patient, reason))
else
raise AppointmentNotCancellable
return
+ recordedEvents(): ReadOnlyList<DomainEvent>
return events.readOnlyView()
class CancelAppointment
- appointments: Appointments
- outbox: Outbox
+ new(appointments: Appointments, outbox: Outbox)
+ run(id: AppointmentId, reason: CancellationReason): void
appointment := appointments.find(id)
appointment.cancel(reason)
appointments.save(appointment)
outbox.store(appointment.recordedEvents())
return
class ReleaseSlot
- slots: Slots
- handled: HandledEvents
+ new(slots: Slots, handled: HandledEvents)
+ handle(id: EventId, event: AppointmentCancelled): void
if handled.contains(id) then
return
else
slot := slots.find(event.slot())
slot.release(event.patient())
slots.save(slot)
handled.add(id)
return
The After's Appointment keeps the shape the repositories skill gives
it: - id: AppointmentId first, the same private constructor and
id(), with book and restore left out of this fence. It differs
from that shape by holding the slot's identity rather than the slot
object, as rule 3 of designing aggregates asks, by the queries slot()
and patient(), and by events; the private constructor's body sets
events to an empty list. cancel keeps the notation's check and
error, and drops the release of the slot, which ReleaseSlot now makes.
Appointments keeps find(id) and save(appointment); save stores
one whole appointment. Slots keeps the shape the placing domain logic
skill gives it: find(id) raises SlotNotFound, and save(slot)
stores one whole slot. Slot.release(patientId) is the notation's,
unchanged.
What is stored is the cancelled appointment under its AppointmentId
and its event in the outbox, both in the clinic's database, in the
transaction run opens; later, ReleaseSlot stores the released slot
under its SlotId and the event's identity in HandledEvents, both in
the clinic's database, in the handler's own transaction. HandledEvents
is taken to answer contains(id) and to store an identity through
add(id); it stores the identities of the events this handler has
handled, in the clinic's database, in the same transaction as the
released slot. A relay outside this fence hands each stored event, with
the EventId the outbox gave it, to each handler after the commit.
ReleaseSlot checks id because the notation's release frees the slot
whoever holds it, so a repeated event after the slot was booked again
would free the new patient's slot: rule 5, by the identity the outbox
gave the event. The letter becomes a second handler of
AppointmentCancelled, shown in
the outbox reference.
In the Before, run sends cancel once and release once. In the
After, run sends cancel once, and ReleaseSlot.handle sends
release once for the event that first finds its identity. The
constructor sets events before cancel reads it, and handled before
handle reads it; every other field arrives from a constructor
parameter named for it.
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 use case that sends an email, a text or a message before its
transaction commits.
- A use case whose body grows one step for each new reaction to the same
change.
- A domain object that holds a message bus, a mailer or a handler.
- An event named for an action to take, such as
SendReminder, or for a
field, such as StatusChanged.
- An event that carries the whole aggregate rather than the identities
and facts its handlers use.
- A handler that changes something without checking whether it has
handled that event before.
Common mistakes
- Publishing the event inside the transaction, before the change
commits.
- Letting one handler perform several unrelated reactions, so a failure
in one repeats the others.
- Using an event for a reaction the caller must see succeed before it
replies.
- Assuming each event arrives exactly once and in order.
- Telling the user that a reaction has happened when its handler has not
yet run.
Related skills
Further reading
- The outbox
- Events or direct messages
1---2name: oo-publishing-domain-events3description: Use when other parts react after a change is saved, when a use case grows a step per reaction, or a message goes out before the change commits.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-publishing-domain-events7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Publishing Domain Events1213**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## Overview1920One change often sets other parts of the clinic in motion. A cancelled21appointment frees a slot for the waiting list and calls for a letter; a22completed visit calls for an invoice. This skill names such a change as23a past-tense event, records it inside the aggregate that makes the24change, publishes it only after the transaction commits, and runs each25reaction as its own handler in a transaction of its own. An event that26must not be lost is stored with the change in an outbox, and every27handler is safe to receive it twice. Where the caller needs the28reaction's outcome to finish, the skill keeps a direct message instead.2930## When to use3132- A letter, a notice, an invoice or another part must follow a change33 once it is saved.34- One use case grows a step for each new reaction to the same change.35- A message leaves before the transaction commits, so a rollback leaves36 a letter about a change that never happened.37- A reaction may fail while the change must stay saved.38- An event must reach another process, or must not be lost when one39 stops.40- A handler runs twice for one event and changes something twice.4142## When not to use4344- The reaction must be true at the same moment as the change, by a rule45 that covers both objects: those objects belong in one aggregate46 (designing aggregates, rule 1).47- The caller needs the reaction's outcome to finish, such as booking,48 which reserves the slot before the appointment exists.49- The question is storing an aggregate as the list of its past events,50 or building read-only views from events: that is51 [separating reads from writes](../oo-separating-reads-from-writes/SKILL.md).52- The question is the shape or the version of a message that another53 organisation's system reads.5455## Core rules56571. Rule. **Name a domain event for a change in the clinic that other58 parts react to, in the past tense and in the staff's words, and make59 it a value that carries the identities and the facts its handlers60 need.** A cancellation becomes `AppointmentCancelled`, which holds61 the appointment, the slot, the patient and the reason. An event is62 not a command: `SendCancellationLetter` asks for an action, while the63 event says what happened. Nor is it a copy of the whole aggregate,64 which would tie every handler to the aggregate's fields. The words65 come from speaking the domain language, not from a database column.66672. Rule. **Record the event inside the aggregate method that makes the68 change, and let the aggregate hand out the events it has recorded.**69 A domain object never calls a handler, a message bus or a broker.70 `Appointment.cancel` records `AppointmentCancelled` in the branch71 that changes the status, so the event exists exactly when the change72 happens, and a test of `cancel` reads the recorded events with73 nothing else running.74753. Rule. **Publish an event only after the transaction that recorded it76 commits, and run each handler's change in a transaction of its own.**77 A handler that runs before the commit can act on a change that then78 rolls back, such as a letter about a cancellation that never79 happened; a handler that joins the first transaction changes two80 aggregates in it. This is the later step of designing aggregates,81 rule 4: until the handler runs, the other aggregate is behind, and82 the reply to the user says what has happened, not what will.83844. Default. **When an event must reach another process, or must not be85 lost, store it in an outbox: the transaction that stores the change86 also stores the event, in the same database, and a relay outside that87 transaction sends each stored event and then marks it sent.**8889 The exception is an event whose loss costs nothing, such as a hint90 that a screen may refresh: it may be sent after the commit with no91 outbox.92935. Rule. **Make each handler safe to receive the same event twice:94 before it changes anything, it checks whether it has already handled95 that event, by the identity the outbox gave the event or by the state96 of what it changes.** A relay that stops after sending and before97 marking sends the event again, so delivery is at least once, never98 exactly once.991006. Judgement. **Choose an event when the change is complete without its101 reactions and the reactions vary or belong to other modules; choose a102 direct message when the caller needs the outcome to finish its own103 work.** Cancelling an appointment is complete before the letter goes104 out, so the letter is a handler; booking needs the slot reserved105 before the appointment exists, so it sends the slot a message inside106 one transaction, the exception of designing aggregates, rule 4. What107 tips the balance is whether the use case is done while the reaction108 has not yet run, and how many parts react: one reaction in the same109 module that must happen at once stays a direct message, because an110 event makes the flow harder to follow.111112## Pattern113114Before, `CancelAppointment` changes the appointment, releases its slot,115stores both and sends the letter inside one transaction. After, the116appointment records what happened, the use case stores the event with117the change, and each handler runs after the commit in a transaction of118its own.119120Before:121122```text123class CancelAppointment124 - appointments: Appointments125 - slots: Slots126 - letters: Letters127 + new(appointments: Appointments, slots: Slots, letters: Letters)128 + run(id: AppointmentId, reason: CancellationReason): void129 appointment := appointments.find(id)130 appointment.cancel(reason)131 slot := slots.find(appointment.slot())132 slot.release(appointment.patient())133 letters.sendCancellation(id, reason)134 slots.save(slot)135 appointments.save(appointment)136 return137```138139The Before's `Appointment` is the After's class without `events` and140`recordedEvents`. `CancelAppointment` carries the name the assigning141responsibilities skill gives this use case; that fence passes the whole142appointment and shows the delegation, while this one takes the appointment's143identity and the ports it calls, because it opens the transaction and stores the144change. `CancelAppointment.run` changes two aggregates in one transaction:145`appointments.save` stores the changed appointment under its `AppointmentId` and146`slots.save` stores the changed slot under its `SlotId`, both in the clinic's147database, in the transaction `run` opens, and the letter goes out before either148is stored. Every new reaction edits `run`. `Appointments.find` raises149`AppointmentNotFound` when no appointment has that identity, and `Slots.find`150raises `SlotNotFound` when no slot has that identity. `Letters.sendCancellation`151is taken to send one letter and change nothing in the aggregates. `Letters` is152the clinic's port for a posted letter; it is not the aggregates reference's153`Notices`, which sends a patient a message.154155After:156157```text158interface DomainEvent159160value AppointmentCancelled implements DomainEvent161 - appointment: AppointmentId162 - slot: SlotId163 - patient: PatientId164 - reason: CancellationReason165 + new(appointment: AppointmentId, slot: SlotId, patient: PatientId,166 reason: CancellationReason)167 + appointment(): AppointmentId168 return appointment169 + slot(): SlotId170 return slot171 + patient(): PatientId172 return patient173 + reason(): CancellationReason174 return reason175176class Appointment177 - id: AppointmentId178 - slot: SlotId179 - patient: PatientId180 - status: AppointmentStatus181 - events: List<DomainEvent>182 - new(id: AppointmentId, slot: SlotId, patient: PatientId,183 status: AppointmentStatus)184 events := new List<DomainEvent>()185 + id(): AppointmentId186 return id187 + slot(): SlotId188 return slot189 + patient(): PatientId190 return patient191 + cancel(reason: CancellationReason): void192 raises AppointmentNotCancellable193 if status = Scheduled then194 status := Cancelled195 events.add(new AppointmentCancelled(id, slot, patient, reason))196 else197 raise AppointmentNotCancellable198 return199 + recordedEvents(): ReadOnlyList<DomainEvent>200 return events.readOnlyView()201202class CancelAppointment203 - appointments: Appointments204 - outbox: Outbox205 + new(appointments: Appointments, outbox: Outbox)206 + run(id: AppointmentId, reason: CancellationReason): void207 appointment := appointments.find(id)208 appointment.cancel(reason)209 appointments.save(appointment)210 outbox.store(appointment.recordedEvents())211 return212213class ReleaseSlot214 - slots: Slots215 - handled: HandledEvents216 + new(slots: Slots, handled: HandledEvents)217 + handle(id: EventId, event: AppointmentCancelled): void218 if handled.contains(id) then219 return220 else221 slot := slots.find(event.slot())222 slot.release(event.patient())223 slots.save(slot)224 handled.add(id)225 return226```227228The After's `Appointment` keeps the shape the repositories skill gives229it: `- id: AppointmentId` first, the same private constructor and230`id()`, with `book` and `restore` left out of this fence. It differs231from that shape by holding the slot's identity rather than the slot232object, as rule 3 of designing aggregates asks, by the queries `slot()`233and `patient()`, and by `events`; the private constructor's body sets234`events` to an empty list. `cancel` keeps the notation's check and235error, and drops the release of the slot, which `ReleaseSlot` now makes.236`Appointments` keeps `find(id)` and `save(appointment)`; `save` stores237one whole appointment. `Slots` keeps the shape the placing domain logic238skill gives it: `find(id)` raises `SlotNotFound`, and `save(slot)`239stores one whole slot. `Slot.release(patientId)` is the notation's,240unchanged.241242What is stored is the cancelled appointment under its `AppointmentId`243and its event in the outbox, both in the clinic's database, in the244transaction `run` opens; later, `ReleaseSlot` stores the released slot245under its `SlotId` and the event's identity in `HandledEvents`, both in246the clinic's database, in the handler's own transaction. `HandledEvents`247is taken to answer `contains(id)` and to store an identity through248`add(id)`; it stores the identities of the events this handler has249handled, in the clinic's database, in the same transaction as the250released slot. A relay outside this fence hands each stored event, with251the `EventId` the outbox gave it, to each handler after the commit.252`ReleaseSlot` checks `id` because the notation's `release` frees the slot253whoever holds it, so a repeated event after the slot was booked again254would free the new patient's slot: rule 5, by the identity the outbox255gave the event. The letter becomes a second handler of256`AppointmentCancelled`, shown in257[the outbox reference](references/the-outbox.md).258259In the Before, `run` sends `cancel` once and `release` once. In the260After, `run` sends `cancel` once, and `ReleaseSlot.handle` sends261`release` once for the event that first finds its identity. The262constructor sets `events` before `cancel` reads it, and `handled` before263`handle` reads it; every other field arrives from a constructor264parameter named for it.265266## Red flags267268Places to look, not verdicts. A red flag becomes a finding only with269evidence: a measurement, a reproducible bug, or a failing test.270271- A use case that sends an email, a text or a message before its272 transaction commits.273- A use case whose body grows one step for each new reaction to the same274 change.275- A domain object that holds a message bus, a mailer or a handler.276- An event named for an action to take, such as `SendReminder`, or for a277 field, such as `StatusChanged`.278- An event that carries the whole aggregate rather than the identities279 and facts its handlers use.280- A handler that changes something without checking whether it has281 handled that event before.282283## Common mistakes284285- Publishing the event inside the transaction, before the change286 commits.287- Letting one handler perform several unrelated reactions, so a failure288 in one repeats the others.289- Using an event for a reaction the caller must see succeed before it290 replies.291- Assuming each event arrives exactly once and in order.292- Telling the user that a reaction has happened when its handler has not293 yet run.294295## Related skills296297- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule298 labels.299- [oo-designing-aggregates](../oo-designing-aggregates/SKILL.md) draws300 the boundary that makes a reaction a later step after the commit.301- [oo-placing-domain-logic](../oo-placing-domain-logic/SKILL.md) gives302 the use-case object that opens and ends the transaction.303- [oo-modeling-lifecycles](../oo-modeling-lifecycles/SKILL.md) keeps304 the history of transitions inside the aggregate.305- [oo-speaking-the-domain-language](../oo-speaking-the-domain-language/SKILL.md)306 finds the staff's words for the event.307- [oo-separating-reads-from-writes](../oo-separating-reads-from-writes/SKILL.md)308 keeps read models current from events and decides when event sourcing309 earns its cost.310311## Further reading312313- [The outbox](references/the-outbox.md)314- [Events or direct messages](references/events-or-direct-messages.md)