- Part 4 of 21 in System Design Roadmap: From Beginner to Intermediate Architecture Beginner
Layered Software Architecture: Structuring Scalable Systems Across Boundaries
Design, implement, and test modular enterprise applications using strict presentation, business, and data access layers.
MonksBit Desk
November 25, 2026 · 9 min read · 35 views
Read
Layered architecture is a software design pattern where code is organized into distinct horizontal tiers, each assigned a specific role: presentation handles user interaction, business logic enforces domain rules, and data access manages persistent storage. Each layer communicates exclusively with its adjacent lower layer through well-defined contracts.
You will need. Object-oriented programming concepts such as classes and interfaces · Basic knowledge of client-server application flows
The full lesson
Level 1 · Beginner: Core concepts and the three foundational tiers
Software applications grow complicated quickly when user interface code, calculation rules, and database queries live in the same place. Changing a database column might break the screen display, or updating an interface layout might inadvertently corrupt database values. Layered architecture solves this by enforcing a separation of concerns.
The architecture consists of three core components. The presentation layer captures inputs and formats outputs for human or machine clients. The business logic layer validates actions, executes calculations, and decides outcomes. The data access layer executes operations against storage mechanisms like databases, external caches, or files.
Execution flows downward in a single direction. The client talks only to the presentation layer. The presentation layer delegates strictly to the business layer. The business layer delegates strictly to the data layer. Responses flow back up the chain in reverse order without any layer skipping its neighbor.
A minimal three-tier implementation in Python
class UserRepository: def __init__(self): self._storage = {} def save(self, user_id: int, user_data: dict) -> None: self._storage[user_id] = user_data def find_by_id(self, user_id: int) -> dict | None: return self._storage.get(user_id)class UserService: def __init__(self, repository: UserRepository): self._repository = repository def register_user(self, user_id: int, email: str, age: int) -> dict: if age < 18: raise ValueError("User must be at least 18 years old") record = {"email": email, "age": age} self._repository.save(user_id, record) return recordclass UserController: def __init__(self, service: UserService): self._service = service def handle_post_request(self, payload: dict) -> tuple[int, dict]: try: user = self._service.register_user( user_id=payload["id"], email=payload["email"], age=payload["age"] ) return 201, {"status": "created", "data": user} except (ValueError, KeyError) as error: return 400, {"status": "error", "message": str(error)}repo = UserRepository()service = UserService(repo)controller = UserController(service)code, body = controller.handle_post_request({"id": 1, "email": "alice@example.com", "age": 22})assert code == 201assert body["data"]["email"] == "alice@example.com"
Key takeaways
- Presentation manages incoming input and outgoing output formatting.
- Business logic enforces constraints and domain operations independently of transport and storage.
- Data access encapsulates storage mechanics, hiding databases from upper layers.
Level 2 · Intermediate: Decoupling with abstractions and handling edge cases
In production systems, direct concrete coupling between layers prevents unit testing and locks the application into a single storage technology. To achieve loose coupling, we introduce protocol or interface abstractions between the business layer and the data access layer.
Under this pattern, the business layer defines an abstract boundary describing the persistence capabilities it requires. The data access layer implements this interface. The concrete implementation is passed into the business layer using dependency injection during application startup.
Edge cases must be trapped and translated at layer boundaries. Database connectivity failures or unique constraint violations originating in data access should not leak as raw database driver exceptions to the presentation layer. Instead, data access transforms low-level errors into domain-specific exceptions, which the business layer handles or passes up for appropriate presentation formatting.
Decoupled architecture using abstract interfaces and custom domain errors
from abc import ABC, abstractmethodfrom dataclasses import dataclassclass DomainError(Exception): passclass UserAlreadyExistsError(DomainError): passclass ValidationError(DomainError): pass@dataclass(frozen=True)class UserEntity: id: int email: str credits: intclass UserDataGateway(ABC): @abstractmethod def get_by_id(self, user_id: int) -> UserEntity | None: raise NotImplementedError @abstractmethod def save(self, user: UserEntity) -> None: raise NotImplementedErrorclass MemoryUserDataGateway(UserDataGateway): def __init__(self) -> None: self._records: dict[int, UserEntity] = {} def get_by_id(self, user_id: int) -> UserEntity | None: return self._records.get(user_id) def save(self, user: UserEntity) -> None: self._records[user.id] = userclass AccountService: def __init__(self, gateway: UserDataGateway) -> None: self._gateway = gateway def create_account(self, user_id: int, email: str, initial_credits: int) -> UserEntity: if "@" not in email: raise ValidationError("Invalid email format") if initial_credits < 0: raise ValidationError("Initial credits cannot be negative") if self._gateway.get_by_id(user_id) is not None: raise UserAlreadyExistsError(f"User {user_id} already exists") user = UserEntity(id=user_id, email=email, credits=initial_credits) self._gateway.save(user) return userclass RestPresentationHandler: def __init__(self, service: AccountService) -> None: self._service = service def post_user(self, payload: dict) -> tuple[int, dict]: required_fields = ("id", "email", "credits") if not all(field in payload for field in required_fields): return 400, {"error": "Missing required fields"} try: user = self._service.create_account( user_id=int(payload["id"]), email=str(payload["email"]), initial_credits=int(payload["credits"]) ) return 201, {"id": user.id, "email": user.email, "credits": user.credits} except ValidationError as err: return 422, {"error": str(err)} except UserAlreadyExistsError as err: return 409, {"error": str(err)}handler = RestPresentationHandler(AccountService(MemoryUserDataGateway()))status, body = handler.post_user({"id": 42, "email": "test@domain.com", "credits": 10})assert status == 201assert body["id"] == 42status_dup, _ = handler.post_user({"id": 42, "email": "test@domain.com", "credits": 10})assert status_dup == 409
Key takeaways
- Abstract boundaries enable swapping concrete data sources without altering business logic.
- Exceptions from underlying systems must be captured and translated into domain-level exceptions.
- Presentation layers should solely validate wire-format shape; domain validation belongs in the business layer.
Level 3 · Advanced: Strict layering, performance optimizations, and boundary limits
In a strict layered architecture, a layer can only call the layer immediately below it. In a relaxed layered architecture, a layer may bypass adjacent layers to query lower tiers directly, such as presentation reading directly from data access for high-speed read operations. While relaxed layering reduces overhead for read-heavy screens, it introduces coupling that can leak persistence details into the interface.
The primary performance bottleneck in strict layered architectures is the object-relational mapping (ORM) overhead and duplicate object translation across boundaries. Creating separate Data Transfer Objects (DTOs), Domain Entities, and Database Records incurs CPU and memory penalties. High-throughput systems solve this by defining projection models that bypass domain entity synthesis for read-only flows, commonly formalized as Command Query Responsibility Segregation (CQRS).
Layered architectures reach their architectural limits when domain rules span distributed data sources or when business logic becomes too interconnected to fit into straightforward top-down hierarchies. In such environments, hexagonal or clean architecture is often favored to invert dependencies completely, or services are split along bounded contexts into microservices.
Strict vs projection query paths with a Unit of Work boundary
from typing import Protocol, NamedTupleclass UserReadProjection(NamedTuple): user_id: int email: str credits: intclass ReadOnlyDataGateway(Protocol): def get_projection(self, user_id: int) -> UserReadProjection | None: ...class ReadQueryService: def __init__(self, reader: ReadOnlyDataGateway) -> None: self._reader = reader def fetch_user_summary(self, user_id: int) -> dict | None: projection = self._reader.get_projection(user_id) if projection is None: return None return { "id": projection.user_id, "contact": projection.email, "balance": projection.credits }class FastInMemoryReader(ReadOnlyDataGateway): def __init__(self, data: dict[int, tuple[str, int]]) -> None: self._data = data def get_projection(self, user_id: int) -> UserReadProjection | None: row = self._data.get(user_id) if not row: return None return UserReadProjection(user_id=user_id, email=row[0], credits=row[1])reader = FastInMemoryReader({100: ("bob@example.com", 500)})query_service = ReadQueryService(reader)result = query_service.fetch_user_summary(100)assert result == {"id": 100, "contact": "bob@example.com", "balance": 500}
Key takeaways
- Strict layering maintains clean isolation, whereas relaxed layering allows selective shortcuts for read throughput.
- CQRS can mitigate the performance penalty of converting entities across every layer for read queries.
- When domain models become excessively coupled across horizontal tiers, domain-driven microservices or hexagonal models provide better boundaries.
Complexity
- Time: O(1) layer overhead, overall runtime bounded by database operations O(f(N))
- Space: O(1) memory overhead beyond object allocation for layer-crossing models
Passing invocations and parameters through each layer introduces fixed-cost function call stack frames and lightweight object mapping overhead, which scales as O(1). The aggregate time and space complexity of an operation is dominated entirely by the business algorithm executed or the database query performed within the data access layer.
Common mistakes
- Placing SQL queries or direct database drivers inside controllers or presentation handlers.
- Bypassing business validation during update operations by directly mutating the database from presentation components.
- Leaking database entities directly into UI templates or external REST responses without DTO mapping, exposing sensitive columns.
- Throwing raw database driver errors directly up to the UI, revealing infrastructure implementation details to end users.
Practice problems
- Add in-memory pagination to data access layer (easy). Hint: Pass limit and offset parameters down from the controller through the service into the gateway.
- Implement credit transfer with transactional rollback (medium). Hint: Ensure the business service coordinates debit and credit steps such that failure in one aborts both in the storage layer.
- Build a caching decorator between business and data layers (hard). Hint: Create a layer that implements the same gateway interface, checks a cache first, and falls back to the underlying persistence implementation.
Summary
Layered architecture establishes distinct operational boundaries across presentation, business logic, and data access tiers. By enforcing strict downward communication and abstract contracts, teams can independently develop, test, and swap underlying storage technologies without compromising business rules or UI delivery.
Finish the Prove step above to complete this lesson.
System Design Roadmap: From Beginner to Intermediate Architecture · 4 of 21
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!