Layered Architecture
Intent
Organize code into stacked horizontal layers so that each layer only uses the layer directly beneath it, keeping UI, business logic, and data access cleanly separated.
When It Helps
- Small to medium team building a conventional business application (e.g. internal tools, CRUD systems).
- Requirements are fairly stable and the domain logic is simple enough to live in one middle layer.
- You want a structure every developer recognizes on day one, without extra abstractions.
Structure
flowchart TB
P["Presentation<br/>(UI / Controllers)"] --> B["Business Logic<br/>(Services / Rules)"]
B --> DA["Data Access<br/>(Repositories / Queries)"]
DA --> DB[("Database")]
Rules
- Presentation may call Business Logic, but never Data Access or the database directly.
- Business Logic may call Data Access, but never Presentation.
- Data Access owns all persistence details; upper layers never write SQL or touch connection objects.
- Dependencies point strictly downward — no layer calls upward and no layer skips a level.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the layer boundary
layer Presentation:
on submit_order(request):
# may only talk to the layer below
result = Business.OrderService.place(request.items)
render(result)
layer Business:
function place(items):
validate(items)
total = price(items) + tax(items)
return DataAccess.OrderStore.save(items, total)
layer DataAccess:
function save(items, total):
# only layer allowed to touch persistence
return database.insert("orders", {items, total})
Basic Recap
Layered architecture separates presentation, business rules, and persistence into a downward-pointing stack. Each layer exposes a contract to the layer above and hides the mechanics of the layer below. The approach works because most developers can infer where a change belongs without learning a large framework. Its value disappears when layers become labels rather than enforced dependency boundaries.
Complex Scenario
A claims operations team runs one application for adjusters, nightly renewals, and customer document uploads. A new regulatory report must combine claim rules with several database queries without duplicating policy calculations. The team adds a reporting facade above the business layer, but a shortcut lets that facade call back into presentation formatting. The resulting topology looks orderly until dependency checks and peak load expose the shortcuts.
flowchart TB
Adjuster["Adjuster UI"] --> Presentation["Presentation controllers"]
Renewal["Nightly renewal job"] --> Presentation
Presentation --> Business["Business services and policy rules"]
Business --> Access["Data access repositories"]
Access --> DB[("Claims database")]
Access --> Cache[("Policy cache")]
Report["Regulatory report facade"] --> Business
Presentation -. "forbidden callback" .-> Report
Failure walkthrough. During a tenfold renewal batch, each business call waits on the exhausted database pool while presentation threads remain blocked above it. The reporting callback also creates a dependency cycle, so a harmless formatting change now requires business code to recompile. Mitigate the runtime failure with bounded job concurrency, query timeouts, and a separate reporting read pool; remove the cycle by moving neutral formatting below presentation or passing formatted output outward.
Edge cases — concurrent renewals can reserve the same claim, retries can duplicate a submission, and partial failure can leave a report mixing policy versions. Use database-backed claim versions, idempotency keys, and a report snapshot token rather than relying on layer placement to solve these problems.
Sketch (illustrative pseudocode, not runnable):
dependency_rules:
presentation -> business
business -> data_access
forbidden: business -> presentation
forbidden: presentation -> data_access
renewal_job:
workers: 4
claim_lock: optimistic_version
repository_timeout: 800ms
retry: only_if idempotency_key_present
Trade-offs
- Benefit: simple, familiar separation that keeps UI and SQL out of each other’s way.
- Cost: rigid layering can force trivial logic through every level, and the business layer tends to become a catch-all as the system grows.
When to Use / When Not to Use
Use when:
- Small team, uniform stack, CRUD-heavy app with stable layers.
Avoid when:
- One feature routinely cuts across all layers with independent deploy needs — consider Vertical Slice.
Anti-pattern / Failure Mode
- Misuse: Every feature edits every layer with circular imports between them.
- Review signal: Changes that touch 4+ layers for one field.
Failure Modes / Trade-offs
- Pass-through stack: controllers, services, and repositories repeat the same method names without adding decisions. Collapse empty layers for simple features instead of preserving symmetry.
- Business-layer sink: validation, orchestration, caching, and UI formatting all migrate into one service package. Review signals are thousand-line services and imports from every other package.
- Layer skipping: a controller issues SQL for a quick report, then production behavior diverges from tested business rules. Make the exception a deliberate read path rather than an undocumented shortcut.
- Operational trade-off: a shared stack keeps transactions and debugging straightforward, but one slow lower layer can stall every entry point unless resource budgets are applied per workload.
Boundary review. A change to presentation markup should not alter repository tests, and a schema change should not require controller edits except at an explicit mapping boundary.
Transaction review. Document which layer begins and ends a transaction; hidden commits inside repositories make retries and batch recovery unpredictable.
Test review. Test policy beneath the UI with repository fakes, then retain a few full-stack tests to prove that the real downward wiring still works.
Release review. Track changes that cross all three layers; frequent vertical changes are normal for a feature, but widespread edits for one rule suggest misplaced responsibility.
- Reuse trade-off: generic services shared by unrelated features become coordination points, so reuse should follow stable policy rather than similar method signatures.
- Security trade-off: authorization only in presentation leaves jobs exposed, while authorization only in repositories loses caller intent; place each check at its appropriate boundary.
- Data trade-off: one shared persistence model is simple, but reporting-specific queries may need separate projections without becoming a new business layer.
- Change trade-off: strict downward dependencies aid navigation, yet they do not replace feature ownership or prevent a large business layer from becoming coupled.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Team of 2–8 developers with conventional CRUD work | Use a small three-layer stack; it is easy to navigate and needs little architectural staffing. |
| Strict latency budget for simple queries | Use cautiously: permit measured read-only shortcuts, but avoid forcing every query through ceremonial mappings. |
| Many autonomous teams changing unrelated domains | Avoid one shared layered codebase; feature or domain boundaries will usually serve ownership better. |
| Regulatory requirement for repeatable calculations | Use an enforced business layer with versioned rules, and keep reporting on a consistent snapshot. |
Related Patterns
- Hexagonal — keeps the same idea of isolating business logic but replaces stacked layers with ports and adapters.
- Vertical Slice — organizes the same code by feature instead of by technical layer.
- MVC / MVVM / MVP — a finer-grained split for structuring just the presentation layer above.
- Modular Monolith — layering inside enforced module boundaries.
- Separation of Concerns — the principle behind the layers.