Skip to content

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 forGo to
The whole chapter in three tablesEverything in one minute
Why anyone layers softwareWhy it exists
Dijkstra 1968, POSA 1996, PoEAA 2002, Cockburn 2005, Palermo 2008, Martin 2012Where it comes from
Presentation, application, domain, persistenceLayers
Closed vs open, layers of isolationClosed and open layers
Which way imports may pointThe dependency rule
Hexagonal, clean, onion: same or different?Layered vs hexagonal vs clean vs onion
Transaction script, domain model, table moduleDomain logic patterns
Service layer / application layerService layer
Layers that do nothingArchitecture sinkhole
Layers vs tiers, n-tierLayers are not tiers
Technical vs domain partitioning, big ball of mudPartitioning
Logging, auth, transactions across layersCross-cutting concerns
Request path, data shapes, errors, enforcement, tests, performanceMechanics
Ordering system as a layered Go serviceGo
Ordering system as a layered Laravel appLaravel
Fat controllers, sinkholes, N+1, side effects, violationsSolving the classic problems
When layered is right, when it rots, how to migrateChoosing
Monolith → modular → microservices → distributed, deploymentIn architecture
Hands-onLab
Wrong beliefs, summary, test yourself, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four layers. Every row is unpacked in Layers.

LayerAnswers the questionLaravel 13GoMust not contain
PresentationHow does the outside world talk to us?Routes, middleware, controllers, Form Requests, API Resources, Blade, Artisan commandsnet/http handlers, CLI flags, gRPC serversSQL, business rules
Application (service)Which use case is this, and in which transaction?Actions / services (App\Actions\PlaceOrder), jobs that call theminternal/app use-case typesHTTP types, SQL
Domain (business)What are the rules?Eloquent models with behaviour, App\Domain\* value objects and policiesinternal/domain structs and methodsFramework imports, I/O
Persistence (infrastructure)How is state stored and fetched?Eloquent queries, repositories, query builder, external API clientsinternal/storage/postgres, database/sql, pgxBusiness decisions

Vocabulary.

TermIn plain wordsTiny exampleWhat goes wrong without it
Closed layerYou must go through itController → service → repositoryEvery layer reaches everywhere: no isolation
Open layerCallers may go around itA read-only query path the controller calls directlyCeremony: five classes for one SELECT
Layers of isolationA change in one layer stays in that layerSwap MySQL for PostgreSQL, only persistence changesA column rename touches controllers
Dependency ruleImports point one way onlyapp imports domain, never the reverseCycles, untestable domain
Service layerThin layer that defines the use cases and the transactionPlaceOrder::handle()Transaction logic copied into each controller
SinkholeA request that passes every layer without workfind($id) forwarded three timesCost of layers without their benefit
TierA physical deployment unitWeb servers, DB serverConfusing logical design with network hops
Architecture testA test that fails on a forbidden importPest arch(), deptrac, Go go/parser testRules 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):

StrongWeak
Simple to understand, every developer knows itOne deployment unit: all or nothing
Cheap to start; frameworks generate itTechnically 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 layersLong 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 layersWith layers
Faster for the first weekFaster 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 databaseTesting a rule is a plain function call
A second entry point (CLI, queue) copies the logicA second entry point calls the same use case
Fewer files, more lines per fileMore files, fewer lines per file, some ceremony
Good for: a 200-line prototypeGood 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 ​

  1. "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.
  2. "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".
  3. "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.

text
     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 partitioning

The 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:

  1. Presentation (user interface): accepts input, renders output. Laravel's own docs describe its Http and Console directories 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."
  2. 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."
  3. 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."
  4. 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).

text
     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:

PlatformHow layers are expressedEnforced by
Laravel 13Namespaces under app/: Http, Actions, Models, Domain, RepositoriesConvention; Pest arch(), deptrac
GoPackages under internal/: httpapi, app, domain, storageCompiler: no import cycles, internal/; go-arch-lint, go/parser tests
Java / SpringPackages, @Controller / @Service / @Repository stereotypes, JPMS modulesArchUnit, JPMS exports
.NETSeparate projects (assemblies) per layerProject references (the compiler refuses cycles), NetArchTest
Ruby on Railsapp/controllers, app/models, app/servicesConvention; 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."
All layers closedOne open layerPresentationcontrollers, views, JSONBusinessuse cases, rulesPersistencerepositories, SQLDatabasePresentationBusinessServices (OPEN)shared utilities, audit, mailPersistenceDatabaseforbidden:skips Businessallowed:skips theopen layerEach layer talks only to the one directly below.Change in Persistence stops at Business: layers of isolation.Open = callers may go around it. Document which layers are open and why.

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.

text
     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 -> JSON

Real 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 / toolHow you mark a layer closed or open
deptracruleset: lists, per layer, the layers it may depend on; anything not listed is a violation
go-arch-lintdeps: <component>: mayDependOn: [...]
Pestarch()->expect('App\Http')->not->toUse('App\Repositories') closes the path
Go compilerNo 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.
text
     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:

PlatformMechanism for inverting a dependency
GoInterfaces 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."
LaravelInterface in App\Domain or App\Contracts, implementation bound in a service provider ($this->app->bind(...)); the container autowires constructors
Java / SpringInterface in the domain module, @Repository implementation in infrastructure, injected by Spring
.NETInterface 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).

Layered (top-down)Hexagonal / Onion / Clean (inside-out)Presentationhandler, controllerApplication / Serviceuse cases, transactionsDomainentities, rulesPersistenceSQL, ORMDomain depends on persistence (down)Persistence moves to the right-hand adaptersDomainentities, rulesApplicationuse cases + portsHTTP handlerCLI / Artisanqueue consumertest harnessPostgreSQLSMTPpayment APIdriving adaptersdriven adaptersEvery arrow points inward: adapters implement or call ports; the domain imports nothing

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.

AspectClassic layered (Fowler 2015, Richards)Hexagonal / Ports & Adapters (Cockburn 2005)Onion (Palermo 2008)Clean (Martin 2012)
PictureHorizontal stackHexagon, inside vs outsideConcentric ringsConcentric circles
CenterDatabase at the bottomApplicationDomain ModelEntities
RuleUpper uses lowerOutside reaches inside only through ports"all coupling is toward the center""source code dependencies can only point inwards"
Where the DB livesBottom layerSecondary adapterOuter ring ("The database is not the center. It is external.")Frameworks and drivers (outermost)
Interfaces for persistenceOptionalPorts (required)Repository interfaces in the coreGateways owned by use cases
Number of layers3–5Inside + adapters"will vary""the circles are schematic" (4 typical)
Explicit about testsNoYes, tests are a primary actorTests in the outer ringUse cases testable without UI or DB
Recommended forMost CRUD-heavy productsApps 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):

PatternFowler's one-line definitionShape in codeFits 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 constructorsMany 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 setRecord-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 aboveSeveral 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".

text
     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 set

Real 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:

PlatformNatural defaultPushing toward a domain model
LaravelActive Record (Eloquent) + transaction scripts in controllers or actionsBehaviour methods on models, value objects via custom casts, App\Domain pure classes
GoTransaction scripts in services over database/sqlDomain structs with methods, constructors that enforce invariants, data mapper in storage
RailsActive Record, "fat model"Service objects, domain objects (POROs)
Spring / JPAAnemic entities + @Service scripts (very common)Rich entities, aggregates (see DDD)
.NET / EF CoreAnemic entities + servicesRich 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."

text
     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); COMMIT

Real 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:

PlatformTypical name of the service-layer classTransaction primitive
LaravelAction (App\Actions\PlaceOrder), Service (OrderService), Job (when queued)DB::transaction(fn () => ...)
GoUse-case struct (app.PlaceOrder) or service (OrderService)db.BeginTx(ctx, nil) behind a TxRunner interface
Spring@Service with @TransactionalDeclarative transactions
.NETApplication service / MediatR handlerTransactionScope, DbContext.SaveChanges
RailsService object / interactorActiveRecord::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.

GET /orders/42 (sinkhole)POST /orders (real work)Controllerreturn service.find(id)Servicereturn repo.find(id)Repositoryreturn Order::find(id)DatabaseController + FormRequestvalidate, authorize, map 422Action / use casetransaction, rules, event after commitRepositoryone batched IN (...) query, mappingDatabaseEvery layer only forwards: cost of extra objects and indirection, no isolation gained.ratio20%100%pass-through/ all requestshigh = smell
text
     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 something

Real 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:

SignalHow to measureThreshold that should worry you
Pass-through methodsGrep service and repository methods whose body is one return $this->x->sameName(...) lineMore than half of all methods
Files touched per fieldgit log --stat on "add field X" commits5+ files for a field with no rules
Endpoints without rulesLabel each route: rules / no rulesMost routes have none
Interfaces with one implementation that is never mockedSearch for interface + single implementsInterfaces 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."

text
     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").

LayerTier
Kind of boundaryLogical (namespaces, packages)Physical (process, host, container)
Crossing costA function call (nanoseconds)A network call (sub-millisecond to many ms), serialisation
Failure between themExceptionsTimeouts, partial failure, retries
ScaledTogether, with the processIndependently
Typical count in a layered monolith3–51 (plus database, cache)
Owned byThis chapterClient-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".

text
     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 module

Real 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.

text
     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)
ConcernLaravel 13Go
Authenticationauth:sanctum middleware, Form Request authorize()Middleware that puts the user in context.Context
AuthorizationPolicies, GatesExplicit checks in the use case
TransactionsDB::transaction in the actionTxRunner.WithinTx in the use case
Logging and tracingLog facade, DB::listen, OpenTelemetry packageslog/slog, OpenTelemetry middleware
CachingCache::remember in a query object or decoratorDecorator implementing the same interface
ValidationForm 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 ​

text
     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 JSON

What crosses a boundary: data shapes per layer ​

BoundaryWhat goes downWhat comes upRule
Presentation → applicationA command/input object (PlaceOrderInput, validated array)Domain object or result DTONo Request, no http.Request below this line
Application → domainPlain values, domain objectsDomain objects, domain errorsNo DTOs from HTTP in the domain
Application → persistenceDomain objects, ids, criteriaDomain objects or read modelsNo *sql.Rows or query builders above this line
Presentation ← anything—Resource / response structJSON 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 ​

WhereError you will seeLayer that should translate itInto
Go buildimport cycle not allowed— (a design error: two layers import each other)Move the interface to the consumer
Go builduse 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
LaravelIlluminate\Database\LazyLoadingViolationExceptionDeveloper, in dev/CIEager load in the action or query
LaravelIlluminate\Validation\ValidationExceptionForm Request (presentation)422 with field errors
DomainOrderRejected / domain.ErrUnknownProductController / handler422 with a message
PersistenceUnique violation (SQLSTATE 23505, MySQL 1062)Repository or actionA domain error (DuplicateOrder)
Pestfailed arch() expectation naming the class and the forbidden dependency—Fix the dependency
deptraca 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.

ToolLanguageWhat you declareRuns in
Go compilerGoNothing: import cycles are illegal by spec ("It is illegal for a package to import itself, directly or indirectly"); internal/ limits importersgo build
go/parser testGoA map layer → allowed layers (arch_test.go on this page)go test
go-arch-lintGo.go-arch-lint.yml: components, deps.mayDependOngo-arch-lint check, CI
Pest arch()PHPexpect('App\Http')->not->toUse('App\Repositories'), toOnlyBeUsedIn, toOnlyUse, presets (preset()->laravel())./vendor/bin/pest
deptracPHPdeptrac.yaml: layers with collectors, rulesetvendor/bin/deptrac analyse, CI
ArchUnit / NetArchTestJava / .NETFluent layer rulesUnit 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 ​

LayerTest typeSpeedWhat it provesLaravelGo
DomainUnitmicrosecondsRules and invariantsPest unit test on Pricing, no app bootdomain/order_test.go, table-driven
ApplicationUnit with fakes or integration with a DBmsOrchestration, transaction, error mapping to domain errorsAction with RefreshDatabase (SQLite in memory or PostgreSQL)app/place_order_test.go with storage/memory
PersistenceIntegration10–100 msSQL is correct, N+1 absentRepository test + expectsDatabaseQueryCountstorage/postgres against a real PostgreSQL (testcontainers)
PresentationHTTP / featurems–100 msStatus codes, JSON contract, authpostJson()->assertCreated()httptest.NewRecorder on the real mux
ArchitectureFitnessmsLayer rulesPest 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:

text
     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.

go
// 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"):

text
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 runs

Domain layer. No imports from the project, no SQL, no HTTP. Invariants live in the constructor.

go
// 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
}
go
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.

go
// 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
}
go
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.

go
// 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()
}
go
// 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.

go
// 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.

go
// 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)
}
go
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.

go
// 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).

go
// 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)
	}
}
yml
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 featureRole in layeringSource
Package = layer unitImports are the dependency graph; visible in every file headerGo spec
No import cyclesA 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 interfacesThe application declares ports; persistence satisfies them implicitly, so the import still points inwardGo Code Review Comments
cmd/<name>One composition root per binary (web, worker, migrator)Organizing a Go module
context.ContextCarries deadlines, the transaction and request-scoped values across layers without globalscontext package
golang-standards/project-layoutPopular but unofficial; its README states it is "NOT an official standard defined by the core Go dev team" and points to the official layout pageGitHub README
/pkgOptional; for libraries meant for others. For a service, internal/ is the safer defaultSame 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
<?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 ​

text
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.yaml

Presentation 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
<?php

use App\Http\Controllers\PlaceOrderController;
use Illuminate\Support\Facades\Route;

Route::post('/orders', PlaceOrderController::class)->middleware('auth:sanctum');
php
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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');
yaml
# 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 featureLayerWhat to know
app/Http (controllers, middleware, requests)PresentationThe 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)Presentationauthorize() + rules(); $request->validated() hands clean data to the action
API ResourcesPresentationJSON contract independent of column names
Single action controllersPresentation__invoke; one class per endpoint keeps controllers thin
Actions / servicesApplicationNot a framework feature; a plain class resolved by the container. lorisleiva/laravel-actions is a community package for the same idea
DB::transactionApplicationOne use case, one transaction
Eloquent modelsDomain + persistenceActive Record: the model is both; keep rules as methods, keep HTTP/mail out
App\Domain\*DomainPure PHP classes and value objects; Pest can assert they use nothing from Illuminate
RepositoriesPersistenceOptional with Eloquent; add one for batched or complex queries, not to wrap find()
Events + ShouldDispatchAfterCommitApplication → infrastructureSide effects after commit; listeners ShouldQueue
Jobs (make:job)Presentation (entry point) or infrastructureA job is another way in; it should call an action, not hold rules
Service providersComposition root"the central place of all Laravel application bootstrapping"; registered in bootstrap/providers.php
Model::preventLazyLoading()Persistence guardThrows LazyLoadingViolationException; use outside production
Pest arch() / deptracEnforcementLayer rules as tests in CI

The "fat model vs service" debate. Both camps are partly right; the question is which logic.

LogicPut it inWhy
A rule about one model's own data (cancel() only when placed, total())Model method or App\Domain classKept next to the data; reusable from every use case
A rule spanning several models (stock + order + coupon)Action (application layer) or a domain serviceNo single model owns it
A workflow with a transaction and side effectsActionTransaction and ordering of effects are application concerns
Queries for screensQuery object, scope, or controller with Resource (open read path)No rules; layers would be a sinkhole
HTTP, mail, queues, files inside a modelNowhere in the modelThat 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) ​

SolutionHowAdvantageCost / limitation
Extract an actionMove the body into PlaceOrder::handle, controller only mapsReusable from CLI/queue/testsOne more class per use case
Form RequestShape validation and authorization out of the controllerController becomes 5 linesBusiness validation still belongs to domain
Domain methodsRules on the model or App\DomainRules exist onceNeeds discipline in reviews
Arch testexpect('App\Http')->not->toUse('Illuminate\Support\Facades\DB')Stops regressionMust be kept in CI

The sinkhole ​

SolutionHowAdvantageCost / limitation
Open read pathQuery objects / internal/query called from presentationNo ceremony for screensMust be documented and test-enforced
Delete pass-through repositoriesUse Eloquent directly in actionsFewer filesPersistence is now Eloquent (fine for most apps)
Merge layersApplication + domain as one "business" layer for CRUD areasSimpleLoses isolation where rules later appear
Change style for CRUD areasAdmin generator (Filament, Nova)Hours, not daysAnother 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 ​

SolutionHowAdvantageCost / limitation
Set-based portsPricesFor(ids), ProductPrices::for($ids)One query per use case stepPorts become less "pure CRUD"
Eager loadingwith('lines.product') in the action/queryConstant query countMust know the shape needed
Prevent lazy loadingModel::preventLazyLoading(! $this->app->isProduction())N+1 fails in dev/CILegacy code throws until fixed
Query count testsexpectsDatabaseQueryCount(n); Go: count queries in a test driver/tracerRegression-proofBrittle 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.

sql
-- 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 ​

SituationRecommendationExtra techniqueReason
New product, unclear domainLayered monolithArch tests from day oneCheapest 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 monolithActions + domain methodsOne mental model, one deploy
CRUD-heavy back officeThin layers, open read pathsAdmin generator for pure CRUDAvoid the sinkhole
Rich rules (billing, insurance, logistics)Layered with ports (hexagonal)Domain model, ports for persistenceRules testable without infrastructure
Several teams, clear business areasModular monolithModules internally layeredTechnical partitioning stops scaling with people
Independent scaling or deploy cadence per areaExtract services from a modular monolithStrangler figOnly when the premium is worth it
Tight budget, deadlineLayered monolithFramework conventionsRichards & Ford rate cost and simplicity as the style's strengths (summary)

When it degrades ​

Warning signWhat it meansNext step
Every PR touches Models/ and Controllers/ of unrelated featuresTechnical partitioning has stopped scalingSplit by domain at the top level
app/Services has 100+ classes importing each otherGod services, hidden cyclesActions per use case; deptrac to find cycles
Build/test suite above 15–20 minutesOne unit of change for everythingModules with their own test suites
Deploys weekly at best, release trainsRisk per deploy too highSmaller changes, feature flags, then modules
One hot endpoint forces scaling the whole appScale only as a wholeSeparate process for that path (worker, read service)
Nobody can draw the layersBig ball of mudWrite the layer ADR, add arch tests, fix violations incrementally

Migration path to a modular monolith ​

text
     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-microservices

The 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× ​

LoadbalancerBLUE v41 (live)GREEN v42 (warming)PostgreSQL primarywrites, migrationsRead replicaquery / report pathsRedissessions, cache, queuewebpresentationapplicationdomainpersistencewebpresentationapplicationdomainpersistenceworker(same image)applicationdomainpersistencewebsame layersnew codewebsame layersnew codeworkersame imagenew codeswitch afterhealth checksone artifact, N stateless copies;state lives only in the stores
LoadShapeWhat changes in the layers
1× (hundreds of req/s)2 instances behind a load balancer, one PostgreSQLNothing; 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 tablesThe 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):

sql
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.

text
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:

text
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 path

Step 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 ​

BeliefReality
Layers and tiers are the sameLayers are logical; tiers are physical. Fowler: "logical layers not physical tiers"
More layers = better architectureLayers that only forward are the sinkhole anti-pattern
Hexagonal/clean/onion replace layeringThey are layering with the persistence dependency inverted
The service layer holds the business logicIn Fowler/Evans it is thin; the domain holds the rules
Every Eloquent model needs a repositoryOnly when it adds something (batching, complex queries, a second backend)
Transaction script is always wrongIt is the right tool for simple domains (Fowler)
A layered monolith cannot scaleIt scales horizontally if its layers are stateless; it scales as a whole
Layered architecture prepares you for microservicesLayers cut horizontally; services cut by domain. A modular monolith prepares you
Folders are layersOnly enforced dependency rules make a folder a layer
Open layers are a mistakeDocumented open paths for reads are normal; undocumented ones rot
Layering costs performanceCalls cost nanoseconds; hidden queries (N+1) cost milliseconds
Separate frontend, backend and DB teams match the layers nicelyFowler calls teams per layer an anti-pattern; teams should be cross-functional
golang-standards/project-layout is the official Go layoutIts README says it is not; the official page is Organizing a Go module

Cheat sheet ​

TopicRemember
Four layersPresentation, application (service), domain (business), persistence (infrastructure)
Closed layerMust pass through; gives layers of isolation
Open layerMay be skipped; document why, enforce the exception
Dependency ruleImports point inward / downward only; the domain imports nothing
Hexagonal vs layeredSame layers; persistence implements a port owned by the inside
Domain logicTransaction Script (simple), Domain Model (rich), Table Module (record sets)
Service layerThin: use cases + transaction; rules live in the domain
SinkholePass-through requests; some is fine, most is a smell (the "80-20" rule of thumb)
Layers vs tiersLogical vs physical; a layered monolith is one tier
PartitioningLayers = technical; split by domain when it grows (modular monolith)
Laravel shapeRoute → Form Request → controller (__invoke) → action → model/domain → repository only if useful
Go shapecmd/ → internal/httpapi → internal/app (ports) → internal/domain; internal/storage implements ports
EnforceGo: no cycles, internal/, arch test, go-arch-lint; PHP: Pest arch(), deptrac
Test per layerDomain unit, application with fakes/DB, persistence integration, HTTP feature, arch
PerformanceSet-based ports, eager loading, preventLazyLoading, query-count tests
DeployOne artifact, stateless instances, rolling or blue/green, graceful shutdown

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
LayerA group of modules with one responsibility and the same allowed dependencies
Layered architectureA style that stacks layers so upper layers use lower ones
Layered monolithA single deployable application organised in layers
Presentation layerAccepts input and renders output (controllers, handlers, views, CLI)
Application layer / service layerDefines use cases and transaction boundaries; thin
Domain layer / business layerBusiness concepts and rules
Persistence layer / infrastructure layerStorage 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 isolationChanges in one layer do not affect others while interfaces hold
Dependency ruleSource dependencies point inward only (Martin)
Dependency inversionMaking the lower layer implement an interface the upper layer owns
PortAn interface the application exposes or needs (hexagonal)
AdapterAn implementation connecting a port to a technology
Driving / primary adapterCalls the application (HTTP handler, CLI, test)
Driven / secondary adapterCalled by the application (database, SMTP)
Hexagonal architectureCockburn's ports and adapters (2005)
Onion architecturePalermo's concentric layers with the domain model at the center (2008)
Clean architectureMartin's concentric circles governed by the dependency rule (2012)
Transaction ScriptBusiness logic as one procedure per request
Domain ModelObjects that hold both behaviour and data
Table ModuleOne class handling business logic for all rows of a table
Active RecordObjects that load and save themselves (Eloquent)
Data MapperA separate layer moving data between objects and tables
Anemic domain modelDomain objects without behaviour; logic in services
Fat model / fat controllerLogic concentrated in models (can be fine) or controllers (bad)
ActionA Laravel community convention: one class per use case
Form RequestLaravel class holding validation rules and authorization for a request
Architecture sinkholeRequests that pass through layers without any work
TierA physical deployment unit (process, host)
N-tierAn architecture split across several physical tiers
Technical partitioningTop-level split by kind of code (layers)
Domain partitioningTop-level split by business capability (modules)
Big ball of mudA haphazardly structured system with no enforced boundaries
Modular monolithOne deployable split into domain modules with enforced boundaries
Composition rootThe one place that wires concrete implementations (main, service providers)
Consumer-side interfaceAn interface declared in the package that uses it (Go idiom)
internal/Go directory whose packages only the parent tree may import
Import cycleTwo packages importing each other; illegal in Go
Fitness function / architecture testAutomated check that an architectural rule holds
deptracPHP static analysis tool enforcing layer rules from deptrac.yaml
go-arch-lintGo linter enforcing component dependencies from .go-arch-lint.yml
Pest arch()Pest's architecture testing expectations
N+1 queryOne query for a list plus one per item, often hidden by lazy loading
preventLazyLoadingEloquent switch that throws on lazy loading
Cross-cutting concernBehaviour needed in every layer (logging, auth, tracing)
Blue/green deploymentTwo full environments; switch traffic at once, roll back by switching back
Rolling deploymentReplace instances one by one
Stateless layerA layer that keeps no per-user state in process memory

References ​

Built by Morteza Negahi