Layered Architecture
- NestJS
- Node.js
Organising an application into horizontal layers — presentation, business logic, and data access — each with a clear responsibility and a one-directional flow.
Prerequisites
- Controllers and services (see Related Topics)
What you'll understand
- What the layers in a layered architecture are
- Why each layer has one responsibility
- How the one-directional flow keeps the system organised
Explanation
Layered architecture organises an application into horizontal layers, each with a single responsibility, stacked so that each layer talks only to the one below it. The classic three are the presentation layer (handling requests and responses), the business logic layer (the rules of the application), and the data access layer (talking to the database). You have already built these: controllers, services, and repositories map straight onto them (see Related Topics).
The value is separation of concerns made concrete. Each layer knows only its own job and depends only on the layer beneath it: presentation calls business logic, business logic calls data access, and data access talks to the database. A request flows down through the layers and a response flows back up. Because responsibilities are cleanly divided, you can change how one layer works, swap the database, restructure the API, without disturbing the others.
Layered architecture is the most common way backends are structured because it is simple and effective. Its main discipline is respecting the direction of dependencies: a lower layer must never call up into a higher one, and layers should not be skipped (a controller should not reach straight into the database). Keeping that flow one-directional is what prevents the layers from tangling back into the mess they were meant to avoid, an idea taken further by clean architecture (see Related Topics).
Examples
A request flows down through the layers and the response flows back up:
Presentation (Controller) -> handles HTTP, no business rules
|
Business Logic (Service) -> the application rules
|
Data Access (Repository) -> talks to the database
|
DatabaseCommon mistakes
- Skipping layers, such as a controller querying the database directly.
- Leaking business rules into the presentation or data layer.
- Letting a lower layer depend on a higher one.
- Making layers so thin they only pass calls through without adding value.
Best practices
- Give each layer one clear responsibility.
- Keep dependencies one-directional: each layer uses only the one below.
- Route every request through the layers rather than skipping them.
- Keep business rules in the business layer, not the edges (see Related Topics).
Further reading
- Microsoft, N-tier architecture style — https://learn.microsoft.com/en-us/azure/architecture/guide/architecture-styles/n-tier
- Martin Fowler, PresentationDomainDataLayering — https://martinfowler.com/bliki/PresentationDomainDataLayering.html