Architecture Styles
What you’ll learn. What “architecture” means beyond box-and-arrow diagrams; the major styles (layered, hexagonal/clean/onion, modular monolith, microservices, event-driven, CQRS and event sourcing); the core vocabulary of domain-driven design (bounded contexts, aggregates, ubiquitous language); and how to choose a style from the forces you actually face rather than from fashion.
What architecture is
Section titled “What architecture is”Architecture is the set of decisions that are expensive to change: how the system is divided into parts, how those parts communicate, where data lives, and which constraints (latency, availability, team structure) the design optimizes. Ralph Johnson’s quip: architecture is “the stuff that’s hard to change”. Architecture styles are reusable shapes for those decisions, each with a characteristic set of trade-offs.
Two guiding ideas:
- Quality attributes drive architecture. Functionality barely constrains architecture; “must handle 50k requests/s”, “deploy ten times a day”, “team of 200 engineers”, “auditable” do. Identify the dominant quality attributes (availability, scalability, modifiability, testability, security, cost) before choosing.
- Conway’s law (1968): organizations produce designs that mirror their communication structure. Systems and teams co-evolve; the “inverse Conway maneuver” shapes teams to get the architecture you want.
Layered architecture
Section titled “Layered architecture”The oldest style: organize code into horizontal layers, each depending only on the layer below.
+---------------------------+| Presentation (HTTP, UI) |+---------------------------+| Application / Service |+---------------------------+| Domain / Business logic |+---------------------------+| Persistence / Data access |+---------------------------+ (dependencies point downward)Strengths: simple, widely understood, enforces separation of concerns, easy to onboard. Weaknesses: the domain depends on persistence (the bottom layer), so business logic gets entangled with SQL and ORM details; changes tend to ripple through every layer (“sinkhole anti-pattern”: a request passes through layers that add nothing); and the layering is technical, not business-oriented, so a feature touches all layers while the team structure hardens along layer lines. It is a fine default for CRUD-heavy applications with little domain logic.
Hexagonal, onion and clean architecture
Section titled “Hexagonal, onion and clean architecture”Alistair Cockburn’s hexagonal architecture (ports and adapters, 2005), Jeffrey Palermo’s onion architecture, and Robert Martin’s Clean Architecture converge on one idea: invert the dependency so that the domain is at the center and depends on nothing; infrastructure depends on the domain (Core Principles: the Dependency Inversion Principle).
Driving (primary) side Driven (secondary) side HTTP controller ----+ +---- PostgresOrderRepo CLI command -------+--> [ PORT ] [ PORT ] <----+---- SmtpMailer Message consumer ---+ use cases domain interfaces +---- StripeGateway (application core)- Domain: entities, value objects, domain services; pure logic, no I/O.
- Application (use cases): orchestrates domain objects to fulfill a request; defines ports (interfaces) for what it needs from the outside.
- Adapters: implement ports (database, queues, HTTP clients) and call into the application (controllers, CLIs, consumers). This is the Adapter pattern.
# Python sketch: the dependency rule# domain/order.py (imports nothing from infrastructure)from dataclasses import dataclass
@dataclassclass Order: id: str lines: list[tuple[str, int, int]] # sku, qty, unit_price_cents def total_cents(self) -> int: return sum(q * p for _, q, p in self.lines)
# application/ports.pyfrom typing import Protocolclass OrderRepository(Protocol): def get(self, order_id: str) -> Order: ... def save(self, order: Order) -> None: ...class PaymentGateway(Protocol): def charge(self, amount_cents: int, token: str) -> str: ...
# application/pay_order.pydef pay_order(order_id: str, token: str, repo: OrderRepository, pay: PaymentGateway) -> str: order = repo.get(order_id) receipt = pay.charge(order.total_cents(), token) repo.save(order) return receipt# infrastructure/ contains SqlOrderRepository, StripePaymentGateway and the web framework glueBenefits: the core is testable with in-memory fakes and no database; frameworks and databases become replaceable details; the business rules are readable on their own. Costs: more files and mapping code (DTOs, entities vs ORM models), real overhead for simple CRUD. Apply it where there is significant domain logic with a long life; skip it for glue services.
Monolith, modular monolith, microservices
Section titled “Monolith, modular monolith, microservices”A monolith is a single deployable unit. A microservice architecture splits the system into independently deployable services, each owning its data and communicating over the network.
The decision is mostly organizational and operational, not about code quality.
| Monolith | Modular monolith | Microservices | |
|---|---|---|---|
| Deployment | One unit | One unit | Many units, independent |
| Module boundaries | Often blurred | Enforced in code | Enforced by network |
| Data | One shared DB | Shared DB, owned schemas/tables per module | DB per service |
| Calls | In-process | In-process via module APIs | Network (latency, partial failure) |
| Transactions | ACID | ACID | Distributed (sagas, eventual consistency) |
| Ops complexity | Low | Low | High (orchestration, tracing, versioning) |
| Team scaling | Poor beyond ~tens of devs | Moderate | Good (independent teams) |
Why microservices cost so much. Every function call that became a network call acquires latency, timeouts, retries, partial failure and version skew. You need service discovery, API gateways, distributed tracing, per-service CI/CD, and you give up cross-service ACID transactions (Distributed Systems covers sagas and consistency). The “distributed monolith”, where services must be deployed together and share a database, combines the downsides of both.
Modular monolith. One deployable, but strict internal module boundaries: each module has a public API, private internals and (ideally) its own database schema; modules do not reach into each other’s tables. Tools can enforce this (ArchUnit in Java, import-linter in Python, ESLint boundary rules or Nx constraints in TypeScript). It captures most of the modularity benefits at a fraction of the operational cost and leaves a path to extract a service later along an already-clean seam. Since roughly 2020, many well-known teams have publicly retreated from over-fragmented microservices toward modular monoliths; the pragmatic advice (“monolith first”, Martin Fowler) is to start modular and split only for a concrete reason.
Legitimate reasons to extract a service: independent scaling profile (a GPU-bound or very hot component), different tech or security requirements, team autonomy at large organizational scale, fault isolation for a critical path, and regulatory separation. “It’s the modern thing” is not one.
Event-driven architecture
Section titled “Event-driven architecture”Components communicate by producing and consuming events (facts that happened: OrderPlaced) through a broker (Kafka, RabbitMQ, SNS/SQS, NATS, cloud event buses) rather than by calling each other directly.
OrderService --OrderPlaced--> [ broker/topic ] --> InventoryService --> EmailService --> AnalyticsPipelineBenefits: temporal decoupling (consumers can be down and catch up), fan-out without producer knowledge, natural audit trail, buffering of load spikes (System Design Fundamentals on queues). Costs: harder to reason about flow (no single place shows the whole business process), eventual consistency, duplicate and out-of-order delivery (consumers must be idempotent), schema evolution across producers and consumers, debugging difficulty.
Distinguish three kinds of message: commands (“do this”, addressed to one handler), events (“this happened”, broadcast, past tense) and queries. Two collaboration styles: choreography (services react to each other’s events; no central coordinator; flow is emergent) vs orchestration (a coordinator, such as a workflow engine, directs steps; easier to see and debug). Also distinguish event notification (thin: just an ID), event-carried state transfer (fat: includes data so consumers need not call back), and event sourcing (below).
The transactional outbox pattern solves the dual-write problem: if a service writes to its DB and then publishes an event, a crash in between loses consistency. Instead, write the event to an outbox table in the same DB transaction, and a relay publishes it afterwards (at-least-once, so consumers dedupe).
CQRS and event sourcing
Section titled “CQRS and event sourcing”CQRS (Command Query Responsibility Segregation, Greg Young, building on Bertrand Meyer’s CQS) separates the model used to change state (commands) from the model used to read it (queries). At its simplest this means different classes or endpoints for writes and reads. At its fullest, there are separate stores: a normalized write model enforcing invariants and one or more denormalized read models (projections) optimized for specific queries, updated asynchronously via events.
Why: read and write workloads have different shapes (reads are often 10-1000x more frequent and need joins and search; writes need consistency and validation). Cost: eventual consistency between sides (read-your-writes needs care), more moving parts. Use it where read/write asymmetry or complex query needs justify it; do not apply it to the whole system by default.
Event sourcing stores state as an append-only log of events rather than the current state; current state is derived by replaying (folding) events.
# Python: event-sourced bank accountfrom dataclasses import dataclass
@dataclass(frozen=True)class Deposited: amount: int@dataclass(frozen=True)class Withdrawn: amount: int
def apply(balance: int, event) -> int: match event: case Deposited(a): return balance + a case Withdrawn(a): return balance - a return balance
def rebuild(events) -> int: balance = 0 for e in events: balance = apply(balance, e) return balance
def withdraw(events, amount): # command handler enforces invariants if rebuild(events) < amount: raise ValueError("insufficient funds") return events + [Withdrawn(amount)]Benefits: complete audit trail, temporal queries (“balance on 1 March”), ability to rebuild new read models by replay, natural fit with CQRS. Costs: significant: schema evolution of stored events (upcasting) is hard and permanent, replay can be slow (mitigated by snapshots), deleting data (GDPR “right to erasure”) conflicts with immutability (crypto-shredding is one approach), steep learning curve, and querying current state requires projections. Event sourcing is powerful for domains where history is itself the business (ledgers, trading, logistics); it is overkill for most CRUD.
Domain-driven design basics
Section titled “Domain-driven design basics”DDD (Eric Evans, 2003) is an approach for software with complex business logic. Its ideas have shaped microservice boundaries and hexagonal cores.
Strategic design (the big picture):
- Ubiquitous language: one shared vocabulary used by developers and domain experts, in conversation and in code. If the business says “policy lapse”, the code has
Policy.lapse(), notstatus = 3. - Bounded context: a boundary within which a model and its language are consistent. The word “Customer” means different things in Sales (a lead with a pipeline), Billing (an account with payment terms) and Support (a person with tickets). Trying to build one universal
Customermodel produces a bloated, contradictory class. Each context gets its own model. - Context map: how contexts relate: shared kernel, customer/supplier, conformist, anti-corruption layer (translate a foreign model so it does not pollute yours), open host service / published language.
- Subdomains: core (competitive advantage; invest and build in-house), supporting (necessary, simple), generic (buy or use off-the-shelf: auth, billing).
Tactical design (building blocks inside a context):
- Entity: identity matters over time (
Order#123). - Value object: defined by its attributes, immutable, no identity (
Money(10, "EUR"),Address). - Aggregate: a cluster of entities and value objects treated as one consistency unit, with a single aggregate root that is the only entry point. Invariants are enforced within an aggregate in one transaction; between aggregates, use eventual consistency and references by ID.
- Repository: collection-like interface to load and save aggregates (a port).
- Domain service: logic that does not naturally belong to one entity.
- Domain event: something meaningful that happened (
OrderPlaced).
// TypeScript: aggregate root protecting an invariantclass Money { constructor(readonly cents: number, readonly currency: string) { if (!Number.isInteger(cents)) throw new Error("cents must be an integer"); } add(o: Money) { if (o.currency !== this.currency) throw new Error("currency mismatch"); return new Money(this.cents + o.cents, this.currency); }}
class Order { // aggregate root private lines: { sku: string; qty: number; price: Money }[] = []; private placed = false; constructor(readonly id: string) {} addLine(sku: string, qty: number, price: Money) { if (this.placed) throw new Error("cannot modify a placed order"); if (qty <= 0) throw new Error("qty must be positive"); this.lines.push({ sku, qty, price }); } place() { if (this.lines.length === 0) throw new Error("empty order"); this.placed = true; // would also emit OrderPlaced }}Rules of thumb for aggregates: keep them small, reference other aggregates by ID, one aggregate modified per transaction. Big aggregates cause contention and lock conflicts.
DDD is investment-heavy. Its strategic half (language, bounded contexts) pays off broadly; the tactical half pays off where logic is rich. Do not impose aggregates and repositories on a CRUD admin screen.
Choosing: a decision procedure
Section titled “Choosing: a decision procedure”- Is the domain simple and the team small? A well-structured monolith with layers.
- Rich domain logic, long life? Hexagonal core with DDD-style modeling inside a modular monolith.
- Need decoupled reactions, buffering, or integration with many consumers? Add events (with an outbox) at specific seams.
- Read/write asymmetry or radically different query needs? Add CQRS for that slice only.
- Many autonomous teams, differing scaling, clear bounded contexts? Extract microservices along bounded-context lines, one at a time.
- History is the product? Consider event sourcing for that bounded context.
Architecture should be recorded as decisions with context and consequences; see Architecture Decision Records in Engineering Practice.
Pitfalls
Section titled “Pitfalls”- Resume-driven architecture: Kafka, Kubernetes and ten services for a product with a hundred users.
- Distributed monolith: services sharing a DB or requiring lockstep releases.
- Anemic domain model: entities are bags of getters/setters; all logic in “service” classes, defeating DDD’s point.
- Shared database integration between services: hidden coupling at the schema level.
- Technology-first boundaries (split by layer rather than by business capability).
- Premature microservices: splitting before you know the boundaries; wrong boundaries are far costlier across a network than inside a process.
Key takeaways
Section titled “Key takeaways”- Architecture is the set of hard-to-change decisions, driven by quality attributes and team structure (Conway’s law).
- Layered is simple but couples domain to persistence; hexagonal/clean inverts dependencies so the domain is at the center.
- Modular monolith first; extract microservices for concrete scaling, autonomy or isolation reasons, accepting the distributed-systems tax.
- Event-driven designs decouple in time and enable fan-out but demand idempotency, schema discipline and the outbox pattern.
- CQRS and event sourcing are specialized tools with real costs; apply to bounded slices.
- DDD: ubiquitous language and bounded contexts matter most; aggregates define consistency boundaries.
Exercises
Section titled “Exercises”- Conceptual. A startup with 8 engineers proposes 15 microservices. Argue for or against using the table above and name the first signs of a distributed monolith.
- Hands-on (Python). Refactor a function that reads orders from SQLite and emails customers into a use case taking
OrderRepositoryandMailerprotocols. Write a test with fakes. - Conceptual. Identify the bounded contexts and the different meanings of “Product” in an e-commerce system (catalog, inventory, pricing, shipping).
- Hands-on (TypeScript). Design an
Orderaggregate that prevents adding lines after payment and forbids negative quantities. What events would it raise? - Conceptual. Explain the dual-write problem and how an outbox solves it. What delivery guarantee results, and what must consumers do?
Solutions (sketch)
- Against: ops overhead, cross-service transactions, no independent team scaling needed; start with a modular monolith. Distributed-monolith signs: lockstep deploys, shared DB, chatty synchronous call chains, one team changing many services per feature.
- Catalog: descriptions, images, categories. Inventory: SKU and stock counts. Pricing: price rules, currency. Shipping: weight and dimensions. Each context has a different model keyed by a shared
productId. - Raise
LineAdded,OrderPlaced,OrderPaid; guard against changes afterpaid. - Writing to DB and broker are not atomic; a crash between them desynchronizes. The outbox stores the event in the same transaction as the state change; a relay publishes afterward. Result: at-least-once delivery, so consumers must be idempotent.
Further reading
Section titled “Further reading”- Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software (2003).
- Vaughn Vernon, Implementing Domain-Driven Design (2013) and Domain-Driven Design Distilled (2016).
- Robert C. Martin, Clean Architecture (2017).
- Alistair Cockburn, “Hexagonal Architecture” (2005).
- Sam Newman, Building Microservices (2nd ed., 2021) and Monolith to Microservices (2019).
- Martin Kleppmann, Designing Data-Intensive Applications (2017), for event logs and stream processing.
- Neal Ford, Mark Richards, et al., Fundamentals of Software Architecture (2020).
- Martin Fowler, “MonolithFirst” and “CQRS” articles (martinfowler.com).