Layered (N-Tier) Architecture
Organize an application into horizontal layers—Presentation, Business, and Data—where each layer only calls the layer directly below it.
1. Intent
Separate an application into horizontal technical layers—Presentation, Business, and Data—so UI handling, business rules, and database queries do not live in the same file, with dependencies flowing strictly downward.
2. Problem
When a small Order API grows inside route handlers, HTTP parsing, discount rules, tax math, and SQL queries end up tangled together. Changing a table column breaks validation; testing a discount calculation requires a running Postgres instance.
Over time, two classic layered pitfalls appear even after splitting files:
- Leaky layers: A controller bypasses the business layer and queries the database directly, or the business layer accepts raw HTTP
Requestobjects. - Database-centric design: Because Business depends on Data, and Data mirrors SQL tables, domain models turn into thin wrappers around database rows instead of expressing business rules.
3. Solution
Group code by technical responsibility into stacked horizontal layers:
- Presentation: Parses HTTP requests, validates input shapes, and formats JSON responses.
- Business (Domain / Service): Enforces Order rules—stock checks, totals, and discounts—without knowing about HTTP status codes or SQL syntax.
- Data (Persistence): Reads and writes
ordersrows in Postgres.
Each layer only talks to the layer immediately below it. Presentation calls Business; Business calls Data; Data talks to Postgres.
4. Real-world analogy
5. Flow: watch it work
Layered Order Service: Place Order
Press Start or tap any step dot to trace the path.
▸All steps (8)
6. Structure: Dependency Rule
In classic Layered architecture, dependencies point top-down. Presentation depends on Business, and Business depends on Data.
7. Code
// --- Data Layer (src/data/order-repo.ts) ---
export interface OrderRow {
id: string;
customerId: string;
totalCents: number;
}
export class OrderRepo {
async insert(customerId: string, totalCents: number): Promise<OrderRow> {
// Simulated Postgres INSERT
return { id: 'ord_101', customerId, totalCents };
}
}
// --- Business Layer (src/business/order-service.ts) ---
export interface OrderItemInput {
priceCents: number;
qty: number;
}
export class OrderService {
constructor(private readonly repo: OrderRepo) {}
async placeOrder(customerId: string, items: OrderItemInput[]): Promise<OrderRow> {
if (items.length === 0) {
throw new Error('Order must contain at least one item');
}
const totalCents = items.reduce((sum, item) => sum + item.priceCents * item.qty, 0);
return this.repo.insert(customerId, totalCents);
}
}
// --- Presentation Layer (src/presentation/order-controller.ts) ---
export class OrderController {
constructor(private readonly service: OrderService) {}
async handlePost(body: { customerId: string; items: OrderItemInput[] }) {
const order = await this.service.placeOrder(body.customerId, body.items);
return { status: 201, data: order };
}
}labs/arch-order-serviceRun the Layered Order service alongside Hexagonal and Clean implementations in one repo.
cd labs/arch-order-service && npm install && npm run typecheck && npm test && npm run start:layered8. When to use / when to avoid
- You are building a straightforward CRUD app or internal admin tool with simple domain rules.
- The team is small and wants a familiar folder layout (controllers, services, repositories) on day one.
- Database schema and business objects map closely without complex invariants.
- Business rules are rich and need fast unit tests with zero database or ORM setup.
- You need to swap databases, message brokers, or external APIs without touching business logic.
- The app is large enough that horizontal layers create a big ball of mud across features.
9. How to implement
Split folders by horizontal layer
Create presentation/, business/, and data/ directories so team members know where each responsibility belongs.
Keep HTTP types out of Business
Parse request bodies and set HTTP status codes in Presentation; pass plain TypeScript objects into OrderService.
Enforce downward-only imports
Add an ESLint import rule so presentation/ never imports data/ directly, preventing leaky shortcuts.
Watch for DB-centric drift
When OrderService starts returning raw ORM models with lazy-loaded relations, consider introducing Dependency Inversion or Hexagonal Architecture.
10. Pros / Cons
- Minimal boilerplate and fast to scaffold for CRUD-heavy services.
- Every developer immediately recognizes the Controller → Service → Repository flow.
- Easy to enforce basic separation of concerns in small codebases.
- Business logic depends directly on the Data layer, making pure domain unit tests harder.
- Layers often turn into pass-throughs ("sinkhole" anti-pattern) that add files without logic.
- Schema changes in the database ripple upward into business services.
11. Relations
Inverts the Business → Data dependency so the domain owns an interface and Postgres plugs in as an adapter.
Side-by-side comparison of Layered, Hexagonal, Onion, and Clean on the same Order request.
The SOLID principle that breaks the Business → Data coupling.
12. Check yourself
Check Yourself
1. In classic Layered Architecture, why is testing Business logic without a database harder than in Hexagonal Architecture?
2. What happens in a 'leaky layer' shortcut?
Sources
Related Notes
Pattern Relations: Bridge vs Adapter vs Strategy vs Decorator vs State
Five patterns that share composition and interface delegation—how their intents, lifecycles, and trade-offs differ.
Hexagonal Architecture (Ports & Adapters)
Isolate core business logic inside ports and plug in external drivers—REST, CLI, Postgres, or in-memory fakes—as interchangeable adapters.