Layered Architecture
Presentation, application, domain, and infrastructure - the dependency rules that keep a codebase understandable as it grows.
A layered architecture slices a codebase horizontally, gives each slice one job, and restricts which slices may know about which. It earns its place as the default architecture by answering the two questions that dominate maintenance cost: where does this code go? and what breaks if I change this?
The four layers
| Layer | Job | Typical contents |
|---|---|---|
| Presentation | Translate between the outside world and the application | HTTP controllers, views, request/response DTOs, input validation of shape |
| Application | Orchestrate use cases | Use-case services, transaction boundaries, authorization checks |
| Domain | Business rules — the reason the software exists | Entities, value objects, domain services, repository interfaces |
| Infrastructure | Talk to technology | Database access, message queues, external API clients, email senders |
Presentation code decides how to say it, never what is true. A controller parses an HTTP request into a command and renders the result; it should not know that an order with shipped items cannot be cancelled.
Application code decides what happens: it loads the order, asks it to cancel itself, saves it, and publishes an event — inside one transaction. It coordinates but holds no business rules of its own.
Domain code decides what is allowed. The Order entity knows its own cancellation rules; this is Information Expert applied at scale — put the rule next to the data it governs.
Infrastructure is everything you would rewrite if you swapped Postgres for DynamoDB or Stripe for Adyen.
The dependency rule
The whole scheme rests on one rule: source-code dependencies point downward (or inward) only. Presentation may depend on application, application on domain. The domain depends on nothing above it — no HTTP types, no ORM annotations, no queue clients.
Why this direction? Business rules change for business reasons; frameworks and databases change for technical ones. If the stable core depends on the volatile edge, every vendor migration ripples through your rules. Reverse the arrows and the edge can churn while the core stands still. (If you sketch this as a package diagram, the layer-to-layer arrows are ordinary UML dependencies — the rule is a design convention layered on top of that notation, not something UML itself enforces.)
Keeping the domain free of infrastructure
The domain still needs persistence. The trick is ownership: the domain (or application) layer declares an interface, and infrastructure implements it.
// domain/orders/order-repository.ts — the domain owns this contract
export interface OrderRepository {
findById(id: OrderId): Promise<Order | null>;
save(order: Order): Promise<void>;
}// infrastructure/persistence/postgres-order-repository.ts
export class PostgresOrderRepository implements OrderRepository {
constructor(private readonly db: Pool) {}
async findById(id: OrderId): Promise<Order | null> {
const row = await this.db.query(SELECT_ORDER, [id.value]);
return row ? OrderMapper.toDomain(row) : null;
}
async save(order: Order): Promise<void> {
await this.db.query(UPSERT_ORDER, OrderMapper.toRow(order));
}
}At runtime, calls flow from application code into Postgres. At compile time, the arrow points the other way: infrastructure imports the domain's interface. This is the Dependency Inversion Principle at architecture scale, and it is what makes the core testable — a use case runs against an in-memory fake with no database in sight.
Strict vs relaxed layering
Must every call pass through the layer directly below, or may a layer skip ahead? Both conventions exist; neither is a formal rule, and teams should pick one deliberately.
| Strict layering | Relaxed layering | |
|---|---|---|
| Rule | Each layer calls only the layer immediately below | A layer may call any layer beneath it |
| Simple read screens | Controller -> application service -> repository, even for a plain list | Controller queries a read model or repository directly |
| Cost | Pass-through methods that add nothing | Easier to smuggle logic into controllers |
| Benefit | Uniform structure; every seam is mockable | Less ceremony where there is nothing to protect |
A pragmatic middle ground — sometimes called CQRS-lite — lets reads bypass the domain (a query handler returning DTOs straight from SQL) while all writes go through application and domain layers, because writes are where the invariants live.
What layers buy you, and what they cost
Reach for it
- A single team owns one deployable application with real business rules
- You want the domain testable without a database or web server
- You expect to replace edges like the ORM or a payment provider over the system lifetime
Avoid it
- A thin CRUD tool where every layer would only forward calls
- A throwaway prototype where structure slows discovery
- A script or integration glue with no domain logic to protect
The benefits are navigability (a new developer can predict where cancellation rules live), a testable core, and replaceable edges. The honest costs: in small applications you pay for mapping boilerplate — DTO to command to entity to row — and pass-through methods that exist only to satisfy the diagram. Worse is the anemic failure mode: four folders of ceremony while the entities are bare data bags and the rules sit in services or controllers anyway. Layers that protect nothing are pure overhead.
When layers are enough
For most single-team applications, they are. One process, in-process calls, one database, clear internal boundaries — that combination handles far more load and complexity than teams expect. Reach for distribution only when independent deployment or independent scaling of parts becomes a genuine organizational need; see microservices trade-offs for that decision. Well-layered monoliths also split far more safely than tangled ones.
Common mistakes
- Domain entities importing ORM or framework types. The moment
Ordercarries persistence annotations, the schema and the framework dictate your model, and the core is no longer independently testable. - Business rules in controllers. An
ifguarding cancellation inside an HTTP handler is invisible to every other entry point — the message consumer and the admin CLI will each grow their own, slightly different, copy. - Layers by folder name only. Directories called
domainandinfrastructuremean nothing if imports cross freely in both directions. Enforce the arrows with lint rules or module boundaries, not intentions.
Practice
Take a hotel booking feature: a BookingController that checks room availability, applies a no-overlap rule, writes a row with an ORM call, and sends a confirmation email — all in one method. Split it into the four layers: define a Booking entity that owns the overlap rule, a BookingRepository interface owned by the domain, an application service that runs the use case in a transaction, and infrastructure classes for the ORM and email. Then write one unit test for the overlap rule that runs with no database, and check every import to confirm no arrow points upward.