Skip to content

Onion Architecture in Practice

This pattern works identically in Go, Java, C#, TypeScript, Kotlin, Rust, and PHP — it is not about language syntax, it is about the direction of dependencies.

The Core Idea

Code is arranged in concentric layers like an onion. Inner layers know nothing about outer layers; outer layers depend inward on inner layers.

The main payoff is that the blast radius of changes becomes predictable at scale:

  1. Need to change the response format of a single API endpoint? Edit one handler. Every other endpoint, CLI command, queue consumer, and cron job sharing the same business logic stays untouched.
  2. Need to change a business rule? Edit the corresponding service method once, and every driving adapter — HTTP handlers, gRPC endpoints, CLI commands, queue consumers, cron jobs — inherits the updated behavior automatically.
  3. Hit a database bottleneck? Introduce a fast secondary store in the data-source layer and teach the repository to read/write through both (hot path in cache/NoSQL, system of record in SQL). The entire application gets the speedup without rewriting services or handlers.

From outside in, the layers are:

  • Layer 1. Entry points (Driving adapters): HTTP controllers, gRPC handlers, consumers, cron jobs, CLI commands.
  • Layer 2. Service layer: application use cases and business rules.
  • Layer 3. Repository layer: data normalization and multi-source orchestration.
  • Layer 4. Data sources (Driven adapters): SQL/NoSQL databases, outbound message brokers, filesystems, external APIs.
  • Core (Layer 0). Domain: pure business concepts with zero external dependencies.

One rule holds everything together: dependencies point strictly inward, achieved via dependency inversion — interfaces (ports) are declared by the consumer layer and implemented by the outer layer below it.

Layer 1. Entry Points

Responsibility: accept a raw external signal, translate it into a clean domain call, and map the result back to the transport format.

What belongs here:

  • HTTP controllers, gRPC handlers, GraphQL resolvers, queue consumers, cron jobs, CLI commands;
  • transport parsing (protobuf, JSON, form data, CLI flags → domain input);
  • syntactic validation (required fields, numeric bounds, format checks);
  • authentication and coarse authorization (“is this caller allowed to invoke this endpoint?”);
  • mapping domain results and typed domain errors into transport status codes (UserNotFound → 404, InsufficientFunds → 422 or gRPC FAILED_PRECONDITION).

What does not belong here:

  • business rules (“if the customer is on tier X, waive the fee” belongs in a service);
  • direct database queries or external API calls;
  • any awareness of storage schemas.

Analogy: hotel front desk. Checks ID, registers the guest, hands over the room key — neither cleans rooms nor cooks breakfast.

Layer 2. Service Layer — Business Logic

Responsibility: express what the system does in domain terms, completely agnostic to how the request arrived or where data is stored.

What belongs here:

  • application workflows (“place order”, “issue refund”, “settle payment”);
  • business rules: preconditions, ordering of steps, policy decisions;
  • orchestration across domain ports: query repository A, invoke repository B, apply domain rule;
  • port interfaces for repositories and external capabilities — the service declares what it needs (“fetch user by ID”), never how it is implemented.

What does not belong here:

  • HTTP, gRPC, or Kafka types;
  • SQL queries, Redis keys, or vendor SDK clients;
  • transport DTOs or ORM table models;
  • noisy inline logging scattered through every if-statement (use decorators/middleware at layer boundaries instead).

Analogy: head chef. Knows the recipe, step order, and flavor pairings — neither knows which vendor delivered the carrots nor which walk-in cooler holds them.

Layer 3. Repository Layer — Normalization & Source Orchestration

Responsibility: hide where data lives and how it is represented. The service asks for a domain entity; the repository figures out how to assemble it.

What belongs here:

  • implementations of ports declared in the service layer;
  • bidirectional mapping between domain entities and persistence/API models (ActiveRecord / Eloquent models live here as persistence records, never as domain entities);
  • read/write strategy across stores (read-through cache → SQL → populate cache);
  • multi-source aggregation, pagination, retries, rate limiting, and transaction boundaries;
  • translating low-level infrastructure failures into typed domain errors (SQL timeout → RepositoryUnavailable, upstream 404 → NotFound).

Pragmatic Departure from Strict DDD Canon

Strict DDD/Onion literature often insists on one repository per aggregate backed by one store, pushing cache/API orchestration up into application services. In practice, treating a repository as a data port that may coordinate cache + SQL + upstream API to answer a single domain question keeps infrastructure plumbing out of business services. The boundary stays crisp: a repository may decide where to fetch data from, never whether business rules permit fetching it.

Analogy: kitchen steward. The chef asks for peeled carrots; the steward checks the fridge, reorders from suppliers if needed, and hands over washed carrots — without ever deciding to change today’s menu.

Layer 4. Data Sources

Responsibility: physically read from or write to one concrete external system — nothing more.

  • SQL queries for specific tables, Redis commands, S3 operations, HTTP/gRPC clients for individual third-party APIs;
  • connection pools, timeouts, OAuth/mTLS/HMAC credentials, wire serialization.

No cross-source joins, no fallback decisions, no business rules. Each client is a thin, easily mockable driven adapter.

Core. The Domain (Layer 0)

Responsibility: model the business in its own ubiquitous language — entities, immutable value objects (Money, DateRange, EmailAddress), typed domain errors, pure domain services, and invariants enforced in constructors and state-transition methods.

Strict Isolation

The domain package imports nothing from outer layers or third-party infrastructure: no HTTP frameworks, no SQL drivers, no ORM tags, no JSON/protobuf struct tags, no loggers, no direct time.Now() or random UUID calls when determinism matters.

Litmus test:

  • The domain module compiles standalone with zero database, network, or framework dependencies in its transitive dependency graph.
  • Every domain unit test runs purely in memory without containers, sockets, or databases.

Wiring Everything Together: Composition Root

Exactly one place in the binary wires concrete implementations together (cmd/<service>/main.go in Go, Program.cs in .NET, explicit @Configuration in Spring, ServiceProvider bindings in Laravel):

data source clients → repositories (+ cache/metrics decorators) → services → entry-point handlers.

DI containers are fine inside the composition root, never as a global service locator (Container::get(...)) called from business code.

Cross-Cutting Concerns: Logging, Metrics, Tracing, Config

  • Thread request context (context.Context, CancellationToken, AsyncLocalStorage) across layers for deadlines, trace spans, and request IDs.
  • Attach logging, latency histograms, cache hit counters, and retries via middleware, interceptors, and interface decorators at layer boundaries so domain and service code stays clean.
  • Pass strongly typed configuration structs via constructors from the composition root rather than reading global Config::get(...) singletons.

Applying to Legacy Monoliths Incrementally

  1. Do not rewrite the whole monolith at once. Clean up the module you are actively changing.
  2. Draw an explicit directory/namespace boundary (internal/v2/, app/Domain/) where strict dependency rules apply without compromise.
  3. Place a thin, temporary anti-corruption layer at the boundary to convert legacy ORM objects into clean domain entities — and delete that adapter once the legacy caller is retired.
  4. Lock existing behavior down with black-box characterization tests before extracting clean inner layers covered by fast in-memory unit tests.

Practical Payoff

Architecture is not about drawing neat concentric circles on slides. Its real value is making the cost of any change obvious before code review: changes at the edge stay local to a single adapter, while changes to core domain invariants propagate cleanly and predictably across every entry point.