Layered (N-Tier) Architecture

Presentation, application, domain and data access stacked so each layer only calls the one below. Know layers from tiers, strict from relaxed, the sinkhole, and why the arrow from domain to database is the weak spot.

Overview

Layered architecture splits an application by kind of work: code that talks to the user, code that runs a use case, code that holds the business rules, and code that reads and writes storage. Each kind lives in its own layer, and a layer may call the layers below it but never the ones above it. Martin Fowler calls the three-part version (presentation, domain, data) one of the most common ways to modularize an information-rich program.

It is the default most teams reach for without naming it. Most web frameworks ship with folders for views, models and data, and many tutorials teach a controller, a service and a repository. Interviewers ask about it to see whether you can say what belongs in each layer, whether you know a layer from a tier, and whether you can spot the one dependency in the classic stack that points the wrong way.

The four layers

The three-layer split is the classic one. Many codebases add a fourth, thin application (or service) layer between presentation and domain to run one use case from start to finish.

Each layer owns some things, must never contain others, and has a typical member.

  • Presentation owns parsing input, formatting output, status codes and views. It never contains business rules or SQL. Example: the POST /withdraw handler.
  • Application (service) owns the steps of one use case, the transaction boundary and authorization checks. It never contains rules about money or stock, or HTML. Example: WithdrawService.withdraw().
  • Domain owns entities, invariants, calculations and decisions. It never contains HTTP, SQL or framework types. Example: Account.withdraw(amount).
  • Data access owns queries, mapping rows to objects, and connections. It never contains decisions about the business. Example: AccountStore.load(id).

Fowler's catalog in Patterns of Enterprise Application Architecture describes the Service Layer as the application's boundary: a set of operations that coordinates the response to each one. The Service Layer topic covers it in depth; here it is the layer that turns one request into calls on the domain and the store.

Interview questions

  • What is the difference between a layer and a tier?
  • Strict or relaxed layering: which would you choose, and when may a layer be skipped?
  • What is the architecture sinkhole anti-pattern, and what do you do about it?
  • In a classic layered design the domain depends on the persistence layer. Why is that a problem, and how do you fix it?
  • Where would you put validation, transactions and authorization in a layered system?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio