Course contents

10. Software Architecture Lesson 1 of 10

Layered Architecture

Follow an order through presentation, application, domain and data layers; compare strict and relaxed layering, see changes ripple, and separate layers from tiers.

14 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A layered application groups code by technical concern: presentation, application, domain, data access.
  • Each layer depends only on layers below it; strict layering allows only the next one down.
  • Strict layering breeds pass-through code; relaxed layering removes it but adds dependencies.
  • Because dependencies point toward the database, data changes ripple up through every layer.
  • Layers are logical and cost nothing at runtime; tiers are physical and add network hops.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A layered architecture organises an application into horizontal layers, each with one kind of responsibility. The classic four are:

  • Presentation: controllers or minimal-API endpoints, request and response models, input checks, HTTP status codes.
  • Application: use-case orchestration. Loads what a use case needs, calls the domain, controls the transaction.
  • Domain (business logic): the rules of the business. An order needs at least one line; a cancelled order cannot be shipped.
  • Data access (persistence, infrastructure): EF Core DbContext, SQL, repositories, external API clients.

A layer may use the layers below it and never the ones above. In .NET this is often four projects (Shop.Api, Shop.Application, Shop.Domain, Shop.Data) whose project references form a one-way chain.

Why it exists

Without structure, UI code issues SQL, business rules hide in click handlers and nothing can be changed or tested in isolation. Layering is the oldest, simplest answer: separate concerns so each part can be understood on its own, give developers an obvious place for every class, and allow one layer to be replaced (a new UI, a different database) without rewriting the rest. It is easy to explain to a new team, which is a large part of its success.

How it works

A request walks the stack. POST /orders arrives at OrdersController, which maps JSON to a command and calls the application service. The service starts a transaction, asks the domain to create an Order (which enforces its rules) and saves it through the repository. The answer returns up the same path.

public sealed class OrderService(IOrderRepository orders, AppDbContext db)
{
    public async Task<Guid> PlaceOrder(PlaceOrderCommand cmd, CancellationToken ct)
    {
        var order = Order.Create(cmd.CustomerId, cmd.Lines); // domain rules
        orders.Add(order);
        await db.SaveChangesAsync(ct);                       // one transaction
        return order.Id;
    }
}

Strict or relaxed. In strict (closed) layering a layer may only call the one directly below. Every layer is insulated from everything except its neighbour, but simple reads pass through layers that add nothing. In relaxed (open) layering a layer may call any layer below; the presentation layer can run a read-only query without a pass-through service method. Many teams mix the two: commands go through every layer, queries take a short path.

Dependencies point down, toward data. In the traditional form the domain layer references the data layer: it uses the repository classes and often the EF entities themselves. That is what makes changes ripple: a new column changes the entity, then the domain logic that reads it, then the DTO, then the API response.

Layers are not tiers. A layer is a logical grouping of code in one process; calling the next layer is a method call. A tier is a physical deployment unit (a separate process or machine). "Three-tier" (browser, application server, database) says nothing about how the application server's code is layered.

When to use it

  • Line-of-business and CRUD-heavy applications with modest business rules.
  • Teams that need a structure everyone recognises immediately.
  • As a first structure for a small service, with the option to evolve toward clean architecture or vertical slices when it starts to hurt.

When not to

  • Rich domains where business rules should not depend on persistence details: use clean or hexagonal architecture so the domain is at the centre.
  • Codebases where almost every change is a feature cutting through all layers: vertical slices keep such changes in one place.
  • When the "layers" would mostly forward calls: that is ceremony without structure.

Trade-offs

Choice You gain You pay
Strict layering Each layer depends on one neighbour only Pass-through code for simple operations
Relaxed layering Less code, shorter read paths More dependencies; lower layers harder to change
Domain depends on data layer Simple, direct code; EF entities double as model Database changes ripple up; domain hard to test without a database
Layers as separate tiers Independent scaling, security zones Network hops, serialisation, partial failures

Alternatives

  • Clean / onion architecture: same idea of layers, but the domain is in the centre and the data layer depends on interfaces the core owns.
  • Hexagonal (ports and adapters): the application core talks to the outside world only through ports; adapters on both sides plug in.
  • Vertical slice architecture: organise by feature instead of by technical layer; each slice holds its endpoint, logic and data access.
  • Modular monolith: split by business capability first, then choose a structure inside each module.

Failure modes

  • Architecture sinkhole: most requests pass through layers that do nothing. A common rule of thumb is to question the structure when this is true of most requests.
  • Anemic domain: the "domain layer" holds only property bags; all rules live in services, so the layer exists in name only.
  • Leaky layers: IQueryable or EF entities escape to controllers, so the presentation layer silently depends on the database schema.
  • Shotgun changes: every feature touches every project; merge conflicts concentrate in the shared service and repository classes.
  • Accidental tiers: layers deployed as separate services for no reason, adding latency and failure points.

In production

Enforce the direction with project references, and check it in CI with an architecture test (NetArchTest or ArchUnitNET) so a stray using Shop.Api in the domain fails the build. Keep controllers thin, return DTOs rather than entities, and use AsNoTracking() or projections on the read path. Decide deliberately which reads may bypass layers instead of letting shortcuts accumulate.

Common misconceptions

  • "Layers make the app slow." In one process they are method calls. The cost is in change effort, not latency, unless layers are turned into tiers.
  • "A repository per table is the data layer." Repositories are one option; EF Core's DbContext already is a unit of work and a set of repositories.
  • "Layered means three-tier." Tiers are deployment, layers are code organisation.
  • "Strict layering is always better." It trades simplicity for isolation; for read-heavy code relaxed layering is often the better trade.

Interview angle

Name the layers and the dependency direction, then show you know the weaknesses: changes cut across layers, the domain depends on persistence, strictness leads to pass-through code. Strong answers distinguish layers from tiers, mention enforcement with architecture tests, and explain when you would move to clean architecture (rich rules, testability) or vertical slices (feature-driven change).

Model assumptions

The call order, the strict and relaxed read paths and the change ripple are scripted illustrations: packets are placed by hand and slowed to 30 ms per hop so they can be followed, although in-process calls take microseconds. The runtime steps are simulated: each layer is a server with 16 workers and a 0.5–1 ms mean service time, joined to the next by 0 ms links (in-process calls); the shopper is 20 ms away, the database 1 ms, and a query takes about 6 ms (lognormal, cv 0.3) on a pool of 4 connections. Arrivals are random (Poisson). In the tiers step two links become network hops of 2 ms each way, an illustrative figure for a data-centre hop including serialisation. Numbers show behaviour and orders of magnitude, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Four layers, stacked by responsibility

    A layered application sorts its code by technical responsibility. In an ASP.NET Core shop that usually means four projects or folders: Presentation (controllers, request and response models), Application (use-case orchestration and transactions), Domain (business rules: an order needs at least one line, totals must match) and Data access (EF Core, SQL, repositories).

    Each layer may call the layer below it, never the one above. The arrows here are dependencies: who references whom.

    Scene: Four layer nodes stand in a row inside dashed boundaries: OrdersController (presentation), OrderService (application), Order (domain) and OrderRepository (data access), with SQL Server at the end. Arrows point from each layer to the one below.

    Key idea: Layers group code by technical concern, and dependencies only point downward.

  2. 2. An order travels down and back up

    The shopper sends POST /orders. The controller maps the JSON to a command and calls OrderService.PlaceOrder. The service starts a transaction and asks the domain to build an Order, which checks its rules. The order is saved through OrderRepository, which issues the INSERT.

    The answer climbs back the same way, one layer at a time. Every call goes to the layer directly below; nothing skips a layer. (The packets are a scripted illustration, slowed down: in-process calls take microseconds.)

    Scene: A request packet travels Shopper → OrdersController → OrderService → Order → OrderRepository → SQL Server, then the response climbs back up the same chain, one layer at a time.

    Key idea: A request crosses every layer on the way down and again on the way back.

  3. 3. Layers cost almost nothing at runtime

    Now real (simulated) shoppers place 20 orders per second. Each order takes about 50 ms: 40 ms of network to and from the shopper, about 8 ms for the database round trip and query, and roughly 2 ms for all four layers together.

    Layers are a way to organise code inside one process. Calling the next layer is a method call, not a network call. Their price is paid in design time and change effort, which the next steps show, not in latency.

    Scene: Shoppers send 20 orders per second through the four layers to SQL Server. Each order takes about 50 ms, almost all of it network and database time; every order succeeds.

    Key idea: Layers live in one process: the calls between them are method calls.

  4. 4. Strict layering: even a read walks every layer

    With strict layering a layer may only call the one immediately below. Fetching an order for display (GET /orders/42) has no business rules, yet it still goes controller → service → domain → repository. OrderService.GetOrder just forwards to the next layer.

    Those forwarding methods are the architecture sinkhole anti-pattern: code that exists only to obey the layering. A few are harmless; if most requests just fall through, the layers are adding ceremony, not structure.

    Scene: A read request passes through OrderService and the domain layer, which only forward it, before reaching the repository and the database; the answer climbs back through the same layers.

    Key idea: Strict layering isolates each layer, at the price of pass-through code for simple reads.

  5. 5. Relaxed layering: reads may skip down

    Relaxed layering lets a layer call *any* layer below it. The controller now asks a read-only query object in the data layer directly, and the read skips the service and domain layers entirely.

    Less code, but a new dependency: Presentation now references Data access as well as Application. Every extra arrow is one more place a change below can break something above.

    Scene: A new arrow runs from OrdersController straight to OrderRepository. The read request now goes Shopper → controller → repository → database and back, skipping the application and domain layers.

    Key idea: Relaxed layering trades isolation for less pass-through code: more arrows, more coupling.

  6. 6. A change at the bottom ripples upward

    The business wants a delivery window on every order. A new column lands in the Orders table. Because each layer depends on the one below, the change climbs: the EF Core entity and mapping, the Order model (here it is the same class EF maps), the service DTO, the controller response.

    The controller is hit twice: once through the service and once through the relaxed shortcut. Dependencies that point down toward the database mean database changes travel up through everything. Clean and hexagonal architecture exist to turn that arrow around.

    Scene: Change pulses travel upward from SQL Server to the repository, then to the domain, the service and the controller. A second pulse reaches the controller directly from the repository along the relaxed shortcut.

    Key idea: Everything depends on the data layer, so data changes ripple through every layer above it.

  7. 7. Layers are not tiers

    A layer is a logical grouping of code; a tier is a separate process or machine. Suppose the controllers move to web servers and the data access to a separate data service (the shortcut is removed again). Each of those two calls is now a network hop of about 2 ms each way in this model, with serialisation.

    Orders get about 8 ms slower, and every request now has two more remote calls that can time out or fail. Split layers into tiers only for a reason (security zones, independent scaling), not because the code is layered.

    Scene: The controller-to-service and domain-to-repository links are now network hops. Orders still all succeed but take about 8 ms longer than when every layer ran in one process.

    Key idea: Layering is free at runtime; turning layers into tiers adds network hops and failure points.

  8. 8. When layers fit, and when they fight you

    Layering is easy to explain and to staff, and it suits applications that are mostly CRUD with modest rules. Its weak spots: changes cut across every layer, dependencies point toward the database, and strictness breeds pass-through code.

    Back in one process, the app serves orders in about 50 ms again. Next: clean architecture keeps the layers but reverses the data dependency, and vertical slices cut the code by feature instead.

    Scene: All four layers run in one process again. Shoppers send 20 orders per second; each takes about 50 ms and all succeed.

    Key idea: Layers organise code by concern; they do not stop changes from crossing every layer.