Software Architecture
Layered and N-Tier Architecture: Tiers, Layers and the Dependency Rule
Beginner9 min readReviewed by Mariem Ouled on Updated
Layering is the first architectural decision most systems make, and one of the most misunderstood. After reading this you will be able to distinguish physical tiers from logical layers, choose a sensible layer structure for a business application, keep dependencies pointing in the right direction, and recognise the anti-patterns that turn a layered codebase into a maze.
What you will learn
- Explain the difference between a physical tier and a logical layer, and why the two are often confused
- Describe how two-tier client-server, three-tier and n-tier systems differ and what problem each step solved
- Structure presentation, application, domain and infrastructure layers with dependencies pointing inward
- Document an application architecture with a component view and a flow matrix
- Identify layering anti-patterns such as leaky entities, anaemic services and business logic in controllers
Almost every business application you will ever open is layered, and most of them are layered badly. Layering is cheap to introduce and expensive to fix, because a layer structure that lets business rules leak into controllers or SQL leak into the domain spreads through thousands of classes before anyone notices. Getting it right requires understanding three things that are routinely conflated: physical tiers, logical layers, and the direction in which dependencies are allowed to point.
Tiers are physical, layers are logical
A tier is a deployment boundary: a process, a machine or a cluster that talks to another one over a network. A layer is a code boundary: a set of packages with a defined responsibility and rules about what it may call. The two are independent. A single-process desktop application can have five clean layers; a distributed system with six tiers can have no meaningful layering at all.
The confusion arises because the classic three-tier deployment — a browser, an application server and a database — happens to line up with three obvious layers: presentation, business logic and data access. That coincidence made "three-tier" and "three-layer" interchangeable in everyday speech, and it hides an important truth: moving code to another tier is a network and operations decision, moving it to another layer is a design decision. You can change either without changing the other.
How tiers evolved
Two-tier client-server
In the two-tier model a fat client contains the user interface and all business logic, and talks directly to a shared database over a database protocol. Business rules live in the client program and sometimes in stored procedures. The model is simple and fast to build, which is why it dominated the 1990s, but it has structural problems:
- Every client needs a database connection, so the database becomes the scaling limit.
- A rule change means redeploying every client installation.
- The database schema becomes the integration contract between applications, so nobody dares change it.
- Security is enforced at the database user level, which is far too coarse for business authorisation.
Three-tier
Three-tier deployments inserted an application server between clients and the database. The client became thin (eventually a browser), business logic moved to the middle tier, and the database was hidden behind it. That change fixed the connection problem (the middle tier pools connections), the deployment problem (one server to update), and the integration problem (other applications call the middle tier's interface instead of the tables). It also introduced a new set of concerns — sessions, connection pools, remote invocation — that the enterprise application-server platforms of the 2000s were built to handle.
N-tier
"N-tier" is what happens when the middle tier itself splits: a web server serving static assets and terminating TLS, an application server, a separate integration layer wrapping legacy systems or partner APIs, a caching tier, a message broker, one or more databases. Each extra tier buys isolation, independent scaling or a security boundary, and costs a network hop, a failure mode and something else to operate.
| Model | Where business logic lives | What it fixed | What it costs |
|---|---|---|---|
| Two-tier | Client program, stored procedures | Simplicity, direct data access | Scaling, deployment, schema coupling |
| Three-tier | Application server | Connection pooling, central rules, hidden schema | Sessions, remote calls, a server to run |
| N-tier | Application and integration tiers | Security zones, independent scaling, legacy isolation | Latency per hop, more failure modes, operational load |
The four levels of an architecture description
Architects describing a system usually work at four levels, each answering a different question. Naming them avoids meetings where one person is arguing about servers while another is arguing about packages.
- Functional architecture — what business capabilities the system provides and how they are grouped, in vocabulary the business understands. No technology appears here.
- Application architecture — which applications and components exist, which one owns which data, and how they call each other. This is where you draw the component diagram and the flow matrix.
- Technical (infrastructure) architecture — which servers, zones, networks, load balancers and databases host those components, with availability and security policies attached.
- Software architecture — how the code inside one component is organised: frameworks, modules, layers, coding rules.
Layers belong to the fourth level; tiers belong to the third. A flow matrix at the second level is the artefact that links them, and it is worth producing for any system with more than a handful of components:
| Ref | Protocol | Caller | Callee | Security | Traced |
|---|---|---|---|---|---|
| F1 | HTTPS | Customer browser | Web front end | TLS, session cookie | yes |
| F2 | HTTP/JSON | Web front end | Order service | mTLS inside zone | yes |
| F3 | JDBC | Order service | Orders database | DB credentials from vault | no |
| F4 | HTTPS | Order service | Payment provider | OAuth 2.0 client credentials | yes |
Every row becomes a firewall rule, a monitoring probe and a potential timeout. Writing them down early is the difference between an architecture and a drawing.
Logical layers inside a service
Inside one deployable component the conventional structure is four layers. The names vary; the responsibilities do not.
- Presentation (or interface) — receives requests, validates their shape, converts them to calls on the layer below and renders responses. HTTP controllers, message listeners, CLI commands and scheduled jobs all live here. It knows about HTTP status codes and JSON; nothing below it does.
- Application — orchestrates a use case: loads the objects it needs, calls domain behaviour, manages the transaction, publishes events. It contains no business rules of its own, only sequencing.
- Domain — business concepts and the rules that govern them: what a valid order is, when a discount applies, what happens when stock runs out. This is the layer that should survive a change of framework, database or delivery channel.
- Infrastructure — talks to the outside world: database access, HTTP clients, message brokers, file systems, email. It implements interfaces declared by the domain or application layer.
// Presentation: knows HTTP, knows nothing about pricing rules
@RestController
@RequestMapping("/orders")
class OrderController {
private final PlaceOrder placeOrder;
OrderController(PlaceOrder placeOrder) { this.placeOrder = placeOrder; }
@PostMapping
ResponseEntity<OrderResponse> create(@Valid @RequestBody OrderRequest body) {
OrderId id = placeOrder.handle(body.customerId(), body.lines());
return ResponseEntity.created(URI.create("/orders/" + id.value()))
.body(new OrderResponse(id.value()));
}
}
// Application: one use case, one transaction, no rules of its own
@Service
class PlaceOrder {
private final OrderRepository orders; // interface owned by the domain
private final PricingPolicy pricing; // domain service
PlaceOrder(OrderRepository orders, PricingPolicy pricing) {
this.orders = orders; this.pricing = pricing;
}
@Transactional
OrderId handle(CustomerId customer, List<OrderLine> lines) {
Order order = Order.draft(customer, lines); // domain enforces invariants
order.price(pricing); // domain rule, not controller code
orders.save(order);
return order.id();
}
}
// Infrastructure: implements the domain's interface with JPA
@Repository
class JpaOrderRepository implements OrderRepository {
// mapping between Order and the persistence entity lives here, not in the domain
}
The important detail is the arrow direction. PlaceOrder depends on OrderRepository, an interface declared next to Order in the domain package. JpaOrderRepository in the infrastructure package implements it. The domain therefore has no import of JPA, Spring or anything else outside plain Java, and you can unit-test Order and PricingPolicy without a database.
Strict versus relaxed layering
In strict layering each layer may call only the one immediately below it. In relaxed layering a layer may call any layer beneath it, so a controller can go straight to a repository for a trivial read. Strict layering produces pass-through methods that do nothing but delegate; relaxed layering invites controllers to grow business logic. A defensible middle: presentation may call application only; application may call domain and infrastructure interfaces; nothing calls presentation.
Ports and adapters: the same idea, drawn differently
Hexagonal architecture, also called ports and adapters, and the "clean" and "onion" variants that followed it, keep the same responsibilities but change the picture. Instead of a stack with the database at the bottom, the domain and application layers sit in the centre and everything that talks to the outside world — HTTP, database, broker, UI — is an adapter plugged into a port (an interface) on the edge of the core. The database is no longer "below" the domain; it is just another adapter, on the same footing as the web controller.
Why does the redrawing matter? Because in the traditional stack the persistence layer sits at the bottom and everything appears to depend on it, so teams design the domain around the tables. Putting the domain in the centre makes the dependency rule explicit: source code dependencies point inward, toward the domain, never outward. The OrderRepository interface above is a port; JpaOrderRepository is an adapter. If you already follow that rule, you already have a hexagonal architecture regardless of what the diagram looks like.
Data crossing layer boundaries
Each boundary raises the question of which objects cross it.
- Between presentation and application: use request and response objects specific to the API (records work well in Java 21). Never expose persistence entities directly; the API contract and the table schema change for different reasons, and serialising entities drags lazy-loaded relationships and internal fields into responses.
- Between application and domain: pass domain objects. Mapping here is usually waste.
- Between domain and infrastructure: the repository interface speaks in domain terms (
Order,OrderId) and the adapter maps to whatever the store needs.
The rule of thumb: a DTO (data transfer object) earns its place when the two sides evolve independently or cross a network; inside one process between two layers that always change together, it is ceremony.
Common mistakes
Business logic in the controller. A controller that checks stock, computes a discount and decides whether to notify a warehouse cannot be reused from a batch job or a message listener, and cannot be tested without HTTP. Fix: the controller translates and delegates; every if about the business moves to the domain.
Anaemic domain, fat service. Domain classes with only getters and setters while a *Service class holds every rule. The rules end up duplicated across services and impossible to enforce as invariants. Fix: put behaviour on the objects that own the data — order.addLine(...) validates, not OrderService.validateLine(...).
Entities leaking to the API. Returning JPA entities from a REST endpoint couples the wire format to the schema, causes lazy-initialisation exceptions and exposes fields you never meant to publish. Fix: dedicated response records and an explicit mapper.
Layer by technology, package by layer only. A codebase with top-level packages controllers, services, repositories and hundreds of classes in each is hard to navigate and lets any service call any repository. Fix: package by feature first (orders, billing), by layer within the feature, and make the feature's internals package-private.
Tiers added for fashion. A separate "integration tier" for a system with one external partner adds a hop and a deployment for nothing. Fix: add a tier when you can name the isolation, scaling or security property it buys.
Cross-cutting concerns implemented per layer. Logging, authentication and transaction management copied into every class. Fix: handle them once — filters or interceptors at the edge, declarative transactions in the application layer, aspects where appropriate.
Best practices
- Write the flow matrix before the first deployment diagram; it forces the security and traceability questions.
- Enforce the dependency rule mechanically. ArchUnit-style tests that fail the build when
domainimportsinfrastructurecost an hour to set up and prevent years of drift. - Keep the domain layer free of framework annotations where practical. If a rule needs
@Transactionalto be correct, it is in the wrong layer. - Make the application layer the transaction boundary: one use case, one transaction, one place to look when something is half-committed.
- Treat a new tier as a product decision with an owner, an SLA and a runbook, not as a box on a slide.
- When a feature crosses many layers to do something trivial, question strictness rather than adding pass-through methods.
Key takeaways
- Tiers are deployment boundaries; layers are code boundaries. Change one without assuming the other must change.
- Two-tier put logic in the client, three-tier moved it to an application server, n-tier split the middle for isolation and scale — each step traded simplicity for a property you should be able to name.
- Describe a system at four levels — functional, application, technical, software — and use a flow matrix to tie applications to infrastructure.
- Inside a component, dependencies point inward toward the domain; the domain declares the interfaces that infrastructure implements.
- Hexagonal architecture is the same rule with the domain drawn in the centre, which stops teams designing around the database.
- The costly anti-patterns are logic in controllers, anaemic domains and entities on the wire; all three are cheap to prevent early and expensive to unwind later.
Sources and further reading
Frequently asked questions
- Is a three-tier architecture the same as a three-layer architecture?
- No. Tiers are physical: separate processes or machines such as a browser, an application server and a database server. Layers are logical: groups of code with distinct responsibilities that can all run in one process. A three-tier deployment usually contains more than three logical layers, and a single-tier desktop application can still be cleanly layered.
- Should every layer have its own data classes (DTOs)?
- Have a separate representation wherever the shape or lifecycle differs. API request/response objects should be distinct from persistence entities because they evolve for different reasons and expose different fields. Between the application layer and the domain layer, passing domain objects directly is usually fine; adding a mapping step there is ceremony without benefit.
- Is layered architecture outdated compared with microservices?
- They answer different questions. Layering organises code inside one deployable unit; microservices split a system into several deployable units. Every well-built microservice is internally layered, and most successful microservice migrations start from a monolith whose layers were clean enough to carve up. Poor layering makes both styles painful.
- Can a lower layer call an upper layer?
- Not directly. Dependencies must point one way, usually from the outside in. When a lower layer needs to trigger behaviour in an upper one, it publishes an event or calls an interface it owns that the upper layer implements. This inversion keeps the core free of references to frameworks and delivery mechanisms.