Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Clean Architecture

Intent

Arrange the system as concentric rings around entities and use cases with one strict rule: source-code dependencies may only point inward.

When It Helps

  • Long-lived product where frameworks, UI toolkits, and databases will be replaced during its lifetime.
  • Teams need a shared vocabulary: entities (what the business is), use cases (what it does), adapters (how it connects).
  • Testability matters — use cases should run with in-memory gateways and no framework boot.

Structure

flowchart TB
  subgraph Rings["Clean rings (outer → inner)"]
    FW["Frameworks & drivers<br/>(web, DB, devices)"] --> ADAPT["Interface adapters<br/>(controllers, presenters, gateways)"]
    ADAPT --> UC(["Use cases<br/>(application rules)"])
    UC --> ENT(["Entities<br/>(business rules)"])
  end

Rules

  1. Dependency rule: inner rings know nothing about outer rings; all dependencies point inward.
  2. Use cases orchestrate entities and declare the gateway interfaces they need; outer rings implement them.
  3. Interface adapters convert between external formats (HTTP, SQL rows) and the plain data that use cases accept.
  4. Frameworks and drivers are details in the outermost ring and are never referenced by name from use cases or entities.

Illustrative Snippet

Illustrative pseudocode — not runnable.

# sketch of the dependency-rule boundary

inner Entities:
  entity Order { items, total }
  rule place_valid(cart): cart is non-empty

inner UseCases:
  function checkout(cart, orders: OrderGateway, notify: Notifier):
    check place_valid(cart)        # pure business orchestration
    id = orders.save(build(cart))
    notify.sent(id)
    return id

outer InterfaceAdapters:
  controller CheckoutController:
    on POST(cart_json): return checkout(parse(cart_json), SqlOrders, EmailNotify)
  gateway SqlOrders implements OrderGateway:
    function save(order): database.insert("orders", order)

Basic Recap

Clean architecture separates enterprise entities, application use cases, interface adapters, and external drivers. Source dependencies point inward, while outer adapters translate transport and persistence data into plain inputs and outputs. Use cases coordinate policy without knowing which web framework or database invokes them. The structure pays off when business behavior outlives several generations of technology.

Complex Scenario

A travel company runs reservation changes through web, mobile, and call-center clients. The ChangeItinerary use case validates fare and ticketing rules, then coordinates booking and notification gateways. Search traffic is much heavier than change traffic, so developers initially reuse that use case to answer availability queries. This couples high-volume reads to transactional write dependencies and framework-specific response mapping.

flowchart TB
  Web["Web and mobile drivers"] --> Controllers["Controllers and presenters"]
  Agents["Call-center desktop"] --> Controllers
  Controllers --> Change[["ChangeItinerary use case"]]
  Change --> Entities[("Fare and ticket entities")]
  Change --> Booking[["Booking gateway interface"]]
  Change --> Notices[["Notification gateway interface"]]
  Search["Availability query adapter"] --> ReadGateway[["Availability read gateway"]]
  Booking --> GDSAdapter["Booking adapter"] --> GDS["External reservation system"]
  ReadGateway --> SearchDB[("Availability read store")]
  Notices --> Mail["Notification driver"]

Scaling walkthrough. A marketing launch raises availability traffic tenfold. Every search now constructs write-side gateways, opens reservation transactions, and waits on the external booking system, exhausting workers even though no ticket changes. Mitigate by giving queries a narrow adapter and denormalized read store, reserving ChangeItinerary for writes, and applying independent connection pools and autoscaling limits to the two paths.

Edge cases — concurrent itinerary changes need expected booking versions, retries need a client operation key, and partial failure needs a recoverable state when the booking succeeds before notification. Search results may be stale, so their timestamp must survive adapter mapping.

Sketch (illustrative pseudocode, not runnable):

use_case ChangeItinerary:
  input: {operation_key, booking_id, expected_version, new_segments}
  output: {booking_id, status, fare_delta}
  dependencies: BookingGateway, NotificationGateway  # inner-owned interfaces

query_adapter Availability:
  input: {route, date, passengers}
  reads: AvailabilityReadGateway
  returns: {options[], snapshot_time}

wiring:
  change_controller -> ChangeItinerary -> booking_adapter
  search_controller -> Availability -> read_store
  forbidden: entities -> any controller or database package

Trade-offs

  • Benefit: business rules are fully decoupled from delivery and persistence, so frameworks become replaceable details.
  • Cost: the most ceremony of the ring family — four layers of mapping for even small features.

When to Use / When Not to Use

Use when:

  • Long-lived product where frameworks and databases will be replaced.
  • Teams needing shared vocabulary of entities and use cases with fast in-memory tests.

Avoid when:

  • Small CRUD app where four rings add ceremony without benefit.

Anti-pattern / Failure Mode

  • Misuse: Use cases referencing framework types directly.
  • Review signal: Cannot run business tests without booting the framework.

Failure Modes / Trade-offs

  • Mapping ceremony: near-identical request, entity, gateway, and response objects multiply without protecting behavior. Consolidate representations where their change reasons are actually the same.
  • Framework gravity: controllers acquire policy, while use cases import sessions or serialization decorators. Inner-ring imports and framework-free tests reveal the drift.
  • Use-case mega-service: unrelated commands share one orchestrator and all gateways, making every client depend on every infrastructure concern. Split by application operation and transaction boundary.
  • Delivery trade-off: clear roles and isolated policy ease long-term migration, but small features cross many boundaries and require disciplined dependency wiring.

Dependency review. Build inner rings separately from drivers so an accidental framework import fails quickly; package names alone do not prove the dependency rule.

Boundary-data review. Include operation identity, expected versions, and freshness in plain boundary models rather than retrieving them implicitly from web sessions or ORM contexts.

Query review. Separating availability search from reservation changes is still clean architecture: both have explicit adapters, but only the write operation needs transactional use-case orchestration.

  • Test trade-off: use-case tests avoid slow framework startup, while adapter tests must still cover the external errors that plain inner models cannot represent directly.
  • Performance trade-off: repeated data conversion costs CPU and allocations, so hot paths need measurement rather than automatic acceptance of every mapping layer.
  • Ownership trade-off: shared entities can unify enterprise policy, but forcing every bounded context into one entity model creates coupling that rings cannot fix.

Constraint-based use / avoid

ConstraintRecommendation
Product expected to survive UI and database migrationsUse inward dependencies and adapters to contain those migrations.
Very different read and write latency targetsUse narrow query adapters rather than routing searches through transactional use cases.
Four-person team building a prototype with uncertain rulesAvoid full ring ceremony; start with direct application services and add boundaries as policy stabilizes.
Compliance demands repeatable business decisions across channelsUse framework-independent use cases with recorded inputs, policy versions, and adapter outcomes.
  • Onion — same inward-pointing rings, centered on the domain model rather than entities plus use cases.
  • Hexagonal — same isolation through interfaces, framed as ports and adapters instead of rings.
  • Vertical Slice — alternative that cuts across rings to keep one feature’s code together.
  • Dependency Rule — the strict form of the rule.
  • Modular Monolith Orders — clean inside module boundaries.