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 2 of 6 · Concept · 25 min · revision 1

Aggregates as consistency boundaries

Draw an aggregate around the business rules that must hold in one transaction, watch three boundaries race under optimistic concurrency, and size aggregates with Vaughn Vernon's four rules, one repository per aggregate.

Contentsand lesson path

What you will learn

  • Design aggregates around invariants, sized so that one transaction changes one aggregate.

01. Why it matters

At 08:59 on a Monday, two receptionists at Larkfield Works each take a call. One books room R2 from 09:00 to 10:00, the other from 09:30 to 10:30. Each screen checked that the room was free, and each member received a confirmation. At 09:30 two groups meet at the same door.

Lesson 1 gave you value objects that cannot hold a backwards time range. This rule is different: no single booking can be wrong on its own, because the rule is about several bookings together. Where should such a rule live, which objects must be loaded and saved together to keep it, and what happens when two people change them at the same moment? The tactical DDD answer is the aggregate.

02. Invariants and the consistency boundary

Vaughn Vernon's articles Effective Aggregate Design (2011) define an invariant as a business rule that must always be consistent, meaning consistent at the moment a transaction commits, not 'eventually'. Larkfield's room rules are invariants: bookings of one room on one day must not overlap, a booking must fit the room's seats, and it must fall inside opening hours.

Evans's DDD Reference describes an aggregate as a cluster of entities and value objects with a boundary around it. One entity is the root. Code outside may hold references to the root only, and the root enforces the invariants of the whole cluster. Martin Fowler adds the practical consequences: you load and save whole aggregates, and transactions should not cross aggregate boundaries. Vernon sums it up: an aggregate is a transactional consistency boundary.

So the no-overlap rule needs one object that can see every booking it compares. A Booking cannot check it alone, the screen can be bypassed by an import script, and a nightly clean-up lets the clash stand until morning. Only a root that owns all bookings of a room for a day can refuse the second booking before anything is saved. That root is RoomDay.

03. Three boundaries, one race

Choosing the boundary is the hard part, so the script below races two requests against three boundaries, then repeats one race. Each request does its first half (load and check) before either saves, exactly as at 08:59. The Store keeps a version number for every aggregate: a save must say which version it loaded, and if someone saved since then, the save is refused. This is optimistic concurrency; in SQL it is an UPDATE ... WHERE id = ? AND version = ? that reports zero rows when the version moved on, as the lost updates lesson shows.

Save the file next to values.py from lesson 1. Python 3.11 or newer is enough; the output comes from Python 3.12.13.

Python · boundaries.py
"""Three boundaries for room bookings, raced with the same two requests."""
import copy
from dataclasses import dataclass, field
from datetime import date, time

from values import TimeRange


class StaleVersion(Exception):
    """Someone saved this aggregate after we loaded it."""


class Store:
    """Rows with a version number each, like a table with a version column."""

    def __init__(self) -> None:
        self.rows: dict[object, tuple[int, object]] = {}

    def load(self, key: object, empty: object) -> tuple[int, object]:
        version, data = self.rows.get(key, (0, empty))
        return version, copy.deepcopy(data)

    def save(self, key: object, data: object, expected: int) -> int:
        current = self.rows.get(key, (0, None))[0]
        if current != expected:
            raise StaleVersion(f"{key} loaded at v{expected}, now v{current}")
        self.rows[key] = (current + 1, copy.deepcopy(data))
        return current + 1


@dataclass
class Schedule:
    """Aggregate root that owns some bookings; its key decides how many."""

    bookings: dict[str, tuple[date, TimeRange]] = field(default_factory=dict)

    def book(self, booking_id: str, day: date, wanted: TimeRange) -> None:
        for other_id, (other_day, taken) in self.bookings.items():
            if other_day == day and wanted.overlaps(taken):
                raise ValueError(f"{wanted} overlaps {other_id} at {taken}")
        self.bookings[booking_id] = (day, wanted)


def load_and_book(store, key, booking_id, day, wanted):
    """First half of a request: load the aggregate and apply the rule."""
    version, schedule = store.load(key, Schedule())
    schedule.book(booking_id, day, wanted)
    return lambda: store.save(key, schedule, expected=version)


def check_then_insert(store, booking_id, room, day, wanted):
    """First half when each booking is its own aggregate: query, then insert."""
    for other_id, (_, row) in store.rows.items():
        if row["room"] == room and row["day"] == day and wanted.overlaps(row["at"]):
            raise ValueError(f"{wanted} overlaps {other_id}")
    row = {"room": room, "day": day, "at": wanted}
    return lambda: store.save(booking_id, row, expected=0)


def race(title, first, second):
    """Both requests do their first half before either one saves."""
    print(title)
    store = Store()
    save_first, save_second = first(store), second(store)
    print("  first request saved, version", save_first())
    try:
        print("  second request saved, version", save_second())
    except StaleVersion as conflict:
        print("  second request refused:", conflict)
        try:
            print("  retried and saved, version", second(store)())
        except ValueError as rule:
            print("  retried and rejected:", rule)
    return store


MON, TUE = date(2026, 12, 7), date(2026, 12, 8)
NINE = TimeRange(time(9, 0), time(10, 0))
HALF_NINE = TimeRange(time(9, 30), time(10, 30))

store = race(
    "A. Each booking is its own aggregate",
    lambda s: check_then_insert(s, "BK-1", "R2", MON, NINE),
    lambda s: check_then_insert(s, "BK-2", "R2", MON, HALF_NINE),
)
first, second = (row["at"] for _, row in store.rows.values())
print("  stored:", first, "and", second, "| overlap:", first.overlaps(second))

race(
    "B. RoomDay: one room on one day is the aggregate",
    lambda s: load_and_book(s, f"R2/{MON}", "BK-1", MON, NINE),
    lambda s: load_and_book(s, f"R2/{MON}", "BK-2", MON, HALF_NINE),
)
race(
    "C. Room: every day of one room is one aggregate (different days)",
    lambda s: load_and_book(s, "R2", "BK-3", MON, NINE),
    lambda s: load_and_book(s, "R2", "BK-4", TUE, NINE),
)
race(
    "D. RoomDay again with the requests from C",
    lambda s: load_and_book(s, f"R2/{MON}", "BK-3", MON, NINE),
    lambda s: load_and_book(s, f"R2/{TUE}", "BK-4", TUE, NINE),
)
Terminal
python3 boundaries.py
Expected output
A. Each booking is its own aggregate
  first request saved, version 1
  second request saved, version 1
  stored: 09:00-10:00 and 09:30-10:30 | overlap: True
B. RoomDay: one room on one day is the aggregate
  first request saved, version 1
  second request refused: R2/2026-12-07 loaded at v0, now v1
  retried and rejected: 09:30-10:30 overlaps BK-1 at 09:00-10:00
C. Room: every day of one room is one aggregate (different days)
  first request saved, version 1
  second request refused: R2 loaded at v0, now v1
  retried and saved, version 2
D. RoomDay again with the requests from C
  first request saved, version 1
  second request saved, version 1

Design A makes each booking its own aggregate, so the overlap check is a query followed by an insert. Both queries ran before either insert, both found the room free, and two overlapping bookings were stored: the 08:59 bug. Nothing in A owns the rule, so nothing can refuse it.

Design B puts every booking of R2 on Monday inside one RoomDay. The second save was refused because its copy was stale, and the retry reloaded version 1, ran the rule again and refused the clash. Notice what B did not need: no lock was held while a receptionist talked to a member. The version check only stops a save that was based on old data.

Design C makes the whole room one aggregate. The rule is still protected, but a Monday booking and a Tuesday booking now conflict although they cannot clash, and every request would load the room's whole history. Lazy loading in an ORM only delays that load; the single version still makes unrelated changes collide. Design D shows the same two requests succeeding side by side with RoomDay. This is the cost Vernon describes in his project example: two users edit unrelated parts of one large aggregate, and one of them fails because of the other.

What if Larkfield allowed late events that run past midnight? A booking from 23:00 to 01:00 could clash with bookings on two different days, so RoomDay would no longer contain everything the rule compares, and the boundary would have to change. A boundary is correct only for the rules you actually have.

A fair comparison needs one more option. PostgreSQL can enforce this particular rule itself with an exclusion constraint, EXCLUDE USING GIST (room WITH =, during WITH &&) once the btree_gist extension is installed, and its documentation uses meeting rooms as the example. If your rule fits a constraint like that, add it as a safety net. Many rules do not fit, such as a seat count that depends on the room's layout that day, and the aggregate keeps all the rules of one cluster in one place in code, where tests can reach them.

04. Sizing rules and repositories

Vernon's articles end with four rules of thumb. Each answers a sizing question.

  1. Model true invariants in consistency boundaries. Put objects together only when a real business rule compares them at commit time. Vernon calls the others false invariants: artificial constraints imposed by developers, such as 'a room has bookings, so the room must contain all of them'.
  2. Design small aggregates. Vernon's guidance is the root entity plus the minimum attributes and value-typed properties: 'the ones necessary, and no more'. Small aggregates load faster and collide less often.
  3. Reference other aggregates by identity. RoomDay stores a member_id, not a Member object. It cannot accidentally load, lock or change the member, and the two can be stored, cached or even run in different services.
  4. Use eventual consistency outside the boundary. When one change must lead to another in a different aggregate, the second follows in its own transaction, a moment later. Larkfield counts each member's monthly room hours in a separate MemberUsage aggregate that catches up after each booking; lesson 4 shows the mechanism. A stricter isolation level is no substitute: it guards one transaction that still couples, and contends on, two aggregates.

How do you decide whether a rule must be immediate? Vernon reports a tie-breaker from a conversation with Eric Evans: ask whose job it is to make the data consistent. If the user making the change must see it consistent at once, keep it in one transaction and one aggregate. If it is another user's job or the system's, let it be eventually consistent. Vernon notes that domain experts are sometimes more comfortable with a delay than developers are; the hours counter may lag by a few seconds.

Each aggregate type that code must find gets one repository, an object that acts like a collection of whole aggregates: room_days.get(room, day) and room_days.save(room_day, expected_version). There is no BookingRepository. Evans advises providing repositories only for aggregate roots that need direct access, so no code can fetch one booking and change it behind the root's back. The design patterns lesson covers the repository pattern itself.

05. When to bend the rules

'One aggregate per transaction' is a rule of thumb, and Vernon says so. He discusses four reasons to break the rules. Three can justify changing several aggregates in one transaction: a screen that creates a batch of new aggregates at once, which is no different from creating them one by one; a platform with no messaging, timers or background work to deliver eventual updates; and enterprise policies that impose global two-phase-commit transactions. The fourth, query performance, can justify holding a direct object reference instead of an id. Each is a conscious trade-off to write down, not a default.

Size cuts both ways. Design A was too small to protect its rule; design C was so large that unrelated work collided. And some parts of a system need no aggregate at all: a list of room names and photos that staff edit, with no rule beyond 'name required', is plain create-read-update-delete work, and wrapping it in roots and versions only adds code. Use aggregates where rules compare several objects and concurrent changes are likely.

06. Check your understanding

Practice check · 3 questions

Boundaries, versions and repositories

Each question has one best answer.

Q1. Two receptionists load RoomDay R3 for Friday at version 5. One books 09:00 to 10:00 and saves. A moment later the other saves a 15:00 to 16:00 booking made on her copy. With this lesson's version check, what happens to the second save?
Q2. A climbing gym runs coached sessions that members sign up for. Which rule needs the session and its sign-ups inside one aggregate, checked in the same transaction as each sign-up?
Q3. To speed up the reception screen, a developer adds BookingRepository.update(booking), which writes one booking row directly without loading its RoomDay. What is the main risk?
Practice only: not graded, not saved, not evidence.

07. Apply it

Take the clinic appointment context from your strategic DDD notes.

  1. List the rules about appointments and mark each: must it hold at commit, or can it follow later? Ask 'whose job is it?' when unsure.
  2. Draw boundaries for two aggregates, for example a clinician's day and a patient's record, and list what each root contains and which ids it holds instead of objects.
  3. Change boundaries.py so that design B uses your first aggregate, and race two requests that should conflict and two that should not.

08. Review prompt

Without looking back:

  1. What is an invariant, and why can no single booking enforce the no-overlap rule?
  2. In design A, at which step did the race let the overlap through?
  3. How does a version number stop a stale save without holding a lock?
  4. Why did design C refuse a Tuesday booking because of a Monday booking?
  5. State Vernon's four rules and the 'whose job is it?' question.
  6. Why is there no repository for Booking?

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