Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 1

Domain events, domain services and avoiding an anemic model

Let one aggregate record what happened as a domain event and let others react in their own transactions, put rules that belong to no single object in a domain service, and spot an anemic model, plus the CRUD areas where a simple transaction script is the better choice.

Contentsand lesson path

What you will learn

  • Coordinate behavior across aggregates with domain events and domain services without breaking encapsulation.

01. Why it matters

When a Larkfield member books a room, other things should follow: the member's monthly minutes go up and the door system issues an access code. The first version did all of it inside one book() call and one transaction. When the door-code service was slow, bookings were slow; when it was down, bookings failed; and every new reaction meant editing the booking code.

Lesson 2 said one transaction should change one aggregate. So how do other aggregates learn about a booking, where does a rule live that belongs to none of them, and what goes wrong when a team moves every rule out of its entities? This lesson answers with domain events, domain services, and a warning about the anemic domain model.

02. Domain events: facts the aggregate records

Evans's DDD Reference defines a domain event as 'something happened that domain experts care about'. It is a record of the past, so it is immutable, and it usually carries the time and the identities of the entities involved. Its name is a past-tense phrase from the ubiquitous language, such as RoomBooked or BookingMoved, the orange notes from EventStorming.

Three design choices make events useful:

  • The aggregate records the event, inside the method that changes its state, because only the aggregate knows whether something really happened. Moving a booking to the time it already has changes nothing, so no event is recorded.
  • The event carries the facts handlers need, here the member id and the minutes, so a handler does not have to load the RoomDay to find them.
  • Each reaction is a handler with its own transaction on its own aggregate. RoomDay never calls the usage repository or holds a usage object; it does not even know who listens. The usage counter and the door system each change their own data. If one fails, the booking stands and only that handler is retried; Vernon describes exactly this, with the message delivered again until the handler succeeds or reaches a retry limit.

The script below adds those ideas to a richer RoomDay, a second aggregate MemberUsage and a domain service. Save it next to values.py from lesson 1 and run it with Python 3.11 or newer.

Python · rich.py
"""A rich RoomDay that raises events, a second aggregate and a domain service."""
from dataclasses import dataclass
from datetime import date, datetime, time

from values import TimeRange


@dataclass(frozen=True)
class RoomBooked:
    event_id: str  # one id per occurrence: room/day/n
    occurred_at: datetime
    room: str
    booking_id: str
    member_id: str
    minutes: int


@dataclass(frozen=True)
class BookingMoved:
    event_id: str
    occurred_at: datetime
    room: str
    booking_id: str
    member_id: str
    old: TimeRange
    new: TimeRange


class RoomDay:
    """Aggregate root: all bookings of one room on one day."""

    def __init__(self, room: str, day: date) -> None:
        self.room, self.day, self._recorded = room, day, 0
        self._bookings: dict[str, tuple[str, TimeRange]] = {}
        self.events: list[object] = []  # recorded now, published after saving

    def _next_id(self) -> str:
        self._recorded += 1  # saved with the aggregate, so never reused
        return f"{self.room}/{self.day}/{self._recorded}"

    def is_free(self, wanted: TimeRange, ignore: str | None = None) -> bool:
        return not any(wanted.overlaps(taken) for booking_id, (_, taken)
                       in self._bookings.items() if booking_id != ignore)

    def book(self, booking_id: str, member_id: str, wanted: TimeRange,
             now: datetime) -> None:
        if not self.is_free(wanted):
            raise ValueError(f"{self.room}: {wanted} is taken")
        self._bookings[booking_id] = (member_id, wanted)
        self.events.append(RoomBooked(self._next_id(), now, self.room, booking_id,
                                      member_id, wanted.minutes))

    def move(self, booking_id: str, wanted: TimeRange, now: datetime) -> None:
        member_id, old = self._bookings[booking_id]
        if wanted == old:
            return  # nothing changed, so nothing happened
        if not self.is_free(wanted, ignore=booking_id):
            raise ValueError(f"{self.room}: {wanted} is taken")
        self._bookings[booking_id] = (member_id, wanted)
        self.events.append(BookingMoved(self._next_id(), now, self.room, booking_id,
                                        member_id, old, wanted))


class MemberUsage:
    """A second aggregate: room minutes a member used this month."""

    def __init__(self, member_id: str, allowance: int) -> None:
        self.member_id, self.allowance, self.used = member_id, allowance, 0

    def record(self, event: RoomBooked | BookingMoved) -> None:
        if isinstance(event, RoomBooked):
            self.used += event.minutes
        else:
            self.used += event.new.minutes - event.old.minutes


def smallest_free_room(days: list[RoomDay], seats: dict[str, int],
                       wanted: TimeRange, people: int) -> RoomDay | None:
    """Domain service: Larkfield's allocation policy. It reads and changes nothing."""
    fits = [d for d in days if seats[d.room] >= people and d.is_free(wanted)]
    return min(fits, key=lambda d: seats[d.room], default=None)


seats = {"R1": 4, "R2": 8, "R3": 16}
day, now = date(2026, 12, 7), datetime(2026, 12, 1, 9, 0)
days = {room: RoomDay(room, day) for room in seats}
usage = {"M-7": MemberUsage("M-7", allowance=600)}

days["R2"].book("BK-1", "M-9", TimeRange(time(9, 0), time(10, 0)), now)
days["R2"].events.clear()  # pretend BK-1 was saved and published yesterday

ten_to_twelve = TimeRange(time(10, 0), time(12, 0))
chosen = smallest_free_room(list(days.values()), seats, ten_to_twelve, people=6)
print("policy picked:", chosen.room)
chosen.book("BK-2", "M-7", ten_to_twelve, now)
try:
    chosen.move("BK-2", TimeRange(time(9, 30), time(11, 30)), now)
except ValueError as rule:
    print("refused:", rule)
later = TimeRange(time(10, 30), time(12, 30))
chosen.move("BK-2", later, now)
chosen.move("BK-2", later, now)  # same again: nothing happened, no event
chosen.move("BK-2", ten_to_twelve, now)  # back again: a new occurrence, a new id

pending, chosen.events = chosen.events, []  # the save succeeded: publish now
for event in pending:
    print("published:", event.event_id, type(event).__name__, event.booking_id)
    usage[event.member_id].record(event)  # the usage handler, its own transaction
print("M-7 used", usage["M-7"].used, "of", usage["M-7"].allowance, "minutes")
Terminal
python3 rich.py
Expected output
policy picked: R2
refused: R2: 09:30-11:30 is taken
published: R2/2026-12-07/2 RoomBooked BK-2
published: R2/2026-12-07/3 BookingMoved BK-2
published: R2/2026-12-07/4 BookingMoved BK-2
M-7 used 120 of 600 minutes

The policy chose R2 for six people. The move into 09:30 was refused, repeating a move to the same time recorded nothing, and moving back to 10:00 recorded a new event. M-7's usage stays at 120 minutes, because no move changed the length.

Look at the ids. Each names one occurrence, not a kind of change: RoomDay numbers every event it records, and the counter is saved with the aggregate, so once a save succeeds no two of its events share a number. An id built from the change itself, such as BK-2/moved/10:00-12:00, would repeat when the booking moves back, or when a cancelled booking id is booked again, and a handler that skips ids it has already seen would silently drop a real event. A random uuid4() is also unique per occurrence and needs no counter; a sequence number adds order, so a handler can notice that event 4 arrived before event 3. Either way the id is fixed when the event is recorded and travels with it, beside occurred_at.

The events wait in chosen.events until the save is done. If they were published before the save and the save then failed, for example on a stale version, the handler would count minutes for a booking that was never stored. So: record events during the change, publish them only after the commit.

That leaves one gap. If the process crashes after the commit but before publishing, the event is lost and the usage counter never catches up. The standard fix is a transactional outbox: write the events into an outbox table in the same database transaction as the aggregate, and let a separate relay read the table and publish them. Either both the booking and its events are stored, or neither is. The relay may publish an event twice, for example if it crashes after sending but before marking the row as sent, so handlers must be idempotent: applying the same event twice has the same effect as applying it once. A handler usually achieves this by remembering the ids of events it has applied, which is why each id must name one occurrence; the DDD Reference notes that an event's identity lets a receiver recognise two copies as the same event. Delivery guarantees are covered in the message queues lesson, and the outbox in event-driven architecture.

03. Domain services and application services

Larkfield's allocation policy says: give a group the smallest free room that seats it, so big rooms stay free for big groups. RoomDay cannot own that rule, because one room knows nothing about the others, and inventing a RoomPicker entity with an identity would be artificial. Evans's answer is a domain service: when a significant process in the domain is not the natural job of an entity or value object, declare it as a standalone operation, named in the ubiquitous language. smallest_free_room is one. It has no state, reads several aggregates and changes none of them.

Some domain services do coordinate a change, such as a transfer between two accounts that needs both balances and an exchange rate. Even then the service never edits another object's fields: it calls each aggregate's own methods, so each root still enforces its rules, and the one-aggregate-per-transaction rule may split the work into a first change plus an event.

Do not confuse it with an application service, the code that runs one use case: it loads aggregates from repositories, calls domain objects and services, saves, and publishes events. Fowler quotes Evans's description of this layer: it is kept thin and does not contain business rules. A domain service holds a business rule; it usually receives the aggregates it needs from the application service rather than loading or saving them itself.

04. The anemic domain model

Services are easy to overuse. In 2003 Martin Fowler described the anemic domain model: classes named after domain nouns that are 'little more than bags of getters and setters', with all the logic in service classes above them. It looks like a domain model but behaves like procedural code, so in his words it carries the costs of a domain model without its benefits. Here is the failure it invites. The rule lives in one service; a second service, written months later by someone else, changes the same data and does not know the rule exists.

Python · anemic.py
"""An anemic model: the data class has no behaviour, services hold the rules."""
from dataclasses import dataclass, field
from datetime import time

from values import TimeRange


@dataclass
class RoomDayRecord:
    room: str
    bookings: dict[str, TimeRange] = field(default_factory=dict)


class BookingService:
    def book(self, day: RoomDayRecord, booking_id: str, wanted: TimeRange) -> None:
        if any(wanted.overlaps(taken) for taken in day.bookings.values()):
            raise ValueError(f"{wanted} overlaps an existing booking")
        day.bookings[booking_id] = wanted


class RescheduleService:  # added six months later by another developer
    def move(self, day: RoomDayRecord, booking_id: str, wanted: TimeRange) -> None:
        day.bookings[booking_id] = wanted


day = RoomDayRecord("R2")
BookingService().book(day, "BK-1", TimeRange(time(9, 0), time(10, 0)))
BookingService().book(day, "BK-2", TimeRange(time(11, 0), time(12, 0)))
RescheduleService().move(day, "BK-2", TimeRange(time(9, 30), time(10, 30)))
for booking_id, at in day.bookings.items():
    print(booking_id, at)
first, second = day.bookings.values()
print("overlap stored:", first.overlaps(second))
Terminal
python3 anemic.py
Expected output
BK-1 09:00-10:00
BK-2 09:30-10:30
overlap stored: True

Compare RoomDay.move in rich.py. It runs the same is_free check as book, because every change has to go through the root's methods and the bookings dictionary is private (by convention only: Python does not enforce it, so reviews and tests guard the rule). The cure for anemia is not 'no services'; it is putting each rule on the object that owns the data the rule protects.

05. When a transaction script is the better choice

Fowler is also clear that domain models are not always the best tool. A transaction script organises logic as one procedure per request, which is simpler when there are few rules. Larkfield has such areas: staff edit each room's name, photos and equipment list, members update their profile, and finance downloads a monthly CSV. Their only rules are 'required' and 'valid email'. Plain records and short scripts are the better choice there, and they can live in the same codebase as the rich RoomDay. Strategic DDD's subdomain lesson explains where a rich model pays off.

Events have costs too. The flow of one request is spread across handlers, so it is harder to follow and to debug, and readers of the second aggregate see data that lags. Use an event when the reaction belongs to another aggregate and may happen a moment later; keep the change inside one aggregate when it must be immediate.

06. Check your understanding

Practice check · 3 questions

Events, services and anemia

Each question has one best answer.

Q1. In anemic.py, RescheduleService stored an overlap because it never checked for one. Which change best stops this from happening again?
Q2. The usage handler must react when a booking's time changes. Which event should RoomDay record when a booking is moved?
Q3. BookingMoved has two handlers: MemberUsage, and DoorAccess, which reissues a door code through an outside service. The door service is down. What should happen?
Practice only: not graded, not saved, not evidence.

07. Apply it

Use your clinic model.

  1. Name three domain events that a clinician's day aggregate records, in the past tense, and list the fields each must carry so that no handler needs to load the aggregate.
  2. For one event, write two handlers on two different aggregates and decide what each does if it fails.
  3. Find one rule that belongs to no single aggregate, such as 'offer the nearest clinician with a free slot', and write it as a domain service with no state.
  4. Name one part of the clinic system where a transaction script is enough.

08. Review prompt

Without looking back:

  1. Why does the aggregate, not the application service, record a domain event?
  2. What goes wrong if events are published before the save, and what gap remains if they are published after it?
  3. How does an outbox close that gap, and why must handlers then be idempotent?
  4. What makes smallest_free_room a domain service and not an application service?
  5. Describe the anemic domain model and the bug it invited in anemic.py.
  6. Name a part of a system where you would choose a transaction script.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check