Onion Architecture
How Onion Architecture organizes code into concentric rings around the Domain Model so all dependencies point inward.
TL;DR
Onion Architecture places the Domain Model at the center, surrounded by Domain Services, Application Services, and an outer ring of Infrastructure and UI. Source-code dependencies point strictly inward, so database drivers and HTTP frameworks depend on your core—never the other way around.
Intent
Keep business rules and domain state independent of databases, ORMs, and web frameworks by wrapping the core in concentric rings with an inward-only dependency rule.
Problem
In a traditional database-centric layered architecture, the domain and business logic depend directly on the data-access layer. Changing an ORM, upgrading a database driver, or testing order validation without a live database becomes slow and fragile because infrastructure concerns leak into core business rules.
Solution
Jeffrey Palermo introduced Onion Architecture around four key tenets:
- Domain Model (center): Entities (
Order), value objects (OrderItem), and invariants live here with zero external imports. - Domain Services: Interfaces such as
OrderRepositoryand domain-level coordination that operate on domain objects. - Application Services: Use-case orchestration (
PlaceOrderAppService) that coordinates domain objects and calls repository interfaces. - Infrastructure / UI (outermost ring): HTTP controllers, PostgreSQL repositories, message brokers, and test harnesses implement the inner interfaces and wire everything at startup.
Real-world analogy
▶ Flow: watch it work
Onion Architecture: Placing an Order
Press Start or tap any step dot to trace the path.
▸All steps (8)
Code
Using the shared Order service in TypeScript—notice how Order and OrderRepository have zero imports from Postgres or HTTP:
// --- Ring 1: Domain Model (src/domain/order.ts) ---
export interface OrderItem {
sku: string;
priceCents: number;
qty: number;
}
export class Order {
constructor(
public readonly id: string,
public readonly customerId: string,
public readonly totalCents: number,
) {}
static create(customerId: string, items: OrderItem[]): Order {
if (items.length === 0) throw new Error('Order must contain at least one item');
const totalCents = items.reduce((sum, i) => sum + i.priceCents * i.qty, 0);
return new Order(crypto.randomUUID(), customerId, totalCents);
}
}
// --- Ring 2: Domain Services / Interfaces (src/domain/order-repository.ts) ---
export interface OrderRepository {
save(order: Order): Promise<Order>;
}
// --- Ring 3: Application Services (src/application/place-order.ts) ---
export class PlaceOrderAppService {
constructor(private readonly repo: OrderRepository) {}
async execute(customerId: string, items: OrderItem[]): Promise<Order> {
const order = Order.create(customerId, items);
return this.repo.save(order);
}
}
// --- Ring 4: Infrastructure (src/infrastructure/postgres-order-repo.ts) ---
export class PostgresOrderRepository implements OrderRepository {
async save(order: Order): Promise<Order> {
// Runs SQL INSERT INTO orders ...
return order;
}
}When to use / when to avoid
- You are building a domain-rich application (DDD) where business invariants should outlive frameworks and databases.
- You want fast unit tests on Application and Domain layers without booting a database.
- Your app is simple CRUD with minimal business logic—Layered architecture is simpler with fewer indirections.
- You are writing a quick script or prototype where ring boundaries add unnecessary boilerplate.
How to implement
Model the center first
Define entities and value objects (Order, OrderItem) with pure TypeScript and zero external imports.
Declare repository interfaces in Domain Services
Keep OrderRepository inside the core so Application Services never import SQL or ORM packages.
Implement Infrastructure in the outer ring
Write PostgresOrderRepository and HTTP controllers in outer folders, and wire them together at the composition root.
Pros / Cons
- Business rules are completely isolated from databases, ORMs, and HTTP frameworks.
- Easy to swap Postgres for an in-memory fake in unit tests via Dependency Inversion.
- More files, interfaces, and DTO mapping than a straightforward 3-layer app.
- Teams new to DDD sometimes blur Domain Services and Application Services.
Relations
Shares the same Dependency Inversion core, framed around Driving/Driven Ports and Adapters.
Side-by-side comparison of Layered, Hexagonal, Onion, and Clean on the same Order service.
The SOLID principle that lets inner rings define interfaces implemented by outer rings.
Check yourself
Check Yourself
1. In Onion Architecture, where should the OrderRepository interface be defined?
2. What is allowed to import what under the Onion dependency rule?
Sources
Related Notes
Hexagonal Architecture (Ports & Adapters)
Isolate core business logic inside ports and plug in external drivers—REST, CLI, Postgres, or in-memory fakes—as interchangeable adapters.
Clean Architecture
How Robert C. Martin's Clean Architecture separates Entities, Use Cases, Interface Adapters, and Frameworks using the Dependency Rule.