Layered Monolithic Architecture
"One of the most common ways to modularize an information-rich program is to separate it into three broad layers: presentation (UI), domain logic (aka business logic), and data access." — Martin Fowler, Presentation Domain Data Layering, martinfowler.com, 26 August 2015
Summary: A layered monolith is one deployable application split into horizontal layers (presentation, application, domain, persistence) where each layer only talks to the layers below it; it is the default style of most products, cheap and simple, and it stays healthy only while the layer rules are written down and checked by a test. Focus: What a layer is, closed vs open layers, the dependency rule, layered vs hexagonal vs clean vs onion, transaction script vs domain model vs table module and the service layer, the architecture sinkhole, layers vs tiers, layering in Laravel 13 and Go, enforcing layers with deptrac, go-arch-lint and Pest, testing per layer, the cost of layering, when it is right, when it rots, how to move to a modular monolith and how to deploy it. Learning goal: Given an existing codebase, draw its layers, say which are closed and which open, find the sinkholes and the layer violations, write an architecture test that keeps them out, and decide whether the next step is "keep it layered" or "split into modules".
This is the first style chapter of the Architecture path after Styles vs Patterns. It owns the layered style itself. The next chapter, Modular Monolith, owns splitting a monolith by domain; Monolith vs Microservices vs Modular Monolith owns the decision between the three. Inside one layer, the design path takes over: Data Persistence in Design for repositories and mappers, MVC, MVP, MVVM for the presentation layer, Dependency Inversion for the trick that turns layers into hexagons, and on the DDD path Anemic vs Rich Models and Domain, Application & Infrastructure Services.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in three tables | Everything in one minute |
| Why anyone layers software | Why it exists |
| Dijkstra 1968, POSA 1996, PoEAA 2002, Cockburn 2005, Palermo 2008, Martin 2012 | Where it comes from |
| Presentation, application, domain, persistence | Layers |
| Closed vs open, layers of isolation | Closed and open layers |
| Which way imports may point | The dependency rule |
| Hexagonal, clean, onion: same or different? | Layered vs hexagonal vs clean vs onion |
| Transaction script, domain model, table module | Domain logic patterns |
| Service layer / application layer | Service layer |
| Layers that do nothing | Architecture sinkhole |
| Layers vs tiers, n-tier | Layers are not tiers |
| Technical vs domain partitioning, big ball of mud | Partitioning |
| Logging, auth, transactions across layers | Cross-cutting concerns |
| Request path, data shapes, errors, enforcement, tests, performance | Mechanics |
| Ordering system as a layered Go service | Go |
| Ordering system as a layered Laravel app | Laravel |
| Fat controllers, sinkholes, N+1, side effects, violations | Solving the classic problems |
| When layered is right, when it rots, how to migrate | Choosing |
| Monolith → modular → microservices → distributed, deployment | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, test yourself, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The four layers. Every row is unpacked in Layers.
| Layer | Answers the question | Laravel 13 | Go | Must not contain |
|---|---|---|---|---|
| Presentation | How does the outside world talk to us? | Routes, middleware, controllers, Form Requests, API Resources, Blade, Artisan commands | net/http handlers, CLI flags, gRPC servers | SQL, business rules |
| Application (service) | Which use case is this, and in which transaction? | Actions / services (App\Actions\PlaceOrder), jobs that call them | internal/app use-case types | HTTP types, SQL |
| Domain (business) | What are the rules? | Eloquent models with behaviour, App\Domain\* value objects and policies | internal/domain structs and methods | Framework imports, I/O |
| Persistence (infrastructure) | How is state stored and fetched? | Eloquent queries, repositories, query builder, external API clients | internal/storage/postgres, database/sql, pgx | Business decisions |
Vocabulary.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Closed layer | You must go through it | Controller → service → repository | Every layer reaches everywhere: no isolation |
| Open layer | Callers may go around it | A read-only query path the controller calls directly | Ceremony: five classes for one SELECT |
| Layers of isolation | A change in one layer stays in that layer | Swap MySQL for PostgreSQL, only persistence changes | A column rename touches controllers |
| Dependency rule | Imports point one way only | app imports domain, never the reverse | Cycles, untestable domain |
| Service layer | Thin layer that defines the use cases and the transaction | PlaceOrder::handle() | Transaction logic copied into each controller |
| Sinkhole | A request that passes every layer without work | find($id) forwarded three times | Cost of layers without their benefit |
| Tier | A physical deployment unit | Web servers, DB server | Confusing logical design with network hops |
| Architecture test | A test that fails on a forbidden import | Pest arch(), deptrac, Go go/parser test | Rules rot within months |
The style's scorecard (qualitative; Richards & Ford rate the layered style low on deployability, elasticity, scalability and fault tolerance and high on cost and simplicity, per a chapter summary of Fundamentals of Software Architecture; see References):
| Strong | Weak |
|---|---|
| Simple to understand, every developer knows it | One deployment unit: all or nothing |
| Cheap to start; frameworks generate it | Technically partitioned: one feature touches every layer |
| Easy to test the domain in isolation (if the rules hold) | Scales only as a whole (all layers scale together) |
| Mature tooling to enforce (deptrac, Pest, go-arch-lint) | Degrades into a big ball of mud if the rules are not enforced |
| One process: no network failures between layers | Long builds and risky releases once it is large |
Why it exists
Any program larger than a script mixes three kinds of code: code that talks to the outside world (HTTP, CLI, queues), code that encodes the rules of the business, and code that stores and fetches data. Each kind changes for different reasons and at different speeds. HTML changes weekly, pricing rules monthly, the database driver every few years. Layering puts each kind in its own place so that a change of one kind does not drag the others along. Fowler's reason is even simpler: "It's biggest advantage (for me) is that it allows me to reduce the scope of my attention."
| Without layers | With layers |
|---|---|
| Faster for the first week | Faster from about the third feature on |
| A rule lives wherever it was first needed (often a controller) | A rule lives in the domain layer, once |
| Testing a rule needs HTTP and a database | Testing a rule is a plain function call |
| A second entry point (CLI, queue) copies the logic | A second entry point calls the same use case |
| Fewer files, more lines per file | More files, fewer lines per file, some ceremony |
| Good for: a 200-line prototype | Good for: anything you will maintain |
The analogy we reuse on this page: a restaurant. The waiter (presentation) takes the order, checks it is readable and brings the plate back; the waiter never cooks. The head chef at the pass (application layer) turns an order into tasks, decides the sequence and calls "service" when everything is ready. The cooks (domain) know the recipes and refuse to put fish in a vegetarian dish. The storeroom (persistence) holds ingredients; whoever runs it decides the shelves. A waiter who walks into the storeroom to fetch a dessert himself is a layer violation; it is fast once, and a month later nobody knows what is in stock. A head chef who only repeats every order word for word to one cook is a sinkhole: the role adds a step and no value.
Three common misunderstandings, up front
- "Layered means microservices-ready." No. Layers are a logical split inside one process; Fowler: "These layers are logical layers not physical tiers." Layers cut horizontally (technology), while service boundaries cut vertically (business capability). A perfectly layered app is not easier to split into services; a modular monolith is.
- "More layers are more architecture." Extra layers that only forward calls are the sinkhole anti-pattern. Neal Ford: "a little of it is okay, but a lot of it becomes a really bad idea".
- "Hexagonal, onion and clean replace layering." They keep the layers and change one thing: the domain no longer depends on persistence. Fowler calls this variation "often referred to as a Hexagonal Architecture". See the comparison.
Where it comes from
Dijkstra, THE multiprogramming system, 1968. The first published layered system. Dijkstra's team at Eindhoven built the operating system in "levels", each hiding a resource from everything above: "At level 1 we have the so-called 'segment controller' … in all higher levels identification of information takes place in terms of segments, the actual storage pages having lost their identity". The point that still matters is about testing: "Starting at level 0 the system has been tested, each time adding (a portion of) the next level only after the previous level has been thoroughly tested."
Network stacks, 1970s–80s. The OSI and TCP/IP models made "layer N uses only layer N-1" a familiar idea to every engineer (not covered further here).
POSA, 1996. Buschmann, Meunier, Rohnert, Sommerlad and Stal, Pattern-Oriented Software Architecture, Volume 1, catalogued Layers as an architectural pattern and distinguished strict (closed) from relaxed (open) layering. We did not read the book's text; Wikipedia's Multitier architecture page cites it for the definitions: "In a strict layered system, each layer depends on the layer below it and can exist without the layers above it. In a relaxed layered system, a layer can also depend on all of the layers below it" (secondary source).
Foote & Yoder, Big Ball of Mud, 1997. Presented at PLoP '97, the paper named what layering degrades into when nobody guards it: "A BIG BALL OF MUD is haphazardly structured, sprawling, sloppy, duct-tape and bailing wire, spaghetti code jungle." It places itself explicitly against "PIPELINE and LAYERED ARCHITECTURE".
Fowler, PoEAA, 2002. Patterns of Enterprise Application Architecture is structured around three layers and gave the vocabulary for organising the domain layer: Transaction Script, Domain Model, Table Module, and the Service Layer on top (catalogue entries dated 5 March 2003 on martinfowler.com).
Evans, DDD, 2003. Domain-Driven Design named the four layers most people use today: user interface, application, domain, infrastructure. We quote his definitions as Fowler reproduces them in AnemicDomainModel.
Cockburn, Hexagonal Architecture, 2005. "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." He drew a hexagon to escape "the one-dimensional layered picture".
Palermo, Onion Architecture, 29 July 2008. "The fundamental rule is that all code can depend on layers more central, but code cannot depend on layers further out from the core."
Martin, The Clean Architecture, 13 August 2012. Merged hexagonal, onion and others into one rule: "source code dependencies can only point inwards."
Fowler, Presentation Domain Data Layering, 26 August 2015. The short modern statement: three layers, logical not physical, dependencies "from top to bottom", and the warning to split "your top level into domain oriented modules which are internally layered" once the layers grow.
Richards (2015) and Richards & Ford (2020 onward). Mark Richards' O'Reilly report Software Architecture Patterns and Fundamentals of Software Architecture gave the layered style its practitioner vocabulary: closed vs open layers, layers of isolation, the architecture sinkhole anti-pattern, technical partitioning. We could not fetch the book text (O'Reilly denied access); we cite a podcast with the authors and a chapter summary, and say so where we do.
Year Idea What it added
1 1968 Dijkstra: THE system in levels Each level hides a resource; test bottom-up
2 1996 POSA: Layers pattern Strict (closed) vs relaxed (open) layering
3 1997 Foote & Yoder: Big Ball of Mud Name for what unguarded layering becomes
4 2002 Fowler: PoEAA Transaction Script / Domain Model / Table Module / Service Layer
5 2003 Evans: DDD UI / application / domain / infrastructure
6 2005 Cockburn: Ports and Adapters Inside vs outside, not top vs bottom
7 2008 Palermo: Onion Coupling toward the center; DB is external
8 2012 Martin: Clean Architecture One rule: dependencies point inward
9 2015 Fowler: PresentationDomainDataLayering Logical not physical; split by domain when big
10 2015+ Richards; Richards & Ford Closed/open, sinkhole, technical partitioningThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a request flow, real scenarios, how products express it, and the fix.
Layer, and the four standard layers Must-know
In plain words: a layer is a group of code with one kind of job, stacked so that the upper groups use the lower ones and never the other way round.
Common misunderstanding: "A layer is a folder." A folder is how you store a layer. The layer exists only if the dependency rules between folders hold; app/Services that imports app/Http is a folder, not a layer.
Definition: a layer is a set of modules with the same responsibility and the same allowed dependencies; Wikipedia's Layer (object-oriented design) puts it as "a group of classes that have the same set of link-time module dependencies to other modules" (secondary, citing Lakos 1997). The usual four, with Evans's names in brackets:
- Presentation (user interface): accepts input, renders output. Laravel's own docs describe its
HttpandConsoledirectories this way: "think of the Console and Http directories as providing an API into the core of your application. The HTTP protocol and CLI are both mechanisms to interact with your application, but do not actually contain application logic." - Application / service (application layer): one entry point per use case, controls the transaction, coordinates domain objects. Evans (via Fowler): "This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down."
- Domain / business (domain layer): "Responsible for representing concepts of the business, information about the business situation, and business rules … This layer is the heart of business software."
- Persistence / infrastructure (infrastructure layer): databases, files, message brokers, mail, external APIs.
Richards & Ford's four are presentation, business, persistence, database; they fold application and domain into "business" and count the database as its own layer (chapter summary, secondary).
Request: POST /orders {lines:[{product_id:1, quantity:3}]}
1 Presentation decode JSON, validate shape, authenticate -> PlaceOrderInput
2 Application BEGIN; load prices (1 query); call domain -> domain.Order
3 Domain NewOrder: quantity 1..100, subtotal, 10% discount -> invariants hold
4 Persistence INSERT orders, INSERT order_lines; COMMIT -> id = 501
5 Application raise OrderPlaced (after commit)
6 Presentation 201 Created {"id":501,"total_cents":10800}Real scenario: an online shop adds a CSV import of orders from a marketplace. With layers, the importer is one more presentation adapter calling the same PlaceOrder use case; without them, someone copies 120 lines out of a controller. A bank adds a mobile API next to the web app: the same thing. A support team asks for a CLI to cancel an order: a 15-line Artisan command or cmd/ordering-admin.
What provides it:
| Platform | How layers are expressed | Enforced by |
|---|---|---|
| Laravel 13 | Namespaces under app/: Http, Actions, Models, Domain, Repositories | Convention; Pest arch(), deptrac |
| Go | Packages under internal/: httpapi, app, domain, storage | Compiler: no import cycles, internal/; go-arch-lint, go/parser tests |
| Java / Spring | Packages, @Controller / @Service / @Repository stereotypes, JPMS modules | ArchUnit, JPMS exports |
| .NET | Separate projects (assemblies) per layer | Project references (the compiler refuses cycles), NetArchTest |
| Ruby on Rails | app/controllers, app/models, app/services | Convention; Packwerk for packages |
Fix / how to use it: name the layers in a README or ADR, give each a namespace or package, and add one architecture test from Enforcing layers before the second developer joins.
Closed and open layers, layers of isolation Must-know
In plain words: a closed layer is a door you must walk through; an open layer is a door you may walk around.
Common misunderstanding: "Closed means slower, so open everything." Opening a layer saves one function call and costs a dependency: every caller now knows the layer below it, so changing that lower layer touches more code. Microsoft's guide states both sides: a closed layer architecture "limits the dependencies between layers", but "might create unnecessary network traffic if one layer only passes requests along to the next layer" (the latter matters for tiers, not in-process layers).
Definition:
- Closed layer (POSA: strict): a request must pass through it; the layer above may call only this layer. Microsoft: "In a closed layer architecture, a layer can only call the next layer immediately down."
- Open layer (POSA: relaxed): the layer above may skip it and call further down. Microsoft: "In an open layer architecture, a layer can call any layers under it."
- Layers of isolation (Richards & Ford): because layers are closed, a change inside one layer does not leak into the others as long as its interface holds. The chapter summary we read: "changes in one layer should not affect others as long as contracts remain stable."
The left stack is fully closed: the presentation layer cannot reach persistence. The right stack adds a shared "services" layer (audit log, mail, file storage helpers) marked open: the business layer may call persistence directly without going through it, because forcing every call through a utility layer would be pure ceremony.
Closed (strict) Open path for reads (relaxed, documented)
1 GET /orders/42 GET /customers/7/orders
2 Controller -> OrderService::find(42) Controller -> query.Orders.ForCustomer(7)
3 OrderService -> OrderRepository::find(42) (no service, no domain object)
4 OrderRepository -> SELECT ... WHERE id = 42 SELECT ... JOIN ... GROUP BY ... LIMIT 50
5 -> domain Order -> mapped to JSON -> read model rows -> JSONReal scenario: an e-commerce admin list page (no rules, many joins) gets a dedicated query path that skips domain objects: open. Placing an order (stock, discount, payment) must go through the application layer: closed. A finance export reads straight from a read replica: open, documented in an ADR. A team "temporarily" lets a Blade view call Order::where(...) for a widget; two years later 40 views do it: an undocumented open layer, the worst kind.
What provides it:
| Product / tool | How you mark a layer closed or open |
|---|---|
| deptrac | ruleset: lists, per layer, the layers it may depend on; anything not listed is a violation |
| go-arch-lint | deps: <component>: mayDependOn: [...] |
| Pest | arch()->expect('App\Http')->not->toUse('App\Repositories') closes the path |
| Go compiler | No direct enforcement of "closed", only of cycles and internal/; use a test |
| ArchUnit (Java) | Layered-architecture rules declared in a unit test (not verified here) |
Fix / how to use it: default every layer to closed; open a path only for a named reason (read-only queries, cross-cutting utilities), write the reason down, and encode it in the architecture test so the opening does not spread.
Dependency direction and the dependency rule Must-know
In plain words: imports may point in one direction only; the code that holds the rules must not know who calls it or where its data is stored.
Common misunderstanding: "If the call goes down, the dependency must go down too." Not necessarily. Call direction (control flow) and source-code dependency can be opposite: the application calls the database adapter, but the adapter implements an interface owned by the application, so the import points up. That is the Dependency Inversion Principle applied at layer level.
Definition:
- Classic layering: dependencies "generally run from top to bottom through the layer stack: presentation depends on the domain, which then depends on the data source" (Fowler 2015).
- The dependency rule (Martin 2012): "source code dependencies can only point inwards. Nothing in an inner circle can know anything at all about something in an outer circle." Palermo said it in 2008 as "all coupling is toward the center."
- Practical form: the domain imports nothing from the project; the application imports the domain; persistence and presentation import both; only the composition root (
main, service providers) imports everything.
Who imports whom (Go ordering service on this page)
1 cmd/ordering -> httpapi, app, domain, storage/memory (composition root)
2 internal/httpapi -> app, domain, query
3 internal/app -> domain (declares Catalog, Orders, TxRunner)
4 internal/storage/* -> domain (implements app's interfaces implicitly)
5 internal/domain -> (standard library only)
6 internal/query -> (standard library only) (open read path)Real scenario: a payment provider switch (Stripe to Adyen) should touch one adapter, not the checkout use case. A move from MySQL to PostgreSQL touches persistence only. Running the domain tests in CI takes 0.4 s instead of 4 minutes because the domain imports no database.
What provides it:
| Platform | Mechanism for inverting a dependency |
|---|---|
| Go | Interfaces declared in the consuming package; satisfied implicitly. Go Code Review Comments: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values." |
| Laravel | Interface in App\Domain or App\Contracts, implementation bound in a service provider ($this->app->bind(...)); the container autowires constructors |
| Java / Spring | Interface in the domain module, @Repository implementation in infrastructure, injected by Spring |
| .NET | Interface in the core project, implementation in infrastructure project, registered in Program.cs |
Fix / how to use it: keep the domain import-free; let the application layer declare the ports it needs (Catalog, Orders); put concrete adapters in persistence; wire them in one place (Go, Laravel).
Layered vs hexagonal vs clean vs onion Important
In plain words: four drawings of nearly the same idea: keep the business rules in the middle and keep technology at the edge. They differ in where the database sits and which way the arrows point.
Common misunderstanding: "Hexagonal is a different architecture style from layered, you must pick one." Fowler treats it as a variation of layering ("A common variation is to arrange things so that the domain does not depend on its data sources by introducing a mapper … often referred to as a Hexagonal Architecture"), and Palermo calls his onion layers "layers". The real decision is smaller: does the domain import persistence, or does persistence implement an interface the domain or application owns?
Definition: Cockburn's motivation reads like a critique of careless layering: "people tend not to take the 'lines' in the layered drawing seriously. They let the application logic leak across the layer boundaries". His fix is to draw inside vs outside: "there is an application on the inside communicating over some number of ports with things on the outside." Primary (driving) ports and adapters are on the left (users, tests, batch); secondary (driven) ones on the right (database, mail).
The picture maps one onto the other: presentation becomes the driving adapters, persistence becomes a driven adapter, application keeps the ports, and the domain is the center. The only arrow that changes direction is the one between domain/application and persistence.
| Aspect | Classic layered (Fowler 2015, Richards) | Hexagonal / Ports & Adapters (Cockburn 2005) | Onion (Palermo 2008) | Clean (Martin 2012) |
|---|---|---|---|---|
| Picture | Horizontal stack | Hexagon, inside vs outside | Concentric rings | Concentric circles |
| Center | Database at the bottom | Application | Domain Model | Entities |
| Rule | Upper uses lower | Outside reaches inside only through ports | "all coupling is toward the center" | "source code dependencies can only point inwards" |
| Where the DB lives | Bottom layer | Secondary adapter | Outer ring ("The database is not the center. It is external.") | Frameworks and drivers (outermost) |
| Interfaces for persistence | Optional | Ports (required) | Repository interfaces in the core | Gateways owned by use cases |
| Number of layers | 3–5 | Inside + adapters | "will vary" | "the circles are schematic" (4 typical) |
| Explicit about tests | No | Yes, tests are a primary actor | Tests in the outer ring | Use cases testable without UI or DB |
| Recommended for | Most CRUD-heavy products | Apps with many entry points/backends | "not appropriate for small websites" (Palermo) | Long-lived systems with rich rules |
Real scenario: a Laravel SaaS with one web UI and one MySQL database runs well as classic layers with Eloquent. A Go payments service with HTTP, gRPC, a Kafka consumer and three provider adapters benefits from ports and adapters. A banking core with decades of rules is the onion/clean case.
Fix / how to use it: start classic; introduce a port (interface) at the persistence boundary when you have a second implementation or when domain tests need to run without a database. The Go example on this page already does this for Catalog and Orders; the Laravel example deliberately does not (Eloquent is the persistence layer).
Domain logic patterns: transaction script, domain model, table module Must-know
In plain words: three ways to organise the rules inside the business layer: one procedure per request, objects that own their data and rules, or one class per table.
Common misunderstanding: "Transaction script is bad code, domain model is good code." Fowler presents them as tools for different complexity; AnemicDomainModel: "Domain Models aren't always the best tool." A transaction script for a CRUD admin screen is correct; a transaction script for an insurance rating engine is a maintenance trap.
Definition (PoEAA catalogue, quoted):
| Pattern | Fowler's one-line definition | Shape in code | Fits when |
|---|---|---|---|
| Transaction Script | "Organizes business logic by procedures where each procedure handles a single request from the presentation." | One method per use case, calls the DB "directly or through a thin database wrapper" | Few rules, mostly CRUD, small team |
| Domain Model | "An object model of the domain that incorporates both behavior and data." | Order::cancel(), Order::total(), value objects, invariants in constructors | Many interacting rules, long-lived product |
| Table Module | "A single instance that handles the business logic for all rows in a database table or view." | OrdersModule.totalFor(dataset, orderId) over a record set | Record-set-oriented platforms (.NET DataSet era); rare today |
| Service Layer | "Defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation." | PlaceOrder::handle() on top of either of the above | Several entry points; transactions spanning objects |
Related persistence patterns from the same book that decide how the domain touches the database: Active Record (the object saves itself; Eloquent, Rails) and Data Mapper (a separate mapper moves data between objects and tables; Doctrine, the Go storage/postgres package here). Anemic domain model is Fowler's name for a domain model whose objects have only getters and setters: "By pulling all the behavior out into services, however, you essentially end up with Transaction Scripts".
The same rule, three ways ("10% off orders of at least 100.00")
1 Transaction script PlaceOrderScript.run(): loop lines, sum, if >= 10000 then discount, INSERT
2 Domain model Order::placeFor(lines) computes subtotal; Pricing::volumeDiscount(subtotal)
3 Table module OrdersTable.applyDiscount(dataset) runs over all rows of the order setReal scenario: an internal tool for editing shipping zones: transaction scripts in controllers or actions, done in a day. A subscription billing system (proration, trials, coupons, tax): domain model, or every new rule breaks two old ones. A reporting module over a warehouse: table-module-like set operations, often just SQL.
What provides it:
| Platform | Natural default | Pushing toward a domain model |
|---|---|---|
| Laravel | Active Record (Eloquent) + transaction scripts in controllers or actions | Behaviour methods on models, value objects via custom casts, App\Domain pure classes |
| Go | Transaction scripts in services over database/sql | Domain structs with methods, constructors that enforce invariants, data mapper in storage |
| Rails | Active Record, "fat model" | Service objects, domain objects (POROs) |
| Spring / JPA | Anemic entities + @Service scripts (very common) | Rich entities, aggregates (see DDD) |
| .NET / EF Core | Anemic entities + services | Rich entities with private setters |
Fix / how to use it: start with transaction scripts inside the application layer; the moment two scripts share a rule, move the rule onto the domain object or a pure domain class (Pricing::volumeDiscount). The deeper treatment lives in Anemic vs Rich Models.
Service layer (application layer) Must-know
In plain words: the list of things the application can do, one entry per use case, each running in one transaction.
Common misunderstanding: "The service layer is where the business logic goes." In Fowler's and Evans's framing the service layer is thin: "The key point here is that the Service Layer is thin - all the key logic lies in the domain layer." In practice many teams put everything into services, which produces an anemic model with transaction scripts called *Service. That is a legitimate choice for simple domains, but call it what it is.
Definition: "A Service Layer defines an application's boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations." The motivation: interfaces such as "data loaders, user interfaces, integration gateways" need the same operations, and "Encoding the logic of the interactions separately in each interface causes a lot of duplication."
Three entry points, one use case
1 HTTP POST /orders -> PlaceOrderController -> PlaceOrder::handle(customer, lines)
2 Artisan orders:import file -> ImportOrdersCommand -> PlaceOrder::handle(customer, lines) (per row)
3 Queue job MarketplaceOrder -> HandleMarketplaceOrder -> PlaceOrder::handle(customer, lines)
4 PlaceOrder::handle BEGIN; prices; Order::placeFor; save; OrderPlaced (after commit); COMMITReal scenario: an order can be placed from the web shop, the mobile API, a B2B CSV import and a marketplace webhook. All four call one PlaceOrder. A bug fix in the discount rule ships once. A new rule "B2B orders skip the discount" becomes a parameter of the use case or a domain policy, not four ifs.
What provides it:
| Platform | Typical name of the service-layer class | Transaction primitive |
|---|---|---|
| Laravel | Action (App\Actions\PlaceOrder), Service (OrderService), Job (when queued) | DB::transaction(fn () => ...) |
| Go | Use-case struct (app.PlaceOrder) or service (OrderService) | db.BeginTx(ctx, nil) behind a TxRunner interface |
| Spring | @Service with @Transactional | Declarative transactions |
| .NET | Application service / MediatR handler | TransactionScope, DbContext.SaveChanges |
| Rails | Service object / interactor | ActiveRecord::Base.transaction |
Fix / how to use it: one class per use case (an action), named after the verb the business uses; it opens the transaction, loads what the domain needs in as few queries as possible, calls the domain, saves, and publishes events after commit. The community package lorisleiva/laravel-actions formalises this ("Classes that take care of one specific task"); you do not need the package to follow the idea. The service-layer vs domain-service distinction is unpacked in Domain, Application & Infrastructure Services.
The architecture sinkhole anti-pattern Must-know
In plain words: a request falls through every layer and no layer does anything except call the next one.
Common misunderstanding: "Any pass-through method is a sinkhole, delete it." Some pass-through is the normal price of closed layers. In the authors' words (Neal Ford, Thoughtworks podcast with Mark Richards): "The sinkhole anti-pattern is another example that where a little of it is okay, but a lot of it becomes a really bad idea, and something like a layered architecture." The problem is the proportion.
Definition: an architecture sinkhole is a request path through a layered architecture in which most or all layers perform no logic. Symptoms named in the chapter summary we read: "'pass-through' layering", "unnecessary object instantiation", "wasted processing", "increased maintenance overhead without corresponding structure benefits". The usual heuristic is a ratio: the share of requests that are pass-through. Richards' writing is commonly quoted as an 80-20 rule (about 20% sinkhole requests is acceptable, a large majority means the layering is wrong for this system); we could not read the book text to verify the exact wording, so treat the numbers as a rule of thumb.
Sinkhole: GET /orders/42 Real work: POST /orders
1 OrderController::show($id) PlaceOrderController + PlaceOrderRequest (validate, authorize)
2 return $this->service->find($id); PlaceOrder::handle: DB::transaction, map unknown product -> 422
3 OrderService::find($id) ProductPrices::for([...]) one IN (...) query
4 return $this->repo->find($id); Order::placeFor: discount rule, invariants
5 OrderRepository::find($id) save + saveMany; OrderPlaced after commit
6 return Order::find($id); OrderResource: JSON contract
-> 3 classes, 3 interfaces, 0 decisions -> every layer decides somethingReal scenario: a CRUD-heavy admin back office where 85% of endpoints are list/show/update of reference data: every request crosses controller → service → repository → model with nothing happening; each new field touches five files. An "enterprise" Spring app with XServiceImpl and XRepositoryImpl for every table. A Go service with a UserService whose 20 methods each return s.repo.Same(ctx, args).
How to detect it:
| Signal | How to measure | Threshold that should worry you |
|---|---|---|
| Pass-through methods | Grep service and repository methods whose body is one return $this->x->sameName(...) line | More than half of all methods |
| Files touched per field | git log --stat on "add field X" commits | 5+ files for a field with no rules |
| Endpoints without rules | Label each route: rules / no rules | Most routes have none |
| Interfaces with one implementation that is never mocked | Search for interface + single implements | Interfaces that exist "for layering" only |
| Review comments | "Why does this need a service?" | Recurring |
Fix / how to use it: (1) open a documented read path for rule-free queries (the Go internal/query package, a Laravel controller using a query object or an Eloquent scope); (2) delete repositories that only wrap find(); Eloquent already is the persistence layer; (3) keep the layers closed for writes, where rules live; (4) if almost everything is a sinkhole, the system is CRUD and maybe a simpler style fits (an admin generator such as Filament, or a thinner two-layer design).
Layers are not tiers Important
In plain words: a layer is a box in your code; a tier is a machine (or container) in your deployment.
Common misunderstanding: "Three-tier and three-layer are the same thing." Fowler: "These layers are logical layers not physical tiers. I can run all three layers on my laptop". A layered monolith runs all its layers in one tier; only the database is usually a second tier.
Definition: Microsoft's Azure Architecture Center: "Layers separate responsibilities and manage dependencies … Tiers are physically separated and run on separate machines." Tiers too can be strict or relaxed: "In the strict model, a request must go through adjacent tiers, one by one … The strict approach has greater latency and overhead. The relaxed approach has more couplings". "You might host each layer in its own tier, but this approach isn't required."
Same four layers, three deployments
1 1 tier + DB [presentation|application|domain|persistence] -> PostgreSQL (layered monolith)
2 2 tiers + DB [SPA presentation] --HTTP--> [application|domain|persistence] -> PostgreSQL
3 3 tiers + DB [web] --HTTP--> [business API] --HTTP--> [data service] -> PostgreSQL (classic n-tier)
Each extra tier adds a network hop (~0.2-1 ms in one data center), a failure mode and a deploy unit.Real scenario: a 2005-era Java EE system with a web tier, an EJB tier and a database tier, where the EJB tier only forwarded calls: the sinkhole across the network, with latency and serialisation on every hop. A modern Laravel app with an Inertia/Vue front end: the browser is a presentation tier, the Laravel app is one tier with all server-side layers. A Next.js BFF in front of a Go API: Fowler would call the BFF a presentation layer ("I treat the BFF as a presentation layer").
| Layer | Tier | |
|---|---|---|
| Kind of boundary | Logical (namespaces, packages) | Physical (process, host, container) |
| Crossing cost | A function call (nanoseconds) | A network call (sub-millisecond to many ms), serialisation |
| Failure between them | Exceptions | Timeouts, partial failure, retries |
| Scaled | Together, with the process | Independently |
| Typical count in a layered monolith | 3–5 | 1 (plus database, cache) |
| Owned by | This chapter | Client-Server, Scaling Strategies |
Fix / how to use it: decide layers for code clarity and tiers for operational reasons (independent scaling, security zones, a separate client); never create a tier to "enforce" a layer, an architecture test does that for free.
Technical vs domain partitioning, and the big ball of mud Important
In plain words: layers split code by kind of code; modules split code by business area. The first is easy to start, the second is easier to grow.
Common misunderstanding: "A layered app cannot be modular." It can, by nesting: Fowler: "once any of these layers gets too big you should split your top level into domain oriented modules which are internally layered."
Definition: Richards & Ford call the layered style technically partitioned: "a business capability is typically spread across layers" (chapter summary). The opposite, domain partitioning, puts ordering, billing and catalog in separate top-level modules, each internally layered. A big ball of mud (Foote & Yoder) is what either becomes when nobody enforces boundaries: "Information is shared promiscuously among distant elements of the system".
Technical partitioning (layered) Domain partitioning (modular monolith)
1 app/Http/Controllers/OrderController app/Modules/Ordering/Http/...
2 app/Http/Controllers/InvoiceController app/Modules/Ordering/Actions/...
3 app/Actions/PlaceOrder app/Modules/Ordering/Models/...
4 app/Actions/IssueInvoice app/Modules/Billing/Http/...
5 app/Models/Order, Invoice, Product app/Modules/Billing/Actions/...
"add a field to invoices" touches 4 dirs "add a field to invoices" touches 1 moduleReal scenario: a ten-person team on one Laravel app with 300 models: every pull request touches app/Models and app/Http/Controllers, merge conflicts daily, nobody owns anything. A Go service whose internal/service package has 90 files and imports every repository. Both are the moment to move toward the modular monolith.
Fix / how to use it: keep technical layers while the app fits in one head; split by domain at the top when layers get big, and keep layers inside each module. The step-by-step path is in Migration to a modular monolith.
Cross-cutting concerns Good to know
In plain words: some things every layer needs (logging, authentication, transactions, caching, metrics); put them in one place that wraps the layers instead of copying them into each.
Common misunderstanding: "Logging is infrastructure, so only the persistence layer may log." Logging is cross-cutting; every layer may use a logger interface. What must not cross is knowledge: the domain may log, it may not know about HTTP status codes.
Definition: a cross-cutting concern is a behaviour that applies across layers and is implemented once, around them: HTTP middleware (Laravel middleware, Go func(http.Handler) http.Handler), decorators around use cases, framework events, the container.
Request with cross-cutting concerns
1 middleware: request id, auth, rate limit (presentation, once for all routes)
2 controller -> action (application)
3 decorator: start span, start transaction (around every use case)
4 domain logic (no tracing code inside)
5 repository: query logging via DB::listen / pgx tracer (persistence)| Concern | Laravel 13 | Go |
|---|---|---|
| Authentication | auth:sanctum middleware, Form Request authorize() | Middleware that puts the user in context.Context |
| Authorization | Policies, Gates | Explicit checks in the use case |
| Transactions | DB::transaction in the action | TxRunner.WithinTx in the use case |
| Logging and tracing | Log facade, DB::listen, OpenTelemetry packages | log/slog, OpenTelemetry middleware |
| Caching | Cache::remember in a query object or decorator | Decorator implementing the same interface |
| Validation | Form Requests (shape), domain (rules) | Decoder + domain constructors |
Fix / how to use it: middleware for transport concerns, decorators for use-case concerns, and never a "Utils" layer that everybody imports (that is how an open layer is born by accident).
Mechanics
The request path through the layers Must-know
Laravel 13 (PHP 8.4) Go (net/http)
1 public/index.php -> bootstrap/app.php cmd/ordering/main.go builds the graph once
2 middleware stack (auth:sanctum, throttle) middleware chain (request id, auth)
3 route -> PlaceOrderController::__invoke mux "POST /orders" -> Orders.create
4 PlaceOrderRequest: authorize() + rules() (422 on fail) json.Decoder -> createRequest (400 on fail)
5 PlaceOrder::handle(customerId, lines) app.PlaceOrder.Handle(ctx, PlaceOrderInput)
6 DB::transaction: ProductPrices::for, Order::placeFor WithinTx: Catalog.PricesFor, domain.NewOrder
7 save(), lines()->saveMany(), OrderPlaced::dispatch Orders.Save (2 INSERTs)
8 COMMIT -> listeners queued (ShouldDispatchAfterCommit) Commit
9 OrderResource -> 201 JSON orderResponse -> 201 JSONWhat crosses a boundary: data shapes per layer
| Boundary | What goes down | What comes up | Rule |
|---|---|---|---|
| Presentation → application | A command/input object (PlaceOrderInput, validated array) | Domain object or result DTO | No Request, no http.Request below this line |
| Application → domain | Plain values, domain objects | Domain objects, domain errors | No DTOs from HTTP in the domain |
| Application → persistence | Domain objects, ids, criteria | Domain objects or read models | No *sql.Rows or query builders above this line |
| Presentation ← anything | — | Resource / response struct | JSON keys are a contract, not column names (OrderResource) |
Mapping between shapes costs a few allocations; the alternative (one shape everywhere) welds the JSON contract to the database schema. In Laravel, passing Eloquent models up to the presentation layer and shaping them with API Resources is the accepted compromise.
Transaction boundary Important
The transaction belongs to the application layer: one use case, one transaction. Not the controller (then every entry point must remember it), not the repository (then two repositories cannot share one). In Go, hide *sql.Tx behind a TxRunner and carry it in context.Context; in Laravel, DB::transaction() in the action. Side effects that cannot be rolled back (mail, HTTP calls, queue messages) run after commit: Laravel's ShouldDispatchAfterCommit on events ("only dispatch an event after the active database transaction has committed"), ShouldQueueAfterCommit on listeners, ->afterCommit() on jobs; for cross-service guarantees use the transactional outbox. Isolation details: ACID & Transactions.
Errors: translate once per boundary
| Where | Error you will see | Layer that should translate it | Into |
|---|---|---|---|
| Go build | import cycle not allowed | — (a design error: two layers import each other) | Move the interface to the consumer |
| Go build | use of internal package ... not allowed | — (Go 1.4 rule) | Import through the public package |
| Go test (this page) | internal/domain/bad.go (internal/domain) imports .../storage/memory (internal/storage): not allowed | — (fitness function) | Remove the import |
| Laravel | Illuminate\Database\LazyLoadingViolationException | Developer, in dev/CI | Eager load in the action or query |
| Laravel | Illuminate\Validation\ValidationException | Form Request (presentation) | 422 with field errors |
| Domain | OrderRejected / domain.ErrUnknownProduct | Controller / handler | 422 with a message |
| Persistence | Unique violation (SQLSTATE 23505, MySQL 1062) | Repository or action | A domain error (DuplicateOrder) |
| Pest | failed arch() expectation naming the class and the forbidden dependency | — | Fix the dependency |
| deptrac | a violation line per forbidden dependency, non-zero exit code | — | Fix or add an explicit, reviewed rule |
Enforcing layers Must-know
Cockburn's warning is the reason: a new layer promises "no business logic", but "having no mechanism to detect when a violation of that promise occurs, the organization finds a few years later that the new layer is cluttered with business logic". Make the mechanism a test.
| Tool | Language | What you declare | Runs in |
|---|---|---|---|
| Go compiler | Go | Nothing: import cycles are illegal by spec ("It is illegal for a package to import itself, directly or indirectly"); internal/ limits importers | go build |
go/parser test | Go | A map layer → allowed layers (arch_test.go on this page) | go test |
| go-arch-lint | Go | .go-arch-lint.yml: components, deps.mayDependOn | go-arch-lint check, CI |
Pest arch() | PHP | expect('App\Http')->not->toUse('App\Repositories'), toOnlyBeUsedIn, toOnlyUse, presets (preset()->laravel()) | ./vendor/bin/pest |
| deptrac | PHP | deptrac.yaml: layers with collectors, ruleset | vendor/bin/deptrac analyse, CI |
| ArchUnit / NetArchTest | Java / .NET | Fluent layer rules | Unit tests |
The Go compiler gives you one layer check for free: two packages that import each other do not build. In PHP nothing stops a cycle; deptrac or Pest must.
Testing per layer Important
| Layer | Test type | Speed | What it proves | Laravel | Go |
|---|---|---|---|---|---|
| Domain | Unit | microseconds | Rules and invariants | Pest unit test on Pricing, no app boot | domain/order_test.go, table-driven |
| Application | Unit with fakes or integration with a DB | ms | Orchestration, transaction, error mapping to domain errors | Action with RefreshDatabase (SQLite in memory or PostgreSQL) | app/place_order_test.go with storage/memory |
| Persistence | Integration | 10–100 ms | SQL is correct, N+1 absent | Repository test + expectsDatabaseQueryCount | storage/postgres against a real PostgreSQL (testcontainers) |
| Presentation | HTTP / feature | ms–100 ms | Status codes, JSON contract, auth | postJson()->assertCreated() | httptest.NewRecorder on the real mux |
| Architecture | Fitness | ms | Layer rules | Pest arch() | arch_test.go |
Dijkstra's lesson still applies: test bottom-up, so a failure in an upper layer is not a failure in a lower one. The pyramid shape follows: many domain tests, fewer application tests, a few HTTP tests per endpoint.
Performance of layering Good to know
The abstraction cost is small; the hidden I/O is not. An extra method call is nanoseconds; an extra interface dispatch in Go is a few nanoseconds; mapping a row to a struct a few hundred nanoseconds. One extra database round trip is 0.2–1 ms. Layering never makes a service slow by itself; layering that hides queries does:
N+1 through layers (the controller looks innocent)
1 foreach ($order->lines as $line) // presentation: loop over 50 lines
2 $line->product->name // lazy load: SELECT * FROM products WHERE id = ?
3 -> 1 query for the order + 1 for lines + 50 for products = 52 round trips (~25-50 ms)
Fix in the application or persistence layer, where the query is decided:
4 Order::with('lines.product')->findOrFail($id) // 3 queries regardless of line count
5 Go: Catalog.PricesFor(ctx, ids) -> one "WHERE id IN ($1,...,$n)"Design rules: (1) repository and port methods take sets (PricesFor(ids)), not single ids called in a loop; (2) in Laravel turn lazy loading into an error outside production with Model::preventLazyLoading(! $this->app->isProduction()); (3) assert query counts in tests ($this->expectsDatabaseQueryCount(5)); (4) read paths that need joins get an open query path instead of being assembled from domain objects. ORM-specific detail: ORM Pitfalls.
Go
The running example is the ordering system: place an order with lines, price them from the catalog, apply "10% off orders of at least 100.00", save, and list a customer's orders. The module is docs/snippets/architecture/layered-monolith/go; gofmt -l ., go vet ./... and go test ./... pass.
Before
One handler does everything: JSON, validation, one price query per line (N+1), the discount rule, SQL and the response.
// Package main shows the "no layers" starting point: one HTTP handler parses
// JSON, validates, reads prices, applies business rules, writes SQL and
// formats the response. It works, but nothing in it can be reused or tested
// without an HTTP request and a real database.
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
)
type placeOrderRequest struct {
CustomerID int64 `json:"customer_id"`
Lines []struct {
ProductID int64 `json:"product_id"`
Quantity int `json:"quantity"`
} `json:"lines"`
}
func placeOrder(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req placeOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || len(req.Lines) == 0 {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
tx, err := db.BeginTx(r.Context(), nil)
if err != nil {
http.Error(w, "db", http.StatusInternalServerError)
return
}
defer tx.Rollback()
var total int64
for _, l := range req.Lines {
// One query per line: the N+1 pattern hidden in a loop.
var price int64
err := tx.QueryRowContext(r.Context(),
`SELECT price_cents FROM products WHERE id = $1`, l.ProductID).Scan(&price)
if err != nil {
http.Error(w, "unknown product", http.StatusUnprocessableEntity)
return
}
total += price * int64(l.Quantity)
}
// Business rule buried in the transport code.
if total >= 100_00 {
total = total * 90 / 100
}
var id int64
err = tx.QueryRowContext(r.Context(),
`INSERT INTO orders (customer_id, total_cents, status) VALUES ($1, $2, 'placed') RETURNING id`,
req.CustomerID, total).Scan(&id)
if err != nil {
http.Error(w, "db", http.StatusInternalServerError)
return
}
if err := tx.Commit(); err != nil {
http.Error(w, "db", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]int64{"id": id, "total_cents": total})
}
}
func main() {
// A driver import (for example github.com/jackc/pgx/v5/stdlib) is omitted;
// the point of this file is its shape, not running it.
var db *sql.DB
http.Handle("POST /orders", placeOrder(db))
log.Fatal(http.ListenAndServe(":8080", nil))
}After
The layout follows the Go team's Organizing a Go module advice for server projects ("it's recommended to keep the Go packages implementing the server's logic in the internal directory … keep all Go commands together in a cmd directory"):
go/ordering/
├── arch_test.go # fitness function: layer import rules
├── .go-arch-lint.yml # the same rules for go-arch-lint
├── cmd/ordering/main.go # composition root, graceful shutdown
└── internal/
├── httpapi/ # PRESENTATION: handlers, JSON, status codes
│ ├── orders.go
│ └── orders_test.go # httptest
├── app/ # APPLICATION: use cases + the ports they need
│ ├── place_order.go
│ └── place_order_test.go
├── domain/ # DOMAIN: Order, Line, Money, rules (stdlib only)
│ ├── order.go
│ └── order_test.go
├── query/ # OPEN read path: SQL read models for screens
│ └── summaries.go
└── storage/ # PERSISTENCE
├── postgres/store.go # database/sql, data mapper, tx in context
└── memory/store.go # same ports, for tests and local runsDomain layer. No imports from the project, no SQL, no HTTP. Invariants live in the constructor.
// Package domain is the innermost layer: business concepts and rules.
// It imports only the standard library, never app, httpapi or storage.
package domain
import (
"errors"
"fmt"
"time"
)
// Errors the outer layers translate (to HTTP 422, to a CLI exit code...).
var (
ErrEmptyOrder = errors.New("order has no lines")
ErrInvalidQuantity = errors.New("quantity must be between 1 and 100")
ErrUnknownProduct = errors.New("unknown product")
)
// Money is integer cents; floating point never touches prices.
type Money int64
// Line is one product on an order, priced when the order is placed.
type Line struct {
ProductID int64
Quantity int
UnitPrice Money
}
// Subtotal is quantity times unit price.
func (l Line) Subtotal() Money { return l.UnitPrice * Money(l.Quantity) }
// Status is the order lifecycle state.
type Status string
const (
StatusPlaced Status = "placed"
StatusCancelled Status = "cancelled"
)
// Order is the aggregate the use cases work on. Its fields are exported for
// mapping by the persistence layer; its invariants live in the methods.
type Order struct {
ID int64
CustomerID int64
Lines []Line
Discount Money
Status Status
PlacedAt time.Time
}
// NewOrder builds a placed order and enforces the rules that must always hold.
func NewOrder(customerID int64, lines []Line, now time.Time) (*Order, error) {
if len(lines) == 0 {
return nil, ErrEmptyOrder
}
for _, l := range lines {
if l.Quantity < 1 || l.Quantity > 100 {
return nil, fmt.Errorf("product %d: %w", l.ProductID, ErrInvalidQuantity)
}
}
o := &Order{CustomerID: customerID, Lines: lines, Status: StatusPlaced, PlacedAt: now}
o.Discount = volumeDiscount(o.Subtotal())
return o, nil
}
// Subtotal sums the lines.
func (o *Order) Subtotal() Money {
var s Money
for _, l := range o.Lines {
s += l.Subtotal()
}
return s
}
// Total is subtotal minus discount.
func (o *Order) Total() Money { return o.Subtotal() - o.Discount }
// Cancel is allowed only for a placed order.
func (o *Order) Cancel() error {
if o.Status != StatusPlaced {
return fmt.Errorf("cannot cancel order in status %q", o.Status)
}
o.Status = StatusCancelled
return nil
}
// volumeDiscount: 10% off orders of at least 100.00, rounded down to the cent.
func volumeDiscount(subtotal Money) Money {
if subtotal < 100_00 {
return 0
}
return subtotal / 10
}package domain
import (
"errors"
"testing"
"time"
)
// Unit tests for the domain layer: no database, no HTTP, microseconds each.
func TestNewOrder(t *testing.T) {
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
tests := []struct {
name string
lines []Line
wantTotal Money
wantErr error
}{
{"empty", nil, 0, ErrEmptyOrder},
{"zero quantity", []Line{{ProductID: 1, Quantity: 0, UnitPrice: 500}}, 0, ErrInvalidQuantity},
{"below threshold", []Line{{ProductID: 1, Quantity: 2, UnitPrice: 40_00}}, 80_00, nil},
{"discounted", []Line{{ProductID: 1, Quantity: 3, UnitPrice: 40_00}}, 108_00, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
o, err := NewOrder(7, tt.lines, now)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
if err == nil && o.Total() != tt.wantTotal {
t.Fatalf("total = %d, want %d", o.Total(), tt.wantTotal)
}
})
}
}Application layer. The use case declares the interfaces it consumes (Catalog, Orders, TxRunner) and owns the transaction. PricesFor takes a slice so the boundary cannot hide an N+1 loop.
// Package app is the application (service) layer: one type per use case.
// It owns the transaction boundary and orchestrates domain objects. It
// declares the interfaces it needs (consumer side); storage implements them.
package app
import (
"context"
"fmt"
"time"
"academy/layered-monolith/ordering/internal/domain"
)
// Catalog returns current unit prices for many products in ONE call, so the
// layer boundary cannot hide an N+1 loop.
type Catalog interface {
PricesFor(ctx context.Context, productIDs []int64) (map[int64]domain.Money, error)
}
// Orders persists the aggregate.
type Orders interface {
Save(ctx context.Context, o *domain.Order) error
ByID(ctx context.Context, id int64) (*domain.Order, error)
}
// TxRunner runs fn in one database transaction. The context carries the
// transaction to the repositories; app never sees *sql.Tx.
type TxRunner interface {
WithinTx(ctx context.Context, fn func(ctx context.Context) error) error
}
// LineInput is the use case's input; it is not the HTTP JSON shape.
type LineInput struct {
ProductID int64
Quantity int
}
// PlaceOrderInput is a plain command object.
type PlaceOrderInput struct {
CustomerID int64
Lines []LineInput
}
// PlaceOrder is the use case "a customer places an order".
type PlaceOrder struct {
Tx TxRunner
Catalog Catalog
Orders Orders
Now func() time.Time
}
// Handle validates through the domain, prices in one query, saves in one
// transaction and returns the saved order.
func (uc PlaceOrder) Handle(ctx context.Context, in PlaceOrderInput) (*domain.Order, error) {
ids := make([]int64, 0, len(in.Lines))
for _, l := range in.Lines {
ids = append(ids, l.ProductID)
}
var placed *domain.Order
err := uc.Tx.WithinTx(ctx, func(ctx context.Context) error {
prices, err := uc.Catalog.PricesFor(ctx, ids)
if err != nil {
return fmt.Errorf("load prices: %w", err)
}
lines := make([]domain.Line, 0, len(in.Lines))
for _, l := range in.Lines {
p, ok := prices[l.ProductID]
if !ok {
return fmt.Errorf("product %d: %w", l.ProductID, domain.ErrUnknownProduct)
}
lines = append(lines, domain.Line{ProductID: l.ProductID, Quantity: l.Quantity, UnitPrice: p})
}
o, err := domain.NewOrder(in.CustomerID, lines, uc.Now())
if err != nil {
return err
}
if err := uc.Orders.Save(ctx, o); err != nil {
return fmt.Errorf("save order: %w", err)
}
placed = o
return nil
})
return placed, err
}package app_test
import (
"context"
"errors"
"testing"
"time"
"academy/layered-monolith/ordering/internal/app"
"academy/layered-monolith/ordering/internal/domain"
"academy/layered-monolith/ordering/internal/storage/memory"
)
// Application-layer test: real use case, in-memory adapters, no database.
func TestPlaceOrder(t *testing.T) {
store := memory.NewStore(map[int64]domain.Money{1: 40_00, 2: 15_00})
uc := app.PlaceOrder{Tx: store, Catalog: store, Orders: store,
Now: func() time.Time { return time.Unix(0, 0) }}
o, err := uc.Handle(context.Background(), app.PlaceOrderInput{
CustomerID: 7,
Lines: []app.LineInput{{ProductID: 1, Quantity: 3}},
})
if err != nil {
t.Fatal(err)
}
if o.ID == 0 || o.Total() != 108_00 {
t.Fatalf("got id=%d total=%d", o.ID, o.Total())
}
_, err = uc.Handle(context.Background(), app.PlaceOrderInput{
CustomerID: 7,
Lines: []app.LineInput{{ProductID: 99, Quantity: 1}},
})
if !errors.Is(err, domain.ErrUnknownProduct) {
t.Fatalf("err = %v, want ErrUnknownProduct", err)
}
}Persistence layer. postgres.Store satisfies the three interfaces without importing app. The transaction travels in the context; PricesFor issues one IN (...) query; Save one multi-row insert for the lines.
// Package postgres is the persistence layer for PostgreSQL through
// database/sql. It maps rows to domain types; SQL never leaves this package.
package postgres
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
"academy/layered-monolith/ordering/internal/domain"
)
type txKey struct{}
// querier is what *sql.DB and *sql.Tx have in common.
type querier interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
// Store implements app.TxRunner, app.Catalog and app.Orders.
type Store struct{ db *sql.DB }
// New wraps an open pool (driver registered by the caller, e.g. pgx/v5/stdlib).
func New(db *sql.DB) *Store { return &Store{db: db} }
func (s *Store) q(ctx context.Context) querier {
if tx, ok := ctx.Value(txKey{}).(*sql.Tx); ok {
return tx
}
return s.db
}
// WithinTx is the only place a transaction is begun and committed.
func (s *Store) WithinTx(ctx context.Context, fn func(ctx context.Context) error) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}
// PricesFor loads all prices with one query: WHERE id IN ($1, $2, ...).
func (s *Store) PricesFor(ctx context.Context, ids []int64) (map[int64]domain.Money, error) {
out := make(map[int64]domain.Money, len(ids))
if len(ids) == 0 {
return out, nil
}
ph := make([]string, len(ids))
args := make([]any, len(ids))
for i, id := range ids {
ph[i] = "$" + strconv.Itoa(i+1)
args[i] = id
}
rows, err := s.q(ctx).QueryContext(ctx,
`SELECT id, price_cents FROM products WHERE id IN (`+strings.Join(ph, ",")+`)`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id, price int64
if err := rows.Scan(&id, &price); err != nil {
return nil, err
}
out[id] = domain.Money(price)
}
return out, rows.Err()
}
// Save inserts the order and all its lines (one multi-row INSERT).
func (s *Store) Save(ctx context.Context, o *domain.Order) error {
q := s.q(ctx)
err := q.QueryRowContext(ctx,
`INSERT INTO orders (customer_id, status, subtotal_cents, discount_cents, total_cents, placed_at)
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`,
o.CustomerID, string(o.Status), int64(o.Subtotal()), int64(o.Discount), int64(o.Total()), o.PlacedAt).Scan(&o.ID)
if err != nil {
return fmt.Errorf("insert order: %w", err)
}
vals := make([]string, len(o.Lines))
args := make([]any, 0, len(o.Lines)*4)
for i, l := range o.Lines {
n := i * 4
vals[i] = fmt.Sprintf("($%d, $%d, $%d, $%d)", n+1, n+2, n+3, n+4)
args = append(args, o.ID, l.ProductID, l.Quantity, int64(l.UnitPrice))
}
_, err = q.ExecContext(ctx,
`INSERT INTO order_lines (order_id, product_id, quantity, unit_price_cents) VALUES `+
strings.Join(vals, ","), args...)
return err
}
// ByID loads the order and its lines in two queries (not one per line).
func (s *Store) ByID(ctx context.Context, id int64) (*domain.Order, error) {
q := s.q(ctx)
o := domain.Order{ID: id}
var status string
err := q.QueryRowContext(ctx,
`SELECT customer_id, status, discount_cents, placed_at FROM orders WHERE id = $1`, id).
Scan(&o.CustomerID, &status, &o.Discount, &o.PlacedAt)
if err != nil {
return nil, err
}
o.Status = domain.Status(status)
rows, err := q.QueryContext(ctx,
`SELECT product_id, quantity, unit_price_cents FROM order_lines WHERE order_id = $1`, id)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var l domain.Line
if err := rows.Scan(&l.ProductID, &l.Quantity, &l.UnitPrice); err != nil {
return nil, err
}
o.Lines = append(o.Lines, l)
}
return &o, rows.Err()
}// Package memory is an in-process persistence adapter for tests and local
// runs. It satisfies app.Catalog, app.Orders and app.TxRunner without
// importing app: Go interfaces are satisfied implicitly.
package memory
import (
"context"
"errors"
"sync"
"academy/layered-monolith/ordering/internal/domain"
)
// ErrNotFound is returned by ByID.
var ErrNotFound = errors.New("order not found")
// Store keeps products and orders in maps.
type Store struct {
mu sync.Mutex
prices map[int64]domain.Money
orders map[int64]domain.Order
nextID int64
}
// NewStore seeds the product prices.
func NewStore(prices map[int64]domain.Money) *Store {
return &Store{prices: prices, orders: map[int64]domain.Order{}}
}
// WithinTx runs fn; the map store has no rollback, which is fine for tests.
func (s *Store) WithinTx(ctx context.Context, fn func(ctx context.Context) error) error {
return fn(ctx)
}
// PricesFor returns prices for the known ids.
func (s *Store) PricesFor(_ context.Context, ids []int64) (map[int64]domain.Money, error) {
s.mu.Lock()
defer s.mu.Unlock()
out := make(map[int64]domain.Money, len(ids))
for _, id := range ids {
if p, ok := s.prices[id]; ok {
out[id] = p
}
}
return out, nil
}
// Save assigns an id and stores a copy.
func (s *Store) Save(_ context.Context, o *domain.Order) error {
s.mu.Lock()
defer s.mu.Unlock()
if o.ID == 0 {
s.nextID++
o.ID = s.nextID
}
s.orders[o.ID] = *o
return nil
}
// ByID returns a copy of the stored order.
func (s *Store) ByID(_ context.Context, id int64) (*domain.Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
o, ok := s.orders[id]
if !ok {
return nil, ErrNotFound
}
return &o, nil
}The open read path. A screen that lists orders has no rules; it gets a read model straight from SQL and the handler calls it directly. This is the documented open layer; the architecture test allows httpapi → query and nothing else.
// Package query is a deliberately OPEN path for read-only screens: the
// presentation layer may call it directly, skipping app and domain, because
// a list of orders has no business rules. Writes never come here.
package query
import (
"context"
"database/sql"
"time"
)
// Summary is a read model shaped for one screen, not a domain object.
type Summary struct {
ID int64 `json:"id"`
Status string `json:"status"`
TotalCents int64 `json:"total_cents"`
Lines int `json:"lines"`
PlacedAt time.Time `json:"placed_at"`
}
// Orders runs read-only SQL against the pool (or a read replica).
type Orders struct{ DB *sql.DB }
// ForCustomer returns the latest 50 orders with a line count, in one query.
func (q Orders) ForCustomer(ctx context.Context, customerID int64) ([]Summary, error) {
rows, err := q.DB.QueryContext(ctx, `
SELECT o.id, o.status, o.total_cents, count(l.*), o.placed_at
FROM orders o LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1
GROUP BY o.id
ORDER BY o.placed_at DESC
LIMIT 50`, customerID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Summary
for rows.Next() {
var s Summary
if err := rows.Scan(&s.ID, &s.Status, &s.TotalCents, &s.Lines, &s.PlacedAt); err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}Presentation layer. Decode, call one use case, translate domain errors to status codes.
// Package httpapi is the presentation layer: decode, call one use case,
// map errors to status codes, encode. No SQL and no business rules here.
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"academy/layered-monolith/ordering/internal/app"
"academy/layered-monolith/ordering/internal/domain"
"academy/layered-monolith/ordering/internal/query"
)
// OrderPlacer is declared here, by the consumer; app.PlaceOrder satisfies it.
type OrderPlacer interface {
Handle(ctx context.Context, in app.PlaceOrderInput) (*domain.Order, error)
}
// OrderLister is the open read path (see package query).
type OrderLister interface {
ForCustomer(ctx context.Context, customerID int64) ([]query.Summary, error)
}
// Orders groups the order endpoints.
type Orders struct {
Place OrderPlacer
List OrderLister
}
// Routes registers the endpoints with Go 1.22+ method patterns.
func (h Orders) Routes(mux *http.ServeMux) {
mux.HandleFunc("POST /orders", h.create)
mux.HandleFunc("GET /customers/{id}/orders", h.list)
}
type createRequest struct {
CustomerID int64 `json:"customer_id"`
Lines []struct {
ProductID int64 `json:"product_id"`
Quantity int `json:"quantity"`
} `json:"lines"`
}
type orderResponse struct {
ID int64 `json:"id"`
Status string `json:"status"`
SubtotalCents int64 `json:"subtotal_cents"`
DiscountCents int64 `json:"discount_cents"`
TotalCents int64 `json:"total_cents"`
}
func (h Orders) create(w http.ResponseWriter, r *http.Request) {
var req createRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "malformed JSON"})
return
}
in := app.PlaceOrderInput{CustomerID: req.CustomerID}
for _, l := range req.Lines {
in.Lines = append(in.Lines, app.LineInput{ProductID: l.ProductID, Quantity: l.Quantity})
}
o, err := h.Place.Handle(r.Context(), in)
switch {
case errors.Is(err, domain.ErrEmptyOrder),
errors.Is(err, domain.ErrInvalidQuantity),
errors.Is(err, domain.ErrUnknownProduct):
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": err.Error()})
return
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
return
}
writeJSON(w, http.StatusCreated, orderResponse{
ID: o.ID, Status: string(o.Status),
SubtotalCents: int64(o.Subtotal()), DiscountCents: int64(o.Discount), TotalCents: int64(o.Total()),
})
}
func (h Orders) list(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad customer id"})
return
}
rows, err := h.List.ForCustomer(r.Context(), id)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
return
}
writeJSON(w, http.StatusOK, rows)
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}package httpapi_test
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"academy/layered-monolith/ordering/internal/app"
"academy/layered-monolith/ordering/internal/domain"
"academy/layered-monolith/ordering/internal/httpapi"
"academy/layered-monolith/ordering/internal/query"
"academy/layered-monolith/ordering/internal/storage/memory"
)
type noList struct{}
func (noList) ForCustomer(context.Context, int64) ([]query.Summary, error) { return nil, nil }
// HTTP-level test: real router, real use case, in-memory persistence.
func TestCreateOrder(t *testing.T) {
store := memory.NewStore(map[int64]domain.Money{1: 40_00})
uc := app.PlaceOrder{Tx: store, Catalog: store, Orders: store, Now: time.Now}
mux := http.NewServeMux()
httpapi.Orders{Place: uc, List: noList{}}.Routes(mux)
cases := []struct {
body string
want int
}{
{`{"customer_id":7,"lines":[{"product_id":1,"quantity":3}]}`, http.StatusCreated},
{`{"customer_id":7,"lines":[]}`, http.StatusUnprocessableEntity},
{`{"customer_id":7,"lines":[{"product_id":9,"quantity":1}]}`, http.StatusUnprocessableEntity},
{`not json`, http.StatusBadRequest},
}
for _, c := range cases {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(c.body)))
if rec.Code != c.want {
t.Errorf("%s: status %d, want %d (%s)", c.body, rec.Code, c.want, rec.Body)
}
}
}Composition root. The only package that imports every layer.
// Command ordering is the composition root: the only package that knows
// every layer and picks the concrete adapters.
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/layered-monolith/ordering/internal/app"
"academy/layered-monolith/ordering/internal/domain"
"academy/layered-monolith/ordering/internal/httpapi"
"academy/layered-monolith/ordering/internal/query"
"academy/layered-monolith/ordering/internal/storage/memory"
)
type emptyList struct{}
func (emptyList) ForCustomer(context.Context, int64) ([]query.Summary, error) {
return []query.Summary{}, nil
}
func main() {
// Production wiring would be:
// db, _ := sql.Open("pgx", os.Getenv("DATABASE_URL"))
// store := postgres.New(db); list := query.Orders{DB: db}
// The in-memory adapter keeps this example runnable without PostgreSQL.
store := memory.NewStore(map[int64]domain.Money{1: 40_00, 2: 15_00})
place := app.PlaceOrder{Tx: store, Catalog: store, Orders: store, Now: time.Now}
mux := http.NewServeMux()
httpapi.Orders{Place: place, List: emptyList{}}.Routes(mux)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("listen", "err", err)
os.Exit(1)
}
}()
<-ctx.Done()
// Stateless layers: draining in-flight requests is all a rolling or
// blue/green deploy needs from this process.
shutdown, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
_ = srv.Shutdown(shutdown)
}Architecture test and go-arch-lint config. Adding import _ ".../storage/memory" to a domain file makes the test print internal/domain/bad.go (internal/domain) imports academy/layered-monolith/ordering/internal/storage/memory (internal/storage): not allowed; making app import httpapi does not even compile (import cycle not allowed).
// Package ordering holds the architecture test: a fitness function that
// fails the build when a layer imports something it must not.
package ordering
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"strings"
"testing"
)
const mod = "academy/layered-monolith/ordering/"
// allowed lists, per layer, the internal layers it may import.
// Anything under internal/ not listed is forbidden. cmd/ may import all.
var allowed = map[string][]string{
"internal/domain": {},
"internal/app": {"internal/domain"},
"internal/query": {},
"internal/storage": {"internal/domain"},
"internal/httpapi": {"internal/app", "internal/domain", "internal/query"},
}
func layerOf(path string) string {
for l := range allowed {
if path == l || strings.HasPrefix(path, l+"/") {
return l
}
}
return ""
}
func TestLayerDependencies(t *testing.T) {
err := filepath.WalkDir("internal", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return err
}
from := layerOf(filepath.ToSlash(filepath.Dir(p)))
f, err := parser.ParseFile(token.NewFileSet(), p, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, imp := range f.Imports {
path, _ := strconv.Unquote(imp.Path.Value)
if !strings.HasPrefix(path, mod) {
continue
}
to := layerOf(strings.TrimPrefix(path, mod))
if to == from {
continue
}
ok := false
for _, a := range allowed[from] {
ok = ok || a == to
}
if !ok {
t.Errorf("%s (%s) imports %s (%s): not allowed", p, from, path, to)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}version: 3
workdir: internal
components:
httpapi: { in: httpapi }
app: { in: app }
domain: { in: domain }
query: { in: query }
storage: { in: storage/** }
deps:
httpapi:
mayDependOn: [app, domain, query]
app:
mayDependOn: [domain]
storage:
mayDependOn: [domain]
domain:
mayDependOn: []
query:
mayDependOn: []The Go angle
| Go feature | Role in layering | Source |
|---|---|---|
| Package = layer unit | Imports are the dependency graph; visible in every file header | Go spec |
| No import cycles | A free check that two layers do not depend on each other: "It is illegal for a package to import itself, directly or indirectly" | Go spec |
internal/ | Code outside the module cannot import your layers: "may not be imported by packages outside the source subtree in which they reside" | Go 1.4 release notes |
| Consumer-side interfaces | The application declares ports; persistence satisfies them implicitly, so the import still points inward | Go Code Review Comments |
cmd/<name> | One composition root per binary (web, worker, migrator) | Organizing a Go module |
context.Context | Carries deadlines, the transaction and request-scoped values across layers without globals | context package |
golang-standards/project-layout | Popular but unofficial; its README states it is "NOT an official standard defined by the core Go dev team" and points to the official layout page | GitHub README |
/pkg | Optional; for libraries meant for others. For a service, internal/ is the safer default | Same README |
Naming: avoid a package called http (it shadows net/http), models (says nothing) and utils (an open layer for everything). Packages named after what they provide (httpapi, app, domain, postgres) read well at call sites: postgres.New(db), domain.NewOrder(...). More on layouts and linting: Project Layout & Linting; on interfaces for tests: Mocking with Interfaces.
Laravel
The same ordering system in a Laravel 13 application (PHP 8.4). Files live under docs/snippets/architecture/layered-monolith/php; PHP is not installed on the authoring machine, so the code was reviewed against the Laravel 13 and Pest docs, not run.
Before
A controller that validates, loads one product per line, applies the discount, writes, and sends mail inside the transaction.
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
// The "everything in the controller" starting point: validation, pricing
// rules, persistence, e-mail and response shaping in one method.
class OrderController extends Controller
{
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'lines' => ['required', 'array', 'min:1'],
'lines.*.product_id' => ['required', 'integer'],
'lines.*.quantity' => ['required', 'integer', 'between:1,100'],
]);
$order = DB::transaction(function () use ($request, $data) {
$total = 0;
foreach ($data['lines'] as $line) {
// One query per line (N+1), and a business rule in HTTP code.
$product = Product::findOrFail($line['product_id']);
$total += $product->price_cents * $line['quantity'];
}
$discount = $total >= 10000 ? intdiv($total, 10) : 0;
$order = Order::create([
'customer_id' => $request->user()->id,
'status' => 'placed',
'discount_cents' => $discount,
'total_cents' => $total - $discount,
]);
// Sending mail inside the transaction: slow, and sent even if
// the commit later fails.
Mail::raw("Order {$order->id} placed", fn ($m) => $m->to($request->user()->email));
return $order;
});
return response()->json(['id' => $order->id, 'total_cents' => $order->total_cents], 201);
}
}After
app/
├── Http/ # PRESENTATION
│ ├── Controllers/PlaceOrderController.php # single action (__invoke)
│ ├── Requests/PlaceOrderRequest.php # authorize() + rules()
│ └── Resources/OrderResource.php # JSON contract
├── Actions/PlaceOrder.php # APPLICATION: use case, DB::transaction
├── Events/OrderPlaced.php # APPLICATION: fact, ShouldDispatchAfterCommit
├── Listeners/SendOrderConfirmation.php # side effect, ShouldQueue
├── Domain/Ordering/ # DOMAIN (framework-free)
│ ├── Pricing.php
│ └── OrderRejected.php
├── Models/ # DOMAIN + PERSISTENCE (Active Record)
│ ├── Order.php OrderLine.php Product.php
├── Repositories/ProductPrices.php # PERSISTENCE: one batched query
└── Providers/AppServiceProvider.php # composition: preventLazyLoading
routes/api.php
tests/Arch/LayersTest.php tests/Unit/PricingTest.php tests/Feature/PlaceOrderTest.php
deptrac.yamlPresentation layer. The route, the Form Request (Laravel docs: "Form requests are custom request classes that encapsulate their own validation and authorization logic"), a single action controller ("you may define a single __invoke method within the controller") and an API Resource.
<?php
use App\Http\Controllers\PlaceOrderController;
use Illuminate\Support\Facades\Route;
Route::post('/orders', PlaceOrderController::class)->middleware('auth:sanctum');<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
// Presentation layer: input shape and authorization, nothing else.
class PlaceOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/** @return array<string, array<int, string>> */
public function rules(): array
{
return [
'lines' => ['required', 'array', 'min:1', 'max:50'],
'lines.*.product_id' => ['required', 'integer', 'distinct'],
'lines.*.quantity' => ['required', 'integer', 'between:1,100'],
];
}
/** @return list<array{product_id: int, quantity: int}> */
public function lines(): array
{
return array_map(
fn (array $l) => ['product_id' => (int) $l['product_id'], 'quantity' => (int) $l['quantity']],
$this->validated('lines'),
);
}
}<?php
namespace App\Http\Controllers;
use App\Actions\PlaceOrder;
use App\Domain\Ordering\OrderRejected;
use App\Http\Requests\PlaceOrderRequest;
use App\Http\Resources\OrderResource;
use Illuminate\Http\JsonResponse;
// Presentation layer: a single action controller. It translates HTTP into a
// call to one application-layer action and the result back into HTTP.
class PlaceOrderController extends Controller
{
public function __invoke(PlaceOrderRequest $request, PlaceOrder $placeOrder): JsonResponse
{
try {
$order = $placeOrder->handle($request->user()->id, $request->lines());
} catch (OrderRejected $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
return (new OrderResource($order))->response()->setStatusCode(201);
}
}<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
// Presentation layer: the JSON contract, decoupled from column names.
class OrderResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'status' => $this->status,
'subtotal_cents' => $this->subtotal_cents,
'discount_cents' => $this->discount_cents,
'total_cents' => $this->total_cents,
'lines' => $this->whenLoaded('lines', fn () => $this->lines->map(fn ($l) => [
'product_id' => $l->product_id,
'quantity' => $l->quantity,
'unit_price_cents' => $l->unit_price_cents,
])),
];
}
}Application layer. One action per use case; the transaction lives here; the event is dispatched only after commit.
<?php
namespace App\Actions;
use App\Domain\Ordering\OrderRejected;
use App\Events\OrderPlaced;
use App\Models\Order;
use App\Repositories\ProductPrices;
use Illuminate\Support\Facades\DB;
// Application (service) layer: one use case. Owns the transaction, loads
// what the domain needs, lets the model enforce the rules, saves, and
// announces the fact. It knows nothing about HTTP, so a console command,
// a queued job or a test can call it the same way.
class PlaceOrder
{
public function __construct(private ProductPrices $prices) {}
/**
* @param list<array{product_id: int, quantity: int}> $lines
*/
public function handle(int $customerId, array $lines): Order
{
return DB::transaction(function () use ($customerId, $lines) {
$prices = $this->prices->for(array_column($lines, 'product_id'));
$priced = array_map(function (array $l) use ($prices) {
if (! isset($prices[$l['product_id']])) {
throw OrderRejected::unknownProduct($l['product_id']);
}
return $l + ['unit_price_cents' => $prices[$l['product_id']]];
}, $lines);
$order = Order::placeFor($customerId, $priced);
$order->save();
$order->lines()->saveMany($order->lines);
// ShouldDispatchAfterCommit: listeners run only if COMMIT succeeds.
OrderPlaced::dispatch($order);
return $order;
});
}
}<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
// Raised by the application layer; delivered only after the transaction commits.
class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(public Order $order) {}
}<?php
namespace App\Listeners;
use App\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
// Infrastructure side effect, queued so the HTTP request does not wait for SMTP.
class SendOrderConfirmation implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
// Explicit load: lazy loading is disabled outside production.
$order = $event->order->loadMissing('customer');
Mail::raw("Order {$order->id} placed.", fn ($m) => $m->to($order->customer->email));
}
}Domain layer. Pure rules in App\Domain, behaviour on the Eloquent model (a fat model in the good sense: consistency rules, not HTTP or mail).
<?php
namespace App\Domain\Ordering;
// Domain layer, framework-free: a pure rule you can unit-test in microseconds.
final class Pricing
{
public const DISCOUNT_THRESHOLD_CENTS = 10_000;
public static function volumeDiscount(int $subtotalCents): int
{
// 10% off orders of at least 100.00, rounded down to the cent.
return $subtotalCents >= self::DISCOUNT_THRESHOLD_CENTS ? intdiv($subtotalCents, 10) : 0;
}
}<?php
namespace App\Domain\Ordering;
// A business refusal; the presentation layer maps it to HTTP 422.
final class OrderRejected extends \DomainException
{
public static function unknownProduct(int $productId): self
{
return new self("Unknown product {$productId}.");
}
public static function notCancellable(string $status): self
{
return new self("An order in status {$status} cannot be cancelled.");
}
}<?php
namespace App\Models;
use App\Domain\Ordering\OrderRejected;
use App\Domain\Ordering\Pricing;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
// Persistence + domain behaviour (Active Record). The rules that keep an
// order consistent live here, not in controllers: a "fat model" in the
// good sense, delegating pure calculations to App\Domain.
class Order extends Model
{
protected $fillable = ['customer_id', 'status', 'subtotal_cents', 'discount_cents', 'total_cents'];
protected function casts(): array
{
return [
'subtotal_cents' => 'integer',
'discount_cents' => 'integer',
'total_cents' => 'integer',
];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
public function customer(): BelongsTo
{
return $this->belongsTo(User::class, 'customer_id');
}
/**
* Build an unsaved, consistent order from priced lines.
*
* @param list<array{product_id: int, quantity: int, unit_price_cents: int}> $pricedLines
*/
public static function placeFor(int $customerId, array $pricedLines): self
{
$lines = new Collection(array_map(fn (array $l) => new OrderLine($l), $pricedLines));
$subtotal = $lines->sum(fn (OrderLine $l) => $l->unit_price_cents * $l->quantity);
$discount = Pricing::volumeDiscount($subtotal);
$order = new self([
'customer_id' => $customerId,
'status' => 'placed',
'subtotal_cents' => $subtotal,
'discount_cents' => $discount,
'total_cents' => $subtotal - $discount,
]);
$order->setRelation('lines', $lines);
return $order;
}
public function cancel(): void
{
if ($this->status !== 'placed') {
throw OrderRejected::notCancellable($this->status);
}
$this->status = 'cancelled';
}
}<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class OrderLine extends Model
{
public $timestamps = false;
protected $fillable = ['product_id', 'quantity', 'unit_price_cents'];
}<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name', 'price_cents'];
}Persistence layer. A repository only where it adds something: here, one query for any number of products.
<?php
namespace App\Repositories;
use App\Models\Product;
// Persistence layer. This class earns its place: it fixes ONE query for any
// number of lines and returns a plain array, so the layer above cannot
// accidentally lazy-load. A repository that only forwards find() would be a
// sinkhole; use the model directly instead.
class ProductPrices
{
/**
* @param list<int> $productIds
* @return array<int, int> product id => price in cents
*/
public function for(array $productIds): array
{
return Product::query()
->whereIn('id', $productIds)
->pluck('price_cents', 'id')
->map(fn ($cents) => (int) $cents)
->all();
}
}<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Concrete classes (PlaceOrder, ProductPrices) need no binding: the
// container autowires them. Bind only interfaces with several
// implementations, e.g. a PaymentGateway.
}
public function boot(): void
{
// Turns an N+1 hidden behind a layer into an exception in dev and CI.
Model::preventLazyLoading(! $this->app->isProduction());
}
}Tests: one per layer, plus architecture.
<?php
use App\Domain\Ordering\Pricing;
// Domain-layer unit test: no framework boot, no database.
it('applies the volume discount at the threshold', function (int $subtotal, int $discount) {
expect(Pricing::volumeDiscount($subtotal))->toBe($discount);
})->with([
'below' => [9_999, 0],
'at threshold' => [10_000, 1_000],
'rounds down' => [10_005, 1_000],
]);<?php
use App\Events\OrderPlaced;
use App\Models\Product;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
pest()->use(RefreshDatabase::class);
// HTTP test: every layer, real database (SQLite or PostgreSQL in CI).
it('places an order through all layers', function () {
Event::fake([OrderPlaced::class]);
$user = User::factory()->create();
$product = Product::create(['name' => 'Mug', 'price_cents' => 4_000]);
$this->actingAs($user)
->postJson('/api/orders', ['lines' => [['product_id' => $product->id, 'quantity' => 3]]])
->assertCreated()
->assertJsonPath('data.total_cents', 10_800);
$this->assertDatabaseHas('orders', ['customer_id' => $user->id, 'total_cents' => 10_800]);
Event::assertDispatched(OrderPlaced::class);
});
it('rejects an unknown product with 422', function () {
$this->actingAs(User::factory()->create())
->postJson('/api/orders', ['lines' => [['product_id' => 999, 'quantity' => 1]]])
->assertStatus(422);
});<?php
// Fitness functions for the layer rules (Pest arch()). Run with ./vendor/bin/pest.
arch('domain is framework-free')
->expect('App\Domain')
->not->toUse(['Illuminate', 'App\Http', 'App\Models', 'App\Actions', 'App\Repositories']);
arch('presentation does not reach persistence')
->expect('App\Http')
->not->toUse(['Illuminate\Support\Facades\DB', 'App\Repositories', 'App\Models']);
arch('actions are not HTTP-aware')
->expect('App\Actions')
->not->toUse(['Illuminate\Http', 'App\Http', 'request', 'response']);
arch('repositories are used only by the application layer')
->expect('App\Repositories')
->toOnlyBeUsedIn('App\Actions');
arch('controllers are single-action')
->expect('App\Http\Controllers')
->toHaveSuffix('Controller')
->toBeInvokable()
->ignoring('App\Http\Controllers\Controller');# Layer rules for deptrac (composer require --dev qossmic/deptrac-shim).
deptrac:
paths:
- ./app
layers:
- name: Presentation
collectors:
- type: classLike
value: ^App\\Http\\.*
- name: Application
collectors:
- type: classLike
value: ^App\\(Actions|Events|Listeners)\\.*
- name: Domain
collectors:
- type: classLike
value: ^App\\(Domain|Models)\\.*
- name: Persistence
collectors:
- type: classLike
value: ^App\\Repositories\\.*
ruleset:
Presentation:
- Application
- Domain
Application:
- Domain
- Persistence
Persistence:
- Domain
Domain: ~The Laravel angle
| Laravel 13 feature | Layer | What to know |
|---|---|---|
app/Http (controllers, middleware, requests) | Presentation | The docs: "Almost all of the logic to handle requests entering your application will be placed in this directory" — handling requests, not business rules |
Form Requests (make:request) | Presentation | authorize() + rules(); $request->validated() hands clean data to the action |
| API Resources | Presentation | JSON contract independent of column names |
| Single action controllers | Presentation | __invoke; one class per endpoint keeps controllers thin |
| Actions / services | Application | Not a framework feature; a plain class resolved by the container. lorisleiva/laravel-actions is a community package for the same idea |
DB::transaction | Application | One use case, one transaction |
| Eloquent models | Domain + persistence | Active Record: the model is both; keep rules as methods, keep HTTP/mail out |
App\Domain\* | Domain | Pure PHP classes and value objects; Pest can assert they use nothing from Illuminate |
| Repositories | Persistence | Optional with Eloquent; add one for batched or complex queries, not to wrap find() |
Events + ShouldDispatchAfterCommit | Application → infrastructure | Side effects after commit; listeners ShouldQueue |
Jobs (make:job) | Presentation (entry point) or infrastructure | A job is another way in; it should call an action, not hold rules |
| Service providers | Composition root | "the central place of all Laravel application bootstrapping"; registered in bootstrap/providers.php |
Model::preventLazyLoading() | Persistence guard | Throws LazyLoadingViolationException; use outside production |
Pest arch() / deptrac | Enforcement | Layer rules as tests in CI |
The "fat model vs service" debate. Both camps are partly right; the question is which logic.
| Logic | Put it in | Why |
|---|---|---|
A rule about one model's own data (cancel() only when placed, total()) | Model method or App\Domain class | Kept next to the data; reusable from every use case |
| A rule spanning several models (stock + order + coupon) | Action (application layer) or a domain service | No single model owns it |
| A workflow with a transaction and side effects | Action | Transaction and ordering of effects are application concerns |
| Queries for screens | Query object, scope, or controller with Resource (open read path) | No rules; layers would be a sinkhole |
| HTTP, mail, queues, files inside a model | Nowhere in the model | That is the bad kind of fat model |
app/Domain structures. Two common shapes: app/Domain/<Area>/ beside the standard folders (this page), or a full domain-first layout app/Domain/<Area>/{Actions,Models,Events} plus app/Http as a thin shell. The second is already halfway to a modular monolith; add architecture tests per area when you adopt it.
Where events and jobs sit. An event class is raised by the application layer and describes a fact; a listener or job is an entry point into the application, like a controller, and should call an action. Laravel's own directory docs describe the default: events "alert other parts of your application that a given action has occurred", and jobs "may be queued … or run synchronously". Queue internals: Laravel Queue Internals.
Solving the classic problems
Business logic leaks into controllers (fat controllers)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Extract an action | Move the body into PlaceOrder::handle, controller only maps | Reusable from CLI/queue/tests | One more class per use case |
| Form Request | Shape validation and authorization out of the controller | Controller becomes 5 lines | Business validation still belongs to domain |
| Domain methods | Rules on the model or App\Domain | Rules exist once | Needs discipline in reviews |
| Arch test | expect('App\Http')->not->toUse('Illuminate\Support\Facades\DB') | Stops regression | Must be kept in CI |
The sinkhole
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Open read path | Query objects / internal/query called from presentation | No ceremony for screens | Must be documented and test-enforced |
| Delete pass-through repositories | Use Eloquent directly in actions | Fewer files | Persistence is now Eloquent (fine for most apps) |
| Merge layers | Application + domain as one "business" layer for CRUD areas | Simple | Loses isolation where rules later appear |
| Change style for CRUD areas | Admin generator (Filament, Nova) | Hours, not days | Another framework to learn |
Anemic models and god services
Symptoms: OrderService with 3,000 lines; models with only relations. Fix: move one rule at a time onto the object that owns the data (Order::cancel()), split services into actions per use case, keep services as coordinators. Detail: Anemic vs Rich Models.
N+1 hidden behind layer boundaries
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Set-based ports | PricesFor(ids), ProductPrices::for($ids) | One query per use case step | Ports become less "pure CRUD" |
| Eager loading | with('lines.product') in the action/query | Constant query count | Must know the shape needed |
| Prevent lazy loading | Model::preventLazyLoading(! $this->app->isProduction()) | N+1 fails in dev/CI | Legacy code throws until fixed |
| Query count tests | expectsDatabaseQueryCount(n); Go: count queries in a test driver/tracer | Regression-proof | Brittle if counts change for good reasons |
Side effects inside the transaction
Mail or HTTP calls inside DB::transaction run even when the commit fails and hold locks while they wait. Fix: ShouldDispatchAfterCommit events, ShouldQueueAfterCommit listeners, dispatch(...)->afterCommit(), or in Go, collect events during the use case and publish after Commit. For guaranteed delivery to other services use the outbox pattern.
Layer violations creep in
Write the rules down (ADR) and enforce them in CI: deptrac or Pest in PHP, arch_test.go or go-arch-lint in Go. A new exception to a rule becomes an explicit line in the config, which shows up in code review.
Teams organised by layer
Fowler names this an anti-pattern: "One common way I've seen this layering lead organizations astray is the AntiPattern of separating development teams by these layers … Developers don't have to be full-stack (although that is laudable) but teams should be." Every feature then needs three teams. Organise teams by business capability and let each own a vertical slice; see Service Boundaries.
-- Find "pass-through" pressure in your own data: endpoints with no domain rule.
-- (Example: a route inventory table you maintain or export from `php artisan route:list --json`.)
SELECT layer_path, count(*) AS endpoints,
count(*) FILTER (WHERE has_rules = false) AS sinkholes,
round(100.0 * count(*) FILTER (WHERE has_rules = false) / count(*), 1) AS sinkhole_pct
FROM route_inventory
GROUP BY layer_path
ORDER BY sinkhole_pct DESC;Choosing
When the layered monolith is the right answer
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New product, unclear domain | Layered monolith | Arch tests from day one | Cheapest to change while you learn; Fowler: "Almost all the successful microservice stories have started with a monolith that got too big and was broken up" |
| One team (fewer than about 8–10 developers) | Layered monolith | Actions + domain methods | One mental model, one deploy |
| CRUD-heavy back office | Thin layers, open read paths | Admin generator for pure CRUD | Avoid the sinkhole |
| Rich rules (billing, insurance, logistics) | Layered with ports (hexagonal) | Domain model, ports for persistence | Rules testable without infrastructure |
| Several teams, clear business areas | Modular monolith | Modules internally layered | Technical partitioning stops scaling with people |
| Independent scaling or deploy cadence per area | Extract services from a modular monolith | Strangler fig | Only when the premium is worth it |
| Tight budget, deadline | Layered monolith | Framework conventions | Richards & Ford rate cost and simplicity as the style's strengths (summary) |
When it degrades
| Warning sign | What it means | Next step |
|---|---|---|
Every PR touches Models/ and Controllers/ of unrelated features | Technical partitioning has stopped scaling | Split by domain at the top level |
app/Services has 100+ classes importing each other | God services, hidden cycles | Actions per use case; deptrac to find cycles |
| Build/test suite above 15–20 minutes | One unit of change for everything | Modules with their own test suites |
| Deploys weekly at best, release trains | Risk per deploy too high | Smaller changes, feature flags, then modules |
| One hot endpoint forces scaling the whole app | Scale only as a whole | Separate process for that path (worker, read service) |
| Nobody can draw the layers | Big ball of mud | Write the layer ADR, add arch tests, fix violations incrementally |
Migration path to a modular monolith
Step Action Check
1 Write down the current layers and rules (ADR) Team agrees on the picture
2 Add architecture tests in "report only" mode List of violations = backlog
3 Fix violations from the bottom up (domain first) Tests turn green per layer
4 Pick one business area (e.g. Billing); move its classes into Arch test: nothing outside imports
app/Modules/Billing/{Http,Actions,Models,...} keeping inner layers Billing internals
5 Give the module a public API (facade / interface), events for others Other modules use only the API
6 Repeat per area; database tables get an owner module No cross-module joins in new code
7 Only then consider extracting a module into a service See monolith-vs-microservicesThe destination is described in Modular Monolith; the extraction step in Strangler Fig.
In architecture: from a single process to a distributed system
Monolith: one process, one database
This is the home of the style. One codebase, one artifact (a Docker image, a Go binary), one PostgreSQL. Layers are namespaces or packages; crossing a layer is a function call; one database transaction covers a whole use case. Example: the ordering system on this page, deployed as ordering:v42 behind a load balancer. The simplest correct usage: closed layers for writes, an open read path for screens, transactions in the application layer, events after commit, architecture tests in CI.
Modular monolith and multiple databases
The layered monolith grows into a modular one by splitting the top level by domain and keeping layers inside each module: Ordering/{Http,App,Domain,Storage}, Billing/{...}. Layer rules become two-dimensional: inside a module, the dependency rule; between modules, only through public APIs and events. Example: Billing listens to OrderPlaced and issues an invoice; it never queries orders directly. Each module may own a schema (ordering.*, billing.*) in the same PostgreSQL. See Modular Monolith.
Microservices: each service is a small layered app
Layering does not disappear in microservices; it moves inside each service. An ordering-service in Go is exactly the package tree of this page. What changes: the application layer now calls other services through adapters (HTTP/gRPC clients, message publishers) that sit in the persistence/infrastructure layer; the transaction no longer spans the whole workflow, so cross-service consistency uses sagas and the outbox. Flow example: POST /orders → ordering's application layer saves the order and an outbox row in one transaction → relay publishes OrderPlaced → billing's presentation layer (a consumer) calls its own IssueInvoice use case. A common mistake is the "layered distributed monolith": a "data service" tier that every other service must call for every read, the sinkhole across the network. See Service Boundaries and Data Ownership.
Distributed data: replicas, caches, read paths
The open read path is where distribution starts: the query package can read from a read replica while writes go through the closed path to the primary; the price is replication lag (a customer may not see the order they just placed unless the read goes to the primary for a few seconds). Caches belong in the persistence layer or as decorators of query objects (Cache::remember), never in the domain. Connection pools are per process, so N instances × pool size must fit the database's connection limit (Connection Pooling). Schema changes are shared by all instances during a rolling deploy, so migrations must be backward compatible (Zero-Downtime Migrations).
Scaling path: 1×, 10×, 100×
| Load | Shape | What changes in the layers |
|---|---|---|
| 1× (hundreds of req/s) | 2 instances behind a load balancer, one PostgreSQL | Nothing; keep the layers stateless (sessions in Redis or DB, files in object storage) |
| 10× | 5–20 instances, read replica, Redis cache, queue workers (same image, php artisan queue:work / cmd/worker) | Open read paths go to the replica; slow side effects move to queued listeners |
| 100× | Hot paths split out (search, feed), connection pooler, partitioned tables | The modular-monolith step; heavy modules become separate deployables only where needed |
Deploying a monolith. One artifact: build once, promote the same image through environments. Horizontal scaling needs stateless layers: no in-memory sessions, no local file uploads, no per-instance caches that must agree. Rolling deploy: replace instances one at a time; old and new code run side by side, so migrations must be expand/contract. Blue/green: start the full green environment with the new version, run smoke tests, switch the load balancer, keep blue for instant rollback (the diagram above). Canary: route a few percent of traffic to the new version first. Graceful shutdown: on SIGTERM stop accepting, drain in-flight requests (the Go srv.Shutdown in main.go; Laravel workers finish the current job with queue:work on SIGTERM). Laravel Octane keeps the application in memory between requests, which is fast but breaks code that keeps request state in singletons: another reason to keep layers stateless. Scaling mechanics: Scaling Strategies, Load Balancing.
Lab
Setup (PostgreSQL 16+, optional for steps 1–3):
CREATE TABLE users (id bigserial PRIMARY KEY, email text NOT NULL UNIQUE);
CREATE TABLE products (id bigserial PRIMARY KEY, name text NOT NULL, price_cents bigint NOT NULL CHECK (price_cents >= 0));
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES users(id),
status text NOT NULL CHECK (status IN ('placed','cancelled')),
subtotal_cents bigint NOT NULL,
discount_cents bigint NOT NULL DEFAULT 0,
total_cents bigint NOT NULL,
placed_at timestamptz NOT NULL DEFAULT now(),
created_at timestamptz, updated_at timestamptz
);
CREATE TABLE order_lines (
id bigserial PRIMARY KEY,
order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_id bigint NOT NULL REFERENCES products(id),
quantity int NOT NULL CHECK (quantity BETWEEN 1 AND 100),
unit_price_cents bigint NOT NULL
);
CREATE INDEX ON orders (customer_id, placed_at DESC);
CREATE INDEX ON order_lines (order_id);
INSERT INTO users (email) VALUES ('ada@example.com');
INSERT INTO products (name, price_cents) VALUES ('Mug', 4000), ('Tea', 1500);Step 1 — run the layered Go service.
1 cd docs/snippets/architecture/layered-monolith/go
2 go test ./... # ok for domain, app, httpapi and the arch test
3 go run ./ordering/cmd/ordering &
4 curl -s -XPOST localhost:8080/orders -d '{"customer_id":1,"lines":[{"product_id":1,"quantity":3}]}'
# {"id":1,"status":"placed","subtotal_cents":12000,"discount_cents":1200,"total_cents":10800}
5 curl -s -XPOST localhost:8080/orders -d '{"customer_id":1,"lines":[{"product_id":9,"quantity":1}]}'
# 422 {"error":"product 9: unknown product"}Step 2 — break a layer rule. Create ordering/internal/domain/bad.go with import _ "academy/layered-monolith/ordering/internal/storage/memory" and run go test ./ordering/. Expected: arch_test.go: ... (internal/domain) imports ... (internal/storage): not allowed. Then make internal/app import internal/httpapi and run go vet ./.... Expected: import cycle not allowed. Delete the file.
Step 3 — measure the sinkhole ratio. In any service you own, count service/repository methods whose body is a single forwarding call:
1 grep -rEn 'return \$this->(service|repo|repository)->[a-zA-Z]+\(' app/ | wc -l # Laravel
2 grep -rEn 'return s\.(repo|store)\.[A-Z][a-zA-Z]*\(ctx' internal/ | wc -l # Go
3 divide by the total number of public service methods; above ~50%: open a read pathStep 4 — catch an N+1 through layers (Laravel). In a Laravel 13 app with the PHP files from this page, add to a controller foreach ($order->lines as $l) { $l->product; } without eager loading, call the endpoint in local env. Expected: Illuminate\Database\LazyLoadingViolationException. Fix with $order->load('lines.product') in the action; add $this->expectsDatabaseQueryCount(3) to the feature test.
Step 5 — enforce layers in PHP. Run ./vendor/bin/pest tests/Arch and vendor/bin/deptrac analyse. Add use Illuminate\Support\Facades\DB; and a DB::table('orders')->count() call to PlaceOrderController. Expected: the "presentation does not reach persistence" expectation fails; deptrac reports nothing for the facade (it is not in a layer) — which is why both tools are useful.
Step 6 — graceful drain. Start the Go service, run hey -z 20s -c 20 -m POST -d '{"customer_id":1,"lines":[{"product_id":1,"quantity":1}]}' http://localhost:8080/orders (or any load tool), and send kill -TERM to the process mid-run. Expected: in-flight requests complete; new connections are refused; no 5xx from requests that were already accepted.
Common misconceptions
| Belief | Reality |
|---|---|
| Layers and tiers are the same | Layers are logical; tiers are physical. Fowler: "logical layers not physical tiers" |
| More layers = better architecture | Layers that only forward are the sinkhole anti-pattern |
| Hexagonal/clean/onion replace layering | They are layering with the persistence dependency inverted |
| The service layer holds the business logic | In Fowler/Evans it is thin; the domain holds the rules |
| Every Eloquent model needs a repository | Only when it adds something (batching, complex queries, a second backend) |
| Transaction script is always wrong | It is the right tool for simple domains (Fowler) |
| A layered monolith cannot scale | It scales horizontally if its layers are stateless; it scales as a whole |
| Layered architecture prepares you for microservices | Layers cut horizontally; services cut by domain. A modular monolith prepares you |
| Folders are layers | Only enforced dependency rules make a folder a layer |
| Open layers are a mistake | Documented open paths for reads are normal; undocumented ones rot |
| Layering costs performance | Calls cost nanoseconds; hidden queries (N+1) cost milliseconds |
| Separate frontend, backend and DB teams match the layers nicely | Fowler calls teams per layer an anti-pattern; teams should be cross-functional |
golang-standards/project-layout is the official Go layout | Its README says it is not; the official page is Organizing a Go module |
Cheat sheet
| Topic | Remember |
|---|---|
| Four layers | Presentation, application (service), domain (business), persistence (infrastructure) |
| Closed layer | Must pass through; gives layers of isolation |
| Open layer | May be skipped; document why, enforce the exception |
| Dependency rule | Imports point inward / downward only; the domain imports nothing |
| Hexagonal vs layered | Same layers; persistence implements a port owned by the inside |
| Domain logic | Transaction Script (simple), Domain Model (rich), Table Module (record sets) |
| Service layer | Thin: use cases + transaction; rules live in the domain |
| Sinkhole | Pass-through requests; some is fine, most is a smell (the "80-20" rule of thumb) |
| Layers vs tiers | Logical vs physical; a layered monolith is one tier |
| Partitioning | Layers = technical; split by domain when it grows (modular monolith) |
| Laravel shape | Route → Form Request → controller (__invoke) → action → model/domain → repository only if useful |
| Go shape | cmd/ → internal/httpapi → internal/app (ports) → internal/domain; internal/storage implements ports |
| Enforce | Go: no cycles, internal/, arch test, go-arch-lint; PHP: Pest arch(), deptrac |
| Test per layer | Domain unit, application with fakes/DB, persistence integration, HTTP feature, arch |
| Performance | Set-based ports, eager loading, preventLazyLoading, query-count tests |
| Deploy | One artifact, stateless instances, rolling or blue/green, graceful shutdown |
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 — Name the four layers and one thing that must never appear in each. Must-know
Answer
Answer: Presentation (no SQL, no business rules), application (no HTTP types), domain (no framework or I/O), persistence (no business decisions). See Layers.
2 — What is the difference between a closed and an open layer, and what does "layers of isolation" buy you? Important
Answer
Answer: A closed layer must be passed through; an open layer may be skipped. Closing layers keeps a change inside one layer as long as its interface holds. See Closed and open layers.
3 — Your controller calls a service that calls a repository that calls Order::find($id), and 80% of your endpoints look like this. What is it called, and what do you do? Must-know
Answer
Answer: The architecture sinkhole. Open a documented read path for rule-free queries, delete pass-through repositories, keep closed layers for writes. If nearly everything is CRUD, consider a simpler style for those areas. See Sinkhole.
4 — In one sentence, what does hexagonal architecture change compared with classic layering? Must-know
Answer
Answer: The domain/application no longer depends on persistence; persistence implements a port owned by the inside, so all source dependencies point inward. See the comparison.
5 — When is a transaction script the right choice, and what is an anemic domain model? Important
Answer
Answer: For simple, mostly CRUD logic. An anemic model has objects with data but no behaviour, with all logic in services; Fowler says it ends up as transaction scripts while paying the cost of a domain model. See Domain logic patterns.
6 — Where does the database transaction belong, and why not in the controller or repository? Important
Answer
Answer: In the application layer: one use case, one transaction. In the controller every entry point must repeat it; in a repository two repositories cannot share it. See Transaction boundary.
7 — Why can't a three-layer Laravel app be called "three-tier"? Must-know
Answer
Answer: All layers run in one process (one tier); tiers are physical deployment units. See Layers are not tiers.
8 — Which Go features give you layer checks for free, and which check needs a test? Good to know
Answer
Answer: Import cycles are illegal by spec and internal/ restricts importers. "App may not import httpapi" happens to be a cycle, but "domain may not import storage" when storage does not import domain, or "httpapi may not import storage", need an architecture test or go-arch-lint. See Go angle.
9 — Your GET /orders/42 page shows lines with product names and takes 50 queries. Which layer fixes it and how? Must-know
Answer
Answer: The application or persistence layer, where the query is decided: eager load lines.product (or one IN query), and make lazy loading fail outside production with preventLazyLoading. See Performance.
10 — Give three signs that your layered monolith should become a modular monolith. Important
Answer
Answer: Unrelated features touch the same Models/ and Controllers/ folders in every PR; god services importing each other; slow builds and rare, risky deploys; nobody can draw the layers. See When it degrades.
11 — What must be true of the layers for a blue/green or rolling deploy to work? Important
Answer
Answer: They must be stateless (sessions, files, caches outside the process), migrations must be backward compatible, and the process must drain on SIGTERM. See Scaling path.
Glossary
| Term | Meaning |
|---|---|
| Layer | A group of modules with one responsibility and the same allowed dependencies |
| Layered architecture | A style that stacks layers so upper layers use lower ones |
| Layered monolith | A single deployable application organised in layers |
| Presentation layer | Accepts input and renders output (controllers, handlers, views, CLI) |
| Application layer / service layer | Defines use cases and transaction boundaries; thin |
| Domain layer / business layer | Business concepts and rules |
| Persistence layer / infrastructure layer | Storage and external systems (DB, mail, APIs) |
| Closed layer (strict) | A layer that callers must pass through |
| Open layer (relaxed) | A layer callers may skip |
| Layers of isolation | Changes in one layer do not affect others while interfaces hold |
| Dependency rule | Source dependencies point inward only (Martin) |
| Dependency inversion | Making the lower layer implement an interface the upper layer owns |
| Port | An interface the application exposes or needs (hexagonal) |
| Adapter | An implementation connecting a port to a technology |
| Driving / primary adapter | Calls the application (HTTP handler, CLI, test) |
| Driven / secondary adapter | Called by the application (database, SMTP) |
| Hexagonal architecture | Cockburn's ports and adapters (2005) |
| Onion architecture | Palermo's concentric layers with the domain model at the center (2008) |
| Clean architecture | Martin's concentric circles governed by the dependency rule (2012) |
| Transaction Script | Business logic as one procedure per request |
| Domain Model | Objects that hold both behaviour and data |
| Table Module | One class handling business logic for all rows of a table |
| Active Record | Objects that load and save themselves (Eloquent) |
| Data Mapper | A separate layer moving data between objects and tables |
| Anemic domain model | Domain objects without behaviour; logic in services |
| Fat model / fat controller | Logic concentrated in models (can be fine) or controllers (bad) |
| Action | A Laravel community convention: one class per use case |
| Form Request | Laravel class holding validation rules and authorization for a request |
| Architecture sinkhole | Requests that pass through layers without any work |
| Tier | A physical deployment unit (process, host) |
| N-tier | An architecture split across several physical tiers |
| Technical partitioning | Top-level split by kind of code (layers) |
| Domain partitioning | Top-level split by business capability (modules) |
| Big ball of mud | A haphazardly structured system with no enforced boundaries |
| Modular monolith | One deployable split into domain modules with enforced boundaries |
| Composition root | The one place that wires concrete implementations (main, service providers) |
| Consumer-side interface | An interface declared in the package that uses it (Go idiom) |
internal/ | Go directory whose packages only the parent tree may import |
| Import cycle | Two packages importing each other; illegal in Go |
| Fitness function / architecture test | Automated check that an architectural rule holds |
| deptrac | PHP static analysis tool enforcing layer rules from deptrac.yaml |
| go-arch-lint | Go linter enforcing component dependencies from .go-arch-lint.yml |
Pest arch() | Pest's architecture testing expectations |
| N+1 query | One query for a list plus one per item, often hidden by lazy loading |
preventLazyLoading | Eloquent switch that throws on lazy loading |
| Cross-cutting concern | Behaviour needed in every layer (logging, auth, tracing) |
| Blue/green deployment | Two full environments; switch traffic at once, roll back by switching back |
| Rolling deployment | Replace instances one by one |
| Stateless layer | A layer that keeps no per-user state in process memory |
References
- Martin Fowler, "Presentation Domain Data Layering", 26 August 2015
- Martin Fowler, Patterns of Enterprise Application Architecture catalogue: Service Layer, Transaction Script, Domain Model, Table Module
- Martin Fowler, "Anemic Domain Model" (quotes Evans's layer definitions); "Monolith First", 3 June 2015
- Alistair Cockburn, "Hexagonal Architecture", 2005
- Jeffrey Palermo, "The Onion Architecture: part 1", 29 July 2008
- Robert C. Martin, "The Clean Architecture", 13 August 2012
- Microsoft, Azure Architecture Center, "N-tier architecture style"
- E. W. Dijkstra, "The structure of the 'THE'-multiprogramming system" (EWD196), 1968
- Brian Foote and Joseph Yoder, "Big Ball of Mud", PLoP '97
- Buschmann et al., Pattern-Oriented Software Architecture, Volume 1, Wiley 1996 — not read; strict/relaxed definitions via Wikipedia: Multitier architecture (secondary) and Wikipedia: Layer (object-oriented design) (secondary)
- Mark Richards and Neal Ford, Fundamentals of Software Architecture (O'Reilly) — book text not accessible; used Thoughtworks Technology Podcast: Architecture anti-patterns and pitfalls (primary, the authors speaking) and a chapter 10 summary (secondary); Mark Richards, Lesson 158 – Layered Architecture (video)
- Go: Organizing a Go module, Go 1.4 release notes (internal packages), The Go Programming Language Specification, Go Code Review Comments, golang-standards/project-layout
- Laravel 13: Directory Structure, Service Providers, Controllers, Validation (Form Requests), Eloquent, Eloquent Relationships (preventing lazy loading), Events, Queues, HTTP Tests, Database Testing, Database, Octane
- Pest: Architecture Testing; deptrac; go-arch-lint; lorisleiva/laravel-actions