Modular monolith
What you will learn on this page
Section titled “What you will learn on this page”- What a modular monolith is: one program, one build, one deployment, made of feature modules with explicit public interfaces.
- How to choose modules by capability and by who owns which data.
- How a C++ module keeps its types private: a public
include/directory, a privatesrc/directory, and PImpl where a class would otherwise expose its internals. - How CMake and CTest enforce the boundaries, and what they cannot enforce.
- The three ways modules talk: calls, in-process events, and shared data, and when each fits.
- How to break a dependency cycle between modules, and when a modular monolith is the wrong choice.
Layers split by technique, modules by feature
Section titled “Layers split by technique, modules by feature”The layered version splits the program by kind of code: user interface, use cases, rules, storage. That makes each kind easy to find, but most changes are about a feature. Suppose the office asks for “students can see their own timetable”. In the layered version that change touches all four layers: a new console command, a new use case, perhaps a new domain query, and a new store lookup.
A modular monolith splits the program by business capability instead. Each module owns one capability, its data, and its rules, and offers a small public interface to the rest. It is still a monolith: one program, built together, deployed together, running in one process. The word describes how it is deployed, not how messy it is.
| Layered | Modular monolith | Separate services | |
|---|---|---|---|
| Splits code by | Kind of code | Business capability | Business capability |
| A feature change hits | Usually every layer | Usually one module | Usually one service |
| Deployed as | One program | One program | One program per service |
| Calls between parts | Function calls | Function calls through public interfaces | Network calls, which can fail or be slow |
| Keeping data consistent | One store | One process; each module owns its data | Per service; across services needs a protocol |
“Usually one module” still leaves room for the user interface. In the modular version the timetable change touches enrollment, which owns the data and the new query, and the console, which adds the command. The rules and the data change in one place.
Layers and modules are not rivals. A module with real rules can be layered inside, as the enrollment module is below. The difference is which split comes first.
Choosing the modules
Section titled “Choosing the modules”Good module boundaries follow three questions:
- What capability does the office talk about as one thing? “Registering students”, “enrolling in courses”, and “telling students” are separate conversations, often with different people.
- Who owns which data? A piece of data should have one module that creates and changes it. Others refer to it by id and ask the owner.
- What changes together? Code that always changes together belongs in one module; code that changes for different reasons, at different times, belongs in different ones.
For the enrollment program that gives four modules:
| Module | Capability | Owns | Changes when |
|---|---|---|---|
| students | Registering students | Student ids and names | The student records office changes what it keeps |
| enrollment | Seats and waitlists | Courses, their seats, and their waitlists | The registrar’s enrollment rules change |
| notifications | Telling students what happened | Message wording and delivery | The wording or the channel changes |
| console | The registrar’s user interface | Nothing | The commands or replies change |
Two choices here are worth explaining.
- Course titles stay in enrollment. Today a course is only a code, a title, and seats, and the same people change all three. If a catalog with descriptions and prerequisites appears, maintained by other people, it becomes its own module. The exercise at the end does that split.
- There is no
commonmodule. A module that everything depends on, holding “shared” types, becomes the place where every change lands. The modules here share only ids, which are plainstd::stringvalues.
What a module looks like in C++
Section titled “What a module looks like in C++”Each module is a directory with two parts:
modules/ students/ include/students/directory.hpp public interface src/directory.cpp private enrollment/ include/enrollment/enrollment.hpp public interface include/enrollment/events.hpp public interface src/course.hpp private: the rules src/course.cpp private src/enrollment.cpp private notifications/ include/notifications/mailer.hpp public interface src/mailer.cpp private console/ include/console/console.hpp public interface src/console.cpp private main.cpp composition rootThe extra directory level in include/students/directory.hpp means
other modules write #include "students/directory.hpp". The include
says which module it comes from, and two modules can each have a
types.hpp without clashing. Each module also has its own namespace.
The students module’s public interface is one class:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The students module's whole public interface. It owns every student's// id and name; other modules keep only ids and ask here for the rest.class Directory {public: // Registers a student under a unique id. // Returns false, and changes nothing, if the id is taken. bool add(const std::string& id, const std::string& name);
// True if a student with this id was added. Enrollment asks this at // the start of every enroll. bool contains(const std::string& id) const; // The student's name, or an empty optional (std::nullopt) for an // unknown id. It returns a copy of the name, so the caller never holds // a reference into this module's map. std::optional<std::string> name_of(const std::string& id) const;
private: std::map<std::string, std::string> names_; // id -> name};Nothing in it needs hiding: the map of names is the module’s data, and showing its type in a header costs little: other modules recompile if the representation changes, but they cannot reach the map, and there is no type with rules to hide.
Hiding a module’s types with PImpl
Section titled “Hiding a module’s types with PImpl”The enrollment module has a type it does want to hide: Course, which
keeps the seat and waitlist rules. Other modules should ask
Enrollment to enroll a student, not change a Course themselves.
C++ makes this harder than it sounds. A class’s private members are
still written in its header, and a member’s type must be complete
there. If Enrollment held a std::map<CourseCode, Course>, its header
would have to include course.hpp, and every module that includes
enrollment.hpp would see Course. private: stops other code from
using a member; it does not stop other code from depending on
its type.
The fix is the PImpl idiom (“pointer to implementation”): the
header declares a State type without defining it and holds a
std::unique_ptr<State>. Only enrollment.cpp defines State, so only
it includes course.hpp:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enrollment module's public interface: courses, seats, and// waitlists. The course type that keeps the rules is private to the// module, so this class holds its state behind a pointer (PImpl).// Callers pass plain values (ids, codes, a capacity) and get back the plain// result types declared above, so no caller ever sees a Course. Refusals// are statuses in those results, not exceptions.class Enrollment {public: // `students` must outlive this object. // It only borrows the directory, to ask questions about students; the // students module still owns that data. The constructor also creates // the hidden State on the heap. explicit Enrollment(const students::Directory& students); // Only declared here. State is incomplete in this header, and the // unique_ptr's destructor must see the complete type to delete it, so // the body (= default) is written in enrollment.cpp. ~Enrollment(); // defined where State is complete // `= delete` forbids copying: a copy would have to duplicate the // courses and the listeners, and unique_ptr cannot be copied anyway. // With these declared, no move operations are generated either. Enrollment(const Enrollment&) = delete; Enrollment& operator=(const Enrollment&) = delete;
// Each of these works on courses kept inside State. enroll and drop // also publish an event (see events.hpp) when a student gains a seat // or a waitlist place. AddCourseResult add_course(const std::string& code, int capacity, const std::string& title); EnrollResult enroll(const std::string& student, const std::string& course); DropResult drop(const std::string& student, const std::string& course); // Empty for an unknown course code. Names come from the students module. std::optional<CourseReport> report(const std::string& course) const;
// Listeners are called in the order they subscribed. Throws // std::invalid_argument for an empty listener. void subscribe(Listener listener);
private: // A forward declaration: "a struct called State exists". Code can hold // a pointer to it without knowing what is inside, which is what keeps // course.hpp out of this header. struct State; // defined in enrollment.cpp
// Calls every subscribed listener with the event, in subscription order. void publish(const Event& event) const;
const students::Directory* students_; // non-owning, never null std::unique_ptr<State> state_; // owned, never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Everything the module keeps. Only this file sees it.// This is the definition promised by `struct State;` in the header. It// can name Course because this file includes the private course.hpp. The// Enrollment object owns exactly one State through its unique_ptr, and the// State owns the courses and the listeners by value.struct Enrollment::State { std::map<CourseCode, Course> courses; // looked up by code, such as "CS101" std::vector<Listener> listeners; // called in the order they subscribed};Three details make it work:
- The destructor is declared in the header and defined in
enrollment.cpp, afterStateis complete.std::unique_ptrneeds the complete type where it deletes the object; with the destructor left to the compiler in the header, the build fails. - Declaring the destructor or the copy operations stops the compiler
from declaring move operations, and copies would be deleted anyway,
because
std::unique_ptrcannot be copied. SoEnrollmentcan be neither copied nor moved, and the deleted copy operations say so in the header. That suits an object that others borrow by reference, and it keeps “state_is never null” true: a moved-from PImpl object would hold a null pointer. If you need moves, declare them in the header and define them as= defaultin the.cppfile. constfunctions such asreportcan still change*state_, because aconstunique_ptrpoints to a non-constobject. The code must keep that promise itself;reportonly reads.
The cost is one heap allocation per Enrollment and one pointer
indirection per call. For one object per program that is nothing. For
a type with millions of small instances it would matter, and those are
rarely the types at a module boundary. The C++ idioms
page covers PImpl in general.
PImpl is not the only choice. If other modules should see a type,
put it in include/ and treat it as part of the interface, with the
same care as any public function. The events below are public on
purpose.
class students::Directory
students: public
Data members
std::map<std::string, std::string> names_;id -> name
Member functions
bool add(const std::string& id, const std::string& name);bool contains(const std::string& id) const;std::optional<std::string> name_of(const std::string& id) const;
class enrollment::Enrollment
enrollment: public
Data members
const students::Directory* students_;non-owning, never nullstd::unique_ptr<State> state_;owned, never null
Member functions
EnrollResult enroll(const std::string& student, const std::string& course);DropResult drop(const std::string& student, const std::string& course);std::optional<CourseReport> report(const std::string& course) const;void subscribe(Listener listener);void publish(const Event& event) const;private:
class enrollment::Enrollment::State
enrollment: private, in enrollment.cpp
Data members
std::map<CourseCode, Course> courses;std::vector<Listener> listeners;
class enrollment::Course
enrollment: private, in src/course.hpp
Data members
std::vector<StudentId> seated_;size() <= capacity_std::deque<StudentId> waitlist_;first in line first
Member functions
EnrollOutcome enroll(const StudentId& student);DropOutcome drop(const StudentId& student);
class notifications::Mailer
notifications: public
Data members
std::ostream* out_;non-owning, never null
Member functions
void on(const enrollment::Event& event);
class console::Console
console: public
Data members
students::Directory* students_;non-owning, never nullenrollment::Enrollment* enrollment_;non-owning, never null
Member functions
std::string run(std::string_view line);
Making the build enforce the boundaries
Section titled “Making the build enforce the boundaries”Each module is a static library. Its include/ directory is a
PUBLIC include directory, so modules that link it can see it; its
src/ directory is PRIVATE, so only the module’s own files can:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# One static library per module. A module's include/ directory is its# public interface and is visible to modules that link it; its src/# directory is private and visible only to the module itself.function(arch_module name) add_library(arch_modules_${name} STATIC ${ARGN}) target_include_directories(arch_modules_${name} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/${name}/include PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/${name}/src)endfunction()
arch_module(students students/src/directory.cpp)
arch_module(enrollment enrollment/src/course.cpp enrollment/src/enrollment.cpp)# PRIVATE: enrollment's public header only declares students::Directory.target_link_libraries(arch_modules_enrollment PRIVATE arch_modules_students)
arch_module(notifications notifications/src/mailer.cpp)# PUBLIC: the mailer's public header names enrollment's event types.target_link_libraries(arch_modules_notifications PUBLIC arch_modules_enrollment)
arch_module(console console/src/console.cpp)target_link_libraries(arch_modules_console PRIVATE arch_modules_students arch_modules_enrollment)
# main is the composition root, so it links every module.lld_add_example(arch_enrollment_modules SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)target_link_libraries(arch_enrollment_modules PRIVATE arch_modules_console arch_modules_notifications arch_modules_enrollment arch_modules_students)
lld_add_test(arch_modules_enrollment_tests SOURCES tests/test_enrollment.cpp)target_link_libraries(arch_modules_enrollment_tests PRIVATE arch_modules_enrollment arch_modules_students)
lld_add_test(arch_modules_notifications_tests SOURCES tests/test_notifications.cpp)target_link_libraries(arch_modules_notifications_tests PRIVATE arch_modules_notifications)
# Boundary checks. The first rejects includes that bypass include# directories; the second shows that it catches one.set(module_dirs students enrollment notifications console)list(TRANSFORM module_dirs PREPEND ${CMAKE_CURRENT_SOURCE_DIR}/)add_test(NAME arch_modules_include_check COMMAND ${CMAKE_COMMAND} "-DDIRS=${module_dirs}" -P ${CMAKE_CURRENT_SOURCE_DIR}/checks/check_includes.cmake)add_test(NAME arch_modules_include_check_catches COMMAND ${CMAKE_COMMAND} -DDIRS=${CMAKE_CURRENT_SOURCE_DIR}/checks/fixtures -P ${CMAKE_CURRENT_SOURCE_DIR}/checks/check_includes.cmake)set_tests_properties(arch_modules_include_check_catches PROPERTIES PASS_REGULAR_EXPRESSION "include check failed: 1 bad include")
# A file that includes enrollment's private header, compiled with only# the include directories a module that links enrollment would get. It# is not part of the normal build; the test builds it and expects the# compiler to report a missing header.add_executable(arch_modules_private_header_violation EXCLUDE_FROM_ALL checks/uses_private_header.cpp)target_include_directories(arch_modules_private_header_violation PRIVATE $<TARGET_PROPERTY:arch_modules_enrollment,INTERFACE_INCLUDE_DIRECTORIES>)add_test(NAME arch_modules_private_header_hidden COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target arch_modules_private_header_violation)set_tests_properties(arch_modules_private_header_hidden PROPERTIES PASS_REGULAR_EXPRESSION "course.hpp.*(No such file or directory|file not found)")
set_tests_properties(arch_modules_include_check arch_modules_include_check_catches arch_modules_private_header_hidden PROPERTIES LABELS "test")This gives the dependencies in the diagram below, and the build refuses anything else:
Text description of the diagram
A component diagram of four modules and main. The console depends on students, to register students, and on enrollment, to enroll, drop, and report. Enrollment depends on students, to ask whether a student is registered and what their name is. Notifications depends on enrollment, because it listens to enrollment’s events. Enrollment does not depend on notifications, and no module depends on the console. Outside the modules, main creates the objects and connects them; it depends on every module, which the dashed arrows show for the console and notifications.
Diagram source (Mermaid)
flowchart TB
Main["main<br/>composition root"]
Con["console<br/>commands and replies"]
Stu["students<br/>ids and names"]
Enr["enrollment<br/>seats and waitlists"]
Not["notifications<br/>messages"]
Con -->|registers students| Stu
Con -->|enrolls, drops, reports| Enr
Enr -->|asks: registered? name?| Stu
Not -->|listens to events of| Enr
Main -.->|creates and connects| Con
Main -.->|creates and connects| NotWhat this enforces:
- A module’s
src/is invisible to every other module. No other target hasenrollment/srcas an include directory, so#include "course.hpp"fails outside the enrollment module. - A module sees only the modules it links. The students module links nothing, so it cannot include an enrollment header. The console links students and enrollment, but not notifications.
- Forward declarations keep dependencies from spreading.
enrollment.hpponly declaresstudents::Directory, so enrollment links studentsPRIVATEand its users do not get the students headers by accident. The console links students itself, because it uses it.
Three CTest tests go further than the include directories. The first
runs a short CMake script that rejects includes that would bypass them: a
path with .., or an absolute path:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# Fails if a source file under one of DIRS includes a header by a path# that climbs out of a directory ("..") or by an absolute path. Include# directories decide what each module can see; such paths bypass them.## Usage: cmake "-DDIRS=<dir>;<dir>" -P check_includes.cmake
set(bad_count 0)set(file_count 0)foreach(dir IN LISTS DIRS) file(GLOB_RECURSE sources "${dir}/*.hpp" "${dir}/*.cpp") foreach(source IN LISTS sources) math(EXPR file_count "${file_count} + 1") file(STRINGS "${source}" includes REGEX "^[ \t]*#[ \t]*include[ \t]*[\"<]") foreach(line IN LISTS includes) string(REGEX MATCH "[\"<]([^\">]*)" path "${line}") set(path "${CMAKE_MATCH_1}") if(path MATCHES "(^|/)\\.\\.(/|$)" OR path MATCHES "^/") message(SEND_ERROR "bad include in ${source}: ${line}") math(EXPR bad_count "${bad_count} + 1") endif() endforeach() endforeach()endforeach()
if(bad_count GREATER 0) message(FATAL_ERROR "include check failed: ${bad_count} bad include(s)")endif()message(STATUS "include check passed: ${file_count} file(s)")A check that never fails proves nothing, so a second test runs the
script on a fixture file that contains
#include "../../enrollment/src/course.hpp" and passes only if the
script reports exactly that one bad include.
The third builds a file that includes course.hpp with exactly
the include directories that a module linking enrollment would get,
and passes only if the compiler reports the header missing. That turns
“src/ is private” from a claim on this page into a test that fails if
someone moves src/ into the public include directories.
What the build still does not enforce:
- New dependencies. Anyone can add a line to
CMakeLists.txtthat makes students link enrollment. Review the build files like code; many teams give them a named owner. - Coupling through behaviour. A module can rely on another’s events arriving in a particular order, or on a reply’s exact text, without any include showing it.
- Shared state outside the interfaces, such as a global variable or one file that two modules both read.
- Which parts of a linked module are used. Notifications needs only
events.hpp, but linking enrollment makesenrollment.hppvisible too, so the mailer could callEnrollment::enroll. Putting the events in their own header-only (INTERFACE) library would narrow that.
How modules talk to each other
Section titled “How modules talk to each other”There are three ways for one module to use another’s work. The example uses the first two on purpose and avoids the third.
Calls through the public interface
Section titled “Calls through the public interface”Enrollment must refuse unknown students (E2, E8), but the students
module owns that data. So enrollment asks: contains before
enrolling, and name_of when building a report. Enrollment never sees
how students are stored:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Enrolls one student in one course, using both other channels between// modules: it asks the students module a question (a call), and it// announces a change to whoever listens (an event). Refusals come back as// a status and change nothing. The course is changed in place in the// map; the event is published after the change and before the return.EnrollResult Enrollment::enroll(const std::string& student, const std::string& course) { // A call into the students module, through its public interface only. // `{EnrollStatus::no_such_student, 0}` builds the EnrollResult to return. if (!students_->contains(student)) return {EnrollStatus::no_such_student, 0}; // ask, by id // map::find gives an iterator to the matching entry, or end() if there // is none. state_-> reaches the hidden State. const auto found = state_->courses.find(course); if (found == state_->courses.end()) return {EnrollStatus::no_such_course, 0}; // found->second is the Course stored in the map (found->first is its // code). A reference, not a copy: changing target changes the stored // course. A std::map never moves its entries, so the reference stays // valid until that entry is erased, and nothing here erases one. Course& target = found->second;
// The private Course applies the seat and waitlist rules. const EnrollOutcome outcome = target.enroll(student); // Only seated and waitlisted changed the course, so only they publish. switch (outcome.kind) { case EnrollOutcome::Kind::seated: // The event carries the code and title, so a listener never has to // ask this module for them. publish runs every listener now, before // this function returns. publish(Seated{student, target.code(), target.title()}); // announce, do not send return {EnrollStatus::seated, 0}; case EnrollOutcome::Kind::waitlisted: publish(Waitlisted{student, target.code(), target.title(), outcome.position}); return {EnrollStatus::waitlisted, outcome.position}; case EnrollOutcome::Kind::already_seated: return {EnrollStatus::already_seated, 0}; case EnrollOutcome::Kind::already_waitlisted: return {EnrollStatus::already_waitlisted, 0}; } // Every kind returns above; this line only satisfies the compiler. return {EnrollStatus::no_such_course, 0}; // not reached: every kind is handled above}A call is the simplest choice when the caller needs an answer now. Its cost is a compile-time dependency: enrollment cannot be built without the students module’s header.
In-process events
Section titled “In-process events”When a student gets a seat, enrollment does not need anything back. It only needs someone to be told. So instead of calling the notifications module, enrollment announces what happened, as an event, to whoever subscribed:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What the enrollment module announces after a change. Each event// carries everything a listener needs, so no listener has to call back// into this module to find out what happened.// They are plain structs of strings and numbers, copied freely, and they// name no private type, so this header can be public.struct Seated { // took a free seat at once std::string student; std::string course_code; std::string course_title;};
struct Promoted { // moved from the waitlist into a freed seat std::string student; std::string course_code; std::string course_title;};
struct Waitlisted { std::string student; std::string course_code; std::string course_title; std::size_t position = 0; // from 1};
// One Event holds exactly one of the three structs at a time, like a box// with a label saying which kind is inside. A listener asks which one it// got with std::visit, std::get_if, or std::holds_alternative. A Seated// (or Promoted, or Waitlisted) value converts to an Event automatically.using Event = std::variant<Seated, Promoted, Waitlisted>;
// Called synchronously, after the change, once per event. A listener// must not call back into the module that is publishing.// std::function<void(const Event&)> can hold any callable (a lambda, a// function, an object with operator()) that takes an Event and returns// nothing. An empty std::function holds nothing, and calling it throws// std::bad_function_call, which is why subscribe refuses one.using Listener = std::function<void(const Event&)>;The notifications module subscribes, and the message wording lives there:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The wording of every message lives here, in the module that sends them.// Three overloads with one name, one per event type. Mailer::on calls// message_for with whichever event it received, and the compiler picks// the overload whose parameter type matches. Each returns the text after// "notify <student>: "; for example a Seated event for CS101 gives// "you have a seat in CS101 Software Design".std::string message_for(const enrollment::Seated& event) { return "you have a seat in " + event.course_code + ' ' + event.course_title;}
std::string message_for(const enrollment::Promoted& event) { return "a seat opened; you are enrolled in " + event.course_code + ' ' + event.course_title;}
// std::to_string turns the waitlist position (a number) into text.std::string message_for(const enrollment::Waitlisted& event) { return "you are number " + std::to_string(event.position) + " on the waitlist for " + event.course_code + ' ' + event.course_title;}main connects the two. It creates the mailer before the enrollment
object, so the mailer outlives the listener that refers to it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { // The same script as version 0; the output must be the same text. // A fixed array of read-only views of quoted text that lives for the // whole program, built at compile time (constexpr). constexpr std::string_view script[] = { "course CS101 2 Software Design", "student S1 Ada Lovelace", "student S2 Grace Hopper", "student S3 Alan Turing", "student S4 Barbara Liskov", "enroll S1 CS101", "enroll S2 CS101", "enroll S3 CS101", "enroll S4 CS101", "enroll S3 CS101", "enroll S9 CS101", "drop S1 CS101", "report CS101", "drop S4 CS101", "enroll S1 CS999", "report CS101", };
// main is the only code that sees every module. It creates each // object before anything that borrows it, and connects the modules: // here it subscribes the mailer to enrollment's events. // All four are local variables that main owns; the modules only // borrow each other through references and pointers. students::Directory directory; notifications::Mailer mailer{std::cout}; // registrar borrows directory, to ask whether students exist. enrollment::Enrollment registrar{directory}; // The connection between modules. The lambda captures mailer by // reference ([&mailer]) and forwards every event to it. registrar keeps // the lambda in its listener list, so mailer must outlive registrar, // which it does: it was created first, so it is destroyed later. registrar.subscribe([&mailer](const enrollment::Event& event) { mailer.on(event); }); // The console borrows the two modules it drives. It never sees mailer. console::Console terminal{directory, registrar};
for (const std::string_view line : script) { std::cout << "> " << line << '\n'; const std::string reply = terminal.run(line); // may print notifications first std::cout << reply << '\n'; }} // destroyed in reverse: terminal, registrar (and its listener), mailer, directoryHow this code works: One enroll command, module by module
Follow the line enroll S3 CS101 from the script, at the point where
S1 and S2 already hold both seats of CS101.
mainprints> enroll S3 CS101and callsterminal.run(line).mainowns all four module objects (directory,mailer,registrar,terminal) as local variables. Each module only borrows the others.- The console module splits the line, checks there are three words,
and calls
registrar.enroll("S3", "CS101"). It uses the enrollment module’s public header only; it cannot includecourse.hpp. - The enrollment module asks the students module.
students_->contains("S3")is a plain function call across a module boundary. The answer is yes, so it goes on. It never sees how the directory stores names. - The enrollment module uses its private
Course.courses.findlocatesCS101insideState, andtarget.enroll("S3")finds no free seat, appendsS3to the waitlist in place, and returnswaitlistedwith position 1. - The enrollment module announces.
publishcalls each listener in turn, here only the lambdamainsubscribed, with the eventWaitlisted{"S3", "CS101", "Software Design", 1}. The lambda callsmailer.on(event). Enrollment has no idea a mailer exists; it only holds astd::function. - The notifications module sees which kind of event it got, picks
the matching
message_for, and printsnotify S3: you are number 1 on the waitlist for CS101 Software Design. Control then returns topublish, and from there toenroll. - Back in the enrollment module,
enrollreturns{waitlisted, 1}to the console, which words the replyok: S3 waitlisted for CS101 (position 1), andmainprints it. That is why the notification line comes out before the reply.
The calls point from the console to enrollment, and from enrollment to
students. The event travels from enrollment to notifications, but the
dependency points the other way: only main’s lambda knows both.
Lifetimes. The objects are created in the order directory,
mailer, registrar, terminal, and destroyed in reverse. So
terminal goes first, then registrar together with the lambda that
refers to mailer, and only then mailer and directory. Nothing is
ever used after the object it borrows has gone.
The dependency now points from notifications to enrollment. Enrollment, which holds the rules, does not depend on how or whether anyone is told. A second listener, such as an audit log, needs no change to enrollment. This is the Observer pattern used between modules.
Text description of the diagram
A sequence diagram for one drop command. The console asks enrollment to drop S1 from CS101. Enrollment asks its private Course to drop S1, and the Course answers that S1 left a seat and S3 was promoted. Enrollment then publishes a Promoted event for S3 and CS101. The notifications module receives it, writes the message for S3, and returns. Only then does enrollment return “left a seat, S3 promoted” to the console, which formats the reply text.
Diagram source (Mermaid)
sequenceDiagram
participant C as console
participant E as enrollment
participant R as Course, private
participant N as notifications
C->>E: drop S1 from CS101
E->>R: drop S1
R-->>E: left a seat, S3 promoted
E->>N: event Promoted, S3, CS101
Note over N: writes the message for S3
N-->>E: returns
E-->>C: left a seat, S3 promoted
Note over C: formats the reply textThese events are synchronous: publish calls each listener before
drop returns. That keeps the example’s output in the same order as
version 0’s, and it has consequences worth knowing:
- A slow listener slows enrollment. Sending real email inside
publishwould make every enrollment wait for the mail server. - A listener that throws stops
publish, and the exception leavesdropafter the course has changed. The seat change stands; the later listeners are not called; the console never formats a reply. Here the exception leavesConsole::run,maindoes not catch it, and the program ends. The example’s listeners do not throw, apart from running out of memory. - A listener must not call back into the enrollment object that is
publishing. Subscribing from inside a listener could make the
listener vector reallocate while
publishis walking it. - An empty listener would throw
std::bad_function_callfrom insidepublish, long after the mistake.subscriberefuses one withstd::invalid_argument, so the error appears at the line that caused it.
Delivering events later, from a queue, removes the first two problems and adds others: the message can be lost or sent twice, and the student may see the reply before the message. The event-driven components page covers that trade.
Shared data: avoid it
Section titled “Shared data: avoid it”The third way is for two modules to read and write the same data: the enrollment code reading the students map directly, or two modules sharing a database table. It is tempting, because it needs no interface. It also means that neither module can change how that data is kept without breaking the other, and that no single module checks the rules about it.
The example avoids it. Enrollment stores only student ids, and asks the students module for anything else. Each module’s data is reachable only through that module’s functions.
| Way | Use when | Cost |
|---|---|---|
| Call | The caller needs an answer to continue | The caller depends on the callee |
| Event | The publisher needs nothing back; any number may react | Harder to follow; delivery order and failures need thought |
| Shared data | Almost never between modules | Neither module can change the data alone; rules have no owner |
Layers inside a module
Section titled “Layers inside a module”The enrollment module is layered on the inside, in miniature:
Course holds the rules and knows nothing else, and Enrollment runs
the use cases, keeps the courses, and publishes events. The students
module is one class, because it has no rules beyond “ids are unique”.
That is the usual shape: split by capability first, then layer the modules that have enough rules to be worth it. A module with no rules does not need four layers.
Same behaviour, different structure
Section titled “Same behaviour, different structure”The modular program runs the same script as version 0:
> course CS101 2 Software Designok: course CS101 added> student S1 Ada Lovelaceok: student S1 added> student S2 Grace Hopperok: student S2 added> student S3 Alan Turingok: student S3 added> student S4 Barbara Liskovok: student S4 added> enroll S1 CS101notify S1: you have a seat in CS101 Software Designok: S1 enrolled in CS101> enroll S2 CS101notify S2: you have a seat in CS101 Software Designok: S2 enrolled in CS101> enroll S3 CS101notify S3: you are number 1 on the waitlist for CS101 Software Designok: S3 waitlisted for CS101 (position 1)> enroll S4 CS101notify S4: you are number 2 on the waitlist for CS101 Software Designok: S4 waitlisted for CS101 (position 2)> enroll S3 CS101refused: S3 is already on the waitlist for CS101> enroll S9 CS101refused: no student S9> drop S1 CS101notify S3: a seat opened; you are enrolled in CS101 Software Designok: S1 dropped CS101; S3 moved from the waitlist> report CS101ok: CS101 Software Design, 2/2 seats taken seated: S2 Grace Hopper, S3 Alan Turing waitlist: S4 Barbara Liskov> drop S4 CS101ok: S4 left the waitlist for CS101> enroll S1 CS999refused: no course CS999> report CS101ok: CS101 Software Design, 2/2 seats taken seated: S2 Grace Hopper, S3 Alan Turing waitlist: (none)The text is identical, which a test checks. The structure is different: the message wording is now in one module, the student records in another, and the rules for seats in a third.
Testing modules
Section titled “Testing modules”Each module is tested through its public interface. The enrollment tests use the real students module, because it is small and fast, and a listener that records events instead of the notifications module, which is not even linked:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enrollment module is tested through its public interface, with// the real students module and a listener that records events. The// notifications module is not linked.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one if// the two values differ. They come from the site's test header, lld_test.hpp.// namespace { ... } with no name keeps the helper private to this file.namespace {
// The shared setup for every test: two registered students (S1, S2), one// course with a single seat, and a listener that copies each event into// `events` so a test can inspect what was announced.struct Office { // Members are built in the order they are written, so directory exists // before registrar borrows it, and is destroyed after it. students::Directory directory; enrollment::Enrollment registrar{directory}; std::vector<enrollment::Event> events;
Office() { // Setup only: add and add_course return results these tests do not // check. directory.add("S1", "Ada Lovelace"); directory.add("S2", "Grace Hopper"); registrar.add_course("CS101", 1, "Software Design"); // [this] lets the lambda reach this Office's events. That is safe // because an Office cannot be copied or moved (its Enrollment // member cannot), so `this` never changes while the lambda lives. registrar.subscribe([this](const enrollment::Event& event) { events.push_back(event); }); }};
} // namespace
// S1 takes the only seat and S2 is waitlisted. Proves two events were// announced, a Seated first and then a Waitlisted for S2 at position 1.LLD_TEST(enrolling_announces_a_seat_or_a_waitlist_place) { Office office; office.registrar.enroll("S1", "CS101"); office.registrar.enroll("S2", "CS101"); LLD_CHECK_EQ(office.events.size(), std::size_t{2}); // holds_alternative asks "is the event inside this variant a Seated?". LLD_CHECK(std::holds_alternative<enrollment::Seated>(office.events[0])); // get_if takes the variant's address and returns a pointer to the // Waitlisted inside, or nullptr if it holds another kind. Checking // nullptr first (&& stops at the first false) makes the reads safe. const auto* waiting = std::get_if<enrollment::Waitlisted>(&office.events[1]); LLD_CHECK(waiting != nullptr && waiting->student == "S2" && waiting->position == 1);}
// S1 seated, S2 waiting; then S1 drops. Proves the result names S2 as// promoted and the last event announced is a Promoted for S2.LLD_TEST(a_dropped_seat_announces_the_promotion) { Office office; office.registrar.enroll("S1", "CS101"); office.registrar.enroll("S2", "CS101"); const enrollment::DropResult dropped = office.registrar.drop("S1", "CS101"); LLD_CHECK(dropped.status == enrollment::DropStatus::left_seat); LLD_CHECK(dropped.promoted == std::optional<std::string>{"S2"}); const auto* promoted = std::get_if<enrollment::Promoted>(&office.events.back()); LLD_CHECK(promoted != nullptr && promoted->student == "S2");}
// S9 was never added to the directory. Proves enroll refuses with// no_such_student, and that a refusal announces nothing.LLD_TEST(unknown_students_are_refused_by_asking_the_students_module) { Office office; LLD_CHECK(office.registrar.enroll("S9", "CS101").status == enrollment::EnrollStatus::no_such_student); LLD_CHECK(office.events.empty());}
// Proves the report shows one seated student and that their name,// "Ada Lovelace", came from the students module: enrollment stores only// the id "S1".LLD_TEST(the_report_takes_names_from_the_students_module) { Office office; office.registrar.enroll("S1", "CS101"); const std::optional<enrollment::CourseReport> report = office.registrar.report("CS101"); // If has_value() failed, the next lines would read an empty optional; // that cannot happen here, because CS101 was added in the setup. LLD_CHECK(report.has_value()); LLD_CHECK_EQ(report->seated.size(), std::size_t{1}); LLD_CHECK_EQ(report->seated[0].name, std::string{"Ada Lovelace"});}The notifications tests go further. They build events by hand and check the messages. No course or student exists, and nothing from the enrollment module runs: the event types are the whole contract between the two modules.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The notifications module is tested with events made by hand. No// course, seat, or student has to exist: the events are the contract.// LLD_TEST(name) defines one test; LLD_CHECK_EQ(actual, expected) records// a failure if the two differ. Both come from lld_test.hpp.
// Sends one event of each kind and proves each becomes exactly one line,// in order, with the right wording. A std::ostringstream is an output// stream that writes into a string, so sent.str() returns everything the// mailer wrote.LLD_TEST(each_event_becomes_one_message) { std::ostringstream sent; notifications::Mailer mailer{sent}; // Each struct, such as Seated{student, course_code, course_title}, // converts to an Event on the way into on(). mailer.on(enrollment::Seated{"S1", "CS101", "Software Design"}); mailer.on(enrollment::Waitlisted{"S2", "CS101", "Software Design", 3}); mailer.on(enrollment::Promoted{"S2", "CS101", "Software Design"}); // String literals written next to each other join into one string, so // this is a single expected text of three lines. LLD_CHECK_EQ(sent.str(), std::string{"notify S1: you have a seat in CS101 Software Design\n" "notify S2: you are number 3 on the waitlist for CS101 " "Software Design\n" "notify S2: a seat opened; you are enrolled in CS101 " "Software Design\n"});}The tests never reach Course, because they cannot: it is private.
The layered version’s domain tests tested Course directly. Here the
rules are tested through Enrollment, the way the rest of the program
uses them. Both are reasonable; testing through the module’s interface
lets the module change its insides without changing its tests.
Dependency cycles, and how to break them
Section titled “Dependency cycles, and how to break them”Module dependencies must form no cycles. If enrollment uses students
and students uses enrollment, neither can be built, tested, or
understood without the other, and they are one module with two names.
The include directories do not stop a cycle on their own: linking two
static libraries to each other is allowed. CMake reports a cycle only
when a shared library is part of it, so check the graph yourself, for
example with cmake --graphviz=deps.dot.
Suppose a new rule arrives: a student who holds a seat cannot be removed from the register. The students module would need to ask enrollment “does this student hold any seats?”, while enrollment already asks students “is this student registered?”. There are three ways out:
- Move the use case. The “remove a student” use case lives in a
module that may use both, such as the console or a new
registrationmodule, which asks enrollment first and then tells students to remove the student. The rule is now one level up. - Invert the dependency. The students module declares an interface
it owns, such as
RemovalCheckwithbool can_remove(id), and enrollment implements it. Students then depends only on its own interface. The Dependency Inversion Principle and the hexagonal architecture page do this systematically. - Use an event the other way. Students announces “student S1 is leaving”; enrollment listens and drops their seats. That fits “removing a student also drops their courses”, which is a different rule from “refuse to remove”. Choose by what the office asked for, not by which is easiest to code.
When a modular monolith fits, and when it does not
Section titled “When a modular monolith fits, and when it does not”A modular monolith fits when:
- One team, or a few that talk to each other, maintains the program.
- Changes that span modules must stay consistent. “A student who holds a seat cannot be removed” touches students and enrollment. In one process that can be one function call, or one database transaction even when each module has its own tables.
- The capabilities are real and separate, each with its own data and its own reasons to change.
- The boundaries may still be wrong. Moving code between two modules in one program is a refactor; moving it between two services is a migration.
It does not fit when:
- The program is small. Version 0 needs no modules, and four libraries for a program this size is ceremony.
- A part must be deployed, scaled, or allowed to fail separately: say, the notifications sender must keep running while enrollment is being upgraded. Then that part becomes a separate program. A module that already owns its data and talks only through events or a small interface is the easiest one to move out, but its calls become network calls, which can fail, time out, or arrive twice.
- The program is really one capability. Splitting it by feature would produce modules that call each other on every request.
For most low-level design problems, a modular monolith, or a single module with layers inside, is the right starting point.
Common mistakes
Section titled “Common mistakes”- Modules by kind of code. Modules called
models,utils, andmanagersare layers with other names; every feature still touches all of them. - A growing
commonmodule. It starts with one shared type and ends up as the dependency of everything, so every change to it rebuilds and risks everything. - Leaking private types. A public header that includes
course.hpp, or returnsCourse&, makes the rules part of the interface, and other modules start changing courses directly. - Reaching into another module’s data. Reading the students map directly, or sharing one table, instead of asking.
- Chatty interfaces. If one request calls another module ten times, the boundary is probably in the wrong place, or the interface is missing the one function the caller needs.
- Events for questions. If the publisher waits for a listener’s answer, it is a call in disguise, and harder to follow than a call.
- Cycles fixed with a shared module. Moving the types both modules need into a third module hides the cycle; the two modules still change together.
When the requirements change
Section titled “When the requirements change”- Notifications also go by SMS: only the notifications module changes. Enrollment’s events already say what happened.
- Notifications must not slow enrollment: the listener puts the event on a queue and another thread or program sends it. The event-driven components page covers the delivery guarantees that then matter.
- Data must survive a restart: each module gets its own tables behind its own interface, possibly in one shared database, and no module reads another’s tables. One database still allows a single transaction across modules, which separate services lose. The Repository and Unit of Work page covers saving a course and its waitlist together.
- Departments add their own enrollment rules: the enrollment module needs an extension point, and the departments’ code becomes plug-ins that depend on enrollment, not the other way round. The plug-in architecture page covers this.
- Tests must replace a module: today the enrollment tests must use the real students module, because enrollment names its concrete class. An interface owned by enrollment, implemented by students, removes that, as the hexagonal architecture page shows.
Exercise: Split a module boundary
The curriculum committee wants a course catalog: each course gets a description, a number of credits, and a list of prerequisites. The committee edits the catalog every term; the registrar’s office still decides how many seats each course has and runs the waitlists.
Today the enrollment module owns course codes, titles, and seats.
Split out a catalog module.
- Which data and functions move to
catalog, and which stay inenrollment? Where does capacity go? - Which way does the dependency point? How does enrollment still put the course title in its events?
- What happens to the console’s
course CS101 2 Software Designcommand? - A new rule: “a student may enroll in CS201 only after passing CS101”. Which module checks it, and what does it need from which module?
- What tests show that the new boundary holds?
Show the explained answer
- Catalog owns what the committee edits: code, title,
description, credits, and prerequisites, with a public class such as
catalog::Catalogofferingaddandfind(code) -> std::optional<CourseInfo>. Enrollment keeps what the registrar’s office decides: capacity, the seated students, and the waitlist, keyed by course code. Capacity stays in enrollment, because the office sets it and the seat rules use it; the committee never changes it. - Enrollment depends on catalog, never the reverse: enrollment asks whether a code exists before opening seats, and asks for the title. Enrollment should look the title up when it publishes, so the events still carry everything a listener needs. If events carried only the code, the notifications module would have to ask the catalog too, and gain a dependency.
- It splits in two, because two owners now do two different things:
course CS101 Software Design ...adds a catalog entry, and a new command such asoffer CS101 2opens seats, which enrollment refuses for a code the catalog does not know. The script and the expected output change; that is a new requirement, recorded as one, not a refactor. - Enrollment checks it, because it decides who gets a seat. It
needs the prerequisites from the catalog and the student’s passed
courses from whoever owns grades, which is a new module (say,
records), not students or catalog. Putting the check in the catalog would make the catalog depend on student data. - Catalog tests that link only the catalog module. Enrollment tests with the real catalog, or a fake one if enrollment owns an interface for it. The include check over the new module’s directory. A build test, like the one on this page, that includes a catalog private header with only catalog’s public include directory and expects it to fail.
Summary
Section titled “Summary”- A modular monolith is one program, built and deployed together, made of feature modules. Each owns one capability and its data, and offers a small public interface.
- Choose modules by capability, by who owns which data, and by
what changes together. Avoid a shared
commonmodule. - In C++, a module is a library with a public
include/<module>/directory and a privatesrc/. PImpl keeps a module’s types out of its public header, at the cost of one allocation and an indirection. - CMake include directories, a check that rejects
..and absolute includes, and a test that proves a private header is unreachable enforce the boundaries. New dependencies and behavioural coupling still need review. - Modules talk by calls when they need an answer, by events when they do not, and almost never by shared data. Synchronous events keep order but make the publisher wait for, and be affected by, every listener.
- Module dependencies must have no cycles; break one by moving the use case, inverting a dependency, or using an event in the other direction, chosen by the requirement.
- Enrollment still names the students module’s concrete class. The hexagonal architecture page replaces such names with interfaces the core owns.