# Onion Architecture

**Also known as:** Jeffrey Palermo architecture  
**Category:** Application Architecture (Mid)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/application/onion

*The database moves from the bottom of the stack to the outer ring.*

Onion architecture takes the layered stack and redraws it as rings. The domain model is in the centre. Application services wrap it, and infrastructure (database, web, file system) forms the outer ring. Nothing new is added; only the direction of the arrows changes.

The one rule: source code may only depend inward. The core declares the interfaces it needs, such as a repository or a clock, and the outer ring implements them. The domain then compiles, and its tests run, with no database. The cost is more interfaces and one place to wire them together.

> **In one sentence.** Every source-code dependency points inward, toward the domain model, so the database and the web framework become replaceable details on the outside.

## Origin (2008)

Named by Jeffrey Palermo in a 2008 blog series. His point: the classic layer diagram puts the database at the bottom, holding everything up, when it should be a replaceable detail on the outside.

## The rings

### Domain model (the centre)

Entities, value objects and the rules that bind them. It imports nothing: no framework, no ORM, no other ring. It would still be true if you rewrote the app in another language.

- No imports from other rings
- The most stable code in the system

### Application services (the middle rings)

Use cases that load domain objects, call their methods and save them. They depend on the domain and on interfaces they declare, never on a concrete adapter.

- Orchestrate the model; do not repeat its rules
- Depend inward only

### Interfaces owned by the core (the inversion itself)

The repository interface lives in the core, next to the code that uses it, not next to the SQL that implements it. This placement makes infrastructure import the domain, instead of the reverse.

> domain/ports/orderRepository.ts declares it; infrastructure/postgresOrderRepository.ts implements it.

### Infrastructure ring (the outside)

Everything replaceable: SQL, HTTP, SDKs and test fakes. It implements the core's interfaces. A composition root (the one file, often index.ts, that creates concrete objects) plugs it in.

- Implements the core's interfaces
- Where all I/O lives

## Keeping the arrows pointing in

### Put each interface in the ring that uses it

A repository interface belongs in the core, not in infrastructure. If it sits next to its implementation, the import still points outward and nothing is inverted.

### Keep framework types out of the core

No ORM decorators on entities and no HTTP types in use-case signatures. If the centre imports your persistence library, the database has leaked in.

### Create concrete objects in one place

Bind PostgresOrderRepository to OrderRepository in the composition root only. An inner ring receives its dependencies; it never looks them up.

### Judge it by the tests, not the folders

The honest check: do the domain tests run with no database, no web server and no container? If not, the rings are only folder names.

## Diagrams

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

- `onion-rings` — see https://layra4.dev/architectures/application/onion
- `onion-imports` — see https://layra4.dev/architectures/application/onion

## Rings, innermost first

```
src/
domain/                         # centre — depends on nothing
  order.ts                      # the entity and its rules
  ports/                        # interfaces the core OWNS
    orderRepository.ts          # declared here, implemented outside
application/                    # use cases; import domain/, never infrastructure/
  placeOrder.ts
infrastructure/                 # outer ring — implements the core's ports
  postgresOrderRepository.ts
index.ts                        # composition root — the only file that names a concrete
```

Compare with the Layered tree: the folders barely moved, but ports/ now lives in domain/. That one move is the whole architecture.

## Examples

### The arrow, turned around

```typescript
// ── domain/ports/orderRepository.ts — the port, owned by the CENTRE ──
export interface OrderRepository {
  save(order: Order): Promise<void>;
}

// ── application/placeOrder.ts — depends on the port, never on a concrete ──
export const placeOrder = (orders: OrderRepository) =>
  async (cmd: PlaceOrder) => {
    const order = Order.create(cmd);      // pure domain
    await orders.save(order);
  };

// ── infrastructure/postgresOrderRepository.ts — the OUTER ring ──
import type { OrderRepository } from "../domain/ports/orderRepository";
export class PostgresOrderRepository implements OrderRepository {   // ← imports inward
  constructor(private db: Db) {}
  async save(order: Order) { await this.db.query(/* ... */); }
}

// ── index.ts — composition root, the one place a concrete is named ──
const place = placeOrder(new PostgresOrderRepository(db));
```

The core declares the port and depends only on it. Infrastructure imports the core to implement it. Nothing in domain/ or application/ names Postgres.

## When to use

- The domain has real rules worth protecting from the database
- You want fast business tests with in-memory adapters
- The database or framework may change during the app's life

## When not to use

- Thin CRUD: the extra interfaces buy nothing over a plain stack
- The team will not enforce the inward rule; half-applied, it is overhead
- Many drivers (HTTP, CLI, queue) need equal treatment: try Hexagonal

## Benefits

- Domain tests run in milliseconds with no database or network
- Storage and framework become replaceable details
- The most valuable code is also the most stable

## Costs

- More interfaces, plus a composition root to wire them
- You map between domain objects and database rows yourself
- Without a check, the rule slowly erodes back into plain layers

## Pitfalls

- Interfaces declared in infrastructure. It looks inverted, but the import still points outward.
- ORM entities used as domain entities, which pulls the database into the centre.
- An inner ring that fetches a service from a global or a service locator instead of receiving it.
- Rings as the goal: folders with one file each and no reason to exist.

## Similar patterns, compared

Onion, Clean and Hexagonal are three names for one idea: dependencies point inward. They were drawn independently, and their small differences are about the inside, not the rule.

### 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** | 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.

### Onion Architecture vs Layered Architecture

The parent. Same layers, nearly the same folders; Onion moves the interfaces into the core and turns the bottom arrow around. — [Layered Architecture](https://layra4.dev/architectures/application/layered)

**What is genuinely the same**

- The same split of delivery, rules and persistence
- One process, one deployable

**What actually differs**

- In Layered, business code imports data access; here persistence imports the domain
- The repository interface lives in the core, not next to its implementation
- The domain compiles and its tests run with no database

**Pick Onion Architecture when:** The domain has rules worth protecting from storage and framework changes, and you want them tested in milliseconds.

### Onion Architecture vs Clean Architecture

The same inward rule. Clean adds a fixed inside: Entities split from Use Cases, and an inverted output side. — [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture)

**What is genuinely the same**

- One law: source-code dependencies point only inward
- Domain in the centre; database, web and framework outside
- Interfaces owned by the inside, concretes wired in one place

**What actually differs**

- Clean splits the middle into Entities and Use Cases
- Clean sends output through a presenter interface instead of returning a value
- Onion's rings are a sketch you adapt; Clean's four have fixed names and jobs

**Pick Onion Architecture when:** The inward rule is what you need, and presenters would be ceremony. Most apps end up here, not on the full four rings.

### Onion Architecture vs Hexagonal

The same inversion, drawn differently: ordered rings versus an inside and an outside with no order. — [Hexagonal](https://layra4.dev/architectures/application/hexagonal)

**What is genuinely the same**

- The core owns its interfaces; infrastructure implements them
- Concretes are wired once, in a composition root
- The domain is testable with no I/O at all

**What actually differs**

- Onion orders the inside into rings; Hexagonal has only inside, edge and outside
- Hexagonal gives the driving side ports too, so HTTP, CLI and tests enter the same way
- Onion assumes a domain model in the centre; Hexagonal does not care how the inside is written

**Pick Onion Architecture when:** Rings match how you already think about a domain model, and there is one obvious driver in front of it.

## Related patterns

- [Layered Architecture](https://layra4.dev/architectures/application/layered) — the parent: the same layers before the arrow was reversed
- [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture) — the same rule, made strict, with four named rings
- [Hexagonal](https://layra4.dev/architectures/application/hexagonal) — the same rule with ports on every side and no ring order
- [Dependency Injection](https://layra4.dev/architectures/infrastructure/dependency-injection) — how concrete adapters reach the core without it importing them
- [Repository](https://layra4.dev/architectures/tactical/repository) — the interface most often moved into the core

## Further reading

- *The Onion Architecture* — Jeffrey Palermo (2008) — The original blog series that named the rings.
- *Implementing Domain-Driven Design* — Vaughn Vernon (2013) — Places the rings around a DDD model.
