Sign in

Software architecture, from modular components to distributed systems

Understand core software architecture concepts, build modular layered boundaries, and design resilient distributed systems with clear trade-offs.

MonksBit Desk

November 25, 2026 · 8 min read · 31 views

Read

Software architecture is the fundamental organisation of a system embodied in its components, their relationships to each other and to the environment, and the principles guiding its design and evolution. It focuses on making high-impact structural decisions that are costly to change once implemented.

You will need. Basic understanding of functions, classes, and modular programming · Familiarity with network requests and client-server concepts

How well do you know this already?

The full lesson

Level 1 · Beginner: Understanding structural boundaries and the separation of concerns

Every software program begins as a series of instructions. When programs grow beyond a few dozen lines, placing all logic in a single file makes reasoning about errors difficult. Software architecture introduces deliberate structure so that individual parts of a system carry distinct responsibilities.

The foundational architectural pattern is the layered architecture. In this pattern, an application is split into horizontal tiers, commonly consisting of a presentation layer that interacts with the user, a domain layer that executes business rules, and a persistence layer that manages raw data storage.

Consider a small task management program. Without architecture, the code that reads user input might directly execute an SQL database query or mutate file records. With a layered architecture, the presentation tier delegates user requests to a service tier, which computes business rules and relies on a repository tier to store records.

Structuring code this way prevents changes in one domain from breaking unrelated functionality. If the database engine changes from a local file to a relational database, only the persistence layer requires modification, while user-facing logic remains untouched.

A minimal layered architecture separating storage from business logic

class TaskRepository:    def __init__(self):        self._storage = {}    def save(self, task_id: int, title: str) -> None:        self._storage[task_id] = title    def get(self, task_id: int) -> str | None:        return self._storage.get(task_id)class TaskService:    def __init__(self, repository: TaskRepository):        self.repository = repository    def create_task(self, task_id: int, title: str) -> str:        if not title.strip():            raise ValueError("Task title cannot be empty")        self.repository.save(task_id, title.strip())        return f"Task {task_id} created successfully"repo = TaskRepository()service = TaskService(repository=repo)print(service.create_task(1, "Write documentation"))

Key takeaways

  • Architecture establishes structural constraints to isolate responsibilities across components.
  • Layering separates business logic from data storage and external user interfaces.
  • Explicit boundaries allow developers to modify storage or presentation without altering core business rules.

Level 2 · Intermediate: Decoupling interfaces through dependency inversion and ports

While layered architectures separate concerns, high-level business rules often end up directly importing low-level persistence mechanisms. This creates hidden coupling where business models cannot be tested without running live database infrastructure.

The Dependency Inversion Principle solves this by requiring high-level modules and low-level modules to depend on abstract interfaces rather than concrete implementations. In hexagonal or ports-and-adapters architecture, the core domain defines interfaces, called ports, and infrastructure components implement them, acting as adapters.

To handle edge cases such as network dropouts or database corruption, intermediate architectures encapsulate error handling within adapters. If an external storage engine fails, the adapter translates low-level transport errors into well-defined domain exceptions.

Testing becomes straightforward under this design. By substituting the live database adapter with an in-memory repository conforming to the same interface, unit tests execute deterministically and without disk or network I/O.

Port and adapter implementation using abstract base classes for testability

from abc import ABC, abstractmethodclass AccountRepositoryPort(ABC):    @abstractmethod    def get_balance(self, account_id: str) -> float:        pass    @abstractmethod    def update_balance(self, account_id: str, new_balance: float) -> None:        passclass BankingService:    def __init__(self, accounts: AccountRepositoryPort):        self.accounts = accounts    def transfer(self, source_id: str, target_id: str, amount: float) -> None:        if amount <= 0:            raise ValueError("Transfer amount must be positive")        source_balance = self.accounts.get_balance(source_id)        if source_balance < amount:            raise ValueError("Insufficient funds")        target_balance = self.accounts.get_balance(target_id)        self.accounts.update_balance(source_id, source_balance - amount)        self.accounts.update_balance(target_id, target_balance + amount)class InMemoryAccountAdapter(AccountRepositoryPort):    def __init__(self, balances: dict[str, float]):        self._balances = balances    def get_balance(self, account_id: str) -> float:        if account_id not in self._balances:            raise KeyError(f"Account {account_id} not found")        return self._balances[account_id]    def update_balance(self, account_id: str, new_balance: float) -> None:        self._balances[account_id] = new_balanceadapter = InMemoryAccountAdapter({"acc-1": 100.0, "acc-2": 50.0})bank = BankingService(accounts=adapter)bank.transfer("acc-1", "acc-2", 40.0)assert adapter.get_balance("acc-1") == 60.0assert adapter.get_balance("acc-2") == 90.0

Key takeaways

  • Dependency inversion ensures core domain policies do not depend on external libraries or frameworks.
  • Ports define behavioural contracts; adapters fulfill those contracts using specific technologies.
  • Decoupled adapters enable deterministic unit testing without spin-up time for third-party systems.

Level 3 · Advanced: Distributed patterns, eventual consistency, and fault tolerance

When applications exceed the vertical compute capacity of a single machine or require independent deployment boundaries, the architecture transitions from monolithic in-memory boundaries to distributed systems.

Distributed systems replace in-memory function calls with network requests. This introduces the fallacies of distributed computing: network latency is non-zero, bandwidth is finite, and networks partition unexpectedly. In this environment, operations cannot rely on immediate ACID transactions across boundaries.

Architects use patterns such as the transactional outbox and asynchronous messaging to manage eventual consistency. Instead of updating a database and synchronously calling another service over HTTP, a service writes both its domain state and an outbox event to the local database in a single atomic transaction. An asynchronous worker then publishes the event.

Reliability patterns such as circuit breakers and retries with exponential backoff prevent cascading failures across service boundaries. If a downstream service degrades, circuit breakers trip to return fallback responses instead of exhausting thread pools waiting for timeouts.

Resilient invocation with an in-memory circuit breaker pattern

import timefrom typing import Callable, Anyclass CircuitBreakerOpenException(Exception):    passclass CircuitBreaker:    def __init__(self, failure_threshold: int = 3, recovery_time: float = 10.0):        self.failure_threshold = failure_threshold        self.recovery_time = recovery_time        self.failure_count = 0        self.last_failure_time = 0.0        self.state = "CLOSED"    def call(self, func: Callable[..., Any], *args, **kwargs) -> Any:        now = time.time()        if self.state == "OPEN":            if now - self.last_failure_time > self.recovery_time:                self.state = "HALF-OPEN"            else:                raise CircuitBreakerOpenException("Circuit is open; call rejected")        try:            result = func(*args, **kwargs)            if self.state in ("HALF-OPEN", "CLOSED"):                self.state = "CLOSED"                self.failure_count = 0            return result        except Exception as e:            self.failure_count += 1            self.last_failure_time = now            if self.failure_count >= self.failure_threshold:                self.state = "OPEN"            raise edef remote_call():    raise ConnectionError("Network failure")breaker = CircuitBreaker(failure_threshold=2, recovery_time=1.0)for _ in range(2):    try:        breaker.call(remote_call)    except ConnectionError:        passtry:    breaker.call(remote_call)except CircuitBreakerOpenException:    print("Circuit successfully opened, protecting downstream service")

Key takeaways

  • Distributed architectures trade transactional simplicity for independent scalability and fault isolation.
  • The transactional outbox pattern guarantees reliable cross-service communication despite crashes.
  • Circuit breakers and rate limiters shield internal systems from cascading network failures.

Complexity

  • Time: O(1) to O(N) depending on communication boundaries and fan-out
  • Space: O(1) to O(N) per operation for payload buffers and distributed state

In monolithic layered architectures, internal layer dispatch introduces negligible in-memory function call overhead O(1). In distributed microservices, network transport adds O(1) latency per serialized RPC hop, expanding to O(N) when queries fan out across N independent services sequentially or aggregate N records in memory.

Common mistakes

  • Prematurely decomposing a small application into distributed microservices before domain boundaries and communication patterns are fully understood.
  • Allowing presentation layers or external HTTP controllers to execute direct database queries, bypassing business rule validation.
  • Leaking infrastructure models into the domain model, such as importing database ORM annotations directly inside core business logic classes.
  • Assuming network calls are deterministic and omitting retry policies, timeouts, and circuit breaking mechanisms in inter-service communications.

Practice problems

  1. Refactor a monolithic script into three distinct architectural layers (easy). Hint: Create a file or class for user input validation, a separate class for business calculations, and a dictionary-backed storage repository.
  2. Implement an interface-driven notification service with swappable adapters (medium). Hint: Define an abstract base class with a send method, then write one adapter for console output and another for in-memory logging.
  3. Design an idempotent event consumer with an outbox mechanism (hard). Hint: Track processed event IDs within a persistence transaction to avoid applying duplicate state transitions when network retries occur.

Summary

Software architecture governs the structural partitioning, interfaces, and trade-offs of a software system. Starting from simple separation of concerns in layered designs, systems scale by decoupling business logic through abstract ports and adapters. In large-scale distributed topologies, architecture shifts focus to fault isolation, eventual consistency, and resilient network communication.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!