# Clean Architecture

**Also known as:** Uncle Bob architecture  
**Category:** Application Architecture (Mid)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/application/clean-architecture

*One Dependency Rule, four named rings, and a way to send results outward.*

Clean Architecture is Robert C. Martin's synthesis of Hexagonal and Onion in one rule: source-code dependencies point only inward. It names four rings: Entities in the centre, then Use Cases, then Interface Adapters (controllers, presenters, gateways), then Frameworks and Drivers.

Its extra idea is the output side. When a use case must send a result out, it calls a presenter interface that it owns, and an outer adapter implements it. Control flows out while the dependency still points in. The price is the most ceremony in this family.

> **In one sentence.** Source-code dependencies point only inward; when control must flow outward, the inner ring defines an interface and an outer ring implements it.

## Origin (2012)

Published by Robert C. Martin as a 2012 blog post that joined Hexagonal, Onion and similar ideas under one rule, then expanded into the book Clean Architecture (2017).

## The four rings, and the rule

### Entities (enterprise business rules)

Rules that would exist even without software, such as how interest is calculated. The innermost ring. It changes only when the business itself changes.

- The most general, most stable rules
- Knows nothing about any use case

### Use Cases (application business rules)

One function or class per thing the system does, such as PlaceOrder. It directs the entities and declares the interfaces it needs. It does not know about HTTP or the browser.

- One use case, one intent
- Declares its input and output interfaces

### Interface Adapters (controllers, presenters, gateways)

Translators. Controllers turn requests into use-case input. Presenters turn use-case output into view models. Gateways turn interface calls into SQL. They make no business decisions.

- Convert formats, never rules
- Where DTOs and view models live

### Frameworks & Drivers (the outermost ring)

The web framework, the database and the UI toolkit. Martin calls these details: glue code that you should be able to replace without touching the rules.

### Crossing a boundary outward (the part Onion leaves implicit)

When a use case must call something further out, it calls an interface it defines, and an outer adapter implements it. Control goes out; the source dependency still points in.

> placeOrder calls OrderPresenter, an interface it owns; the HTTP presenter implements it.

## Applying the Dependency Rule

### Nothing inner may name anything outer

Not a class, a function, a type or a table name. A lint rule on import paths can check this on every commit, which a folder layout never can.

### Invert the crossing; never skip the boundary

When control must flow outward, define the interface inside and implement it outside. A use case that imports a framework response type has broken the scheme.

### Cross boundaries with simple data

Pass plain objects that the inner side defines. Never pass an ORM row or a framework request, because they bring their dependencies with them.

### Match the ceremony to the stakes

Four rings are a maximum, not a quota. A small app can merge adapters into its use cases. Every ring in a CRUD app only adds mapping code.

## Four rings, outermost last

```
src/
entities/                       # ring 1 — enterprise rules, depend on nothing
  order.ts
usecases/                       # ring 2 — application rules
  placeOrder.ts
  boundaries/                   # interfaces this ring OWNS, both directions
    orderGateway.ts             # what the use case needs
    orderPresenter.ts           # the outward crossing, inverted
adapters/                       # ring 3 — controllers, presenters, gateways
  httpOrderController.ts
  sqlOrderGateway.ts
main/                           # ring 4 — frameworks, drivers, and the wiring
  index.ts
```

Look at boundaries/ inside usecases/: the input the use case needs and the output it produces are both interfaces the inner ring owns. Ring 3 only implements them.

## Examples

### Control flows outward; the dependency still points in

```typescript
// ── usecases/boundaries/orderPresenter.ts — defined by the INNER ring ──
export interface OrderPresenter {
  present(result: { orderId: string; total: number }): void;
}

// ── usecases/placeOrder.ts — knows nothing about HTTP, JSON or status codes ──
export const placeOrder =
  (orders: OrderGateway, presenter: OrderPresenter) =>
  async (cmd: PlaceOrder) => {
    const order = Order.create(cmd);
    await orders.save(order);
    presenter.present({ orderId: order.id, total: order.total });  // control OUT
  };

// ── adapters/httpOrderPresenter.ts — the OUTER ring implements it ──
import type { Response } from "express";                       // allowed: ring 3
import type { OrderPresenter } from "../usecases/boundaries/orderPresenter";
export class HttpOrderPresenter implements OrderPresenter {        // ← imports inward
  constructor(private res: Response) {}
  present(result: { orderId: string; total: number }) {
    this.res.status(201).json({ id: result.orderId, total: result.total });
  }
}
```

The use case hands its result to a presenter without knowing it is HTTP. It calls an interface it defined, so the import from adapters/ to usecases/ points inward while the data travels out.

## When to use

- A long-lived app whose framework or database will change before its rules
- Rules complex enough to deserve a ring of their own
- A team that wants one rule it can check with a tool

## When not to use

- CRUD or thin logic: four rings produce more mapping than behaviour
- Small, short-lived services: Onion or Hexagonal give most of the value
- Nobody will enforce the rule; half-applied, it costs the most

## Benefits

- One rule answers every “may this file import that one?” question
- Business rules do not depend on framework, database or UI
- The use-cases folder reads as a list of what the system does

## Costs

- The most ceremony in this family: interfaces and DTOs at each crossing
- Data is mapped again at each ring
- Easy to over-apply until the number of rings becomes the goal

## Pitfalls

- Entities that are really ORM models, so ring 1 depends on ring 4.
- Use cases that import framework request or response types.
- No presenter, so use cases format JSON themselves and the output side is never inverted.
- Four rings on a CRUD app: lots of mapping code and nothing to protect.

## Similar patterns, compared

Clean was written as a synthesis, so it overlaps its sources on purpose. Martin's own post says Hexagonal, Onion and the others share one goal: separation of concerns. What Clean adds is a fixed layout for the inside, and that is where the three differ.

### The family at a glance

| Pattern | What it separates | Dependencies point | What the boundary costs | Use it when |
| --- | --- | --- | --- | --- |
| [Layered Architecture](https://layra4.dev/architectures/application/layered) | 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** | 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.

### Clean Architecture vs Onion Architecture

The same rule with fewer prescriptions. Onion states the inward dependency and stops there. — [Onion Architecture](https://layra4.dev/architectures/application/onion)

**What is genuinely the same**

- Dependencies point only inward, with the domain in the centre
- Interfaces owned by the inside; infrastructure is an outer detail

**What actually differs**

- Clean separates Entities from Use Cases; Onion does not
- Clean inverts the output with presenters; Onion usually returns a value
- Clean's ring names and jobs are fixed, not adapted per project

**Pick Clean Architecture when:** You want one rule a tool can check, and business rules general enough to outlive this app.

### Clean Architecture vs Hexagonal

Clean includes Hexagonal on purpose: Hexagonal is the boundary, Clean is that boundary plus a layout for the inside. — [Hexagonal](https://layra4.dev/architectures/application/hexagonal)

**What is genuinely the same**

- The inside owns the interfaces; adapters implement them
- Frameworks, databases and UI are replaceable details
- Both survive a change of delivery mechanism without touching rules

**What actually differs**

- Hexagonal says nothing about the inside; Clean prescribes four rings
- Hexagonal's sides have no order; Clean's rings are strictly ranked
- Clean sends output through presenters; a Hexagonal driver may just take a return value

**Pick Clean Architecture when:** You want the inside prescribed as well as the boundary.

### Clean Architecture vs Layered Architecture

The stack this rule was written to fix: the same concerns, with the opposite arrow at the bottom. — [Layered Architecture](https://layra4.dev/architectures/application/layered)

**What is genuinely the same**

- Delivery, business rules and persistence are kept apart
- One deployable; the rings are folders, not machines

**What actually differs**

- Layered's domain depends on the database; here nothing inner may name anything outer
- Clean has a rule to enforce; Layered has a folder convention
- Clean adds mapping at every crossing, which is the price of the guarantee

**Pick Clean Architecture when:** The framework and database will change before the business rules do, and the team will enforce the rule.

### Clean Architecture vs Vertical Slice

Often seen as Clean's opposite, but it fills the inside Clean leaves open. A common setup is Clean's boundary with slices inside it. — [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice)

**What is genuinely the same**

- Both keep business rules out of the framework
- Both are folder conventions within one deployable
- Both put something between a feature and its database

**What actually differs**

- Clean fixes the rings and every crossing; slicing fixes only that a folder is a feature
- The rings apply to every use case; a slice with one rule may skip them
- A slice may run SQL directly when there is nothing to protect; the Dependency Rule never bends

**Pick Clean Architecture when:** The rule will really be enforced, and the app will outlive its framework.

## Related patterns

- [Layered Architecture](https://layra4.dev/architectures/application/layered) — the stack this rule was written to fix
- [Onion Architecture](https://layra4.dev/architectures/application/onion) — the same inward rule with fewer named rings
- [Hexagonal](https://layra4.dev/architectures/application/hexagonal) — the boundary shape Clean includes
- [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice) — a common way to arrange the use cases inside the rings
- [Dependency Injection](https://layra4.dev/architectures/infrastructure/dependency-injection) — how the outer ring plugs adapters into use cases

## Further reading

- *The Clean Architecture* — Robert C. Martin (2012) — The original blog post that states the Dependency Rule.
- *Clean Architecture* — Robert C. Martin (2017) — The book, including component and boundary design.
