# Layered Architecture

**Also known as:** N-Layer  
**Category:** Application Architecture (Mid)  
**Complexity:** 1/5  
**Guide:** https://layra4.dev/architectures/application/layered

*Stack the code in horizontal layers, each calling only the one below.*

Layered architecture splits the code inside one app by technical job. Presentation sits on top, business logic in the middle and data access at the bottom. Each layer calls only the layer below it. A request enters at the top, goes down to the database, and the result comes back up.

It is easy to learn, but it has one flaw: the business layer imports the data layer, so your rules depend on the database. Onion and Clean keep the layers and reverse that one arrow. N-Tier keeps the arrow and runs the layers on different machines.

> **In one sentence.** Give each technical job its own layer, so screens, rules and storage each have one home, and every call goes one step down the stack.

## Origin

Layering is as old as structured software; the OSI network stack is the classic example. The inverted descendants came later: Hexagonal (Alistair Cockburn, 2005), Onion (Jeffrey Palermo, 2008) and Clean (Robert C. Martin, 2012).

## The layers

### Presentation layer (UI / API)

The entry point: HTTP controllers, a CLI or UI screens. It turns a request into a call on the business layer and formats the result. It holds no business rules.

- Routes, controllers, request parsing
- Calls business logic, never the reverse

### Business-logic layer (domain / service)

The rules and use cases, such as “an order needs at least one line”. In a plain stack it calls down into data access, so it cannot compile without it. Onion and Clean exist to remove that dependency.

- Use cases and domain rules
- Should be the most stable code

> placeOrder.ts imports OrderRepository from ../data/ — the rules now need SQL to compile.

### Data-access layer (persistence)

Repositories, SQL queries and ORM mappings. It hides how data is stored, so the layers above call save(order), not INSERT.

- Repositories, SQL, ORM
- The layer most often replaced

### Closed vs. open layering (strict vs. relaxed)

In closed layering a layer may call only the layer directly below. In open layering it may skip layers. Closed is the safer default, because a change in one layer then reaches only its neighbour.

> Closed: Presentation → Business → Data. Presentation → Data is not allowed.

## Doing layering well

### Keep business rules in the middle layer

Not in a controller and not in a stored procedure. Rules that leak out of the business layer are the most common way a layered app stops being layered.

### Call only the layer directly below

Presentation calls business, and business calls data. A controller that queries the database directly skips the rules and ties the screen to the table layout.

### Delete pass-through layers

A layer whose methods only forward the call to the next one adds files and no isolation. Give it a real job or remove it. The number of layers is not the goal.

### Invert the bottom arrow when the rules earn it

When the rules are worth testing without a database, let the business layer declare the repository interface and the data layer implement it. That one change turns this stack into Onion.

## Diagrams

Rendered as geometry on the guide page; not reproducible as text.

- `layered-inversion` — see https://layra4.dev/architectures/application/layered

## The stack, on disk

```
src/
presentation/                   # top layer — HTTP in, JSON out; no rules
  orderController.ts
business/                       # the rules; calls only down, into data/
  placeOrder.ts                 # imports data/ — the flaw Onion fixes
data/                           # bottom layer — repositories, SQL, ORM
  orderRepository.ts
index.ts                        # wires the stack and starts the server
```

Folders map one to one onto layers, and every import points down. Compare the import in business/ with the tree on the Onion page.

## Examples

### Classic layering — the dependency points down, into the database

```typescript
// ── data/orderRepository.ts — the data-access layer (bottom) ──
export class OrderRepository {
  constructor(private db: Db) {}
  async save(o: Order) { await this.db.query(/* ... */); }
}

// ── business/placeOrder.ts — depends downward on the concrete repo ──
import { OrderRepository } from "../data/orderRepository";   // ← the flaw
export function placeOrder(repo: OrderRepository) {
  return async (cmd: PlaceOrder) => {
    const order = Order.create(cmd);
    await repo.save(order);          // the rules now need the data layer to compile
  };
}
```

Each layer calls the one below. The use case imports the concrete repository, so the business rules depend on the database code.

## When to use

- A small or CRUD-style app where a top-down stack is easy to follow
- A team new to the code: layers are the most widely known structure
- You want structure now and may invert the data dependency later

## When not to use

- One change usually edits every layer: vertical slices fit better
- The rules are worth testing without a database: use Onion or Clean
- The logic is thin CRUD: a transaction script may be enough

## Benefits

- The most familiar structure; new developers find their way quickly
- A clear split by technical job: screens, rules, storage
- An easy step to Onion later: you move one interface, not every folder

## Costs

- Business rules depend on the database, so their tests usually need one
- One feature is spread across every layer, so a change touches them all
- Pass-through layers add files and no value

## Pitfalls

- Pass-through layers: a service whose methods only call the repository. Every change then edits three files that say the same thing.
- Rules leaking into controllers or stored procedures. The same check ends up in two places, and the two copies disagree.
- Open layering everywhere: controllers import repositories, and the stack becomes a tangle.
- Counting layers as quality. Four thin layers are worse than two real ones.

## Similar patterns, compared

Onion, Clean and N-Tier are this stack with one thing changed, and Hexagonal solves the same problem from a different start. That is why the names get mixed up. Each difference is small enough to state in one line.

### The family at a glance

| Pattern | What it separates | Dependencies point | What the boundary costs | Use it when |
| --- | --- | --- | --- | --- |
| **Layered Architecture** | Code by technical job: presentation, business logic, data access | Down: business logic imports data access | Nothing. Layers are folders and imports, not network calls | The default: a small or CRUD-style app, or a team new to the code |
| [Onion Architecture](https://layra4.dev/architectures/application/onion) | The same layers, drawn as rings around the domain | In: infrastructure imports the domain | Interfaces move into the domain, plus one place that wires them up | The business rules are worth testing without a database |
| [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture) | The same rings, with business rules split into entities and use cases | In, on the output side too, through presenter interfaces | An interface and a plain data object at every crossing | A long-lived app whose framework will change |
| [N-Tier](https://layra4.dev/architectures/application/n-tier) | Where the code runs: the same layers, on separate machines | Still down, but now over a network | A network hop at each boundary: latency, serialization, partial failure | An untrusted client, separate scaling, or a hard security boundary |
| [Hexagonal](https://layra4.dev/architectures/application/hexagonal) | Inside from outside: no top or bottom, ports on the edge | In from every side; callers and called systems treated the same | A port and at least one adapter per capability | Several callers or storage options, with tests as one more caller |
| [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice) | One feature from another: a folder is a use case, not a technical job | Along the slice, then down into a small shared core | Some duplication between slices, and no layer for shared concerns | Work arrives one feature at a time, and each change touches every folder |

Onion, Clean and N-Tier all come from Layered. Hexagonal reaches the same inward arrows from another starting point. Four of the six are the same code with the arrows turned. N-Tier is the one that puts a network between the layers, and Vertical Slice is the one that names folders after features instead.

### Layered Architecture vs Onion Architecture

The same stack with one arrow reversed. The folders barely move; the domain moves to the centre. — [Onion Architecture](https://layra4.dev/architectures/application/onion)

**What is genuinely the same**

- The same split: delivery, business rules, persistence
- One process, one deployable
- Technical job is still how folders are named

**What actually differs**

- Here business code imports data access; in Onion that import is forbidden
- Onion puts the repository interface in the core, and persistence implements it
- An Onion domain compiles and tests with no database; a layered one usually cannot

**Pick Layered Architecture when:** The logic is thin, so protecting it from the database buys nothing. You can still invert later as a refactor, not a rewrite.

### Layered Architecture vs Clean Architecture

Onion's inversion written as a strict rule, with the business layer split in two and the output side inverted too. — [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture)

**What is genuinely the same**

- The same split of delivery, rules and persistence
- One process; the rings are folders, not machines

**What actually differs**

- Clean's Dependency Rule is strict and can be checked by a tool
- Clean splits the middle into Entities and Use Cases
- Clean also inverts the output: a use case calls a presenter instead of returning a value

**Pick Layered Architecture when:** A folder convention is enough discipline. Clean's extra interfaces pay only where someone will enforce the rule.

### Layered Architecture vs N-Tier

The same layers with deployment boundaries between them. A layer is free; a tier costs a network hop. — [N-Tier](https://layra4.dev/architectures/application/n-tier)

**What is genuinely the same**

- The same layers, cut along the same lines
- Dependencies still point down
- Each tier is usually layered inside

**What actually differs**

- A layer is a boundary the compiler sees; a tier is one the network sees
- Crossing a tier adds latency, serialization and partial failure
- Only a tier is a security boundary; layers protect nothing at run time

**Pick Layered Architecture when:** You cannot name what a physical split would buy. Layers are the cheap half, and they keep the split possible later.

### Layered Architecture vs Hexagonal

Hexagonal drops the stack: no top and no bottom, only an inside and an outside with ports between them. — [Hexagonal](https://layra4.dev/architectures/application/hexagonal)

**What is genuinely the same**

- Business rules live in one place, apart from I/O
- One deployable; the difference is in the source, not the topology

**What actually differs**

- Layers put the UI on top and the database at the bottom; Hexagonal treats both as outside
- In Hexagonal the core owns every interface it uses
- A test is just another driving adapter, so the app runs with no infrastructure

**Pick Layered Architecture when:** There is one driver and one database, and there always will be. The plain stack is simpler to read for the same result.

### Layered Architecture vs Vertical Slice

Not this stack rearranged: the same work, but folders are named after features instead of technical jobs. — [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice)

**What is genuinely the same**

- The same jobs exist: parse the request, apply rules, reach the data
- One process; both are source conventions with no run-time cost
- Both need a home for rules that several features share

**What actually differs**

- Here a folder is a technical job and a feature is spread across all of them; there it is the reverse
- A layer applies to every feature; each slice chooses its own depth
- Layers make “show me every repository” easy; slices make “show me all of checkout” easy

**Pick Layered Architecture when:** People read the code by technical job, as in a library or a driver. Or the app is so small that a change rarely leaves one folder.

## Related patterns

- [Onion Architecture](https://layra4.dev/architectures/application/onion) — the same layers as rings, with dependencies pointing inward
- [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture) — the inward rule made strict and given named rings
- [N-Tier](https://layra4.dev/architectures/application/n-tier) — the same layers, deployed on separate machines
- [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice) — the other axis: split by feature instead of by layer
- [Transaction Script](https://layra4.dev/architectures/application/transaction-script) — when the logic is too thin to need layers at all

## Further reading

- *Patterns of Enterprise Application Architecture* — Martin Fowler (2002) — The classic treatment of layering and the patterns inside each layer.
- *Software Architecture Patterns* — Mark Richards (2015) — Layered architecture as a named style, with its “sinkhole” anti-pattern.
- *Presentation Domain Data Layering (bliki)* — Martin Fowler — Why this three-way split has lasted so long.
