Modular Monolith
"A modular monolith is a system where all of the code powers a single application and there are strictly enforced boundaries between different domains." — Kirsten Westeinde, Deconstructing the Monolith: Designing Software that Maximizes Developer Productivity, Shopify Engineering, 21 February 2019
Summary: A modular monolith is one deployable unit split inside into business modules, each with a public API, private internals and its own data, so that you keep the simplicity of a monolith and most of the design benefits of services. Focus: The definition (one deployment unit, strong module boundaries, explicit APIs), why it exists (the microservice premium, monolith first), module design, in-process communication, data ownership inside one database, enforcing boundaries with tools, registration in Laravel and Go, transactions, testing, deployment, extracting a module into a service later, anti-patterns, and one complete Orders / Catalog / Billing example in Go and Laravel 13. Learning goal: Given an application, draw its modules, write each module's public API and schema, enforce the boundaries in CI, and know exactly what must already be true before one module can become a service.
This page is the full chapter on the modular monolith as an architecture style. It sits between Layered Monolithic Architecture (the classic one-deployable, layer-sliced style) and Microservices Architecture. The decision between the three is its own chapter, Monolith vs Microservices vs Modular Monolith: Deciding; here we build the modular monolith properly and show the way out of it. How to find the module lines is DDD's job (Bounded Context, Context Maps); how events are made reliable is the messaging path's job (Transactional Outbox, Idempotent Consumers).
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why not just microservices, why not a plain monolith | Why it exists |
| Parnas, Simon Brown, Fowler, Shopify, Grzybek, Google 2023 | Where it comes from |
| What a module is, public API vs internal | Module, Public API |
| Where to draw module lines | Bounded context alignment |
| How modules talk: calls, events, shared kernel | Direct calls, Events, Shared kernel |
| One database, many owners | Data ownership, Transactions |
Deptrac, Packwerk, go-arch-lint, Pest arch() | Enforcing boundaries, Mechanics |
| Service providers, routes, migrations per module | Registration |
| Testing one module alone | Testing |
| Deploying, scaling, feature flags per module | Deployment and scaling |
| Turning a module into a service later | Extraction |
| Full worked example | Go, Laravel |
| Module soup, common bag, cross-module Eloquent relations, god module | Solving the classic problems |
| Monolith vs modular monolith vs microservices, 12 rows | Comparison |
| When to pick it | Choosing |
| From one process to a distributed system | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Monolith | Exactly one deployment unit | One Laravel app, one Go binary | Nothing; a monolith is not a quality judgement |
| Module | A business capability with a fence around it | Orders, Catalog, Billing | Code is grouped by technology, every feature touches everything |
| Public API (contract) | The only door into a module | CatalogApi::product($sku) | Other modules call whatever is public by accident |
| Internal | Everything behind the door | catalog/internal/store, Catalog\Internal\Product | Internals become someone else's dependency |
| Integration event | A small published fact for other modules | orders.order_placed.v1 | Modules call each other for every side effect |
| Schema per module | Each module's tables live in its own schema | orders.orders, billing.invoices | One table, five writers, nobody can change it |
| Shared kernel | The tiny code every module may use | event bus, Money, clock | A "common" bag that couples everything |
| Composition root | The one place that wires modules together | cmd/shop/main.go, bootstrap/providers.php | Modules construct each other |
| Fitness function | A test or linter that fails when a boundary is crossed | Pest arch(), go-arch-lint, Deptrac | Boundaries erode one shortcut at a time |
| Extraction | Moving one module into its own service | billing-svc | A rewrite instead of a move |
The rules of a module, and who enforces them.
| Rule | Go | Laravel 13 | Enforced by |
|---|---|---|---|
| Only the public API is used from outside | internal/ packages | Contracts\ namespace, Internal\ hidden | Go compiler; Pest toOnlyBeUsedIn, Deptrac |
| No dependency cycles between modules | Import cycle is a compile error | Nothing built in | Go compiler; Deptrac ruleset, arch test |
| A module owns its data | Own schema, own role | Own schema, own migrations folder | PostgreSQL GRANT, code review, arch test on models |
| No cross-module foreign keys or joins | SQL in internal/store only | No Eloquent relation to another module's model | Arch test, migration review |
| Talk by calls through interfaces or by events | Consumer-side interfaces, event bus | Contracts bound in providers, Event::listen | Arch test |
| One registration point per module | Constructor wired in main | One service provider in bootstrap/providers.php | Convention, boot test |
Three styles at a glance (full 12-row table in Comparison):
| Monolith (unstructured) | Modular monolith | Microservices | |
|---|---|---|---|
| Deployment units | 1 | 1 | many |
| Boundaries | none or by layer | by business module, enforced | by service, enforced by the network |
| Call between parts | method call, anywhere | method call through a contract, or in-process event | network call or message |
| Data | one shared schema | one database, schema per module | database per service |
| Cost of moving a boundary | low, but nothing is a boundary | low: a refactoring | high: a migration across teams |
Why it exists
Two facts push teams here. First, microservices are expensive to run: Fowler's Microservice Premium (13 May 2015) says "When you use microservices you have to work on automated deployment, monitoring, dealing with failure, eventual consistency, and other factors that a distributed system introduces," and his advice is "don't even consider microservices unless you have a system that's too complex to manage as a monolith." Second, a monolith without structure rots: Shopify's 2019 post describes code where "the code that handled calculating shipping rates lived alongside the code that handled checkouts, and there was very little stopping them from calling each other," with the result that "making a seemingly innocuous change could trigger a cascade of unrelated test failures."
The modular monolith takes the cheap half of each: one deployable (no network between modules, one transaction available, one thing to run locally) and the boundaries of services (public APIs, owned data, independent change). Fowler's sentence in the same article is the whole idea in one line: "Do pay attention to good modularity within that monolith, but don't try to separate it into separate services."
| Plain monolith | Microservices |
|---|---|
| Simple to build, run, debug and deploy | Independent deploy, scale and failure per service |
| No enforced boundaries; coupling grows silently | Boundaries enforced by the network, at a high price |
| One transaction can touch everything | Sagas and eventual consistency everywhere |
| Moving a boundary is a refactoring | Moving a boundary is a cross-team migration |
| Scale the whole thing | Scale the hot part |
The modular monolith keeps the left column's operational simplicity and takes the right column's boundaries, but enforces them with tools (compiler, tests, linters) instead of the network.
The analogy we reuse on this page: an apartment building. One building, one foundation, one roof, one address for the postman (one deployment). Inside are apartments with locked doors (modules with public APIs). Neighbours talk at the door or leave notes in the mailroom (calls and events); nobody walks into another apartment to borrow the fridge (no reaching into another module's tables). Water and electricity are shared building services (the shared kernel), kept to the minimum. When one tenant outgrows the building, they move to their own house (extraction); because their furniture was always inside their own apartment, the move is a move, not a demolition.
Three common misunderstandings, up front
- "Monolith means badly designed." Grzybek's primer: "Monolith is a system that has exactly one deployment unit," and monolith architecture "does not say anything about quality." Structure is a separate axis from deployment.
- "A modular monolith is folders named after features." Folders are the first step. Without a public API, private internals, owned data and an automated check, it is still a big ball of mud with nicer directory names.
- "It is a stop on the way to microservices." It can be, and it is designed so that extraction is cheap, but many systems should stay modular monoliths forever. Shopify's core is still one: the Packwerk post (2020) says "The Shopify core codebase still stands as a majestic modular monolith."
Where it comes from
The picture is Simon Brown's "modularity vs deployment units" idea redrawn: modularity and the number of deployables are two independent axes. A big ball of mud split into many services becomes a distributed big ball of mud; the safe path is up first (modularity), then right only if a driver demands it.
Parnas, 1972. Modules defined by the design decisions they hide ("information hiding") are the root of every module boundary on this page; Architecture vs Design quotes the paper.
Simon Brown, from about 2013. Brown's page on the topic says he has been talking about modular monoliths and "package by component" "in various forms since ~2013". His tweet from QCon London, 4 March 2015: "if people can't build monoliths properly, microservices won't help." His "package by component" bundles "all of the responsibilities related to a single coarse-grained component into a single Java package", and he writes: "You can think of well-defined components in a monolithic application as being a stepping stone to a microservices architecture." A version of the essay became "The missing chapter" in Clean Architecture. He gave the talk Modular Monoliths at GOTO Berlin 2018.
Fowler, 2015. Microservice Premium (13 May 2015) and Monolith First (3 June 2015). The second records the pattern "Almost all the successful microservice stories have started with a monolith that got too big and was broken up," and adds the condition: "design a monolith carefully, paying attention to modularity within the software, both at the API boundaries and how the data is stored. Do this well, and it's a relatively simple matter to make the shift to microservices." He is honest about the evidence: "I'd feel much more comfortable with this approach if I'd heard a decent number of stories where it worked out that way."
Shopify, 2017 to 2020. The "Componentization" project started in early 2017; the team listed "every ruby class (around 6000 in total) in a massive spreadsheet" and moved them into components "in one big bang PR built by automated scripts" (Westeinde, 2019). They built Wedge, a call-graph tool that hooked "into Ruby tracepoints during CI", with rules such as "Cross-component associations are always violating componentization." By 2020 the core monolith had "over 2.8 million lines of Ruby code and 500,000 commits" (Müller, Under Deconstruction, 16 September 2020), Wedge was replaced by static analysis, and Packwerk was open-sourced (Ong, 23 September 2020): "Packwerk is a static analysis tool used to enforce boundaries between groups of Ruby files we call packages."
Grzybek, 2019 to 2020. Kamil Grzybek's five-part series (A Primer, 2 December 2019; Architectural Drivers; Architecture Enforcement, 22 March 2020; Integration Styles, 26 July 2020; Domain-Centric Design) gave the clearest definition: a module "must be independent and interchangeable", "must have everything necessary to provide desired functionality", and "must have defined interface".
Newman, 2019. Monolith to Microservices (O'Reilly) catalogues the extraction moves we reuse: Strangler Fig, Branch by Abstraction, Parallel Run, Database View, Split Table, Move Foreign-Key Relationship To Code. We read the book's table of contents on samnewman.io, not its full text; we name the patterns and do not quote it.
Google, 2023. Towards Modern Development of Cloud Applications (Ghemawat et al., HotOS '23) argued that "microservices conflate logical boundaries (how code is written) with physical boundaries (how code is deployed)" and proposed writing "monolithic applications that are modularized into logically distinct components", letting a runtime place them, and deploying "atomically". The prototype, Service Weaver, reported latency "up to 15×" lower and cost "up to 9×" lower. Its README now says Service Weaver moved to maintenance mode on 5 December 2024 and that the repository would be frozen and archived on 6 June 2025, because "it required rewriting large parts of existing applications." The idea outlived the framework.
Year Who Step What it gave practitioners
1 1972 Parnas Modules hide decisions The reason a module has an inside
2 ~2013 Simon Brown Package by component, "modular monoliths" Components with one public face
3 2015 Fowler MicroservicePremium, MonolithFirst "Monolith first, but modular"
4 2017-2019 Shopify Componentization, Wedge Big-bang file move, violation scores
5 2019-2020 Grzybek Five-post series + reference repository Definition, drivers, enforcement, integration styles
6 2020 Shopify Packwerk (open source) Static privacy and dependency checks in CI
7 2023 Google (HotOS '23) Logical monolith, physical distribution Separate "how written" from "how deployed"
8 2024-2025 Service Weaver Maintenance mode, archived The framework is gone; the split of concerns staysThe concept catalogue
Every block follows the same order: plain words, the usual wrong belief, a definition, a timeline or flow, real scenarios, what provides it per stack, and the fix.
The diagram is the whole worked example of this page: three modules in one deployable, each with a public strip on top and an internal area below; Orders calls Catalog through a port; Billing hears about orders only through the OrderPlaced event; each module owns one schema.
Module Must-know
In plain words: a module is one business capability (orders, billing, catalog) with all of its code, its data and a single front door.
Common misunderstanding: "A layer is a module." Grzybek calls this out: calling GUI, application logic and database access "modules" groups code by technical function, and then "adding or changing business functionality usually goes through all layers causing changes in each technical module." A business change should land in one module.
Definition: Grzybek's three conditions: a module "must be independent and interchangeable", "must have everything necessary to provide desired functionality", and "must have defined interface". Independence is measured by the number of dependencies, their strength and "stability of the modules on which the module depends on". A modular monolith is "a explicit name for a Monolith system designed in a modular way" in which every module meets the three conditions.
Change request Layered monolith touches Modular monolith touches
1 "Invoices need a due date" controllers/, services/, models/, Billing only (its API, internals,
migrations/, views/ its migration)
2 "Orders show the catalog name" the same five folders Orders (copies name at order time)
3 "Swap the tax engine" everything that calls tax code Tax module behind its contractReal scenario: Shopify's legacy tax engine: after the isolation work "we were able to swap out our tax engine for a completely new tax calculation system" (Westeinde, 2019). Other examples: a payments provider swap behind a Payments module; a recommendations module turned off in one country; a reporting module rewritten without touching checkout.
What provides it:
| Stack | Unit of a module | Visibility mechanism |
|---|---|---|
| Go | A directory tree of packages under one root (shop/orders/...) | Exported identifiers, internal/ (Go 1.4+) |
| Laravel / PHP | A namespace tree (App\Modules\Orders), optionally a Composer path package | None in the language; Pest, Deptrac, phpat |
| Java | A package tree; Spring Modulith application module; JPMS module-info.java | Package-private, JPMS exports, Spring Modulith verify() |
| .NET | One assembly per module | internal modifier, NetArchTest |
| Ruby on Rails | Rails engine or Packwerk package (package.yml) | Packwerk dependency and privacy checks |
Fix / how to use it: name modules after business capabilities, not technologies; give each one folder, one public API file or namespace, one schema and one owner team (Shopify: "every file has a stewardship team assigned").
Public API vs internal (encapsulation) Must-know
In plain words: each module decides what others may use (the API) and hides the rest; anything not in the API can change without asking anyone.
Common misunderstanding: "Making the API is enough." Shopify found the opposite: "the simplest possible way to introduce a public interface could just mean that a previously problematic design is leaked into a separate interface class." The API must be small and abstract, or the coupling just moves into it.
Definition: the contract is "an 'entry point' to our module. Good Contract should be unambiguous and contain only what clients of a given contract need" and "everything that we share outside becomes the public API of the module" (Grzybek). In practice the API is: facade methods or interfaces, the data types they return (copies, not entities), published events, and documented errors.
Caller (Orders) Catalog public API Catalog internal
1 catalog.Product(ctx, "BOOK-1")
2 -> load Row via store.Repository
3 SELECT ... FROM catalog.products
4 <- map Row to Product (copy)
5 <- Product{PriceCents, InStock}
Orders never sees Row, never sees the SQL, cannot import catalog/internal/storeReal scenario: Catalog renames on_hand to available_qty and splits stock into warehouses: callers keep receiving InStock bool. Billing changes its invoice-number format: callers of InvoiceFor() do not care. A team wants a new field: they ask for it in the API, which is a reviewed change.
What provides it:
| Stack | Public | Hidden |
|---|---|---|
| Go | Package orders (exported names) | orders/internal/...: the compiler refuses imports from outside orders/ |
| Laravel | App\Modules\Orders\Contracts\* (interfaces, readonly DTOs, events) | App\Modules\Orders\Internal\*, enforced by Pest toOnlyBeUsedIn |
| Rails | app/public/ in a Packwerk package | everything else when privacy is enforced (now in packwerk-extensions) |
| Spring Modulith | The module's base package | Sub-packages are internal by default |
Fix / how to use it: return copies (ProductView, Product), never ORM models; keep API types immutable (final readonly class in PHP); version event names (.v1); treat an API change like a library release.
Bounded context alignment, vertical slices, package by component Must-know
In plain words: draw module lines where the business language changes; each module is a vertical slice from HTTP to table.
Common misunderstanding: "One module per table" or "one module per entity." That gives what Shopify called informational cohesion, "grouping code that operates on the same data", which "arises from a design process that starts with database tables". They moved to functional cohesion, "grouping code that performs a task together".
Definition: a module boundary should match a bounded context or a subdomain: one model, one language, one owner. Shopify defined its components "as implementations of subdomains of the domain of commerce" and measured success by change locality: "The degree to which code that changes together lives together."
Business word "product" Catalog module Orders module Billing module
1 meaning sellable item, price, line item: SKU, qty, not used; billing sees
stock, images price at order time amounts and order IDs
2 owner Catalog team Checkout team Finance team
3 stored as catalog.products orders.order_lines (copy) billing.invoices (amount)Real scenario: "Customer" in Billing (tax ID, billing address) vs in Support (tickets, tone) vs in Marketing (segments). Three models, three modules, one shared ID. A pull-request bot counting "modules touched per PR" tells you whether the lines are right (Shopify: "The number of components touched should go down over time").
What provides it:
| Technique | What it gives |
|---|---|
| Event Storming | Clusters of events and commands that become modules |
| Context map | Upstream/downstream relations, where an anti-corruption layer is needed |
Change history (git log co-change) | Files that change together and belong together |
| Org chart (Conway's Law) | Module per team, or a mismatch to fix |
Fix / how to use it: start coarse (few, big modules), split later; it is cheap to move a line inside one deployable and expensive across services. Fowler: "even experienced architects working in familiar domains have great difficulty getting boundaries right at the beginning."
Module communication: in-process calls through interfaces Must-know
In plain words: when Orders needs an answer from Catalog now, it calls a method on Catalog's API, in the same process, through an interface.
Common misunderstanding: "In-process calls make it a big ball of mud again." Calls are fine; what makes mud is calling internals and calling in cycles. Grzybek's integration-styles post ranks direct call as "lower coupling than Shared Database Data", "encapsulates modules, relatively simple".
Definition: a synchronous call through a published contract. The caller depends on an interface (in Go best declared by the caller, a consumer-side port; in Laravel a Contracts interface owned by the provider module) and the composition root binds the implementation. Grzybek: "Both the caller and the callee should treat each other as external ... the Anti-Corruption Layer (ACL) should be applied. On the caller side, it could just be a gateway, on the callee side a facade."
Orders.PlaceOrder catalogAdapter (composition root) Catalog
1 catalog.Lookup(ctx, "BOOK-1") ->
2 c.Product(ctx, "BOOK-1") ->
3 Product{4200, InStock: true}
4 <- ProductInfo{4200, Available}
5 total += 4200 * qty
No network: one stack, one goroutine, nanoseconds, no retries, no timeouts neededReal scenario: price lookup at checkout; permission check (Identity.can(user, action)); currency conversion; "is this coupon valid?". All need the answer before responding, so a call is the right style.
What provides it:
| Concern | Go | Laravel |
|---|---|---|
| Contract | Interface in the consumer (orders.Catalog) or exported facade | Interface in Catalog\Contracts |
| Binding | Constructor argument wired in main | $this->app->singleton(CatalogApi::class, EloquentCatalog::class) |
| Translation (ACL) | Adapter struct in the composition root | Mapping inside the Eloquent implementation to a DTO |
| Failure | Plain error values; no network failure modes | Exceptions; no HTTP failure modes |
Fix / how to use it: call through the contract, return copies, avoid chatty APIs (one call per use case, not ten getters), and never create a cycle (A calls B, B calls A); invert one direction with an event.
In-process events: domain events vs integration events Important
In plain words: when Orders finishes something others may care about, it announces a fact; Billing listens. Orders does not know who listens.
Common misunderstanding: "In-process events are free." They remove a compile-time dependency but add temporal questions: does the listener run inside the transaction, after commit, or in a queue? What if it fails? Grzybek: messaging "ensures the lowest coupling, modularity, autonomy but at the cost of complexity."
Definition: a domain event is local to one module's model; an integration event is part of a module's public contract. Grzybek: modules integrate through events, "However, these are not Domain Events because a domain event is local and should be encapsulated in a given Bounded Context. Integration Events contain only as much as needed to avoid the so-called Fat Events." See Domain Events vs Integration Events.
Orders (one DB transaction) Bus / queue Billing
1 BEGIN
2 INSERT orders.orders, orders.order_lines
3 dispatch OrderPlaced (held: ShouldDispatchAfterCommit)
4 COMMIT
5 release OrderPlaced
6 OpenInvoice (queued, retried)
7 INSERT billing.invoices ... ON CONFLICT DO NOTHING
If step 4 rolls back, step 5 never happens; if step 7 fails, the queue retries itReal scenario: OrderPlaced opens an invoice and sends a confirmation email; PaymentCaptured marks the order paid; ProductDiscontinued hides it from search; CustomerDeleted triggers per-module erasure (GDPR) without one module knowing all the others.
What provides it:
| Mechanism | Synchronous in-process | After commit | Queued / durable |
|---|---|---|---|
| Go (this page) | eventbus.Bus.Publish | Publish after tx.Commit() | Outbox table + relay |
| Laravel 13 | Event::dispatch, plain listener | Event implements ShouldDispatchAfterCommit; listener ShouldQueueAfterCommit | Listener ShouldQueue |
| Spring Modulith | ApplicationEventPublisher | @TransactionalEventListener | Event publication registry |
| Rails | ActiveSupport::Notifications (Shopify used it to invert dependencies) | after_commit | Active Job |
Fix / how to use it: publish integration events with IDs and amounts only, version the name, make every handler idempotent (the Inbox pattern), and use an outbox once loss of an event would cost money.
Shared kernel (keep it minimal) Important
In plain words: a small set of code that every module may use, such as the event bus, a Money type, an ID type, a clock.
Common misunderstanding: "Put shared things in Common." The shared kernel is a deliberate, reviewed, tiny contract between all modules; a Common or Utils bag grows into a second monolith that every module depends on.
Definition: in DDD's context-map vocabulary, a shared kernel is a subset of the model that two or more contexts agree to share and change only together (Context Maps). In a modular monolith it is usually platform code (bus, logging, transaction helper) plus a few value objects. It must not depend on any module.
Proposed addition to shared/ Decision
1 Money{amount, currency} yes: stable, used by 3 modules, no business rules
2 eventbus.Bus yes: platform
3 CustomerStatus enum no: belongs to the Customer module's API
4 OrderHelper::formatTotal() no: belongs to Orders
5 BaseRepository with 40 methods no: each module owns its persistenceReal scenario: the Go example keeps only shop/internal/eventbus shared, and an arch test (TestPlatformKnowsNoModule) fails if it ever imports a module. In Laravel, App\Support\Money may be shared; App\Support\OrderStatuses may not.
What provides it:
| Stack | Where the kernel lives | Guard |
|---|---|---|
| Go | shop/internal/... (importable by every package under shop/) | Arch test: kernel imports no module |
| Laravel | App\Support or App\Shared | Pest: expect('App\Support')->not->toUse('App\Modules') |
| go-arch-lint | commonComponents: [platform] | Linter config |
| Packwerk | A package everyone declares as a dependency | package.yml |
Fix / how to use it: a written rule ("value objects and platform only, no business rules") and an arch test; review every addition.
Data ownership inside one database: schema per module Must-know
In plain words: one database server, but each module has its own section (schema) and nobody else reads or writes it directly.
Common misunderstanding: "Same database means shared data." Grzybek: "Sharing the database does not always have to mean sharing data, because modules can store its data in separate tables (most often it is done through database schemas)." And: "In a scenario with one database, it is important to keep the data really in isolation. It means no constrains between tables from separate modules and no transactions between them." (On transactions we take a softer line below.)
Definition: every table belongs to exactly one module; the module is the only code that reads, writes and migrates it; other modules get data through the module's API or events and store their own copies. Cross-module foreign keys and joins are forbidden; a reporting schema of read-only views is the one allowed place for joins.
The picture shows one PostgreSQL database with three module schemas, a database role per module that can only touch its own schema, a foreign key allowed inside orders, no foreign key from billing.invoices.order_id to orders.orders, and a reporting schema of views for cross-module reports.
-- One PostgreSQL database, one schema and one login role per module.
CREATE SCHEMA catalog; CREATE SCHEMA orders; CREATE SCHEMA billing; CREATE SCHEMA reporting;
CREATE ROLE orders_app LOGIN PASSWORD 'change-me';
GRANT USAGE, CREATE ON SCHEMA orders TO orders_app; -- may create and use its own tables
REVOKE ALL ON SCHEMA catalog, billing FROM orders_app; -- cannot even see the others' tables
ALTER ROLE orders_app SET search_path = orders;
-- Billing keeps the order ID as a value: no FOREIGN KEY to orders.orders.
CREATE TABLE billing.invoices (
id bigserial PRIMARY KEY,
order_id uuid NOT NULL UNIQUE, -- idempotency key for OrderPlaced
amount_cents bigint NOT NULL,
currency char(3) NOT NULL,
status text NOT NULL
);
-- Reporting: the only place where module data meets, read-only, owned by a reporting role.
CREATE VIEW reporting.order_revenue AS
SELECT o.id AS order_id, o.created_at, i.amount_cents, i.status AS invoice_status
FROM orders.orders o LEFT JOIN billing.invoices i ON i.order_id = o.id;
GRANT USAGE ON SCHEMA reporting TO reporting_ro;
GRANT SELECT ON reporting.order_revenue TO reporting_ro; orders_app session Result
1 SELECT * FROM orders.orders LIMIT 1; ok
2 SELECT * FROM billing.invoices LIMIT 1; ERROR: permission denied for schema billing (SQLSTATE 42501)
3 SELECT * FROM invoices; ERROR: relation "invoices" does not exist (42P01), search_path = ordersReal scenario: Orders shows "product name" on the order page: it copies the name and price into orders.order_lines at order time (which is also the legally correct price). Finance wants revenue by product category: a reporting view or a replica feeding a warehouse, never a join inside Orders' code. Billing needs the customer's billing address: from the Customer API or a CustomerAddressChanged event, stored in billing.customer_addresses.
What provides it (per database):
| Product | "Schema per module" means | Cross-module join possible? | Isolation knob |
|---|---|---|---|
| PostgreSQL | CREATE SCHEMA; "A database contains one or more named schemas, which in turn contain tables" | Yes, by default; block it with roles | GRANT USAGE ON SCHEMA, search_path, one role per module |
| MySQL / MariaDB | A database per module on the same server ("CREATE SCHEMA is a synonym for CREATE DATABASE") | Yes, db1.t JOIN db2.t on one server | GRANT ... ON billing.* per user |
| SQL Server | CREATE SCHEMA inside one database | Yes | Schema ownership, GRANT ... ON SCHEMA::billing |
| Oracle | A schema is a user | Yes, with grants | Per-schema users |
| SQLite | One file; ATTACH DATABASE per module | Yes across attached files | None (file permissions only) |
| MongoDB | A database or collection prefix per module | $lookup within one database | Roles per database |
Fix / how to use it: one schema and one migrations folder per module, schema-qualified table names (billing.invoices), one database role per module in production if you can afford separate connection pools (or at least in CI to prove nothing crosses), and copies of other modules' data where you need it. Details of the general trade-off are in Data Ownership in Microservices.
Transactions across modules Important
In plain words: because everything is in one database, you can wrap work from two modules in one transaction; the question is when you should.
Common misunderstanding: "Never span modules in one transaction" or "always do". Both are slogans. A shared local transaction is the biggest gift of a modular monolith; it is also the thing you lose the day a module is extracted.
Definition: a local ACID transaction (ACID & Transactions) over tables in several module schemas, started by one module's use case and joined by others' code through their APIs. Safe use requires that each module writes only its own tables through its own code, and that no business rule depends on the cross-module atomicity unless you accept a saga later.
Option A: one local transaction Option B: transaction per module + event
1 BEGIN BEGIN
2 Catalog.reserve(BOOK-1, 1) -- UPDATE catalog.products INSERT orders.orders + outbox row
3 INSERT orders.orders, orders.order_lines COMMIT
4 COMMIT relay -> OrderPlaced -> Billing (own tx, idempotent)
all-or-nothing, simple; breaks on extraction eventually consistent; survives extraction unchangedReal scenario: reserving stock and creating the order: Option A is fine and simple while both live together (the Laravel PlaceOrder action does this). Opening an invoice: Option B, because a slow or failing billing step must not fail checkout, and Billing is the first module you might extract.
When to use which:
| Situation | Choice | Why |
|---|---|---|
| Two modules that will likely always live together; invariant must hold at commit | One transaction | Cheapest correct answer |
| Side effect that may be slow, may fail, or targets a future service | Event after commit, idempotent handler | Survives extraction; isolates failures |
| Event must never be lost | Outbox row in the same transaction | Atomic "state + intent to publish" |
| Long business process (payment, shipping) | Saga | Will be distributed one day anyway |
Fix / how to use it: Go: pass a *sql.Tx (or a unit-of-work interface) through the API only where a cross-module transaction is a conscious decision; Laravel: DB::transaction in the use case plus ShouldDispatchAfterCommit events. Write down every cross-module transaction in an ADR; it is a future extraction cost.
Enforcing boundaries (fitness functions) Must-know
In plain words: a computer checks the module rules on every pull request, so nobody has to remember them.
Common misunderstanding: "Code review will catch it." Grzybek: code review is the last line, people "can be wrong", and "to enforce architecture we should use the computer as much as possible and treat code-review as the last line of defense." Brown goes further for Java: "lean on the compiler to enforce your architectural principles, rather than discipline, post-compilation tooling, and automated fitness functions (e.g. ArchUnit)." Use the compiler where your language has one (Go does); use tests and linters where it does not (PHP).
Definition: three levels (Grzybek): compile time (visibility: Go internal/, .NET internal, JPMS), automated tests and static analysis (architecture tests such as ArchUnit, NetArchTest, Pest arch(), Spring Modulith verify(); linters such as Deptrac, phpat, go-arch-lint, Packwerk), and code review backed by ADRs. Ford, Parsons and Kua call such automated checks fitness functions (we use the idea; see Architecture vs Design).
Developer change Gate Result
1 orders/orders.go imports shop/billing go test ./shop (arch_test) FAIL: module "orders" imports .../billing
2 billing imports orders/internal/store go build use of internal package ... not allowed
3 Orders\PlaceOrder uses Billing\Internal\Invoice pest --filter=Arch FAIL: expectation toOnlyBeUsedIn
4 new Eloquent belongsTo(Catalog\Internal\Product) deptrac analyse violation: Orders must not depend on Catalog
5 legacy violation that cannot be fixed today baseline / "todo" in config recorded, cannot growReal scenario: Shopify ran packwerk check in CI; the 2020 post says they "included this in Shopify’s CI pipeline to prevent any new violations from being merged into the main branch of the codebase", and kept old ones in a recorded list ("we want to stop the bleeding and prevent new violations"). go-arch-lint's README gives the same adoption path: "'legalize' them by adding them to the config and marking todo".
What provides it:
| Tool | Language | Checks | Mode |
|---|---|---|---|
Go compiler (internal/, no import cycles) | Go | Visibility, cycles | Compile time |
go-arch-lint (.go-arch-lint.yml, mayDependOn) | Go | Component dependency graph vs config | Linter, exit code 1 on warnings |
Hand-written go/parser arch test | Go | Any import rule you can express | go test |
Pest arch() (toOnlyBeUsedIn, not->toUse, toUseNothing) | PHP | Namespace dependencies, class shape | Test |
Deptrac (deptrac.yaml: layers, collectors, ruleset) | PHP | Layer-to-layer dependencies | Static analysis |
| phpat (a PHPStan extension) | PHP | Architecture rules as PHPStan rules | Static analysis |
Packwerk (package.yml, packwerk check) | Ruby | Dependency (and, via extensions, privacy) | Static analysis |
ArchUnit, Spring Modulith ApplicationModules.of(...).verify() | Java | Package and module rules | Test |
| NetArchTest | .NET | Assembly and namespace rules | Test |
Fix / how to use it: pick one test-style tool and one linter, run both in CI as required checks, start with a baseline of existing violations, and make the baseline shrink-only. Details in Mechanics.
Module registration: providers, routes, migrations, composition root Important
In plain words: each module plugs itself in at one place; the application only lists which modules it has.
Common misunderstanding: "Registration is plumbing, not architecture." The registration point is where the module boundary becomes real: if a module's routes, bindings and migrations are spread across global files, it cannot be removed, disabled or extracted.
Definition: in Laravel, one service provider per module, listed in bootstrap/providers.php ("All service providers are registered in the bootstrap/providers.php configuration file", Laravel 13 docs). In its register() method the provider binds the module's contracts ("you should only bind things into the service container"); in boot() it calls loadRoutesFrom(), loadMigrationsFrom(), registers listeners, views and translations. In Go, a composition root (cmd/shop/main.go) constructs every module, passes dependencies as interfaces and subscribes handlers; it is the only package allowed to import every module.
Laravel boot Go start
1 bootstrap/providers.php lists 3 module providers main() builds the bus
2 CatalogServiceProvider::register binds CatalogApi catalog.NewInMemory(...)
3 OrdersServiceProvider::boot routes + migrations orders.New(catalogAdapter{cat}, bus)
4 BillingServiceProvider::boot Event::listen(...) billing.New().Subscribe(bus) or remote.NewForwarder(url)
5 php artisan migrate runs all module migration folders http.ListenAndServeReal scenario: turning off Recommendations in one market = one config flag in its provider; adding a module = one line in bootstrap/providers.php; extracting Billing = changing what BillingServiceProvider binds.
What provides it:
| Need | Plain Laravel 13 | nwidart/laravel-modules | internachi/modular | Go |
|---|---|---|---|---|
| Module folder | app/Modules/<Name> | Modules/<Name>/ with module.json | app-modules/<name>/ as a Composer path package | shop/<name>/ |
| Registration | Provider in bootstrap/providers.php | Module providers booted when enabled | Laravel package discovery | Constructor call in main |
| Routes | loadRoutesFrom() | routes/web.php, routes/api.php per module | Module routes/ | http.ServeMux patterns per module |
| Migrations | loadMigrationsFrom() | database/migrations per module | "Migrations will be run by the Migrator" | Per-module SQL folder (goose, migrate) |
| Enable/disable | Your own flag | module:enable, module:disable (status in an activator, "a JSON file by default") | Remove the Composer requirement | Build tags or a flag in main |
| Generators | make:provider | module:make, module:make-model, ... | --module= option on make:* | none needed |
Fix / how to use it: keep everything a module needs inside its folder and wire it from its provider or constructor. InterNACHI's README gives a practical tip for later extraction: configure an organisation namespace because the default Modules\ "makes it harder to extract your module to a separate package".
Testing modules in isolation Important
In plain words: test one module with fakes for its neighbours; test the boundaries with arch tests; test the whole only for a few end-to-end paths.
Common misunderstanding: "In a monolith every test is an integration test." That is the symptom Shopify described: a change "could trigger a cascade of unrelated test failures." With contracts, a module's tests need only fakes of the contracts it uses.
Definition: three test layers: module tests (the module plus fakes of the contracts it consumes, plus its own schema), contract tests (does the provider still satisfy what consumers assume?), and a thin end-to-end layer. Shopify's goal: "Instead of running the test suite on the whole application, we can run it on the smaller subset of components affected by a change".
Test Real Faked
1 orders_test.go orders package Catalog (map), Publisher (recorder)
2 billing_test.go billing + eventbus Orders (an OrderPlaced value is enough)
3 PlaceOrderTest (Pest) Orders HTTP + DB CatalogApi (anonymous class), Event::fake
4 arch_test.go / Arch tests import graph nothing
5 one e2e checkout test everything payment gatewayReal scenario: the Go Orders tests run with no database and no other module; the Billing test proves idempotency by publishing the same event twice; the Laravel test binds a fake CatalogApi with $this->app->instance(...) and asserts OrderPlaced with Event::assertDispatched.
What provides it:
| Need | Go | Laravel |
|---|---|---|
| Fake a neighbour | Small interface + struct or map | $this->app->instance(Contract::class, $fake) |
| Capture events | Recording publisher | Event::fake([OrderPlaced::class]), Event::assertDispatched |
| Run one module's tests | go test ./shop/orders/... | pest app/Modules/Orders or a test suite per module (modules:sync adds a Modules suite in internachi/modular) |
| Database per test | Testcontainers or a schema per test | RefreshDatabase |
Fix / how to use it: see the Go and Laravel tests; more patterns in Testing Messaging Systems.
Deployment and scaling: single artifact, feature flags per module Important
In plain words: you ship one artifact; you scale by running more copies of it; you turn modules on and off with flags.
Common misunderstanding: "A monolith cannot scale." It scales horizontally like any stateless service; what it cannot do is scale one module alone. Grzybek: "we can scale the Modular Monolith only as a whole, which leads to inefficient resource utilization," and he asks whether that matters at your size.
Definition: one build, one version, one deploy pipeline; all modules move together (an atomic deployment, which Google's 2023 paper lists as a benefit: "Deploy applications atomically, preventing different versions of an application from interacting"). Scale by replicas behind a load balancer; isolate heavy work with separate process roles of the same artifact (web, queue workers per module queue, scheduler); release with feature flags per module.
Same image, different roles Command
1 web (all modules' HTTP routes) php artisan octane:start / ./shop
2 worker for billing queue only php artisan queue:work --queue=billing
3 worker for catalog imports only php artisan queue:work --queue=catalog-imports
4 scheduler php artisan schedule:work
scale 2 and 3 independently: the "scale one module" need, without a second codebaseReal scenario: catalog imports eat CPU at night: run them on a dedicated worker pool from the same image. Billing integration with a new provider: behind BILLING_V2 flag per tenant. A module crashes the process (memory leak): Grzybek notes failure impact is larger in a monolith "because everything works in the same process"; isolate that module's work into its own worker role first, extract only if that is not enough.
What provides it:
| Need | Modular monolith answer | Microservices answer |
|---|---|---|
| More throughput | More replicas of the artifact | More replicas of one service |
| One hot module | Separate queue + worker role; read replica; cache | Scale that service |
| Risky change | Feature flag per module | Deploy one service, canary |
| Different runtime needs | Not possible (one runtime) | Different language per service |
| Blast radius of a crash | Whole process (mitigate with roles) | One service |
Fix / how to use it: keep the app stateless (sessions and cache in Redis), give each module its own queue name, and keep the per-module flag that the extraction will later reuse (BILLING_REMOTE, BILLING_URL).
Evolution: extracting a module into a service Must-know
In plain words: if one module really needs its own deploy, scale or technology, you move it out; a well-kept module moves in days, a tangled one in quarters.
Common misunderstanding: "Any monolith can be split later." Fowler: "You cannot assume that you can take an arbitrary system and break it into microservices. Most systems acquire too many dependencies between their modules, and thus can't be sensibly broken apart." The gradual route works "but these cases required a relatively good modular design to start with."
Definition: extraction is a sequence of reversible steps: (1) the module is clean (arch tests green); (2) its data is isolated (own schema, no cross FK, own role); (3) a seam exists: callers use its contract (Branch by Abstraction), events leave through an outbox, the contract has a remote implementation behind a flag; (4) the service runs with its own database, a Parallel Run compares results, the flag flips, the in-process path is deleted (Strangler Fig). Newman's catalogue names these moves; see Strangler Fig.
The extraction picture: four boxes for the four steps, each one deployable on its own, with the list of things to keep ready while Billing is still a module.
Step Change Rollback
1 0 Billing module, arch tests green -
2 1 billing schema, billing_app role, no FKs revert migration
3 2 OrderPlaced via outbox; BillingApi has HttpBillingApi + ForwardOrderPlaced behind BILLING_REMOTE
4 3 billing-svc deployed, fed by the same events; compare invoices (parallel run) BILLING_REMOTE=false
5 4 BILLING_REMOTE=true for 1%, 10%, 100% of tenants flag back
6 5 data copied to billing-svc's database; old billing schema read-only, then dropped
7 6 delete in-process listener and EloquentBilling (no rollback; done)Real scenario: Billing moves out because Finance needs its own release cadence and audit controls; Search moves out because it needs Elasticsearch-heavy machines; Notifications moves out because it is spiky. Catalog and Orders stay together because they share a transaction and a team.
What to keep ready while it is still a module:
| Ready item | Why it matters on extraction |
|---|---|
| Versioned integration events with IDs, not entities | Become messages on a broker without redesign |
| A contract interface per module, used by every caller | Swap in an HTTP or gRPC client in one binding |
| Idempotent handlers keyed by business ID | At-least-once delivery becomes safe |
| Own schema, no cross FK, no cross join, own migrations | Data moves with a copy, not a redesign |
| No shared ORM relationships or base models | Nothing breaks at compile time when the code leaves |
| Per-module tests and per-module flag | Prove and switch the new path gradually |
| Module-level metrics and logs (module tag) | You can see the module's real load before sizing a service |
Fix / how to use it: the Lab extracts Billing from the Go example with cmd/billing-svc and the remote.Forwarder, and the Laravel example does it with BILLING_REMOTE.
Mechanics
How Go enforces a module boundary
The Go 1.4 release notes define the rule: "a mechanism to define 'internal' packages that may not be imported by packages outside the source subtree in which they reside", e.g. "a package .../a/b/c/internal/d/e/f can be imported only by code in the directory tree rooted at .../a/b/c." The module layout guide adds: "It's recommended to keep packages in internal as much as possible." That gives each module a compiler-enforced inside. Two gaps remain, and the arch test covers them: a module's public package can still be imported by any other module (allowed list), and the shared shop/internal must not import modules. Import cycles between packages are already compile errors.
go-arch-lint expresses the same graph as YAML (schema version 3): components map names to package globs (in:), deps.<name>.mayDependOn lists allowed targets, commonComponents may be imported anywhere, anyProjectDeps: true is for the composition root. It "will return" status code 1 when it "Found warnings". The config for this page's example is at docs/snippets/architecture/modular-monolith/go/.go-arch-lint.yml.
# go-arch-lint (github.com/fe3dback/go-arch-lint), schema version 3.
# Run from the module root: go-arch-lint check
version: 3
workdir: shop
allow:
depOnAnyVendor: false
components:
platform: { in: internal/** }
catalog: { in: catalog }
catalogInt: { in: catalog/internal/** }
orders: { in: orders }
ordersInt: { in: orders/internal/** }
billing: { in: billing }
billingInt: { in: billing/internal/** }
billingRemote: { in: billing/remote }
main: { in: cmd/** }
commonComponents:
- platform
deps:
catalog:
mayDependOn: [catalogInt]
orders:
mayDependOn: [ordersInt]
billing:
mayDependOn: [billingInt, orders]
billingRemote:
mayDependOn: [orders]
main:
anyProjectDeps: trueHow PHP and Laravel enforce it
PHP has no package visibility, so enforcement is tooling. Pest expresses rules in tests: toOnlyBeUsedIn() "enables you to limit the usage of a specific class or set of classes to only particular parts of your application", not->toUse() forbids a dependency, toUseNothing() forbids all. Deptrac reads deptrac.yaml: "Define your architectural layers using so-called collectors" and "a ruleset describing which layers can communicate with each other"; the docs say it can "ensure that bundles/modules/extensions in your project are truly independent of each other". phpat is "a PHPStan extension (Static Analysis tool) designed to verify architectural requirements", useful if PHPStan is already your gate.
# Deptrac: one layer per module and per module's internals; the ruleset is
# the allowed dependency graph. Run: vendor/bin/deptrac analyse
deptrac:
paths:
- ./app/Modules
layers:
- name: CatalogContracts
collectors:
- type: directory
value: app/Modules/Catalog/Contracts/.*
- name: Catalog
collectors:
- type: bool
must:
- type: directory
value: app/Modules/Catalog/.*
must_not:
- type: directory
value: app/Modules/Catalog/Contracts/.*
- name: OrdersContracts
collectors:
- type: directory
value: app/Modules/Orders/Contracts/.*
- name: Orders
collectors:
- type: bool
must:
- type: directory
value: app/Modules/Orders/.*
must_not:
- type: directory
value: app/Modules/Orders/Contracts/.*
- name: BillingContracts
collectors:
- type: directory
value: app/Modules/Billing/Contracts/.*
- name: Billing
collectors:
- type: bool
must:
- type: directory
value: app/Modules/Billing/.*
must_not:
- type: directory
value: app/Modules/Billing/Contracts/.*
ruleset:
CatalogContracts: ~
Catalog: [CatalogContracts]
OrdersContracts: ~
Orders: [OrdersContracts, CatalogContracts]
BillingContracts: ~
Billing: [BillingContracts, OrdersContracts]The Ruby and Java equivalents, for comparison
Packwerk defines a package with a package.yml and checks two kinds of violations: "Dependency violations occur when a package references a private constant from a package that hasn't been declared as a dependency. Privacy violations occur when an external constant references a package's private constants." It "is designed to avoid false positives ... and we pay the cost by accepting a small number of false negatives" and "Method calls and objects passed around the application are completely ignored." (The privacy checker now lives in packwerk-extensions, per the README.) Spring Modulith verifies module structure with ApplicationModules.of(Application.class).verify();.
| Tool | Unit | Config | Catches | Misses |
|---|---|---|---|---|
Go internal/ | Directory subtree | none | Imports of internals | Imports of public packages you did not want |
| go-arch-lint | Component (package globs) | .go-arch-lint.yml | Any import not in mayDependOn | Runtime coupling through the database |
Pest arch() | Namespace | test file | use and type references | Dynamic calls (app('...'), string class names) |
| Deptrac | Layer via collectors | deptrac.yaml | Class dependencies between layers | Same dynamic calls |
| Packwerk | Package | package.yml | Static constant references | Method calls, dynamic constants |
| Wedge (Shopify, internal, retired) | Component | - | Runtime call graph, associations | Slow; "a lot of data, so it's hard to separate the signal from the noise" |
| Spring Modulith | Application module (package) | conventions | Access to internal packages, cycles | Reflection |
Error codes and failure messages you will actually see
| Where | Message (verbatim where marked) | Meaning |
|---|---|---|
| Go build | use of internal package academy/modular-monolith/shop/orders/internal/store not allowed (verbatim, from this page's module) | Another module reached into orders/internal |
| Go build | import cycle not allowed (verbatim) | Two modules import each other |
| Go arch test | module "orders" imports academy/modular-monolith/shop/billing; allowed: [internal] (verbatim) | A forbidden but public dependency |
| go-arch-lint | exit status 1, "Found warnings" | Dependency not in mayDependOn |
| Pest | failed arch() expectation naming the class and namespace (wording depends on the Pest version; not verified here) | Boundary violated |
| Deptrac | a violation row "must not depend on" with the two layers (format depends on the formatter) | Ruleset violated |
| Laravel container | Target [App\Modules\Catalog\Contracts\CatalogApi] is not instantiable. | The module's provider is missing from bootstrap/providers.php |
| PostgreSQL | ERROR: permission denied for schema billing, SQLSTATE 42501 | A module's role touched another module's schema |
| PostgreSQL | ERROR: relation "invoices" does not exist, SQLSTATE 42P01 | Unqualified name outside the role's search_path |
| MySQL | Error 1142 SELECT command denied to user ... for table ... | Same, with per-database grants |
Go
The worked example is one shop with three modules: Catalog (products, stock), Orders (orders, order lines) and Billing (invoices). Orders asks Catalog for prices through a port, publishes OrderPlaced, and Billing opens an invoice. The module is docs/snippets/architecture/modular-monolith/go; gofmt -l . is empty, go vet ./... and go test ./... pass, and go run ./shop/cmd/shop prints the placed order and its invoice.
go/
├── .go-arch-lint.yml
├── before/checkout.go one function, three capabilities, one shared schema
└── shop/
├── arch_test.go fitness functions: allowed module graph, platform knows no module
├── internal/eventbus/ shared kernel: in-process event bus
├── catalog/ public: Product, ErrNotFound, Module, Stock
│ └── internal/store/ Row, Repository, Memory, SQL (catalog.products)
├── orders/ public: Module, Catalog port, Publisher, OrderPlaced (events.go)
│ └── internal/store/
├── billing/ public: Module, Invoice, ErrNoInvoice; subscribes to OrderPlaced
│ ├── internal/ledger/
│ └── remote/ extraction seam: forwards OrderPlaced over HTTP
└── cmd/
├── shop/main.go composition root, BILLING_URL feature flag
└── billing-svc/main.go Billing as its own serviceBefore
A monolith with no boundaries: one function reads Catalog's tables with a join, writes Orders' table, writes Billing's table with a foreign key, and updates stock. It is correct code; it is also impossible to give to three teams or to split.
// Package before shows a monolith with no module boundaries: one function
// reads the catalog's tables, writes orders and creates the invoice, all
// against one shared schema. It works; it just cannot be split or owned.
package before
import (
"context"
"database/sql"
"fmt"
)
// PlaceOrder is called by the HTTP handler. Every table it touches belongs
// to a different business capability, and nothing says so.
func PlaceOrder(ctx context.Context, db *sql.DB, customerID int64, sku string, qty int) (int64, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
// Catalog's table, read directly (and locked) by the order code.
var price int64
var stock int
err = tx.QueryRowContext(ctx,
`SELECT p.price_cents, s.on_hand
FROM products p JOIN stock_levels s ON s.product_id = p.id
WHERE p.sku = $1 FOR UPDATE OF s`, sku).Scan(&price, &stock)
if err != nil {
return 0, fmt.Errorf("load product: %w", err)
}
if stock < qty {
return 0, fmt.Errorf("out of stock: %s", sku)
}
var orderID int64
err = tx.QueryRowContext(ctx,
`INSERT INTO orders (customer_id, total_cents) VALUES ($1, $2) RETURNING id`,
customerID, price*int64(qty)).Scan(&orderID)
if err != nil {
return 0, err
}
// Billing's table, written by the order code, with a foreign key to orders.
if _, err = tx.ExecContext(ctx,
`INSERT INTO invoices (order_id, amount_cents, status) VALUES ($1, $2, 'open')`,
orderID, price*int64(qty)); err != nil {
return 0, err
}
if _, err = tx.ExecContext(ctx,
`UPDATE stock_levels SET on_hand = on_hand - $1
WHERE product_id = (SELECT id FROM products WHERE sku = $2)`, qty, sku); err != nil {
return 0, err
}
return orderID, tx.Commit()
}After
The shared kernel is only the event bus. It lives in shop/internal, so every module may import it and nothing outside shop/ can:
// Package eventbus is the in-process event bus shared by all modules. It is
// platform code (part of the minimal shared kernel), so it lives under
// shop/internal: every module in shop/ may import it, nothing outside may.
package eventbus
import (
"context"
"errors"
"sync"
)
// Event is anything with a stable, versioned name such as
// "orders.order_placed.v1". The name is the contract, not the Go type.
type Event interface {
EventName() string
}
// Handler reacts to one event. It must be idempotent: the same event can be
// delivered again after a retry or, later, by a real broker.
type Handler func(ctx context.Context, e Event) error
// Bus delivers events synchronously, in the caller's goroutine, to every
// handler subscribed to the event's name.
type Bus struct {
mu sync.RWMutex
handlers map[string][]Handler
}
// New returns an empty bus.
func New() *Bus {
return &Bus{handlers: map[string][]Handler{}}
}
// Subscribe registers h for events called name.
func (b *Bus) Subscribe(name string, h Handler) {
b.mu.Lock()
defer b.mu.Unlock()
b.handlers[name] = append(b.handlers[name], h)
}
// Publish calls every handler and joins their errors. A failing handler does
// not stop the others; the caller decides whether to roll back.
func (b *Bus) Publish(ctx context.Context, e Event) error {
b.mu.RLock()
hs := append([]Handler(nil), b.handlers[e.EventName()]...)
b.mu.RUnlock()
var errs []error
for _, h := range hs {
if err := h(ctx, e); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}Catalog exposes a facade and a copy type; its storage, including the schema-qualified SQL, is internal:
// Package catalog is the Catalog module. Its public API is this file: the
// Product type, ErrNotFound and the Module methods. Everything else lives
// under catalog/internal and cannot be imported by other modules.
package catalog
import (
"context"
"errors"
"academy/modular-monolith/shop/catalog/internal/store"
)
// ErrNotFound is part of the contract: callers may test for it.
var ErrNotFound = errors.New("catalog: product not found")
// Product is the published view of a product. It is a copy, not the
// module's internal row, so the module can change its tables freely.
type Product struct {
SKU string
Name string
PriceCents int64
InStock bool
}
// Module is the facade other modules call.
type Module struct {
repo store.Repository
}
// New builds the module over any repository (in-memory here, SQL in prod).
func New(repo store.Repository) *Module {
return &Module{repo: repo}
}
// Stock seeds the in-memory store; it is exported so the composition root
// and tests never need catalog/internal (which the compiler forbids anyway).
type Stock struct {
SKU string
Name string
PriceCents int64
OnHand int
}
// NewInMemory is a convenience for demos and tests.
func NewInMemory(seed ...Stock) *Module {
rows := make([]store.Row, 0, len(seed))
for _, s := range seed {
rows = append(rows, store.Row(s))
}
return New(store.NewMemory(rows...))
}
// Product returns the published view of one SKU.
func (m *Module) Product(ctx context.Context, sku string) (Product, error) {
row, ok, err := m.repo.FindBySKU(ctx, sku)
if err != nil {
return Product{}, err
}
if !ok {
return Product{}, ErrNotFound
}
return Product{SKU: row.SKU, Name: row.Name, PriceCents: row.PriceCents, InStock: row.OnHand > 0}, nil
}// Package store is Catalog's persistence. Only Catalog may import it; the
// tables it reads live in the "catalog" schema and nobody else queries them.
package store
import (
"context"
"database/sql"
"errors"
"sync"
)
// Row is the internal shape of a product; it never leaves the module.
type Row struct {
SKU string
Name string
PriceCents int64
OnHand int
}
// Repository is what the module needs from storage.
type Repository interface {
FindBySKU(ctx context.Context, sku string) (Row, bool, error)
}
// Memory is an in-memory repository for demos and tests.
type Memory struct {
mu sync.RWMutex
rows map[string]Row
}
// NewMemory returns a repository pre-filled with rows.
func NewMemory(seed ...Row) *Memory {
m := &Memory{rows: map[string]Row{}}
for _, r := range seed {
m.rows[r.SKU] = r
}
return m
}
// FindBySKU implements Repository.
func (m *Memory) FindBySKU(_ context.Context, sku string) (Row, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
r, ok := m.rows[sku]
return r, ok, nil
}
// SQL reads from the module's own schema with schema-qualified names.
type SQL struct {
DB *sql.DB
}
// FindBySKU implements Repository against PostgreSQL.
func (s SQL) FindBySKU(ctx context.Context, sku string) (Row, bool, error) {
var r Row
err := s.DB.QueryRowContext(ctx,
`SELECT sku, name, price_cents, on_hand FROM catalog.products WHERE sku = $1`, sku).
Scan(&r.SKU, &r.Name, &r.PriceCents, &r.OnHand)
if errors.Is(err, sql.ErrNoRows) {
return Row{}, false, nil
}
return r, err == nil, err
}Orders declares the ports it needs (Catalog, Publisher) and publishes a versioned integration event. It imports no other module:
package orders
import "time"
// OrderPlacedName is the versioned contract name. Renaming the Go type is a
// refactoring; changing this string is a breaking change for subscribers.
const OrderPlacedName = "orders.order_placed.v1"
// OrderPlaced is an integration event: the small, stable fact that Orders
// publishes for other modules. It carries IDs and amounts, not entities.
type OrderPlaced struct {
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
TotalCents int64 `json:"total_cents"`
Currency string `json:"currency"`
PlacedAt time.Time `json:"placed_at"`
}
// EventName implements eventbus.Event.
func (OrderPlaced) EventName() string { return OrderPlacedName }// Package orders is the Orders module. It owns orders and order lines. It
// does not import Catalog or Billing: it declares the small ports it needs
// and publishes OrderPlaced for whoever is interested.
package orders
import (
"context"
"errors"
"fmt"
"time"
"academy/modular-monolith/shop/internal/eventbus"
"academy/modular-monolith/shop/orders/internal/store"
)
// ErrUnavailable is returned when a product cannot be sold.
var ErrUnavailable = errors.New("orders: product unavailable")
// ProductInfo is what Orders needs to know about a product, in Orders'
// own words. The composition root translates Catalog's Product into it.
type ProductInfo struct {
PriceCents int64
Available bool
}
// Catalog is a consumer-side port: declared here, implemented by an adapter.
type Catalog interface {
Lookup(ctx context.Context, sku string) (ProductInfo, error)
}
// Publisher is satisfied by *eventbus.Bus (and by a test recorder).
type Publisher interface {
Publish(ctx context.Context, e eventbus.Event) error
}
// Line is one requested item.
type Line struct {
SKU string
Qty int
}
// Module is the Orders facade.
type Module struct {
catalog Catalog
pub Publisher
repo *store.Memory
now func() time.Time
}
// New wires the module. Dependencies are interfaces, so the module can be
// tested alone and Catalog can later become a remote service.
func New(c Catalog, p Publisher) *Module {
return &Module{catalog: c, pub: p, repo: store.NewMemory(), now: time.Now}
}
// PlaceOrder prices the lines through the Catalog port, stores the order and
// publishes OrderPlaced. With SQL storage the insert and an outbox row would
// share one transaction in the orders schema; see the page's outbox section.
func (m *Module) PlaceOrder(ctx context.Context, customerID string, lines []Line) (string, error) {
if len(lines) == 0 {
return "", errors.New("orders: empty order")
}
var total int64
for _, l := range lines {
p, err := m.catalog.Lookup(ctx, l.SKU)
if err != nil {
return "", fmt.Errorf("orders: lookup %s: %w", l.SKU, err)
}
if !p.Available {
return "", fmt.Errorf("%w: %s", ErrUnavailable, l.SKU)
}
total += p.PriceCents * int64(l.Qty)
}
id := m.repo.Save(store.Order{CustomerID: customerID, TotalCents: total, Currency: "EUR"})
ev := OrderPlaced{OrderID: id, CustomerID: customerID, TotalCents: total, Currency: "EUR", PlacedAt: m.now().UTC()}
if err := m.pub.Publish(ctx, ev); err != nil {
return id, fmt.Errorf("orders: publish %s: %w", ev.EventName(), err)
}
return id, nil
}Billing depends on Orders only through OrderPlaced, and its handler is idempotent:
// Package billing is the Billing module. It depends on Orders only through
// the published OrderPlaced event; it never reads the orders schema.
package billing
import (
"context"
"errors"
"fmt"
"academy/modular-monolith/shop/billing/internal/ledger"
"academy/modular-monolith/shop/internal/eventbus"
"academy/modular-monolith/shop/orders"
)
// ErrNoInvoice is part of the contract.
var ErrNoInvoice = errors.New("billing: no invoice for order")
// Invoice is the published view of an invoice.
type Invoice struct {
OrderID string `json:"order_id"`
AmountCents int64 `json:"amount_cents"`
Currency string `json:"currency"`
Status string `json:"status"`
}
// Module is the Billing facade.
type Module struct {
ledger *ledger.Memory
}
// New returns a Billing module with in-memory storage.
func New() *Module {
return &Module{ledger: ledger.NewMemory()}
}
// Subscribe connects the module to the in-process bus. The composition root
// calls it; when Billing becomes a service this line is replaced by a relay.
func (m *Module) Subscribe(bus *eventbus.Bus) {
bus.Subscribe(orders.OrderPlacedName, func(ctx context.Context, e eventbus.Event) error {
ev, ok := e.(orders.OrderPlaced)
if !ok {
return fmt.Errorf("billing: unexpected payload %T", e)
}
return m.HandleOrderPlaced(ctx, ev)
})
}
// HandleOrderPlaced opens an invoice. It is idempotent: a redelivered event
// for the same order is a no-op, which is what lets us move to a broker.
func (m *Module) HandleOrderPlaced(_ context.Context, ev orders.OrderPlaced) error {
m.ledger.OpenOnce(ledger.Entry{OrderID: ev.OrderID, AmountCents: ev.TotalCents, Currency: ev.Currency, Status: "open"})
return nil
}
// Invoice returns the invoice for an order.
func (m *Module) Invoice(_ context.Context, orderID string) (Invoice, error) {
e, ok := m.ledger.Get(orderID)
if !ok {
return Invoice{}, ErrNoInvoice
}
return Invoice{OrderID: e.OrderID, AmountCents: e.AmountCents, Currency: e.Currency, Status: e.Status}, nil
}// Package ledger is Billing's storage (the "billing" schema in production).
package ledger
import "sync"
// Entry is one invoice row.
type Entry struct {
OrderID string
AmountCents int64
Currency string
Status string
}
// Memory keys invoices by order ID, which doubles as the idempotency key.
type Memory struct {
mu sync.Mutex
rows map[string]Entry
}
// NewMemory returns an empty ledger.
func NewMemory() *Memory {
return &Memory{rows: map[string]Entry{}}
}
// OpenOnce inserts e unless an entry for the order already exists
// (the in-memory twin of INSERT ... ON CONFLICT (order_id) DO NOTHING).
func (m *Memory) OpenOnce(e Entry) bool {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.rows[e.OrderID]; ok {
return false
}
m.rows[e.OrderID] = e
return true
}
// Get returns the entry for an order.
func (m *Memory) Get(orderID string) (Entry, bool) {
m.mu.Lock()
defer m.mu.Unlock()
e, ok := m.rows[orderID]
return e, ok
}The composition root is the only package that knows every module. The catalogAdapter is a tiny anti-corruption layer, and BILLING_URL is the per-module flag that moves Billing out of the process:
// Command shop is the composition root: the only package that knows every
// module. It wires adapters between modules and decides, per module,
// whether it runs in-process or remotely.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"academy/modular-monolith/shop/billing"
"academy/modular-monolith/shop/billing/remote"
"academy/modular-monolith/shop/catalog"
"academy/modular-monolith/shop/internal/eventbus"
"academy/modular-monolith/shop/orders"
)
// catalogAdapter translates Catalog's published API into the port Orders
// declared (a tiny anti-corruption layer).
type catalogAdapter struct{ c *catalog.Module }
func (a catalogAdapter) Lookup(ctx context.Context, sku string) (orders.ProductInfo, error) {
p, err := a.c.Product(ctx, sku)
if errors.Is(err, catalog.ErrNotFound) {
return orders.ProductInfo{}, nil // unknown means unavailable to Orders
}
if err != nil {
return orders.ProductInfo{}, err
}
return orders.ProductInfo{PriceCents: p.PriceCents, Available: p.InStock}, nil
}
func main() {
ctx := context.Background()
bus := eventbus.New()
cat := catalog.NewInMemory(catalog.Stock{SKU: "BOOK-1", Name: "DDD", PriceCents: 4200, OnHand: 3})
ord := orders.New(catalogAdapter{cat}, bus)
// Feature flag per module: BILLING_URL moves Billing out of the process.
var bill *billing.Module
if url := os.Getenv("BILLING_URL"); url != "" {
remote.NewForwarder(url).Subscribe(bus)
} else {
bill = billing.New()
bill.Subscribe(bus)
}
id, err := ord.PlaceOrder(ctx, "cust-7", []orders.Line{{SKU: "BOOK-1", Qty: 1}})
if err != nil {
log.Fatal(err)
}
fmt.Println("placed", id)
if bill != nil {
inv, err := bill.Invoice(ctx, id)
if err != nil {
log.Fatal(err)
}
fmt.Printf("invoice for %s: %d %s (%s)\n", inv.OrderID, inv.AmountCents, inv.Currency, inv.Status)
}
}The fitness functions. The compiler already blocks internal/ imports and cycles; this test adds the allowed module graph and keeps the kernel clean:
// Package shop holds the architecture fitness functions for the modular
// monolith: tests that fail the build when a module boundary is crossed.
package shop
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"slices"
"strings"
"testing"
)
const root = "academy/modular-monolith/shop/"
// allowed lists, per module, the other modules it may import (public
// packages only; internal/ is already blocked by the Go compiler).
// "internal" is the shared platform (event bus), open to every module.
var allowed = map[string][]string{
"catalog": {"internal"},
"orders": {"internal"},
"billing": {"internal", "orders"},
}
// target returns the top-level directory of an import inside shop/.
func target(imp string) (string, bool) {
rest, ok := strings.CutPrefix(imp, root)
if !ok {
return "", false
}
top, _, _ := strings.Cut(rest, "/")
return top, true
}
func TestModuleDependencies(t *testing.T) {
for module, may := range allowed {
err := filepath.WalkDir(module, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, im := range f.Imports {
imp := strings.Trim(im.Path.Value, `"`)
to, inShop := target(imp)
if !inShop || to == module || slices.Contains(may, to) {
continue
}
t.Errorf("%s: module %q imports %s; allowed: %v", path, module, imp, may)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}
// The shared kernel must stay tiny and must not know any module.
func TestPlatformKnowsNoModule(t *testing.T) {
err := filepath.WalkDir("internal", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, im := range f.Imports {
if to, ok := target(strings.Trim(im.Path.Value, `"`)); ok && to != "internal" {
t.Errorf("%s: platform code imports module %q", path, to)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}Modules tested alone. Orders with a fake Catalog and a recording publisher; Billing by publishing the event twice:
package orders_test
import (
"context"
"errors"
"testing"
"academy/modular-monolith/shop/internal/eventbus"
"academy/modular-monolith/shop/orders"
)
// fakeCatalog replaces the whole Catalog module: Orders is tested alone.
type fakeCatalog map[string]orders.ProductInfo
func (f fakeCatalog) Lookup(_ context.Context, sku string) (orders.ProductInfo, error) {
p, ok := f[sku]
if !ok {
return orders.ProductInfo{}, errors.New("unknown sku")
}
return p, nil
}
// recorder captures published events instead of delivering them.
type recorder struct{ events []eventbus.Event }
func (r *recorder) Publish(_ context.Context, e eventbus.Event) error {
r.events = append(r.events, e)
return nil
}
func TestPlaceOrderPublishesOrderPlaced(t *testing.T) {
rec := &recorder{}
m := orders.New(fakeCatalog{"BOOK-1": {PriceCents: 1500, Available: true}}, rec)
id, err := m.PlaceOrder(context.Background(), "cust-7", []orders.Line{{SKU: "BOOK-1", Qty: 2}})
if err != nil {
t.Fatal(err)
}
if len(rec.events) != 1 {
t.Fatalf("want 1 event, got %d", len(rec.events))
}
ev, ok := rec.events[0].(orders.OrderPlaced)
if !ok || ev.OrderID != id || ev.TotalCents != 3000 {
t.Fatalf("unexpected event %#v", rec.events[0])
}
}
func TestPlaceOrderRejectsUnavailable(t *testing.T) {
m := orders.New(fakeCatalog{"BOOK-1": {PriceCents: 1500}}, &recorder{})
_, err := m.PlaceOrder(context.Background(), "cust-7", []orders.Line{{SKU: "BOOK-1", Qty: 1}})
if !errors.Is(err, orders.ErrUnavailable) {
t.Fatalf("want ErrUnavailable, got %v", err)
}
}package billing_test
import (
"context"
"testing"
"time"
"academy/modular-monolith/shop/billing"
"academy/modular-monolith/shop/internal/eventbus"
"academy/modular-monolith/shop/orders"
)
// Billing is tested by publishing the event it subscribes to; no Orders
// module, no database, no HTTP.
func TestInvoiceOpenedOnceForRedeliveredEvent(t *testing.T) {
bus := eventbus.New()
b := billing.New()
b.Subscribe(bus)
ev := orders.OrderPlaced{OrderID: "ord-0001", TotalCents: 4200, Currency: "EUR", PlacedAt: time.Now()}
for i := 0; i < 2; i++ { // the second publish simulates a redelivery
if err := bus.Publish(context.Background(), ev); err != nil {
t.Fatal(err)
}
}
inv, err := b.Invoice(context.Background(), "ord-0001")
if err != nil || inv.AmountCents != 4200 || inv.Status != "open" {
t.Fatalf("got %+v, %v", inv, err)
}
}Extraction seam and the extracted service. The forwarder replaces the in-process subscription; the service wraps the same billing package with HTTP (Go 1.22 method-and-wildcard patterns):
// Package remote is the extraction seam for Billing. When Billing runs as its
// own service, the monolith subscribes this forwarder instead of the
// in-process module. Orders does not change at all.
package remote
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"academy/modular-monolith/shop/internal/eventbus"
"academy/modular-monolith/shop/orders"
)
// Forwarder posts OrderPlaced events to the billing service. In production
// you would write the event to an outbox table in the same transaction as
// the order and let a relay deliver it; a direct POST is the lab version.
type Forwarder struct {
BaseURL string
Client *http.Client
}
// NewForwarder returns a forwarder with a bounded timeout.
func NewForwarder(baseURL string) *Forwarder {
return &Forwarder{BaseURL: baseURL, Client: &http.Client{Timeout: 2 * time.Second}}
}
// Subscribe registers the forwarder on the bus for OrderPlaced.
func (f *Forwarder) Subscribe(bus *eventbus.Bus) {
bus.Subscribe(orders.OrderPlacedName, f.Handle)
}
// Handle sends one event. The order ID is the idempotency key, so the
// service can safely receive the same event twice.
func (f *Forwarder) Handle(ctx context.Context, e eventbus.Event) error {
body, err := json.Marshal(e)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.BaseURL+"/events/"+e.EventName(), bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if ev, ok := e.(orders.OrderPlaced); ok {
req.Header.Set("Idempotency-Key", ev.OrderID)
}
resp, err := f.Client.Do(req)
if err != nil {
return fmt.Errorf("billing service: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("billing service: status %d", resp.StatusCode)
}
return nil
}// Command billing-svc is Billing extracted into its own process. It reuses
// the same billing package; only the transport around it is new.
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"os"
"academy/modular-monolith/shop/billing"
"academy/modular-monolith/shop/orders"
)
func main() {
addr := os.Getenv("BILLING_ADDR")
if addr == "" {
addr = ":8081"
}
b := billing.New()
mux := http.NewServeMux()
mux.HandleFunc("POST /events/"+orders.OrderPlacedName, func(w http.ResponseWriter, r *http.Request) {
var ev orders.OrderPlaced
if err := json.NewDecoder(r.Body).Decode(&ev); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := b.HandleOrderPlaced(r.Context(), ev); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
})
mux.HandleFunc("GET /invoices/{orderID}", func(w http.ResponseWriter, r *http.Request) {
inv, err := b.Invoice(r.Context(), r.PathValue("orderID"))
if errors.Is(err, billing.ErrNoInvoice) {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(inv)
})
log.Printf("billing-svc listening on %s", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}The Go angle
| Go feature | Role in a modular monolith | Note |
|---|---|---|
internal/ directories | Compiler-enforced module internals | Go 1.4 rule; "keep packages in internal as much as possible" (module layout guide) |
| Import cycles are errors | No cyclic module graph, ever | You must invert one direction (port or event) |
| Implicit interfaces | Consumer-side ports: orders.Catalog needs no import of catalog | Lowers compile-time coupling |
cmd/<name>/main.go | One composition root per binary; a second binary for an extracted module | Same packages, different wiring |
go/parser, go list -deps | Arch tests without third-party tools | As in arch_test.go |
| go-arch-lint | Declarative module graph in CI | Could not be run on this machine (its dependency download was blocked); config written against the syntax doc |
database/sql, pgx | One pool per process; schema-qualified SQL per module | One role per module means one pool per module |
| Service Weaver | Components as interfaces, weaver.Ref[T], single or multi process | In maintenance mode since 5 Dec 2024; archived 6 Jun 2025 per its README |
Service Weaver's docs describe the model this page builds by hand: "a component is represented with a regular Go interface, and components interact with each other by calling the methods defined by these interfaces", and with go run "all components run together in a single process, and method calls between components are executed as regular Go method calls"; the weaver multi deployer runs them in separate processes "with method calls between components executed as RPCs". Since the framework is frozen, the plain-Go version (interfaces + composition root + a remote adapter where needed) is the durable form of the idea.
Laravel
The same shop as a Laravel 13 application (PHP 8.4). Files live under docs/snippets/architecture/modular-monolith/php; PHP is not installed on the authoring machine, so the code was reviewed, not run. The example uses plain Laravel (one provider per module); the registration table shows how nwidart/laravel-modules and internachi/modular package the same structure.
app/Modules/
├── Catalog/
│ ├── CatalogServiceProvider.php binds CatalogApi, loads migrations
│ ├── Contracts/CatalogApi.php, ProductView.php
│ ├── Internal/Product.php (catalog.products), EloquentCatalog.php
│ └── database/migrations/..._create_catalog_schema.php
├── Orders/
│ ├── OrdersServiceProvider.php loads routes + migrations
│ ├── Contracts/OrderPlaced.php integration event (ShouldDispatchAfterCommit)
│ ├── Actions/PlaceOrder.php use case, DB::transaction
│ ├── Http/PlaceOrderController.php
│ ├── Internal/Order.php, OrderLine.php orders.orders, orders.order_lines
│ ├── routes/api.php
│ └── database/migrations/..._create_orders_schema.php
└── Billing/
├── BillingServiceProvider.php binds BillingApi, listens to OrderPlaced, BILLING_REMOTE switch
├── Contracts/BillingApi.php, InvoiceView.php
├── Internal/Invoice.php (billing.invoices), EloquentBilling.php
├── Listeners/OpenInvoice.php queued, idempotent
├── Remote/HttpBillingApi.php, ForwardOrderPlaced.php
└── database/migrations/..._create_billing_schema.php
bootstrap/providers.php config/modules.php tests/Arch/ModuleBoundariesTest.php tests/Feature/PlaceOrderTest.php deptrac.yamlBefore
The classic shape: one controller, a shared App\Models bag, Order with belongsTo(Product) and hasOne(Invoice), stock decremented by order code, invoices created by order code, and a cross-module eager load in the response.
<?php
namespace App\Http\Controllers;
use App\Models\Invoice;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// One controller, three business capabilities, one shared "models" bag.
// Order has belongsTo(Product) and hasOne(Invoice), so the three tables are
// tied by Eloquent relationships and foreign keys. Nothing is a module.
final class OrderController
{
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'sku' => ['required', 'string'],
'qty' => ['required', 'integer', 'min:1'],
]);
$order = DB::transaction(function () use ($data, $request) {
$product = Product::where('sku', $data['sku'])->lockForUpdate()->firstOrFail();
abort_if($product->stock < $data['qty'], 422, 'Out of stock');
$order = Order::create([
'customer_id' => $request->user()->id,
'product_id' => $product->id, // FK into the catalog's table
'total_cents' => $product->price_cents * $data['qty'],
]);
$product->decrement('stock', $data['qty']); // order code edits catalog data
Invoice::create([ // order code writes billing data
'order_id' => $order->id,
'amount_cents' => $order->total_cents,
'status' => 'open',
]);
return $order;
});
// A report-style join across all three areas, in a controller.
return response()->json($order->load('product', 'invoice'), 201);
}
}After
Registration. One provider per module in the file Laravel 13 reads:
<?php
// Laravel 13 registers application service providers in this file.
// One provider per module: removing a line removes the module.
return [
App\Providers\AppServiceProvider::class,
App\Modules\Catalog\CatalogServiceProvider::class,
App\Modules\Orders\OrdersServiceProvider::class,
App\Modules\Billing\BillingServiceProvider::class,
];<?php
// Per-module switches. BILLING_REMOTE=true moves Billing out of the process
// without touching Orders (see BillingServiceProvider).
return [
'billing' => [
'remote' => (bool) env('BILLING_REMOTE', false),
],
];Catalog: a contract, a read-only view, an internal model on a schema-qualified table, an implementation that reserves stock with one conditional UPDATE, a provider and a migration that creates the schema:
<?php
namespace App\Modules\Catalog\Contracts;
// The Catalog module's public API. Other modules type-hint this interface;
// they never see Eloquent models or tables from Catalog.
interface CatalogApi
{
public function product(string $sku): ?ProductView;
/** Atomically reserve stock; returns false when not enough is on hand. */
public function reserve(string $sku, int $qty): bool;
}<?php
namespace App\Modules\Catalog\Contracts;
// A read-only copy of what Catalog publishes about a product.
final readonly class ProductView
{
public function __construct(
public string $sku,
public string $name,
public int $priceCents,
public bool $inStock,
) {}
}<?php
namespace App\Modules\Catalog\Internal;
use Illuminate\Database\Eloquent\Model;
// Internal to Catalog. The schema-qualified table name keeps it in the
// "catalog" schema (PostgreSQL connection).
final class Product extends Model
{
protected $table = 'catalog.products';
protected $guarded = [];
}<?php
namespace App\Modules\Catalog\Internal;
use App\Modules\Catalog\Contracts\CatalogApi;
use App\Modules\Catalog\Contracts\ProductView;
final class EloquentCatalog implements CatalogApi
{
public function product(string $sku): ?ProductView
{
$p = Product::query()->where('sku', $sku)->first();
return $p === null ? null : new ProductView(
sku: $p->sku,
name: $p->name,
priceCents: (int) $p->price_cents,
inStock: $p->on_hand > 0,
);
}
public function reserve(string $sku, int $qty): bool
{
// One conditional UPDATE: no read-then-write race, no lock held by the caller.
return Product::query()
->where('sku', $sku)
->where('on_hand', '>=', $qty)
->decrement('on_hand', $qty) === 1;
}
}<?php
namespace App\Modules\Catalog;
use App\Modules\Catalog\Contracts\CatalogApi;
use App\Modules\Catalog\Internal\EloquentCatalog;
use Illuminate\Support\ServiceProvider;
final class CatalogServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(CatalogApi::class, EloquentCatalog::class);
}
public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
DB::statement('CREATE SCHEMA IF NOT EXISTS catalog');
Schema::create('catalog.products', function (Blueprint $table) {
$table->id();
$table->string('sku')->unique();
$table->string('name');
$table->unsignedBigInteger('price_cents');
$table->unsignedInteger('on_hand')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('catalog.products');
DB::statement('DROP SCHEMA IF EXISTS catalog');
}
};Orders: the published event, the use case (one local transaction for reserve + insert, event released after commit), the controller, routes, provider and migration. The Order model has a relationship to its own lines only:
<?php
namespace App\Modules\Orders\Contracts;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
// Integration event published by Orders. It is part of the module's public
// contract: small, versioned, IDs and amounts only (no Eloquent models).
// ShouldDispatchAfterCommit: listeners run only if the order really committed.
final readonly class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable;
public const NAME = 'orders.order_placed.v1';
public function __construct(
public string $orderId,
public string $customerId,
public int $totalCents,
public string $currency,
public string $placedAt,
) {}
}<?php
namespace App\Modules\Orders\Actions;
use App\Modules\Catalog\Contracts\CatalogApi;
use App\Modules\Orders\Contracts\OrderPlaced;
use App\Modules\Orders\Internal\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
// One use case of the Orders module. It talks to Catalog only through
// CatalogApi and announces the result with an event.
final readonly class PlaceOrder
{
public function __construct(private CatalogApi $catalog) {}
/** @param list<array{sku: string, qty: int}> $lines */
public function __invoke(string $customerId, array $lines): Order
{
// One database, so one local transaction may span the stock
// reservation (Catalog) and the order insert (Orders). Each module
// still writes only its own schema, through its own code.
return DB::transaction(function () use ($customerId, $lines) {
$total = 0;
$rows = [];
foreach ($lines as $line) {
$product = $this->catalog->product($line['sku']);
if ($product === null || ! $this->catalog->reserve($line['sku'], $line['qty'])) {
throw ValidationException::withMessages(['lines' => "{$line['sku']} is unavailable"]);
}
$total += $product->priceCents * $line['qty'];
$rows[] = ['sku' => $line['sku'], 'qty' => $line['qty'], 'unit_cents' => $product->priceCents];
}
$order = Order::create(['customer_id' => $customerId, 'total_cents' => $total, 'currency' => 'EUR']);
$order->lines()->createMany($rows);
// Held until COMMIT because OrderPlaced implements ShouldDispatchAfterCommit.
OrderPlaced::dispatch($order->id, $customerId, $total, 'EUR', now()->toIso8601String());
return $order;
});
}
}<?php
namespace App\Modules\Orders\Http;
use App\Modules\Orders\Actions\PlaceOrder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class PlaceOrderController
{
public function __invoke(Request $request, PlaceOrder $placeOrder): JsonResponse
{
$data = $request->validate([
'lines' => ['required', 'array', 'min:1'],
'lines.*.sku' => ['required', 'string'],
'lines.*.qty' => ['required', 'integer', 'min:1'],
]);
$order = $placeOrder((string) $request->user()->id, $data['lines']);
return response()->json(['id' => $order->id, 'total_cents' => $order->total_cents], 201);
}
}<?php
use App\Modules\Orders\Http\PlaceOrderController;
use Illuminate\Support\Facades\Route;
// Loaded by OrdersServiceProvider::boot() with loadRoutesFrom().
Route::middleware(['api', 'auth:sanctum'])
->prefix('api/orders')
->group(function () {
Route::post('/', PlaceOrderController::class)->name('orders.place');
});<?php
namespace App\Modules\Orders;
use Illuminate\Support\ServiceProvider;
final class OrdersServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadRoutesFrom(__DIR__.'/routes/api.php');
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
}
}<?php
namespace App\Modules\Orders\Internal;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Order extends Model
{
use HasUuids;
protected $table = 'orders.orders';
protected $guarded = [];
// A relationship inside the module is fine. There is deliberately no
// product() or invoice() relationship: those belong to other modules.
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
}<?php
namespace App\Modules\Orders\Internal;
use Illuminate\Database\Eloquent\Model;
final class OrderLine extends Model
{
protected $table = 'orders.order_lines';
protected $guarded = [];
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
DB::statement('CREATE SCHEMA IF NOT EXISTS orders');
Schema::create('orders.orders', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('customer_id')->index(); // an ID, not a FK to another module
$table->unsignedBigInteger('total_cents');
$table->char('currency', 3);
$table->timestamps();
});
Schema::create('orders.order_lines', function (Blueprint $table) {
$table->id();
// FK inside the module: allowed.
$table->foreignUuid('order_id')->constrained('orders.orders')->cascadeOnDelete();
$table->string('sku'); // Catalog's public key, copied, no FK
$table->unsignedInteger('qty');
$table->unsignedBigInteger('unit_cents'); // price at the time of the order
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('orders.order_lines');
Schema::dropIfExists('orders.orders');
DB::statement('DROP SCHEMA IF EXISTS orders');
}
};Billing: contract, implementation, an idempotent queued listener, the provider with the per-module remote switch, and a migration without a foreign key to Orders:
<?php
namespace App\Modules\Billing\Contracts;
interface BillingApi
{
public function invoiceFor(string $orderId): ?InvoiceView;
}<?php
namespace App\Modules\Billing\Contracts;
final readonly class InvoiceView
{
public function __construct(
public string $orderId,
public int $amountCents,
public string $currency,
public string $status,
) {}
}<?php
namespace App\Modules\Billing\Internal;
use Illuminate\Database\Eloquent\Model;
final class Invoice extends Model
{
protected $table = 'billing.invoices';
protected $guarded = [];
}<?php
namespace App\Modules\Billing\Internal;
use App\Modules\Billing\Contracts\BillingApi;
use App\Modules\Billing\Contracts\InvoiceView;
final class EloquentBilling implements BillingApi
{
public function invoiceFor(string $orderId): ?InvoiceView
{
$i = Invoice::query()->where('order_id', $orderId)->first();
return $i === null ? null
: new InvoiceView($i->order_id, (int) $i->amount_cents, $i->currency, $i->status);
}
}<?php
namespace App\Modules\Billing\Listeners;
use App\Modules\Billing\Internal\Invoice;
use App\Modules\Orders\Contracts\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
// Billing reacts to Orders' public event. Queued, so a slow or failing
// billing step never fails checkout; idempotent, so a retry is harmless.
final class OpenInvoice implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
// UNIQUE (order_id) + insertOrIgnore = process each order once.
Invoice::query()->insertOrIgnore([
'order_id' => $event->orderId,
'amount_cents' => $event->totalCents,
'currency' => $event->currency,
'status' => 'open',
'created_at' => now(),
'updated_at' => now(),
]);
}
}<?php
namespace App\Modules\Billing;
use App\Modules\Billing\Contracts\BillingApi;
use App\Modules\Billing\Internal\EloquentBilling;
use App\Modules\Billing\Listeners\OpenInvoice;
use App\Modules\Billing\Remote\ForwardOrderPlaced;
use App\Modules\Billing\Remote\HttpBillingApi;
use App\Modules\Orders\Contracts\OrderPlaced;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
final class BillingServiceProvider extends ServiceProvider
{
// Per-module switch (config/modules.php reads BILLING_REMOTE from .env).
private function remote(): bool
{
return (bool) config('modules.billing.remote', false);
}
public function register(): void
{
$this->app->singleton(
BillingApi::class,
$this->remote() ? HttpBillingApi::class : EloquentBilling::class,
);
}
public function boot(): void
{
Event::listen(OrderPlaced::class, $this->remote() ? ForwardOrderPlaced::class : OpenInvoice::class);
if (! $this->remote()) {
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
}
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
DB::statement('CREATE SCHEMA IF NOT EXISTS billing');
Schema::create('billing.invoices', function (Blueprint $table) {
$table->id();
// Orders' ID copied as a value: no foreign key across modules,
// so Billing can move to another database without a migration fight.
$table->uuid('order_id')->unique();
$table->unsignedBigInteger('amount_cents');
$table->char('currency', 3);
$table->string('status', 16);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('billing.invoices');
DB::statement('DROP SCHEMA IF EXISTS billing');
}
};The extraction seam: the same BillingApi contract over HTTP, and a queued listener that forwards OrderPlaced to the Billing service (the Go billing-svc above speaks the same JSON):
<?php
namespace App\Modules\Billing\Remote;
use App\Modules\Billing\Contracts\BillingApi;
use App\Modules\Billing\Contracts\InvoiceView;
use Illuminate\Support\Facades\Http;
// Same contract, different transport: used once Billing runs as a service.
final class HttpBillingApi implements BillingApi
{
public function invoiceFor(string $orderId): ?InvoiceView
{
$response = Http::baseUrl(config('services.billing.url'))
->timeout(2)
->get("/invoices/{$orderId}");
if ($response->notFound()) {
return null;
}
$json = $response->throw()->json();
return new InvoiceView($json['order_id'], $json['amount_cents'], $json['currency'], $json['status']);
}
}<?php
namespace App\Modules\Billing\Remote;
use App\Modules\Orders\Contracts\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Http;
// Extraction step: instead of opening the invoice in-process, forward the
// event to the billing service. The queued listener retries on failure;
// the order ID is the idempotency key on the receiving side.
final class ForwardOrderPlaced implements ShouldQueue
{
public int $tries = 5;
/** @return list<int> */
public function backoff(): array
{
return [1, 5, 30];
}
public function handle(OrderPlaced $event): void
{
Http::baseUrl(config('services.billing.url'))
->withHeaders(['Idempotency-Key' => $event->orderId])
->timeout(2)
->post('/events/'.OrderPlaced::NAME, [
'order_id' => $event->orderId,
'customer_id' => $event->customerId,
'total_cents' => $event->totalCents,
'currency' => $event->currency,
'placed_at' => $event->placedAt,
])
->throw();
}
}The fitness functions and a module test:
<?php
// Pest architecture tests: the module map as executable rules.
// Run with: ./vendor/bin/pest --filter=Arch
$modules = ['Catalog', 'Orders', 'Billing'];
foreach ($modules as $module) {
arch("{$module} internals stay inside {$module}")
->expect("App\\Modules\\{$module}\\Internal")
->toOnlyBeUsedIn("App\\Modules\\{$module}");
}
arch('Catalog depends on no other module')
->expect('App\Modules\Catalog')
->not->toUse(['App\Modules\Orders', 'App\Modules\Billing']);
arch('Orders knows Catalog only through its contracts')
->expect('App\Modules\Orders')
->not->toUse(['App\Modules\Catalog\Internal', 'App\Modules\Billing']);
arch('Billing knows Orders only through its published event')
->expect('App\Modules\Billing')
->not->toUse([
'App\Modules\Orders\Internal',
'App\Modules\Orders\Actions',
'App\Modules\Orders\Http',
'App\Modules\Catalog',
]);
arch('contracts are immutable data and interfaces')
->expect('App\Modules\Catalog\Contracts\ProductView')
->toBeReadonly()
->toBeFinal();<?php
use App\Models\User;
use App\Modules\Catalog\Contracts\CatalogApi;
use App\Modules\Catalog\Contracts\ProductView;
use App\Modules\Orders\Contracts\OrderPlaced;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
uses(RefreshDatabase::class);
// Orders tested in isolation: Catalog is a fake bound to its contract,
// Billing is absent (Event::fake swallows the event and records it).
it('places an order and publishes OrderPlaced', function () {
$this->app->instance(CatalogApi::class, new class implements CatalogApi
{
public function product(string $sku): ?ProductView
{
return new ProductView($sku, 'DDD', 4200, true);
}
public function reserve(string $sku, int $qty): bool
{
return true;
}
});
Event::fake([OrderPlaced::class]);
$this->actingAs(User::factory()->create())
->postJson('/api/orders', ['lines' => [['sku' => 'BOOK-1', 'qty' => 2]]])
->assertCreated()
->assertJsonPath('total_cents', 8400);
Event::assertDispatched(OrderPlaced::class, fn (OrderPlaced $e) => $e->totalCents === 8400);
});The Laravel angle
| Laravel feature | Role in a modular monolith | Note (Laravel 13 docs) |
|---|---|---|
Service providers + bootstrap/providers.php | One registration point per module | "Service providers are the central place of all Laravel application bootstrapping" |
register() vs boot() | Bind contracts vs load routes, migrations, listeners | "Within the register method, you should only bind things into the service container" |
loadRoutesFrom(), loadMigrationsFrom(), loadViewsFrom(), loadTranslationsFrom() | Module-owned routes, migrations, views, lang files | loadRoutesFrom "will not load your routes file if the routes have already been cached"; loadMigrationsFrom is a ServiceProvider method (framework source, 13.x) |
DeferrableProvider | Lazy module bindings | Provider loads only when a binding is requested |
Events: ShouldDispatchAfterCommit | Integration events that never escape a rolled-back transaction | "only dispatch an event after the active database transaction has committed" |
Queued listeners: ShouldQueue, ShouldQueueAfterCommit | Asynchronous module reactions with retries | Per-module queue names for worker roles |
withEvents(discover: [...]) in bootstrap/app.php | Listener discovery in module folders | Or explicit Event::listen in each provider (used here) |
DB::transaction | One local transaction across module tables when chosen | See Transactions |
Eloquent $table = 'billing.invoices' | Schema-qualified tables on PostgreSQL | On MySQL the prefix is a database name |
Pest arch() | Boundary tests | toOnlyBeUsedIn, not->toUse, toBeReadonly, toBeFinal |
Package discovery (extra.laravel.providers) | How internachi/modular registers modules as path packages | From the Laravel packages docs |
Solving the classic problems
Module soup (folders without boundaries)
Folders named after business areas, but every class is public and used from everywhere; the dependency graph is dense and cyclic. Shopify measured exactly this: "every component depended on over half of all the other components. We also had lots of circular dependencies."
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Public/internal split | Contracts\ vs Internal\; Go internal/ | The door exists | Existing callers must migrate |
| Arch test with a baseline | Record today's violations, fail on new ones | Stops the bleeding on day one | Baseline must be paid down |
| Invert dependencies | Port in the consumer, or an event | Breaks cycles | More types |
| Merge modules | When two modules call each other constantly | Fewer, truer boundaries | Bigger module |
The shared "common" bag
App\Common, pkg/utils, shared/ grow until every module depends on them and they depend on modules. Fix: split it. Pure technical utilities become a library (or the standard library); business types move to the module that owns the concept and are exposed through its API; what remains is the shared kernel, with an arch test that it imports no module.
Cross-module Eloquent relationships
Order::belongsTo(Product::class) and Order::hasOne(Invoice::class) tie three modules together at the ORM level: eager loads join across schemas, model events fire across modules, and the relation cannot survive extraction. Shopify's rule for Wedge: "Cross-component associations are always violating componentization", and its 2020 post names the outdated assumption "that all Active Record models are OK to access everywhere".
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Keep IDs, not relations | order_lines.sku, invoices.order_id as values | No ORM coupling; extraction-ready | Two queries instead of one join |
| Copy what you need at the time | Price and name into order_lines | Historical correctness | Data duplication by design |
| Compose in the API layer | Controller asks Orders and Billing contracts, merges DTOs | Clear ownership | More code in read paths |
| Reporting view or read model | reporting.order_revenue, a projection | Fast joins for reports only | One more thing to maintain |
The god module
One module (usually Core, Users or Orders) holds half the code and every other module depends on it. Fix: find the subdomains inside it with Event Storming and change-history analysis, extract them as modules inside the monolith (cheap), and make dependencies point toward stable, abstract modules (Shopify grouped components into platform, supporting and frontend layers and cleaned up cross-layer dependencies first).
Reporting across modules
Reports genuinely need joins. Do not put them into module code. Options, in order of cost: (1) a reporting schema of views owned by a reporting role, (2) a read replica with the same views, (3) a read model fed by integration events (CQRS), (4) a warehouse via CDC. Option 1 is the modular monolith default; options 3 and 4 survive extraction.
Migration collisions and schema drift
Ten modules writing migrations into one folder collide in names and order. Give each module its own migrations folder (loadMigrationsFrom), prefix table names by schema, and forbid migrations that touch another module's schema (a CI grep or review rule). Zero-downtime techniques are in Zero-Downtime Schema Migrations.
Chatty modules and N+1 across boundaries
A list page calls Catalog.product() 50 times. In-process this is cheap, but it becomes 50 network calls on extraction. Design batch APIs now (products(skus []string)), and keep a copy of what you display often.
Comparison: monolith vs modular monolith vs microservices
| Characteristic | Monolith (unstructured or layered) | Modular monolith | Microservices |
|---|---|---|---|
| 1. Deployment units | One | One | Many, independently deployable |
| 2. Module boundaries | None, or technical layers | Business modules, enforced by compiler/tests/linters | Services, enforced by the network |
| 3. Communication | Any method call | Method call through a contract; in-process events | HTTP/gRPC calls; messages via a broker |
| 4. Data | One shared schema | One database, schema per module, no cross FKs/joins | Database per service |
| 5. Transactions | Local ACID anywhere | Local ACID available across modules (use deliberately) | Sagas, outbox, eventual consistency |
| 6. Consistency | Strong | Strong by default; eventual where events are used | Eventual across services |
| 7. Scaling | Whole app, replicas | Whole app, replicas; worker roles per module queue | Per service |
| 8. Failure isolation | None | Little (one process); mitigated by worker roles and bulkheads | Per service, if designed for it |
| 9. Technology diversity | One runtime | One runtime | Any per service |
| 10. Team autonomy | Low; everyone in everything | Medium: module ownership, shared release train | High: own repo, pipeline and release |
| 11. Operational cost | Lowest | Low | High: deploys, discovery, tracing, on-call per service |
| 12. Cost of changing a boundary | Low but meaningless | Low: refactoring inside one codebase | High: API versions, data migration, coordination |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New product, small team, uncertain domain | Modular monolith, few coarse modules | ADR per boundary, Pest/go-arch-lint from day one | Monolith first, but with lines you can move |
| Existing big ball of mud | Modular monolith by refactoring | Shopify-style file move, baseline violations, shrink-only | Structure before distribution |
| One module needs separate scaling or runtime | Extract that module only | Outbox, contract with remote implementation, flag | Pay the premium once, where it buys something |
| Many teams blocked on one release train | Consider extracting by team boundary | Contract tests, independent pipelines | Deploy autonomy is the real driver |
| Strict regulatory isolation for one area (payments, PII) | Separate service or at least separate database and role | mTLS, separate secrets | Isolation is a requirement, not a preference |
| Tiny CRUD app, one developer | Plain layered monolith | Keep feature folders | Modules would be ceremony |
| Spiky, failure-prone integration (imports, webhooks) | Keep in monolith, own queue and worker role | Bulkhead, retries, DLQ | Isolation without a second codebase |
In architecture: from a single process to a distributed system
A modular monolith is an architecture level, so this section follows one shop through the levels instead of one concept through them.
Monolith: one process, one database
Simple example: a 3-developer shop on Laravel, app/Models with 25 models, one orders table with foreign keys to products and users. This is fine at the start (Westeinde: "no architecture is often the best architecture in the early days of a system"). The first modular move costs nothing: put new code in app/Modules/<Name> and add one arch test.
Complex example: 300 models, CI takes 40 minutes, every change breaks unrelated tests. This is the Shopify 2017 situation: list every class, assign it to a module, move files in one scripted change, then start enforcing.
Modular monolith and multiple databases
Simple example: the shop of this page: three modules, three schemas, one PostgreSQL, one pool, one transaction for reserve + order, OrderPlaced after commit for billing.
Complex example: 40 modules, each with a database role and its own connection pool in production; a reporting schema of views; Search moved to Elasticsearch (fed by events from Catalog) while still deployed with the monolith; a module that needs a different database engine (for example a time-series store for metrics) uses it through its own internal adapter: a module may own a second database, the deployable stays one.
Microservices: what survives the boundary
Simple example: Billing extracted. What survives unchanged: the OrderPlaced contract, the idempotent handler, the BillingApi contract (now an HTTP client), the schema (copied into the service's database). What changes: delivery becomes at-least-once through a broker, the call can time out, and "the invoice exists" becomes eventually true.
Monolith (Catalog + Orders) Broker / relay billing-svc
1 BEGIN; INSERT orders.orders; INSERT outbox(OrderPlaced v1); COMMIT
2 relay reads outbox -> publish orders.order_placed.v1
3 consume; INSERT ... ON CONFLICT (order_id) DO NOTHING
4 ack
5 GET /invoices/{id} via HttpBillingApi -> 200 {"order_id": ..., "status": "open"}Complex example: a marketplace splits Billing, Search and Notifications, keeps Catalog + Orders + Inventory as a modular monolith core (Fowler: "a substantial monolith at the heart of the microservices architecture"); cross-service flows such as refunds become sagas; communication rules are in Service Communication, and the warning signs of a bad split in Service Boundaries (the distributed monolith).
Distributed data: replicas, caches and multi-region
A modular monolith inherits the database's distribution story. Read replicas: per-module repositories can route reads to a replica, but read-your-writes must hold inside a module's own use case (see Replication & Failover). Caches: each module caches only its own data and invalidates on its own events; a module never caches another module's internals. Sharding or multi-region: shard keys are per module (Orders by customer, Catalog by tenant); a cross-module transaction that was legal in one database becomes cross-shard and must become an event or a saga first. Google's 2023 paper pushes the other way: keep the logical monolith and let a runtime co-locate or split components; Service Weaver's freeze shows the practical cost of that idea today.
Scaling path: 1×, 10×, 100×
| Load | Shape | What changes |
|---|---|---|
| 1× (one server) | Modular monolith, one DB, one pool | Modules, schemas, arch tests, events in-process |
| 10× | Several replicas behind a load balancer, read replica, Redis, worker roles per module queue | Stateless app, queues per module, read routing, module-level metrics |
| 100× | Hot modules extracted (search, billing, notifications), broker, outbox, core still a modular monolith; per-module database roles and pools, maybe a database per extracted service | Outbox and inbox everywhere, sagas for cross-service flows, contract tests, tracing |
Lab: break a boundary, then extract Billing
Setup: the Go module needs only Go 1.24+; the SQL part needs a local PostgreSQL (docker run --rm -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17).
1. Run the modular monolith.
cd docs/snippets/architecture/modular-monolith/go
go test ./... # ok academy/modular-monolith/shop, .../orders, .../billing
go run ./shop/cmd/shop
# placed ord-0001
# invoice for ord-0001: 4200 EUR (open)2. Break a boundary and watch the arch test fail. Make Orders import Billing (add the import and var _ = billing.ErrNoInvoice to shop/orders/orders.go):
go test ./shop/
# --- FAIL: TestModuleDependencies
# arch_test.go:52: orders/orders.go: module "orders" imports academy/modular-monolith/shop/billing; allowed: [internal]
go build ./...
# package academy/modular-monolith/shop/billing
# imports academy/modular-monolith/shop/orders from billing.go
# imports academy/modular-monolith/shop/billing from orders.go: import cycle not allowedTwo gates fired: the arch test (the allowed graph) and the compiler (a cycle). Revert the change.
3. Reach into internals. In shop/billing/billing.go import academy/modular-monolith/shop/orders/internal/store:
go build ./...
# shop/billing/billing.go:13:2: use of internal package academy/modular-monolith/shop/orders/internal/store not allowedRevert. In Laravel the equivalent is using App\Modules\Orders\Internal\Order inside Billing; ./vendor/bin/pest --filter=Arch fails on "Orders internals stay inside Orders" and on "Billing knows Orders only through its published event".
4. Prove data ownership in PostgreSQL. Run the SQL block from Data ownership, then:
SET ROLE orders_app;
SELECT count(*) FROM orders.orders; -- 0
SELECT count(*) FROM billing.invoices; -- ERROR: permission denied for schema billing (42501)
RESET ROLE;5. Extract Billing to a service stub. Terminal 1 runs the extracted service; terminal 2 runs the monolith with the per-module flag:
# terminal 1
BILLING_ADDR=:8081 go run ./shop/cmd/billing-svc
# billing-svc listening on :8081
# terminal 2
BILLING_URL=http://localhost:8081 go run ./shop/cmd/shop
# placed ord-0001 (no invoice line: Billing is no longer in this process)
curl -s localhost:8081/invoices/ord-0001
# {"order_id":"ord-0001","amount_cents":4200,"currency":"EUR","status":"open"}Orders did not change. Only the composition root chose a different subscriber.
6. Prove idempotency on the new boundary. Send the same event twice:
for i in 1 2; do curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8081/events/orders.order_placed.v1 \
-H 'Content-Type: application/json' -H 'Idempotency-Key: ord-0042' \
-d '{"order_id":"ord-0042","total_cents":999,"currency":"EUR"}'; done
# 202
# 202
curl -s localhost:8081/invoices/ord-0042 # one invoice, amount 999What the lab does not do and production must: write OrderPlaced to an outbox in the same transaction as the order and deliver it with a relay (Transactional Outbox); the direct POST in remote.Forwarder loses the event if the service is down at that moment.
Common misconceptions
| Belief | Reality |
|---|---|
| A monolith is legacy by definition | A monolith is one deployment unit; quality is a separate axis (Grzybek) |
| Feature folders make a modular monolith | Without a public API, internal code, owned data and an automated check, folders are decoration |
| Modules must never share a database | They may share a database server; they must not share tables. Schema per module is the norm |
| Modules must never share a transaction | One local transaction across modules is a legitimate tool; record it, because extraction removes it |
| In-process events remove coupling | They remove compile-time coupling; the event contract is still coupling, and timing (before or after commit) must be designed |
| A modular monolith cannot scale | It scales horizontally; it cannot scale one module alone without worker roles or extraction |
| It is only a step toward microservices | It is a destination for most systems; Shopify's core is still one |
| Any monolith can be split later | Only a modular one; Fowler: most systems "can't be sensibly broken apart" |
| Microservices enforce boundaries better, so start there | They enforce boundaries you drew before you understood the domain; moving them is expensive |
A Common module is harmless | It becomes the most-depended-on and least-owned module; keep a minimal shared kernel instead |
| Static tools catch everything | Packwerk ignores method calls; Pest and Deptrac miss app('...') and string class names; review still matters |
| Service Weaver proves the idea works out of the box | The paper measured gains on a prototype; the framework went into maintenance in December 2024 |
Cheat sheet
| Topic | Remember |
|---|---|
| Definition | One deployment unit + business modules with public API, private internals, owned data |
| Module rule of three | Independent, has everything for its capability, defined interface (Grzybek) |
| Where to draw lines | Bounded contexts / subdomains; measure change locality |
| Talking synchronously | Call through a contract; return copies; no cycles |
| Talking asynchronously | Versioned integration events, after commit, idempotent handlers |
| Shared kernel | Tiny, platform and value objects only, imports no module |
| Data | One database, schema per module, no cross FKs or joins, reporting views for reports |
| Transactions | One local tx across modules is allowed and costly on extraction; events for side effects |
| Enforcement | Compiler (internal/), arch tests (Pest, go/parser), linters (Deptrac, go-arch-lint, phpat, Packwerk) in CI, with a shrink-only baseline |
| Laravel registration | One provider per module in bootstrap/providers.php; loadRoutesFrom, loadMigrationsFrom |
| Go registration | Composition root in cmd/<app>/main.go is the only package that imports every module |
| Testing | Module tests with fakes of contracts, arch tests, a thin e2e layer |
| Deploy and scale | One artifact, replicas, worker roles per module queue, feature flag per module |
| Extraction order | Clean module, isolate data, add seam (outbox + remote contract), run in parallel, flip flag, delete old path |
| Anti-patterns | Module soup, common bag, cross-module ORM relations, god module, chatty APIs |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What exactly makes a system a monolith, and what does that say about its quality? Must-know
Answer
Answer: Exactly one deployment unit. It says nothing about quality: a monolith can be a big ball of mud or a well-structured modular monolith (Grzybek's primer).
2 — Name the three conditions a module must meet. Must-know
Answer
Answer: Independent and interchangeable (few, weak dependencies on stable modules); has everything needed to provide its functionality (a business vertical slice, not a technical layer); has a defined interface (contract) with everything else encapsulated.
3 — Orders needs product prices during checkout. Call or event? How should the dependency be declared in Go and in Laravel? Important
Answer
Answer: A call, because the answer is needed now. In Go, Orders declares a small consumer-side interface (Catalog.Lookup) and the composition root adapts Catalog's facade to it. In Laravel, Orders type-hints Catalog\Contracts\CatalogApi, bound in CatalogServiceProvider.
4 — Why is Order::belongsTo(Product::class) across modules a problem even though it works? Must-know
Answer
Answer: It couples Orders to Catalog's internal model and table at the ORM level, allows cross-schema joins and eager loads, spreads model events across modules, and cannot survive extraction. Keep the SKU (and copied price/name) as values and compose through the contract.
5 — When is one database transaction across two modules acceptable? Important
Answer
Answer: When both modules will very likely stay in the same deployable and an invariant must hold at commit (for example stock reservation plus order insert), each module writes only its own tables through its own code, and the decision is recorded. Side effects that may be slow, may fail, or belong to a future service go through after-commit events instead.
6 — What does ShouldDispatchAfterCommit protect you from? Must-know
Answer
Answer: Listeners reacting to an event whose transaction later rolls back (an invoice for an order that does not exist). Laravel holds the event until the active transaction commits and discards it on rollback.
7 — Which gate catches each violation in the Go example: (a) Billing imports orders/internal/store; (b) Orders imports billing; (c) shop/internal/eventbus imports orders? Important
Answer
Answer: (a) the Go compiler's internal-package rule; (b) the arch test's allowed list, and also the compiler because it creates a cycle with Billing's import of Orders; (c) the arch test TestPlatformKnowsNoModule.
8 — How do you keep cross-module reports without cross-module joins in module code? Important
Answer
Answer: A reporting schema of read-only views owned by a reporting role (or the same views on a replica), or a read model / warehouse fed by events or CDC. Module code never queries it.
9 — List five things to keep ready so that Billing can be extracted later. Good to know
Answer
Answer: Versioned integration events with IDs; one contract interface used by every caller; idempotent handlers; its own schema with no cross-module FKs or joins and its own migrations; no shared ORM relationships; per-module tests, metrics and a per-module flag.
10 — What did Google's 2023 paper claim, and what happened to Service Weaver? Good to know
Answer
Answer: That microservices conflate logical boundaries (how code is written) with physical ones (how it is deployed); write a modular logical monolith, let a runtime place components, deploy atomically; the prototype cut latency up to 15× and cost up to 9×. Service Weaver went into maintenance mode on 5 December 2024 and was scheduled to be archived on 6 June 2025.
11 — Your modular monolith has one module that leaks memory and crashes the process weekly. What do you try before extraction? Important
Answer
Answer: Run that module's work in its own worker role (own queue, own processes from the same artifact) so the crash only takes down those workers; add limits and restarts; fix the leak. Extract only if isolation inside the deployable is not enough.
12 — Why can't Packwerk catch every boundary violation? Important
Answer
Answer: It analyses static constant references only: "Method calls and objects passed around the application are completely ignored", and it only resolves constants loaded by Zeitwerk. It chooses false negatives over false positives.
Glossary
| Term | Meaning |
|---|---|
| Modular monolith | One deployment unit whose code is split into business modules with enforced boundaries |
| Monolith | A system with exactly one deployment unit |
| Big ball of mud | A system with no discernible structure; everything calls everything |
| Distributed monolith (distributed big ball of mud) | Many services with the coupling of a big ball of mud, plus the network |
| Module | A business capability with its code, data and one public API |
| Public API / contract | The interfaces, data types, events and errors a module publishes |
| Internal | Code behind the API; Go internal/, Laravel Internal\ namespace |
| Encapsulation | Hiding a module's internals so they can change freely |
| Vertical slice | Code for one feature from HTTP to database, inside one module |
| Package by component | Simon Brown's style: one coarse-grained component per package, a public interface and hidden implementation |
| Bounded context | DDD: the boundary inside which one model and language apply |
| Change locality | Shopify: "the degree to which code that changes together lives together" |
| Cohesion / coupling | How related a module's parts are / how dependent modules are on each other |
| Direct call | Synchronous in-process call through a contract |
| Port / adapter | Interface declared by the consumer / code that implements it with another module's API |
| Anti-corruption layer (ACL) | Translation between two modules' models (gateway on the caller side, facade on the callee) |
| Domain event | A fact inside one module's model |
| Integration event | A small, versioned fact that is part of a module's public contract |
| In-process event bus | A dispatcher that delivers events inside one process (eventbus.Bus, Laravel Event) |
ShouldDispatchAfterCommit | Laravel interface: dispatch the event only after the transaction commits |
| Shared kernel | The minimal shared code (platform, value objects) all modules may use |
| Schema per module | Each module's tables in its own database schema (PostgreSQL) or database (MySQL) |
| Cross-module foreign key | A constraint linking two modules' tables; forbidden in a modular monolith |
| Reporting view | A read-only view that joins published columns for reports |
| Composition root | The one place that constructs and wires all modules |
| Service provider | Laravel class that registers bindings, routes, migrations, listeners |
bootstrap/providers.php | Laravel 13 file listing application service providers |
loadRoutesFrom / loadMigrationsFrom | ServiceProvider methods to load a module's routes and migrations |
| nwidart/laravel-modules | Laravel package: Modules/ folders, module.json, enable/disable, module:make |
| internachi/modular | Laravel package: app-modules/ as Composer path packages with package discovery |
| Fitness function | An automated check of an architectural rule |
| Architecture test | A unit test about code structure (Pest arch(), ArchUnit, NetArchTest) |
| Deptrac | PHP static analysis of layer dependencies (deptrac.yaml) |
| phpat | PHP Architecture Tester, a PHPStan extension |
| PHPStan | PHP static analyser; architecture rules via extensions such as phpat |
| Packwerk | Shopify's Ruby static analysis for package dependency and privacy |
| Wedge | Shopify's earlier call-graph tool for component violations (retired) |
| go-arch-lint | Go linter that checks a component dependency graph against .go-arch-lint.yml |
| Spring Modulith | Spring project that verifies application modules (ApplicationModules.of(...).verify()) |
| Service Weaver | Google's Go framework for logical monoliths deployed as one or many processes; archived |
| Atomic deployment | All parts of the application released together as one version |
| Feature flag per module | A switch that enables, disables or relocates one module |
| Worker role | The same artifact started as a queue worker for one module's queue |
| Extraction | Moving a module into its own service |
| Strangler Fig | Gradually replacing parts of a system by routing to the new implementation |
| Branch by Abstraction | Introduce an abstraction, build the new implementation behind it, switch, remove the old |
| Parallel Run | Running old and new implementations side by side and comparing results |
| Outbox | Table written in the same transaction as the state change; a relay publishes from it |
| Idempotent handler | A handler that gives the same result when an event is delivered twice |
| Microservice premium | Fowler: the extra cost and risk that microservices add |
| Monolith first | Fowler: start with a monolith, split only when boundaries and needs are known |
| Module soup | Business-named folders without enforced boundaries |
| God module | One module that holds too much and that everything depends on |
| Conway's Law | System structure mirrors the communication structure of the organisation |
| Rails engine / Zeitwerk | Rails' built-in modularity unit / Rails' code loader that Packwerk relies on |
References
- Kamil Grzybek, Modular Monolith: A Primer (2 Dec 2019): https://www.kamilgrzybek.com/blog/posts/modular-monolith-primer
- Kamil Grzybek, Modular Monolith: Architectural Drivers: https://www.kamilgrzybek.com/blog/posts/modular-monolith-architectural-drivers
- Kamil Grzybek, Modular Monolith: Architecture Enforcement (22 Mar 2020): https://www.kamilgrzybek.com/blog/posts/modular-monolith-architecture-enforcement
- Kamil Grzybek, Modular Monolith: Integration Styles (26 Jul 2020): https://www.kamilgrzybek.com/blog/posts/modular-monolith-integration-styles
- Simon Brown, Modular monolith and "package by component": https://simonbrown.je/modular-monolith
- Martin Fowler, Monolith First (3 Jun 2015): https://martinfowler.com/bliki/MonolithFirst.html
- Martin Fowler, Microservice Premium (13 May 2015): https://martinfowler.com/bliki/MicroservicePremium.html
- Sam Newman, Monolith to Microservices (book page and table of contents): https://samnewman.io/books/monolith-to-microservices/
- Kirsten Westeinde, Deconstructing the Monolith (Shopify, 21 Feb 2019): https://shopify.engineering/deconstructing-monolith-designing-software-maximizes-developer-productivity
- Philip Müller, Under Deconstruction: The State of Shopify's Monolith (16 Sep 2020): https://shopify.engineering/shopify-monolith
- Maple Ong, Enforcing Modularity in Rails Apps with Packwerk (23 Sep 2020): https://shopify.engineering/enforcing-modularity-rails-apps-packwerk
- Packwerk README: https://github.com/Shopify/packwerk
- Ghemawat et al., Towards Modern Development of Cloud Applications, HotOS '23: https://serviceweaver.dev/assets/docs/hotos23_vision_paper.pdf
- Service Weaver documentation: https://serviceweaver.dev/docs.html and README (maintenance notice): https://github.com/ServiceWeaver/weaver
- nWidart/laravel-modules README: https://github.com/nWidart/laravel-modules
- InterNACHI/modular README: https://github.com/InterNACHI/modular
- Laravel 13 docs, Service Providers: https://laravel.com/docs/13.x/providers
- Laravel 13 docs, Package Development: https://laravel.com/docs/13.x/packages
- Laravel 13 docs, Events: https://laravel.com/docs/13.x/events
- Laravel framework source,
ServiceProvider.php(13.x): https://github.com/laravel/framework/blob/13.x/src/Illuminate/Support/ServiceProvider.php - Go 1.4 release notes, Internal packages: https://go.dev/doc/go1.4
- Go module layout: https://go.dev/doc/modules/layout
- go-arch-lint README and syntax: https://github.com/fe3dback/go-arch-lint
- Deptrac: https://github.com/deptrac/deptrac
- Pest architecture testing: https://pestphp.com/docs/arch-testing
- phpat: https://github.com/carlosas/phpat
- Spring Modulith, Verifying Application Module Structure: https://docs.spring.io/spring-modulith/reference/verification.html
- PostgreSQL docs, Schemas: https://www.postgresql.org/docs/current/ddl-schemas.html
- MySQL 8.4 docs, CREATE DATABASE: https://dev.mysql.com/doc/refman/8.4/en/create-database.html