Skip to content

DDD building blocks

Difficulty: Intermediate

Key concepts

  • aggregate
  • aggregate root
  • consistency boundary
  • value object
  • domain service
  • domain event
  • bounded context
  • reference by id
  • What an aggregate is: a group of objects changed only through one root, so that its rules hold after every change.
  • How to draw aggregate boundaries from the rules: what must be true immediately goes inside one aggregate; what spans several does not.
  • Why aggregates refer to each other by id, not by pointer.
  • When a rule that needs two aggregates becomes a domain service, and how the application keeps both changes or neither.
  • How an aggregate records domain events, and why they are published only after the change is kept.
  • How value objects that can only be made valid fit in, and what a bounded context is.

The registrar adds a rule: a student may be in at most three courses at a time, counting waitlists. Until now every rule was about one course: its seats, its waitlist, its promotions. The Course class held all the data those rules needed and checked them itself.

The new rule needs data no single course has: how many courses one student is in. Three obvious places for it are all wrong:

  • In Course::enroll. A course would have to look at every other course to count a student’s places. It would need a pointer to all of them, and changing one course would depend on the state of the others.
  • One big object holding every course and student. The rule fits, but now every enrollment changes the same object, and with a database, every enrollment would lock or reload the whole term.
  • In the code that handles the command, as an if before the call. It works until the second place that enrolls students forgets the check.

Domain-driven design (DDD) gives names to the pieces that solve this. The ideas and names are commonly associated with Eric Evans’s 2003 book Domain-Driven Design; this page uses them as common vocabulary.

Block What it is Here
Value object Defined by its value; equal when the values are equal; usually immutable StudentId, CourseCode
Entity Has an identity that stays the same while its state changes Course (by code), StudentLoad (by student)
Aggregate A group of objects that is changed as one unit, with rules that hold after every change a course with its seats, waitlist, and events
Aggregate root The one entity of the aggregate that outside code may hold and call Course; StudentLoad
Domain service A rule that involves several aggregates and belongs to none of them domain::enroll, domain::drop
Domain event A fact the domain records about something that happened StudentSeated, StudentWaitlisted, StudentPromoted
Repository Looks like a collection of aggregates, hides storage maps here; Repository and Unit of Work builds one
Bounded context The part of a system within which one model, and one meaning of each word, applies registration, as opposed to the catalogue or billing

The first two are covered on the modelling page. This page is mostly about the third: the aggregate, because it decides where each rule lives.

Step 1: list the rules, then draw the boundaries

Section titled “Step 1: list the rules, then draw the boundaries”

An aggregate boundary is drawn around the data that one rule needs to be true at the end of every change. So list the rules, and for each one the data it needs:

Rule Data it needs Must hold Lives in
Seated students never exceed capacity one course’s seats and capacity after every change Course
No waitlist while a seat is free one course’s seats and waitlist after every change Course
A student appears at most once in a course one course’s seats and waitlist after every change Course
A student is in at most three courses one student’s list of courses after every change StudentLoad
Enrolling checks the student’s limit and the course both of the above when enrolling domain service
A promoted student is told the promotion, and a way to send soon after event handler

Three things follow from the table:

  • The course’s three rules need only that course’s data, so a course with its seats and waitlist is one aggregate.
  • The limit needs only one student’s list of courses, not the courses themselves. That list is a small aggregate of its own, StudentLoad. It stores course codes, not courses.
  • Telling a student is not an invariant at all. It can happen after the change, so it is an event, not a rule inside an aggregate.

Then classify the members:

  • Data members of an aggregate are the state its rules read. Course keeps seats and the waitlist; StudentLoad keeps a set of codes. Neither keeps a pointer to the other.
  • Member functions of the root are the only ways to change the aggregate: Course changes only through enroll, drop, and take_events; StudentLoad only through join and leave. There is no seated_mut() returning a reference that callers could change.
  • Functions that need two aggregates go into a domain service.
Two aggregates and a domain service: each aggregate's objects are reached only through its root, and the aggregates refer to each other only by id
Text description of the diagram

Two boxes, each an aggregate. The Course aggregate has a root, Course, with the code, title, and capacity, and inside it the seated students, the waitlist, and the recorded events, all reached through the root. The StudentLoad aggregate has a root, StudentLoad, with the student’s id, and inside it a set of at most three course codes. Outside both, a domain service, enroll and drop, calls both roots. Dashed lines show the only links between the aggregates: the seats and the waitlist hold StudentId values that identify a student’s load, and the load holds CourseCode values that identify courses. There are no pointers between the aggregates.

Diagram source (Mermaid)
flowchart LR
subgraph CourseAgg["Course aggregate"]
  Course["Course, the root<br/>code, title, capacity"]
  Seats["seated students"]
  Wait["waitlist"]
  Events["recorded events"]
  Course --> Seats
  Course --> Wait
  Course --> Events
end
subgraph LoadAgg["StudentLoad aggregate"]
  Load["StudentLoad, the root<br/>student id"]
  Codes["course codes, at most 3"]
  Load --> Codes
end
Service["domain service<br/>enroll and drop"]
Service -->|calls| Course
Service -->|calls| Load
Seats -.->|StudentId| Load
Wait -.->|StudentId| Load
Codes -.->|CourseCode| Course

The ids are value objects. A CourseCode can only be made by parse, which refuses badly formed text, so a function that takes a CourseCode never has to check one again:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

ids.hpp
// Value objects: two ids are equal when their text is equal, and a value
// that exists is always well formed, because parse is the only way in.
// A value object has no identity of its own: two StudentIds holding "S1"
// are interchangeable, just as two ints holding 7 are. It is small, cheap
// to copy, and never changes after it is made.
class StudentId {
public:
// "S" followed by one to six digits, such as "S12". Returns the id, or
// an empty optional (std::nullopt) for any other text: "S", "12",
// "s1", "S1a", and "S1234567" are all refused. It never throws for bad
// text; a refusal is an expected answer, so it is a value, not an
// exception. `static` because it makes a new id rather than asking an
// existing one. std::string_view lets a caller pass a string literal
// or part of a longer line without copying it first.
static std::optional<StudentId> parse(std::string_view text);
const std::string& text() const { return text_; }
// `= default` asks the compiler to write the comparison for us: it
// compares the members, here only text_. operator== gives == and !=;
// operator<=> (the "spaceship" operator) gives <, <=, > and >=, which
// std::map and std::set need to keep their keys in order. `friend`
// lets these free functions see the private text_.
friend bool operator==(const StudentId&, const StudentId&) = default;
friend auto operator<=>(const StudentId&, const StudentId&) = default;
private:
// Private, so code outside the class cannot write StudentId{"oops"}:
// the only public way to make a new id is parse, which checks first.
// Copies are still allowed, because a copy of a valid id is valid.
// The text is taken by value and moved into text_ (no second copy).
explicit StudentId(std::string text) : text_{std::move(text)} {}
std::string text_; // well formed; nothing changes it after construction
};
// The same shape as StudentId, with a different rule for the text. They
// are two separate types on purpose: a function that wants a CourseCode
// cannot be handed a StudentId by mistake, even though both hold a string.
class CourseCode {
public:
// Two to four capital letters followed by three digits, such as "CS101"
// or "MATH201". Empty optional for anything else, such as "cs101"
// (small letters) or "CS-1" (a dash, and too few digits).
static std::optional<CourseCode> parse(std::string_view text);
const std::string& text() const { return text_; }
friend bool operator==(const CourseCode&, const CourseCode&) = default;
friend auto operator<=>(const CourseCode&, const CourseCode&) = default;
private:
explicit CourseCode(std::string text) : text_{std::move(text)} {} // only parse calls this
std::string text_;
};

The only constructor that accepts text is private, so new ids come only from parse; copies and assignments copy an id that is already valid. No member function changes text_, so the class needs no other rules. A moved-from id, like the local load after the commit further down, holds unspecified text and may only be assigned to or destroyed. The defaulted operator== and operator<=> compare the text, which makes the ids usable as std::map and std::set keys. Text from outside is parsed once, at the edge of the program, and everything inside works with ids that cannot be wrong.

The root is the only door. Its comment states the invariants, and every member function that returns normally has kept them:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

course.hpp
// The answers Course::enroll and Course::drop can give. A refusal, such as
// already_in_course, is an ordinary result the caller checks, not an
// exception: asking twice is something users really do.
enum class JoinResult { seated, waitlisted, already_in_course };
enum class LeaveResult { left_seat, left_waitlist, not_in_course };
// An aggregate root. Everything inside it (the seats, the waitlist, the
// recorded events) is changed only through these member functions, so
// the invariants below hold after every call:
// - seated().size() <= capacity()
// - the waitlist is empty while a seat is free
// - a student appears at most once, in the seats or the waitlist
// Other aggregates are named by id only: a student is a StudentId here.
// A Course owns all of its data by value (no pointers), so copying a
// Course copies its seats, waitlist and events; the registry relies on
// that to try a change on a copy before keeping it.
class Course {
public:
// Throws std::invalid_argument if capacity is less than 1, so no
// Course with zero seats can exist. The code is already a valid
// CourseCode, so it needs no check here.
Course(CourseCode code, std::string title, int capacity);
const CourseCode& code() const { return code_; }
const std::string& title() const { return title_; }
int capacity() const { return capacity_; }
const std::vector<StudentId>& seated() const { return seated_; }
const std::deque<StudentId>& waitlist() const { return waitlist_; }
// True if the student holds a seat or is anywhere on the waitlist.
bool contains(const StudentId& student) const;
// Seats the student if a seat is free, otherwise adds them to the end of
// the waitlist; either way records one event. A student already in the
// course gets already_in_course, and nothing changes or is recorded.
JoinResult enroll(const StudentId& student);
// Removes the student from the waitlist or their seat. Leaving a seat
// moves the first student in line into it and records StudentPromoted.
// A student in neither gets not_in_course, and nothing changes.
LeaveResult drop(const StudentId& student); // promotes the next in line
// Returns the events recorded since the last call, oldest first, and
// forgets them, so a second call straight after returns an empty list.
std::vector<CourseEvent> take_events();
private:
CourseCode code_;
std::string title_;
int capacity_;
std::vector<StudentId> seated_; // in enrollment order
// A deque ("double-ended queue") because the waitlist is added to at
// the back and served from the front; pop_front is cheap on a deque.
std::deque<StudentId> waitlist_; // first in line first
std::vector<CourseEvent> events_; // not yet taken
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

course.cpp
// The order inside each function matters: every check comes before the
// first change, so a refusal leaves the course exactly as it was.
JoinResult Course::enroll(const StudentId& student) {
// Refuse a second place for the same student, in a seat or in line.
if (contains(student)) return JoinResult::already_in_course;
// A seat is free while fewer students are seated than the capacity.
// seated_.size() is an unsigned std::size_t and capacity_ is an int;
// static_cast converts the int so both sides have the same type. It is
// safe because the constructor made sure capacity_ is at least 1.
if (seated_.size() < static_cast<std::size_t>(capacity_)) {
seated_.push_back(student); // a copy of the id; the caller keeps theirs
// Record what happened; nothing is sent from here. The
// StudentSeated holds copies of both ids and is converted to a
// CourseEvent (a std::variant) as it is added. If this push_back
// runs out of memory and throws, the student is seated with no
// event; the registry works on a copy, so that copy is discarded.
events_.push_back(StudentSeated{student, code_});
return JoinResult::seated;
}
// No seat free: join the back of the line. The waitlist is only ever
// non-empty when every seat is taken, so this keeps the invariant.
waitlist_.push_back(student);
// After the push_back, size() is this student's place, counting from
// 1: the first student to wait sees 1, the next sees 2.
events_.push_back(StudentWaitlisted{student, code_, waitlist_.size()});
return JoinResult::waitlisted;
}
// Leaving has three cases: the student is waiting, seated, or not here.
// The waitlist is searched first; a student is never in both places.
LeaveResult Course::drop(const StudentId& student) {
// std::find returns an iterator (a position) to the first match, or
// waitlist_.end() ("one past the last", meaning "not found").
const auto waiting = std::find(waitlist_.begin(), waitlist_.end(), student);
if (waiting != waitlist_.end()) {
// Leaving the line frees no seat, so nobody is promoted and no
// event is recorded. The iterator is used once, then not again:
// erase makes iterators into the deque invalid.
waitlist_.erase(waiting);
return LeaveResult::left_waitlist;
}
const auto seat = std::find(seated_.begin(), seated_.end(), student);
if (seat == seated_.end()) return LeaveResult::not_in_course; // in neither: change nothing
// erase removes the id and shifts the later ids down one place, so the
// remaining seats stay in enrollment order.
seated_.erase(seat);
// Right here a seat is free while someone may still be waiting: the
// invariant is broken for these few lines, which no caller can see.
if (!waitlist_.empty()) { // keep "no waitlist while a seat is free"
// A seat was just freed, so this push_back cannot reallocate, and
// moving the id cannot throw.
// std::move hands the id's text over instead of copying it; the
// moved-from id left at the front is removed by pop_front at once.
seated_.push_back(std::move(waitlist_.front()));
waitlist_.pop_front();
// seated_.back() is the student just promoted (the last one added).
events_.push_back(StudentPromoted{seated_.back(), code_});
}
return LeaveResult::left_seat;
}
How this code works: Course::enroll and Course::drop on CS101

Both functions follow the same shape: check first, then change, then record. A refusal returns before the first change, so it leaves the course exactly as it was and records no event.

enroll asks two questions in order:

  1. Is the student already in the course, in a seat or in line? Then the answer is already_in_course, and nothing else happens.
  2. Is a seat free (fewer seated than the capacity)? Then the student is added to seated_ and a StudentSeated event is recorded. Otherwise they go to the back of waitlist_, and the StudentWaitlisted event carries their place, which is the waitlist’s size just after the push_back.

drop looks in the waitlist first, then in the seats:

  1. Found in the waitlist: erase that entry and return left_waitlist. No seat was freed, so nobody is promoted and no event is recorded.
  2. Not found in the seats either: return not_in_course, changing nothing.
  3. Found in a seat: erase it. For a moment a seat is free while someone may be waiting, which breaks “no waitlist while a seat is free”. So, if anyone is waiting, the first in line is moved into the seat, removed from the front of the line, and a StudentPromoted event is recorded. The rule holds again before drop returns.

A worked example. CS101 has 2 seats. These are the CS101 commands from the script further down, as they reach the course:

Call seated_ after waitlist_ after Result Event recorded
enroll(S1) S1 (empty) seated StudentSeated S1
enroll(S2) S1, S2 (empty) seated StudentSeated S2
enroll(S3) S1, S2 S3 waitlisted StudentWaitlisted S3, 1
drop(S1) S2, S3 (empty) left_seat StudentPromoted S3

The last row is what report CS101 prints later: seated: S2, S3 and an empty waitlist. The second enroll S3 CS101 in the script never reaches Course::enroll: the domain service below sees that the course already contains S3 and refuses first.

Four details matter:

  • seated() and waitlist() return references to const. Outside code can read the seats but not change them, so no change can bypass the rules.
  • Students are StudentId values, not pointers to student objects. A course does not reach into a student, and a student can be stored, loaded, or removed without the course knowing. An id can still name a removed student, but that shows up as a failed lookup, not a dangling pointer.
  • drop promotes in the same call that frees the seat. Between the two, the rule “no waitlist while a seat is free” is broken, but no one outside can see that moment.
  • Seating, waitlisting, and promoting each record an event instead of sending anything. Leaving records none here, because no handler needs it. The aggregate has no notifier and no stream; it only says what happened.

If an allocation fails partway through enroll or drop, a Course can be left with a change made and its event not recorded. The promotion in drop is written so that the seat change itself cannot fail halfway, and the registry below works on copies, so a failure leaves the stored course as it was.

The student’s load is small: an id and a set of codes. Its root keeps the limit:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

student_load.hpp
// The answers StudentLoad::join can give; none of them is an exception.
enum class LoadResult { joined, already_joined, at_limit };
// A second aggregate root: one student's course load. Its invariant is
// the registrar's limit, courses().size() <= max_courses, counting
// waitlists as well as seats. Courses are named by code only.
class StudentLoad {
public:
// The registrar's limit, one number shared by every load (static) and
// fixed at compile time (constexpr). std::size_t so it compares with
// courses().size() without a cast.
static constexpr std::size_t max_courses = 3;
// A new load starts with no courses. `explicit` stops a StudentId from
// turning into a StudentLoad by accident where a load is expected.
explicit StudentLoad(StudentId student) : student_{std::move(student)} {}
const StudentId& student() const { return student_; }
const std::set<CourseCode>& courses() const { return courses_; }
// Adds the course to the load. Checks in this order: a course already
// in the load gives already_joined (and is not counted twice); a full
// load gives at_limit; only then is the code added. Refusals change
// nothing.
LoadResult join(const CourseCode& course);
bool leave(const CourseCode& course); // false if the course was not in the load
private:
StudentId student_;
// A std::set keeps each code once and in sorted order (it uses the
// CourseCode operator<=>), which is why "load S3" lists codes A to Z.
std::set<CourseCode> courses_;
};

Enrolling needs both aggregates’ rules: the course must not already contain the student, and the student must be under the limit. The rule belongs to neither class, so it is a domain service, here two free functions. They are part of the domain, not the application: the registrar would recognise their logic, and they know nothing about storage or text.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

registrar.hpp
// The domain's answer to "enroll this student in this course": one of four
// outcomes, plus the waitlist place when the answer is waitlisted.
enum class EnrollStatus { seated, waitlisted, already_in_course, at_course_limit };
// A small result struct, returned by value. The `= ...` after each member
// is a default, used when a member is not given; the functions below
// always give both, as in {EnrollStatus::seated, 0}.
struct EnrollDecision {
EnrollStatus status = EnrollStatus::already_in_course;
std::size_t position = 0; // place on the waitlist, from 1, when waitlisted
};
// A domain service: enrolling needs the rules of two aggregates, the
// student's limit and the course's seats, and belongs to neither. It
// changes both objects it is given; the caller must keep both changes
// or neither.
// Both are taken by non-const reference (&): the functions change the very
// objects the caller passes, not copies. They own nothing and keep no
// reference after they return.
EnrollDecision enroll(StudentLoad& load, Course& course);
// Removes the student from the course (seat or waitlist) and, only if they
// were in it, removes the course from their load.
LeaveResult drop(StudentLoad& load, Course& course);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

registrar.cpp
// Three questions in a fixed order; each refusal returns before anything
// later runs. `return {a, b};` builds the EnrollDecision from its two
// members.
EnrollDecision enroll(StudentLoad& load, Course& course) {
// 1. Already seated or waiting here? Refuse first, before the limit,
// and before either aggregate is changed.
if (course.contains(load.student())) return {EnrollStatus::already_in_course, 0};
// 2. Under the limit? join checks and, if there is room, adds the code
// to the load. After this line the load may have changed while the
// course has not yet; that is why the caller keeps both or neither.
// join can also say already_joined, which would mean the two
// aggregates disagree; enrolling below brings them back in step.
if (load.join(course.code()) == LoadResult::at_limit) return {EnrollStatus::at_course_limit, 0};
// 3. The course does not contain the student, so it seats or waitlists.
if (course.enroll(load.student()) == JoinResult::seated) return {EnrollStatus::seated, 0};
// Waitlisted: they were added at the back, so the waitlist size is
// their place, counting from 1.
return {EnrollStatus::waitlisted, course.waitlist().size()};
}
// The course goes first, because only the course knows whether the student
// was in it. Leaving a seat or leaving the waitlist both free a place in the
// load, since waitlist places count towards the limit. If the course says
// not_in_course, the load is left alone. leave's true/false answer is not
// needed here.
LeaveResult drop(StudentLoad& load, Course& course) {
const LeaveResult left = course.drop(load.student());
if (left != LeaveResult::not_in_course) load.leave(course.code());
return left;
}
How this code works: domain::enroll and domain::drop, traced for S3

domain::enroll is handed two aggregates by reference and asks three questions, each of which can end the call:

  1. Already in this course? course.contains checks seats and waitlist. If yes, return already_in_course. Neither object has changed.
  2. Room in the load? load.join(course.code()) refuses with at_limit when the load already has 3 courses; a refused join adds nothing, so again neither object has changed. If there is room, the code is added to the load. From this point the load has changed and the course has not, which is why the caller must keep both changes or neither.
  3. Seat or waitlist? course.enroll cannot answer already_in_course here, because step 1 ruled it out, so it seats or waitlists the student.

domain::drop asks the course first, because only the course knows whether the student was in it. If the course says not_in_course, the load is left alone; otherwise the course code leaves the load, whether the student held a seat or a waitlist place.

A worked example. S3’s commands from the script below. CS101’s 2 seats are already taken by S1 and S2:

Command 1. in course? 2. load.join 3. course.enroll Decision
enroll S3 CS101 no joined: CS101 waitlisted waitlisted, position 1
enroll S3 MA101 no joined: CS101, MA101 seated seated
enroll S3 PH101 no joined: CS101, MA101, PH101 seated seated
enroll S3 EN101 no at_limit (3 already) not called at_course_limit
enroll S3 CS101 yes, waiting not called not called already_in_course

Then drop S1 CS101 runs domain::drop with S1’s load: CS101 leaves S1’s load, and Course::drop promotes S3. S3’s load is not touched, because it already counted CS101. drop S3 PH101 takes PH101 out of S3’s load, so the next enroll S3 EN101 joins and is seated.

The order of checks is a decision: “already in this course” is reported before “at the limit”, because a student who is already enrolled has not asked for a fourth course.

Course::enroll is still public, so code that calls it directly skips the limit. The domain service makes the right path the obvious, tested one; it does not make the wrong one impossible. C++ can enforce that only with extra machinery, such as a passkey parameter that only the service can create, and for most programs a review rule is enough.

A common guideline is one aggregate per transaction: a command changes one aggregate, and anything else follows from its events. The enroll command breaks it deliberately: the course and the load must change together, or the limit is wrong. The application layer handles that:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

registry.hpp
// The application layer: one function per use case. It turns text into
// value objects, loads the aggregates it needs, lets the domain decide,
// keeps the changes, and then publishes the events. To keep the example
// short it also words the replies; earlier pages keep that apart.
// Every use case takes plain text and returns a reply line starting with
// "ok:" or "refused:". Bad input is a refusal, never an exception.
class Registry {
public:
// `notifications` receives one line per event and must outlive this object.
// The stream is taken by reference and its address stored, so the
// registry writes to the caller's stream (std::cout in main, a string
// stream in the tests) without owning it.
explicit Registry(std::ostream& notifications) : out_{&notifications} {}
std::string add_course(std::string_view code, int capacity, const std::string& title);
std::string add_student(std::string_view id);
std::string enroll(std::string_view student, std::string_view course);
std::string drop(std::string_view student, std::string_view course);
// Read-only queries; `const` promises they change nothing.
std::string load(std::string_view student) const;
std::string report(std::string_view course) const;
private:
// Writes one notification line per event, in order. Called only after a
// change has been kept.
void publish(const std::vector<domain::CourseEvent>& events);
// One map per aggregate type, keyed by the root's id. The repository
// page puts these behind interfaces. The maps own the aggregates by
// value; an aggregate lives exactly as long as its map entry.
std::map<domain::CourseCode, domain::Course> courses_;
std::map<domain::StudentId, domain::StudentLoad> loads_;
// A pointer rather than a reference member, so Registry stays
// assignable; it is set from a reference, so it is never null.
std::ostream* out_; // non-owning, never null
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

registry.cpp
// The enroll use case, in four stages: find, decide on copies, commit,
// publish. Takes the raw text of a command such as "enroll S3 CS101" and
// returns the reply line. Unknown or malformed ids are refused before any
// aggregate is touched. Throws only if memory runs out: before the commit,
// the stored aggregates are then unchanged; after it, the change is kept.
std::string Registry::enroll(std::string_view student, std::string_view course) {
// Stage 1, find. parse returns an optional: empty for malformed text.
const auto id = domain::StudentId::parse(student);
const auto code = domain::CourseCode::parse(course);
// `?:` folds two failures into one: a malformed id cannot be looked up,
// so it is treated as "not found" (loads_.end()). Otherwise find
// returns an iterator to the stored entry, or end() if there is none.
const auto load_it = id ? loads_.find(*id) : loads_.end();
if (load_it == loads_.end()) return "refused: no student " + std::string{student};
const auto course_it = code ? courses_.find(*code) : courses_.end();
if (course_it == courses_.end()) return "refused: no course " + std::string{course};
// From here on, *id and *code are safe to use: had either optional been
// empty, the matching early return above would already have happened.
// Stage 2, decide on copies. Work on copies of both aggregates. If
// anything throws before the commit, the stored objects are untouched.
// load_it->second is the stored value in the map entry (->first is the
// key); `=` here makes a full, independent copy of it.
domain::StudentLoad load = load_it->second;
domain::Course target = course_it->second;
// The domain service changes the two copies, or refuses and leaves
// them as they were.
const domain::EnrollDecision decision = domain::enroll(load, target);
// Collect what the course recorded (none after a refusal). After this
// the copy holds no events, so the course committed below carries none.
std::vector<domain::CourseEvent> events = target.take_events();
// Stage 3, commit both or neither: two moves that cannot throw (the
// static_asserts near the top of this file check that when it
// compiles). std::move lets each stored aggregate take over its copy's
// contents instead of copying them again. After this, `load` and
// `target` are moved-from and are not used again.
load_it->second = std::move(load);
course_it->second = std::move(target);
// Stage 4, publish. If publish throws now, the change is already kept
// and the remaining notices are lost; the page's outbox note covers
// that.
publish(events); // only after the change is kept
// Word the reply from the decision.
const std::string who = id->text();
const std::string what = code->text();
// The switch covers every EnrollStatus, and each case returns, so
// control never falls out of it.
switch (decision.status) {
case domain::EnrollStatus::seated: return "ok: " + who + " enrolled in " + what;
case domain::EnrollStatus::waitlisted:
return "ok: " + who + " waitlisted for " + what + " (position " +
std::to_string(decision.position) + ")";
case domain::EnrollStatus::already_in_course:
return "refused: " + who + " is already in " + what;
case domain::EnrollStatus::at_course_limit:
return "refused: " + who + " already has " +
std::to_string(domain::StudentLoad::max_courses) + " courses";
}
// Not reached, but without it the compiler would warn that a function
// returning std::string can reach its end without a return.
return "refused: " + who + " is already in " + what; // not reached
}
How this code works: One enroll command through the layers

Follow enroll S3 CS101 from the script below.

  1. main passes the line to app::run_command, which splits it into words, sees enroll with two arguments, and calls registry.enroll("S3", "CS101"). The words are std::string_views into the script’s text, so no text is copied yet.
  2. Registry::enroll (the application layer) parses both texts into value objects and finds both aggregates in its maps. The maps own the stored StudentLoad and Course; load_it and course_it only point at them.
  3. It copies both aggregates into the locals load and target. The function owns these copies; they are destroyed when it returns.
  4. It calls domain::enroll(load, target) (the domain service), which borrows the two copies by reference and calls Course::contains, StudentLoad::join, and Course::enroll on them. Only the copies change.
  5. target.take_events() moves the recorded events into the local events vector.
  6. Commit: two move assignments put the copies’ contents into the map entries. Both moves cannot throw, so once the first starts, both finish.
  7. publish(events) writes the notification lines to the stream the registry was given, then the reply text is built and returned. main prints the reply after the notifications, which is the order in the output.

What is left after each kind of failure:

Where it stops Stored aggregates Printed
Malformed or unknown student or course (step 2) unchanged; nothing was copied only the refused: reply
Domain refusal, already_in_course or at_course_limit (step 4) unchanged: the copies were never changed, and moving them back stores the same values only the refused: reply
An exception, such as std::bad_alloc, in steps 2 to 5 unchanged: any copies are destroyed as the exception leaves the function nothing
An exception in step 7, after the commit changed, and the change is kept all, some, or none of the notices; no reply

Nothing in the example program catches an exception, so one that leaves Registry::enroll would end the program; the table says what the registry holds at that moment. The commit itself (step 6) is not in the table, because it cannot fail.

The function works on copies of both aggregates. If anything throws while the domain decides, such as std::bad_alloc from a push_back, the stored objects are untouched. After the domain has decided, it commits, with two move assignments. registry.cpp checks with static_assert that both moves cannot throw, so once the first move starts, the second will finish: in a single-threaded program, the in-memory equivalent of a transaction across two aggregates. A refusal commits too; the copies are unchanged, so the moves change nothing, and the example stays shorter without a special case.

Copying a course for every command is cheap here, a few short vectors. With a database, the same shape becomes: load both aggregates, decide, save both in one database transaction. That is reasonable when both live in one database. When they live in different services, a transaction across both is often not available, and the design moves to events and correction after the fact; the transaction and persistence boundaries page covers that.

The course records events as plain structs, collected in a std::variant:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

events.hpp
// Domain events: facts the course records about itself, in the past
// tense. They carry ids, not references, so they stay valid after the
// course that recorded them is gone. Each is a plain struct with public
// members and no functions: data only, copied freely.
struct StudentSeated {
StudentId student;
CourseCode course;
};
struct StudentWaitlisted {
StudentId student;
CourseCode course;
std::size_t position; // from 1
};
struct StudentPromoted {
StudentId student;
CourseCode course;
};
// One type that can hold any of the three. A std::variant holds exactly one
// of its listed types at a time and remembers which, so a
// std::vector<CourseEvent> can keep different kinds of event in order. No
// base class, no pointers, no new: each event is stored by value.
using CourseEvent = std::variant<StudentSeated, StudentWaitlisted, StudentPromoted>;

take_events hands them over and forgets them, and the registry publishes them after the commit, so nobody is told about a change that was thrown away. The reverse can still happen: if publishing fails, the change stays but the notice is lost. Systems that must not lose events store them with the change and send them from there, a technique often called an outbox:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

registry.cpp
// Turns each recorded event into one notification line, in the order the
// events happened. The events are read through a const reference, so
// nothing is copied and nothing is changed. Overloaded (defined at the top
// of this file) is a small struct that inherits from all the lambdas it is
// given, so one object has three call operators, one per event type.
void Registry::publish(const std::vector<domain::CourseEvent>& events) {
for (const domain::CourseEvent& event : events) {
// std::visit looks at which type the variant holds right now and
// calls the lambda whose parameter type matches it: a StudentSeated
// goes to the first lambda, and so on. If a lambda were missing for
// one of the three types, this line would not compile. Each lambda
// captures `this` so it can reach out_, the registry's stream;
// *out_ is that stream.
std::visit(Overloaded{
[this](const domain::StudentSeated& e) {
*out_ << "notify " << e.student.text() << ": you have a seat in "
<< e.course.text() << '\n';
},
[this](const domain::StudentWaitlisted& e) {
*out_ << "notify " << e.student.text() << ": you are number "
<< e.position << " on the waitlist for " << e.course.text()
<< '\n';
},
[this](const domain::StudentPromoted& e) {
*out_ << "notify " << e.student.text()
<< ": a seat opened; you are enrolled in " << e.course.text()
<< '\n';
},
},
event); // the second argument: the variant to look inside
}
}

The Overloaded helper combines three lambdas into one callable, so std::visit picks the one matching the event’s type. Here a new event type without a matching handler is a compile error, as long as no catch-all auto lambda is added. The variant also keeps notification code out of the event structs; with a base class, each event would carry a virtual handle, or you would need a visitor interface to get the same check.

Events are named in the past tense, carry ids rather than references, and contain what a handler needs. These handlers only print; a real one would send mail or update another aggregate.

class domain::CourseCode

value object; StudentId is the same shape

Data members

  • std::string text_; well formed, set only by parse

Member functions

  • static std::optional<CourseCode> parse(std::string_view text);

class domain::Course

aggregate root, entity identified by code_

Data members

  • CourseCode code_;
  • int capacity_; at least 1
  • std::vector<StudentId> seated_; size() <= capacity_
  • std::deque<StudentId> waitlist_; empty while a seat is free
  • std::vector<CourseEvent> events_; recorded, not yet taken

Member functions

  • bool contains(const StudentId& student) const;
  • JoinResult enroll(const StudentId& student);
  • LeaveResult drop(const StudentId& student);
  • std::vector<CourseEvent> take_events();

class domain::StudentLoad

aggregate root, entity identified by student_

Data members

  • StudentId student_;
  • std::set<CourseCode> courses_; size() <= max_courses

Member functions

  • static constexpr std::size_t max_courses = 3;
  • LoadResult join(const CourseCode& course);
  • bool leave(const CourseCode& course);

namespace domain

the domain service: free functions

Functions

  • EnrollDecision enroll(StudentLoad& load, Course& course);
  • LeaveResult drop(StudentLoad& load, Course& course);
The domain of the aggregate example: two aggregate roots, their value objects, and the domain service; members are summarized
One enroll command: the registry copies both aggregates, the domain service applies both sets of rules, the copies are committed, and the recorded events are published last
Text description of the diagram

A sequence diagram for one enroll command. The Registry parses the ids, finds both aggregates, and copies them. It asks the domain service to enroll the load into the course. The service asks the course copy whether it contains the student, and it does not. It asks the load copy to join the course code, and it joins. It asks the course copy to enroll the student, which seats them and records an event. The service returns seated to the Registry. The Registry takes the events from the course copy, commits both copies with moves that cannot throw, then publishes the events and words the reply.

Diagram source (Mermaid)
sequenceDiagram
participant R as Registry
participant D as domain enroll
participant L as StudentLoad copy
participant C as Course copy
R->>R: parse ids, find both aggregates, copy them
R->>D: enroll the load into the course
D->>C: contains the student
C-->>D: no
D->>L: join the course code
L-->>D: joined
D->>C: enroll the student
C-->>D: seated, event recorded
D-->>R: seated
R->>C: take events
R->>R: commit both copies by moves that cannot throw
R->>R: publish the events, then word the reply

The script is new, because the rule is new:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Runs a fixed script of commands through the application, printing each
// command after "> " and then its reply. Notifications from published events
// go to the same std::cout, so they appear just before the reply of the
// command that caused them.
int main() {
// A new script: courses are now limited to three per student.
// A plain array of string_views to string literals: the text lives in
// the program itself for its whole run, so nothing is allocated.
constexpr std::string_view script[] = {
"course CS101 2 Software Design",
"course MA101 30 Linear Algebra",
"course PH101 30 Physics",
"course EN101 30 Technical Writing",
"course cs-1 10 Bad Code", // refused: not a well-formed course code
"student S1",
"student S2",
"student S3",
"enroll S1 CS101",
"enroll S2 CS101",
"enroll S3 CS101", // CS101 has 2 seats, both taken: S3 is waitlisted
"enroll S3 MA101",
"enroll S3 PH101",
"enroll S3 EN101", // refused: 3 courses, counting the CS101 waitlist place
"enroll S3 CS101", // refused: already in CS101 (checked before the limit)
"load S3",
"drop S1 CS101", // frees a seat: S3 is promoted from the waitlist
"report CS101",
"drop S3 PH101",
"enroll S3 EN101",
"load S3",
"enroll S9 CS101", // refused: S9 was never added
};
// The registry writes notifications to std::cout, which outlives it.
app::Registry registry{std::cout};
for (const std::string_view line : script) {
std::cout << "> " << line << '\n';
const std::string reply = app::run_command(registry, line); // may print notifications first
std::cout << reply << '\n';
}
}
Expected output
> course CS101 2 Software Design
ok: course CS101 added
> course MA101 30 Linear Algebra
ok: course MA101 added
> course PH101 30 Physics
ok: course PH101 added
> course EN101 30 Technical Writing
ok: course EN101 added
> course cs-1 10 Bad Code
refused: cs-1 is not a course code
> student S1
ok: student S1 added
> student S2
ok: student S2 added
> student S3
ok: student S3 added
> enroll S1 CS101
notify S1: you have a seat in CS101
ok: S1 enrolled in CS101
> enroll S2 CS101
notify S2: you have a seat in CS101
ok: S2 enrolled in CS101
> enroll S3 CS101
notify S3: you are number 1 on the waitlist for CS101
ok: S3 waitlisted for CS101 (position 1)
> enroll S3 MA101
notify S3: you have a seat in MA101
ok: S3 enrolled in MA101
> enroll S3 PH101
notify S3: you have a seat in PH101
ok: S3 enrolled in PH101
> enroll S3 EN101
refused: S3 already has 3 courses
> enroll S3 CS101
refused: S3 is already in CS101
> load S3
ok: S3 has 3 of 3 courses: CS101, MA101, PH101
> drop S1 CS101
notify S3: a seat opened; you are enrolled in CS101
ok: S1 left CS101
> report CS101
ok: CS101 Software Design, 2/2 seats taken
seated: S2, S3
waitlist: (none)
> drop S3 PH101
ok: S3 left PH101
> enroll S3 EN101
notify S3: you have a seat in EN101
ok: S3 enrolled in EN101
> load S3
ok: S3 has 3 of 3 courses: CS101, EN101, MA101
> enroll S9 CS101
refused: no student S9

S3 is refused a fourth course while waiting for CS101. The next command, enroll S3 CS101, is refused as “already in CS101”, not as “already has 3 courses”, which is the order of checks at work. When S1 drops, S3 is promoted. The load is not touched, because the waitlist place already counted, as the final load S3 still listing CS101 shows. After S3 drops PH101, the EN101 enrollment refused earlier succeeds.

The aggregate, alone. The tests check the rules through results and state, that seating, waitlisting, and promotion each record one event, and that a refusal records none:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_course.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) compares with
// == and prints both values if they differ; LLD_CHECK_THROWS(expression,
// type) fails unless the expression throws that type of exception. They
// come from the site's small test header, lld_test.hpp. The helpers
// student("S1") and course_with_seats(n), defined above this region, make
// a StudentId and a CS101 course with n seats. student uses * on the
// optional from parse, which is safe only because the text is known valid.
// Setup: a course with one seat. S1 takes it, S2 waits, S2 asks again.
// Proves: the results, that seating and waitlisting each record one event
// in order, that the refused third call records none, and that
// take_events hands the events over only once.
LLD_TEST(a_full_course_waitlists_and_records_each_change_as_an_event) {
domain::Course course = course_with_seats(1);
LLD_CHECK(course.enroll(student("S1")) == domain::JoinResult::seated);
LLD_CHECK(course.enroll(student("S2")) == domain::JoinResult::waitlisted);
LLD_CHECK(course.enroll(student("S2")) == domain::JoinResult::already_in_course);
const std::vector<domain::CourseEvent> events = course.take_events();
LLD_CHECK_EQ(events.size(), std::size_t{2}); // a refusal records nothing
// std::holds_alternative<T>(event) is true if the event holds a T now.
LLD_CHECK(std::holds_alternative<domain::StudentSeated>(events[0]));
LLD_CHECK(std::holds_alternative<domain::StudentWaitlisted>(events[1]));
LLD_CHECK(course.take_events().empty()); // taken once
}
// Setup: one seat, S1 seated, S2 waiting; the setup's events are taken
// and thrown away so only the drop's events are left to check.
// Proves: S2 moves into the freed seat, the waitlist empties, and exactly
// one StudentPromoted event names S2.
LLD_TEST(dropping_a_seat_promotes_the_first_in_line) {
domain::Course course = course_with_seats(1);
course.enroll(student("S1"));
course.enroll(student("S2"));
course.take_events();
LLD_CHECK(course.drop(student("S1")) == domain::LeaveResult::left_seat);
LLD_CHECK(course.seated() == std::vector<domain::StudentId>{student("S2")});
LLD_CHECK(course.waitlist().empty());
const std::vector<domain::CourseEvent> events = course.take_events();
LLD_CHECK_EQ(events.size(), std::size_t{1});
// std::get<T>(event) reads the T inside the variant; it would throw
// std::bad_variant_access if the event held another type, which would
// fail the test.
LLD_CHECK(std::get<domain::StudentPromoted>(events[0]).student == student("S2"));
}
// Proves the constructor's rule: a course with 0 seats cannot be made.
LLD_TEST(a_course_needs_a_seat) { LLD_CHECK_THROWS(course_with_seats(0), std::invalid_argument); }

The domain service, with real aggregates and no storage. The test also checks that a refusal leaves the load at three courses and does not add the student to the course:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_registrar.cpp
// LLD_TEST, LLD_CHECK and LLD_CHECK_EQ come from lld_test.hpp, as in the
// course tests. code("CS101"), defined above this region, makes a
// CourseCode from text known to be valid.
// Setup: S3's empty load and four courses; CS101 has one seat, already
// given to S1. S3 joins CS101 (waitlisted), MA101 and PH101 (seated).
// Proves: the waitlist place counts, so EN101 is refused as a fourth
// course, and the refusal leaves both aggregates alone: the load still
// has 3 courses and EN101 has no S3 anywhere.
LLD_TEST(the_limit_counts_waitlists_and_refusal_changes_neither_aggregate) {
domain::StudentLoad load{*domain::StudentId::parse("S3")};
domain::Course full{code("CS101"), "Software Design", 1};
domain::Course algebra{code("MA101"), "Linear Algebra", 30};
domain::Course physics{code("PH101"), "Physics", 30};
domain::Course writing{code("EN101"), "Technical Writing", 30};
full.enroll(*domain::StudentId::parse("S1"));
LLD_CHECK(domain::enroll(load, full).status == domain::EnrollStatus::waitlisted);
LLD_CHECK(domain::enroll(load, algebra).status == domain::EnrollStatus::seated);
LLD_CHECK(domain::enroll(load, physics).status == domain::EnrollStatus::seated);
LLD_CHECK(domain::enroll(load, writing).status == domain::EnrollStatus::at_course_limit);
LLD_CHECK_EQ(load.courses().size(), domain::StudentLoad::max_courses);
LLD_CHECK(writing.seated().empty());
LLD_CHECK(!writing.contains(*domain::StudentId::parse("S3")));
}
// Setup: S3 seated in PH101. Proves: dropping returns left_seat and also
// empties the load, and a second drop is refused as not_in_course.
LLD_TEST(dropping_frees_a_place_in_the_load) {
domain::StudentLoad load{*domain::StudentId::parse("S3")};
domain::Course physics{code("PH101"), "Physics", 30};
domain::enroll(load, physics);
LLD_CHECK(domain::drop(load, physics) == domain::LeaveResult::left_seat);
LLD_CHECK(load.courses().empty());
LLD_CHECK(domain::drop(load, physics) == domain::LeaveResult::not_in_course);
}

The value objects and the application, which checks that a refused command publishes nothing:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_ids.cpp
// LLD_TEST and LLD_CHECK come from lld_test.hpp, as in the course tests.
// Proves parse's rules with a few good and bad cases each: small letters,
// a dash, a bare "S", and digits with no "S" are all refused.
// has_value() is true when the optional holds an id.
LLD_TEST(only_well_formed_text_becomes_an_id) {
LLD_CHECK(domain::CourseCode::parse("CS101").has_value());
LLD_CHECK(domain::CourseCode::parse("MATH201").has_value());
LLD_CHECK(!domain::CourseCode::parse("cs101").has_value());
LLD_CHECK(!domain::CourseCode::parse("CS-1").has_value());
LLD_CHECK(domain::StudentId::parse("S12").has_value());
LLD_CHECK(!domain::StudentId::parse("S").has_value());
LLD_CHECK(!domain::StudentId::parse("12").has_value());
}
// Proves the defaulted comparisons: equal text means equal ids, and order
// follows the text ("CS101" sorts before "MA101"), as map keys need.
// The * takes the id out of each optional; these texts are known valid.
LLD_TEST(ids_with_the_same_text_are_equal) {
LLD_CHECK(*domain::StudentId::parse("S1") == *domain::StudentId::parse("S1"));
LLD_CHECK(*domain::CourseCode::parse("CS101") < *domain::CourseCode::parse("MA101"));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_registry.cpp
// LLD_TEST and LLD_CHECK_EQ come from lld_test.hpp, as in the course tests.
// These tests drive the application layer through its text interface,
// with a std::ostringstream (a stream that writes into a string) in place
// of std::cout, so the notifications can be read back with out.str().
// Setup: CS101 with one seat, students S1 and S2. Proves: a kept
// enrollment publishes one line; a refused second enrollment returns the
// refusal and adds nothing to the stream.
LLD_TEST(events_are_published_only_for_kept_changes) {
std::ostringstream out;
app::Registry registry{out};
registry.add_course("CS101", 1, "Software Design");
registry.add_student("S1");
registry.add_student("S2");
LLD_CHECK_EQ(registry.enroll("S1", "CS101"), std::string{"ok: S1 enrolled in CS101"});
LLD_CHECK_EQ(out.str(), std::string{"notify S1: you have a seat in CS101\n"});
LLD_CHECK_EQ(registry.enroll("S1", "CS101"), std::string{"refused: S1 is already in CS101"});
LLD_CHECK_EQ(out.str(), std::string{"notify S1: you have a seat in CS101\n"}); // nothing new
}
// Proves: text that does not parse is refused with a reply, not an
// exception, and nothing is added.
LLD_TEST(a_malformed_id_is_refused_at_the_edge) {
std::ostringstream out;
app::Registry registry{out};
LLD_CHECK_EQ(registry.add_course("cs-1", 10, "Bad Code"),
std::string{"refused: cs-1 is not a course code"});
LLD_CHECK_EQ(registry.add_student("student1"), std::string{"refused: student1 is not a student id"});
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

CMakeLists.txt
# The domain: two aggregates, their value objects and events, and the
# domain service that needs both. Nothing here knows about storage.
add_library(arch_agg_domain STATIC
domain/ids.cpp domain/course.cpp domain/student_load.cpp domain/registrar.cpp)
target_include_directories(arch_agg_domain PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/domain)
# The application layer: use cases, storage in maps, and event handling.
add_library(arch_agg_app STATIC app/registry.cpp app/commands.cpp)
target_include_directories(arch_agg_app PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
target_link_libraries(arch_agg_app PUBLIC arch_agg_domain)
lld_add_example(arch_enrollment_aggregate SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)
target_link_libraries(arch_enrollment_aggregate PRIVATE arch_agg_app)
lld_add_test(arch_agg_ids_tests SOURCES tests/test_ids.cpp)
target_link_libraries(arch_agg_ids_tests PRIVATE arch_agg_domain)
lld_add_test(arch_agg_course_tests SOURCES tests/test_course.cpp)
target_link_libraries(arch_agg_course_tests PRIVATE arch_agg_domain)
lld_add_test(arch_agg_registrar_tests SOURCES tests/test_registrar.cpp)
target_link_libraries(arch_agg_registrar_tests PRIVATE arch_agg_domain)
lld_add_test(arch_agg_registry_tests SOURCES tests/test_registry.cpp)
target_link_libraries(arch_agg_registry_tests PRIVATE arch_agg_app)

The word “course” means different things to different parts of a university:

Context A course is… It cares about
Registration something with seats and a waitlist capacity, who is in, the limit
Catalogue a description in a published list title, outline, prerequisites
Billing a line on an invoice fee, credits, refund deadlines

A bounded context is the part of the system where one of these models applies. Inside registration, Course has seats and no fee; billing would have its own Course, or CourseCharge, with a fee and no seats. They share the CourseCode to talk about the same course. Forcing one Course class to serve all three gives a class with every field and every rule, changed by every team. Bounded contexts are a large topic; for low-level design, the useful habit is to notice when one name is carrying two meanings, and to split the class.

The blocks pay for themselves when:

  • there are rules that must always hold, such as limits, capacities, and states that may only change in some orders;
  • the rules change and their owners can describe them, so naming them after the domain helps conversations;
  • several commands, front ends, or people change the same data, so a guarded root prevents one of them from breaking a rule.

They do not when:

  • the program stores and shows records with few rules: an aggregate with only getters and setters is ceremony;
  • the data is read-mostly, such as reports: reading straight from storage into plain structs is simpler, and aggregates are for changes;
  • the team adopts the vocabulary without the boundaries: classes named CourseAggregate that still hand out mutable references give none of the protection.
  • Aggregates that are too large. One root for a whole term or a whole customer makes every change contend. Start from the rules that must hold immediately, and make the aggregate just large enough.
  • References between aggregates. Pointers from one aggregate into another make changes spread and lifetimes tangle. Hold the other’s id, and load it when needed.
  • Mutable access to the inside. A std::vector<StudentId>& seated() lets callers break the capacity rule. Return references to const, or copies.
  • Publishing before keeping. Sending a notification inside enroll tells the student about a change that may be thrown away. Record events; publish after the commit.
  • Domain services for everything. If a rule needs only one aggregate’s data, it belongs in that aggregate. A domain service is for rules that really span two.
  • Rules in the application layer. The registry parses, loads, commits, and publishes; it does not decide who may enroll. The limit check is in the domain, where tests reach it without text or storage.
  • Some courses count double. Replace the course count with credits: StudentLoad stores a code and a credit value per course, and join takes both. The course aggregate gains a credits member but no new rule. The domain service passes course.credits().
  • Courses get sections, each with its own capacity. If a section’s seats are only meaningful inside its course (moving between sections must keep the course total), sections are entities inside the course aggregate, reached only through Course. If sections are independent, each is its own aggregate.
  • A student must be told when their load is full. That is a new event, recorded by StudentLoad::join, which then needs its own take_events, and published the same way.
  • Promotion should skip students who no longer want the course. That is a rule about one course’s waitlist, so it goes into Course::drop, perhaps with a new WaitlistEntry value holding the student and a flag.

Exercise: Choose the aggregate roots

A library lends books. Choose the aggregates and their roots, say which rules each guards, and decide which rules span aggregates.

  • A title (one book, such as a novel) has several physical copies. Each copy is on the shelf, on loan, or lost.
  • A member may have at most five copies on loan at a time.
  • A member may place a hold on a title. Holds form a queue per title; when a copy is returned, the first member in the queue has three days to collect it.
  • A fine is charged when a copy is returned late, and a member with unpaid fines over 10 cannot borrow.
Show the explained answer

One reasonable design, with its reasons:

  • Title aggregate, root Title, containing its copies as entities and its hold queue. Rules: a copy is in one state at a time; a copy goes to the first hold before anyone else; only one member is offered a returned copy at a time. These need the title’s copies and queue together, and must hold after every change.
  • Member aggregate, root Member, with the member’s current loans as a set of copy ids and the unpaid fine total. Rules: at most five loans; no borrowing over 10 in fines. These need only the member’s own data.
  • Lending a copy spans both: the title must have a copy on the shelf (or held for this member), and the member must be under both limits. That is a domain service, like domain::enroll on this page, and both aggregates change in one transaction.
  • Fines can be recorded as values inside Member, created when a late return is processed. A late return changes the title (the copy returns to the shelf or to a hold) and the member (one loan fewer, maybe a fine), so it is also a domain service.
  • The three-day collection window does not need to hold at every instant. A CopyOfferedToMember event can start a timer, and an expiry handler later offers the copy to the next member. That rule is corrected soon after, not enforced immediately.

A common wrong answer makes each copy an aggregate root. Then the hold queue, which orders members across all copies of a title, spans aggregates, and “the first member in the queue gets the next copy returned” cannot be guaranteed. Another makes the library the root, which serialises every loan in the building.

  • An aggregate is a group of objects changed only through its root; its rules hold after every change.
  • Draw boundaries from the rules: data that one rule needs at every moment belongs to one aggregate. Keep aggregates as small as the rules allow.
  • Aggregates refer to each other by id, never by pointer.
  • A rule that needs two aggregates is a domain service. The application keeps both changes or neither; in memory, copies and moves that cannot throw do that.
  • Aggregates record events; the application publishes them after the change is kept.
  • Value objects made only by parse move validation to the edge.
  • A bounded context is where one model of a word applies; one name with two meanings usually needs two classes.
  • Whether a cross-aggregate rule must hold immediately is the domain’s decision, and it shapes the design.