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

Onion Architecture

Intent

Put the domain model at the center and wrap it in concentric rings so that every dependency points inward toward the model, never outward toward infrastructure.

When It Helps

  • The domain is rich — entities, value objects, and rules deserve protection from UI and persistence concerns.
  • Multiple outer concerns (web UI, background jobs, several databases) orbit one stable core.
  • You want infrastructure to be a replaceable outer ring rather than something the domain knows about.

Structure

flowchart TB
  subgraph Rings["Onion rings (outer → inner)"]
    INFRA["Infrastructure<br/>(DB, web, messaging)"] --> APP["Application services<br/>(workflows, DTOs)"]
    APP --> DOMAIN_SVC["Domain services<br/>(domain operations)"]
    DOMAIN_SVC --> MODEL(["Domain model<br/>(entities, value objects)"])
  end

Rules

  1. The domain model at the center depends on nothing outside itself.
  2. Each ring may depend only on rings inside it — never on an outer ring.
  3. Outer rings implement interfaces declared by inner rings (dependency inversion at every boundary).
  4. Cross-cutting concerns (logging, configuration) live in the outer rings and are injected inward, never imported by the model.

Illustrative Snippet

Illustrative pseudocode — not runnable.

# sketch of the inward-dependency boundary

center DomainModel:             # depends on nothing
  entity Order { items, total }
  rule: total = sum(items) + tax(items)

ring DomainServices:            # depends only on the model
  function price(order: Order):
    return order.total           # pure domain operation

ring ApplicationServices:       # depends inward
  function checkout(cart, store: OrderRepository):
    order = DomainModel.build(cart)
    return store.save(order)     # repository interface declared inside

outer Infrastructure:           # implements inner interfaces
  repository SqlOrders implements OrderRepository:
    function save(order): database.insert("orders", order)

Basic Recap

Onion architecture wraps a dependency-free domain model in domain services, application services, and infrastructure. Inner rings define policies and required abstractions; outer rings supply technical implementations. This keeps entities and value objects meaningful even when delivery or persistence technology changes. The rings are a dependency rule, not a requirement to create arbitrary projects for every concept.

Complex Scenario

A hospital medication service checks allergies, dosage ranges, and formulary eligibility before a pharmacist approves an order. The domain model must run in bedside devices during network outages, while the hosted application also calls insurance and identity providers. Application services coordinate transactions, but clinical rules remain in the model and domain services. Infrastructure supplies repository and benefits implementations without leaking their types inward.

flowchart TB
  UI["Pharmacist UI"] --> Infra["Infrastructure ring"]
  Bedside["Offline bedside adapter"] --> App
  Infra --> App["Application services ring"]
  App --> DomainServices["Domain services ring"]
  DomainServices --> Model[("Medication domain model")]
  Infra --> DB[("Clinical database")]
  Infra --> Benefits["Insurance benefits API"]
  Infra -. "implements inner interfaces" .-> App

Failure walkthrough. The benefits API stalls during a regional outage, and application workers wait while holding database transactions open. Bedside checks are unaffected only if the domain was kept free of network clients, but hosted approvals soon exhaust their connection pool. Mitigate with benefits calls outside the write transaction, short deadlines, bounded concurrency, and a cached eligibility snapshot whose age is visible to the pharmacist; never turn an unavailable benefit answer into an automatic clinical approval.

Edge cases — concurrent prescription edits need aggregate versions, retries need stable request identity, and partial failure must distinguish a saved clinical order from an unconfirmed insurance claim. Offline synchronization also needs conflict rules based on clinical timestamps and reviewer decisions.

Sketch (illustrative pseudocode, not runnable):

center Model:
  MedicationOrder.check(allergies, dose_limits)  # no imports outside domain

inner DomainServices:
  MedicationReview.evaluate(order, patient, formulary_snapshot)

ring Application:
  approve(command, orders: OrderRepository, benefits: BenefitsGateway):
    order = orders.load(command.id, expected_version=command.version)
    review = MedicationReview.evaluate(order, command.patient, command.snapshot)
    orders.save(order.approve(review))

outer Infrastructure:
  HttpBenefits implements BenefitsGateway:
    deadline: 700ms
    fallback: cached_snapshot_with_age

Trade-offs

  • Benefit: the domain model stays pure and stable while UI and infrastructure churn around it.
  • Cost: several rings and interface boundaries to maintain, which is heavyweight when the domain is thin.

When to Use / When Not to Use

Use when:

  • Domain purity matters most and infrastructure must stay outside concentric rings.

Avoid when:

  • UI-driven app where domain is thin — MVC/MVVM is enough.

Anti-pattern / Failure Mode

  • Misuse: Application services leaking into domain entities.
  • Review signal: Domain package importing infrastructure.

Failure Modes / Trade-offs

  • Decorative rings: every ring contains interfaces and mappers but the center has no meaningful rules. This creates navigation cost without protecting a domain.
  • ORM-centered model: persistence annotations, lazy loading, and framework sessions leak into entities, making offline or unit execution depend on infrastructure.
  • Outer-ring policy: insurance or dosage decisions migrate into controllers and SQL stored procedures. Divergent behavior between bedside and hosted clients is the review signal.
  • Evolution trade-off: inward dependencies support durable policy and replaceable technology, but cross-ring mapping can obscure simple workflows and inflate small changes.

Ring review. A dependency report should prove that model and domain-service code compile without application or infrastructure packages, not merely avoid importing a web controller.

State review. Aggregate boundaries determine what can change atomically; expecting one transaction to cover every clinical system would push infrastructure concerns into the model.

Safety review. Record whether a decision used live, cached, or offline formulary data so later reviewers can interpret the same outcome correctly.

  • Modeling trade-off: rich entities protect invariants but require domain expertise and ongoing collaboration with the people who own clinical policy.
  • Persistence trade-off: translating between aggregates and database rows adds code, yet reusing ORM objects as the center makes lazy loading part of domain behavior.
  • Consistency trade-off: cached eligibility improves availability, but its freshness and clinical authority must be explicit rather than hidden in infrastructure fallback logic.

Constraint-based use / avoid

ConstraintRecommendation
Complex clinical, financial, or engineering invariantsUse a rich center so rules can be exercised without infrastructure.
Offline clients must reuse the same policyUse a portable domain core and keep synchronization in outer rings.
Small team delivering mostly forms and reportsAvoid deep rings until domain behavior justifies their maintenance.
Compliance requires explainable decisions, not just stored outcomesUse explicit domain review outputs with rule and snapshot versions recorded by the application ring.
  • Hexagonal — centers on ports and adapters rather than a domain-model core, but shares inward dependencies.
  • Clean — nearly the same ring idea with entities and use cases named as the inner layers.
  • Layered — simpler horizontal alternative when a rich domain core is overkill.
  • Dependency Rule — the rule onion enforces.