Skip to content

Lesson 11 of 15 · Living With an Architecture

Modular Monolith: Draw and Enforce Module Boundaries

Advanced•
lesson•
November 16, 2026•
~9 min read

The microservices reflex

Around 2014, the year Martin Fowler and James Lewis published their article "Microservices", microservices became a common answer to "how should we structure software?". Many problems turned into "we need to split this into services".

The cost of distributed systems (network failures, eventual consistency, observability, deployment coordination, distributed transactions) is large. Shopify ("Deconstructing the Monolith") and Basecamp ("The Majestic Monolith") have both written about running large products on a monolith.

Monoliths are fine, as long as they're modular. The boundaries that microservices enforce through the network can be enforced inside a single codebase, with much less operational pain. A well-modularized monolith is a better starting point than microservices, and you can extract services later if and when scale forces the issue. Martin Fowler argues for starting with a monolith in MonolithFirst.

What a modular monolith is

A modular monolith is one application, deployed as one process, that internally has clear boundaries between different concerns:

  • One codebase, one deployment, one database (often).

  • Inside the codebase, top-level folders that represent modules. Domain-Driven Design (DDD) calls them "bounded contexts": regions of the code where one consistent language applies.

  • Modules import nothing from each other, with two exceptions covered below: a listener, and the provider that registers it, may import another module's event class; and a provider module implements an interface the consumer defines, importing the types in its signature.

  • Modules communicate through well-defined contracts: events, or sometimes a small interface the asking module defines.

  • Inside a module, the team uses whichever patterns suit (Vertical Slice Architecture, Hexagonal layering, plain Laravel for trivial pieces).

The result is a codebase that behaves like a set of independent services without paying the cost of network calls, distributed transactions, or service discovery.

The case for modular monoliths

A modular monolith gives you some of what microservices offer, with less operational cost:

  • Clear ownership boundaries. "The Booking team owns the Booking module." Same as service ownership without service-shaped infrastructure.

  • Independent reasoning. Changes to pricing don't touch booking. A change should stay inside its module.

  • Evolution toward services if needed. If the Booking module ever needs to scale or deploy independently, it can be extracted later. Until then, deploys are a single artifact.

  • Local transactions. Within the module (and often within the database), you have ordinary database transactions.

  • One observability surface. Logs, metrics, traces all in one process. Much simpler operationally.

  • Faster local dev. One process to run. One database to reset. One framework to boot.

Independent deployment and independent scaling are not part of it.

How to draw module boundaries

The hard question is where the lines go. Some practical guidance:

  • One module per bounded context. "Order" might mean a customer purchase in one context and a supplier purchase in another; those are two different modules.

  • One module per business capability. Booking. Pricing. Housekeeping. Guest Profile. Payments. Each is a distinct thing the business does, with its own rules and stakeholders.

  • Modules align with team structure. Conway's Law says software ends up shaped like the teams that build it, so if a single team owns payments and notifications, those might be one module, even if they're conceptually different.

  • Modules align with the natural seams in the domain. Event Storming (the workshop where the team maps domain events on a wall) is an excellent way to discover them: clusters of events on the wall usually become modules.

  • Modules are small enough to fit in one team's head. A module that doesn't is probably two modules pretending to be one.

The goal is a small number of clear modules at the top level, each with a clear purpose.

How modules communicate

Two patterns for inter-module communication, in order of preference, and one to avoid:

Domain events. Module A dispatches an event when something happens. Module B has a listener for the event. Module B's listener, and the provider that registers it, import the event class, which lives in module A's namespace, and nothing else from module A. The event carries ids and scalars (string ids, ints, timestamps), never module A's value objects, so the event class is the only thing module B needs.

The files the code below touches, across three modules:

TEXT
Hearth/ ├── Booking/ │ ├── ConfirmReservation/ │ │ ├── ConfirmReservationCommand.php │ │ ├── ConfirmReservationCommandHandler.php │ │ └── ReservationConfirmed.php # event Notifications uses │ ├── Reservation/ │ │ └── Reservations.php │ ├── Dispatcher.php │ ├── GuestId.php # in the contract │ ├── GuestProfiles.php # GuestProfile implements │ └── GuestSummary.php # in the contract ├── Notifications/ │ ├── SendConfirmationEmail/ │ │ ├── GuestEmails.php │ │ ├── ReservationConfirmationMail.php │ │ └── SendConfirmationEmailListener.php │ ├── Infrastructure/ │ │ └── DatabaseGuestEmails.php │ └── NotificationsServiceProvider.php └── GuestProfile/ ├── Guest.php ├── GuestProfileLookup.php └── GuestProfileServiceProvider.php

ConfirmReservationCommand carries the reservation id, a PaymentAuthorization and confirmedAt. Reservation::confirm() records ReservationConfirmed the way request() records ReservationRequested, and the handler dispatches what it recorded:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\ConfirmReservation; use Hearth\Booking\Dispatcher; use Hearth\Booking\Reservation\Reservations; final readonly class ConfirmReservationCommandHandler { public function __construct( private Reservations $reservations, private Dispatcher $dispatcher, ) {} public function handle(ConfirmReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $reservation->confirm($command->paymentAuthorization, $command->confirmedAt); $this->reservations->save($reservation); foreach ($reservation->releaseEvents() as $event) { $this->dispatcher->dispatch($event); } } }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\ConfirmReservation; use Carbon\CarbonImmutable; final readonly class ReservationConfirmed { public function __construct( public string $reservationId, public string $guestId, public CarbonImmutable $confirmedAt, ) {} }

The Notifications module reacts to it. The listener imports the event class and nothing else from Booking. ReservationConfirmationMail is an ordinary Laravel Mailable and is not shown. The listener gets the guest's address through GuestEmails, an interface Notifications defines for itself and implements itself:

PHP
<?php declare(strict_types=1); namespace Hearth\Notifications\SendConfirmationEmail; interface GuestEmails { public function addressFor(string $guestId): string; }
PHP
<?php declare(strict_types=1); namespace Hearth\Notifications\SendConfirmationEmail; use Hearth\Booking\ConfirmReservation\ReservationConfirmed; use Illuminate\Contracts\Mail\Mailer; final readonly class SendConfirmationEmailListener { public function __construct( private Mailer $mailer, private GuestEmails $guestEmails, ) {} public function handle(ReservationConfirmed $event): void { $this->mailer ->to($this->guestEmails->addressFor($event->guestId)) ->send(new ReservationConfirmationMail($event->reservationId)); } }

Notifications implements GuestEmails with a read-only query by id on the guests table GuestProfile owns. It reads the table directly and imports nothing from GuestProfile. That read couples Notifications to GuestProfile's schema, so it has to move behind an interface GuestProfile implements before GuestProfile gets its own database:

PHP
<?php declare(strict_types=1); namespace Hearth\Notifications\Infrastructure; use Hearth\Notifications\SendConfirmationEmail\GuestEmails; use Illuminate\Database\ConnectionInterface; final readonly class DatabaseGuestEmails implements GuestEmails { public function __construct(private ConnectionInterface $db) {} public function addressFor(string $guestId): string { return (string) $this->db->table('guests')->where('id', $guestId)->value('email'); } }

Registration and the GuestEmails binding are explicit, in the module's own service provider. Laravel's listener auto-discovery would not find a class in this folder anyway:

PHP
<?php declare(strict_types=1); namespace Hearth\Notifications; use Hearth\Booking\ConfirmReservation\ReservationConfirmed; use Hearth\Notifications\Infrastructure\DatabaseGuestEmails; use Hearth\Notifications\SendConfirmationEmail\GuestEmails; use Hearth\Notifications\SendConfirmationEmail\SendConfirmationEmailListener; use Illuminate\Support\Facades\Event; use Illuminate\Support\ServiceProvider; final class NotificationsServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(GuestEmails::class, DatabaseGuestEmails::class); } public function boot(): void { Event::listen(ReservationConfirmed::class, SendConfirmationEmailListener::class); } }

This is the cleanest pattern and the one this codebase uses by default. Module A doesn't know module B exists; module B subscribes to events module A emits.

Consumer-defined contracts (sparingly). When a module needs to ask another module for data, the module that asks defines the interface it needs, in its own namespace:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking; interface GuestProfiles { public function summaryFor(GuestId $id): GuestSummary; }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking; final readonly class GuestSummary { public function __construct( public string $name, public string $email, ) {} }

Booking knows nothing about the Guest Profile module. The Guest Profile module implements the interface and imports the types in its signature, so the imports point from provider to consumer and Booking still imports nothing. GuestProfileServiceProvider binds GuestProfiles to GuestProfileLookup the same way NotificationsServiceProvider binds GuestEmails:

PHP
<?php declare(strict_types=1); namespace Hearth\GuestProfile; use Hearth\Booking\GuestId; use Hearth\Booking\GuestProfiles; use Hearth\Booking\GuestSummary; final readonly class GuestProfileLookup implements GuestProfiles { public function summaryFor(GuestId $id): GuestSummary { $guest = Guest::query()->findOrFail($id->toString()); return new GuestSummary(name: $guest->name, email: $guest->email); } }

This is a heavier pattern. Use it when events don't fit (e.g., synchronous data lookup is needed) and only for narrow, stable contracts.

Direct imports (never). Module A imports any other class from module B. Avoid this. Once it happens, the module boundary is broken, and the rest of the codebase will follow the precedent.

Cross-module data

A specific pain point: modules often need to reference data from other modules. A reservation belongs to a guest; how does the booking module know about guests?

The recommended pattern:

  • Reference cross-module concepts by ID, not by relationship. A reservation has a GuestId, not a belongsTo Guest Eloquent relationship.

  • Do not put foreign keys across module boundaries. If booking and guest profile are different modules, the reservations.guest_id column is a plain uuid without a FOREIGN KEY constraint to guests.id. The reference is logical.

  • Use queries to enrich data when needed. When a reservation needs to display the guest's name, the query layer fetches the guest separately, through the GuestProfiles contract.

This is uncomfortable for developers used to fully relational schemas. It's also what makes the modules genuinely independent. With foreign keys across modules, the modules can't be split out into their own service, can't have their own databases, and can't evolve their schemas without coordinating. Without them, the modules can.

(For tables inside one module, foreign keys are still fine. The rule is about cross-module references.)

Enforcing the boundaries

Discipline alone doesn't keep boundaries clean. Tools help:

  • Deptrac and PHPArkitect. The deptrac.yaml and phparkitect.php in the Where Framework Code Is Allowed to Live lesson already hold this lesson's module rule. Each module may depend on no other module, with two exceptions: Notifications may import ReservationConfirmed, and GuestProfile may import GuestProfiles, GuestSummary and GuestId. Run both in CI; failures are real failures.

  • Namespace conventions. Even without tooling, a clear namespace convention (Hearth\<Module>\<Slice>\<File>) makes violations grep-able. Code review catches what's left.

Enforcement matters because the path of least resistance, in a Laravel codebase, is to import directly across module boundaries when convenient.

Splitting out a module later

Sometimes the modular monolith needs to become an actual distributed system. A module gets so heavy it deserves its own deployment, its own database, its own scaling characteristics. The split is real engineering work.

A rough sequence:

  1. Confirm the module's boundary is clean (no cross-imports, communication via events and consumer-defined contracts only).

  2. Extract the module to a separate database (or schema). Foreign keys across the boundary stay logical.

  3. Replace in-process event dispatching with cross-process messaging (Kafka, RabbitMQ, SQS).

  4. Move the module's code to its own deployable artifact.

  5. Replace GuestProfileLookup, the in-process implementation of GuestProfiles, with an HTTP or gRPC client.

Pitfalls

Drawing module boundaries by code structure instead of by domain. "We have a Models/ module and a Controllers/ module" misses the point. Conway's Law and the bounded contexts decide the boundaries.

Sharing a database table across modules with foreign keys. Once two modules both have FKs to a third table, they're effectively coupled at the schema level, and you've recreated the cross-import problem at a lower layer.

Treating events as RPC. "Module A dispatches an event, Module B handles it, Module A waits for the result." That's a synchronous call dressed up. If you need synchronous data, use a consumer-defined contract or rethink whether the modules are really separate.

Over-modularizing. Many tiny modules with two slices each is just folders.

Under-modularizing. A "core" module that contains half the codebase is just a monolith again.

Letting tests cross boundaries. A test in Hearth/Booking/Tests/ that boots GuestProfile's Guest model depends on GuestProfile's internals, and the PHPArkitect module rule fails it like any other Booking class. A test that runs two modules together goes in the root tests/Feature/ folder, outside Hearth/, where the module rules don't look.

The one thing to remember

A modular monolith enforces inside one codebase the boundaries microservices enforce over the network. Draw the modules around bounded contexts. Communicate through events. Avoid cross-module foreign keys. Enforce with tooling. Extract to services later if you ever need to.

Course Content