Clean Architecture
How Robert C. Martin's Clean Architecture separates Entities, Use Cases, Interface Adapters, and Frameworks using the Dependency Rule.
TL;DR
Clean Architecture divides software into four concentric circles—Entities, Use Cases, Interface Adapters, and Frameworks & Drivers—governed by one strict Dependency Rule: source-code dependencies point only inward, and outer-ring calls cross boundaries via Input/Output Port interfaces.
Intent
Make your system independent of frameworks, UI, and databases by isolating enterprise rules (Entities) and application workflows (Use Cases) behind explicit Input/Output boundaries.
Problem
When controllers pass framework Request objects straight into business logic, or business logic returns ORM entities straight to HTTP responses, every layer becomes coupled to the web framework and database schema. Testing a single use case requires mocking HTTP and SQL.
Solution
Clean Architecture organizes components into four rings and solves the "crossing boundaries" problem with Dependency Inversion:
- Entities: Enterprise-wide business objects and rules (
Order.create(...)). - Use Cases (Interactors): Application-specific workflows (
PlaceOrderInteractor) that orchestrate Entities and declare Input/Output Ports (PlaceOrderInputPort,OrderGateway,OrderPresenter). - Interface Adapters: Convert data between Use Case models and external formats—Controllers call Input Ports, Presenters implement Output Ports to format ViewModels, and Gateways implement persistence ports.
- Frameworks & Drivers: Web servers, SQL databases, and CLI runners—treated as replaceable plugins at the edge.
Real-world analogy
▶ Flow: watch it work
Clean Architecture: Crossing Boundaries for an Order
Press Start or tap any step dot to trace the path.
▸All steps (8)
Code
Using the shared Order service in TypeScript with explicit Interactor, Gateway, and Presenter boundaries:
// --- Entities (src/entities/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('Empty order');
const totalCents = items.reduce((sum, i) => sum + i.priceCents * i.qty, 0);
return new Order(crypto.randomUUID(), customerId, totalCents);
}
}
// --- Use Cases & Ports (src/use-cases/place-order.ts) ---
export interface PlaceOrderRequest {
customerId: string;
items: OrderItem[];
}
export interface PlaceOrderResponse {
orderId: string;
totalCents: number;
}
export interface OrderGateway {
save(order: Order): Promise<Order>;
}
export interface OrderPresenter {
present(res: PlaceOrderResponse): void;
}
export class PlaceOrderInteractor {
constructor(
private readonly gateway: OrderGateway,
private readonly presenter: OrderPresenter,
) {}
async execute(req: PlaceOrderRequest): Promise<void> {
const order = Order.create(req.customerId, req.items);
const saved = await this.gateway.save(order);
this.presenter.present({ orderId: saved.id, totalCents: saved.totalCents });
}
}When to use / when to avoid
- You are building a long-lived product with complex use cases that must remain testable without web or DB frameworks.
- Multiple delivery mechanisms (REST API, CLI, background jobs) share the same Use Case Interactors.
- Simple CRUD microservices where Presenter + Input/Output Port interfaces just add ceremony.
- Early-stage prototypes where speed of iteration matters more than strict boundary isolation.
How to implement
Write Entities and Use Case Interactors first
Keep Order and PlaceOrderInteractor free of framework or database imports.
Define Gateway and Presenter interfaces in Use Cases
Let the Interactor own the contracts it needs; outer rings implement them.
Pass plain DTOs across boundaries
Map HTTP payloads to PlaceOrderRequest in the Controller and PlaceOrderResponse to HTTP JSON in the Presenter.
Pros / Cons
- Framework, UI, and database become replaceable plugins.
- Use Cases are trivially unit-tested with in-memory Gateways and spy Presenters.
- Highest boilerplate of the four styles (RequestModel, ResponseModel, ViewModel, Ports).
- Over-abstracting trivial reads can slow teams down.
Relations
Closely related concentric-ring model focused on Domain Model and Domain/Application Services.
Uses Ports & Adapters instead of concentric circles, with the same inward dependency rule.
Compare Layered, Hexagonal, Onion, and Clean side by side.
Check yourself
Check Yourself
1. How does PlaceOrderInteractor send output to a Presenter without violating the Dependency Rule?
2. What should cross the boundary between a Gateway and a Use Case Interactor?