Bookmarks

Software architecture

Software architecture is the set of key decisions about how a system is structured, and their trade-offs. This reference covers styles, microservices, DDD, integration, data, resilience, C4 and ADRs.

checked 6 Nov · next check 13 Nov · 83 min read

Sections
14
Reading
83 min
Languages
RU · UZ · EN
Written from
iso.org/standard/74393.html

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What software architecture is and how it works

Software architecture is the set of key decisions about how a system is structured: what parts it consists of, how they are connected and deployed, and why it was done that way. The ISO/IEC/IEEE 42010:2022 standard distinguishes the architecture itself from its description (architecture description): the standard’s requirements apply to the description, not to the system.

There is a shorter definition: “Architecture is the stuff that’s important. Whatever that is” — as Ralph Johnson put it in a conversation with Martin Fowler. Behind the joke is a working criterion: a decision is architectural if you would want to get it right from the start and it is expensive to change later.

Which decisions are architectural

An architecturally significant requirement is a requirement that noticeably affects the architecture and quality of a system: performance, availability, security. An architectural decision is a justified choice that answers a significant functional or non-functional requirement. Examples:

  • monolith or a set of services — shapes teams, deployment and communication
  • the main database — shapes consistency, scaling and cost
  • synchronous or asynchronous communication — shapes failures and latency
  • not significant: a class name or a date-formatting library — changed in hours

A significant decision is recorded as an ADR (architectural decision record): context, options, choice and consequences. The set of records for a project is the decision log.

Levels: system, modules, code

The same question — “who is responsible for what” — comes up at every level; only the price of the answer differs. At the lowest level, Robert Martin’s SOLID principles apply: SRP, OCP, LSP, ISP, DIP — single responsibility, extension without modification, Liskov substitution, interface segregation, dependency inversion.

LevelWhat is decidedExampleCost of change
system architecturewhich parts exist, how they connect, how they are deployedmonolith or services; call or queuehigh: migration and data transfer
module boundarieswho knows what inside the codebasedomains, dependencies through interfacesnoticeable: edits across many files
code designclasses and functions within a boundarysplit a tangled class in twolow: local edits

What an architect does

An architect decides what is important in a system and keeps the important things in order — this is how Martin Fowler describes the role. It is a role, not necessarily a job title: it is often filled by an experienced developer on the team. The role shows in its results: recorded decisions and agreed trade-offs, not documents for their own sake.

Trade-offs and the cost of decisions

Every architectural decision has a price. The ATAM method (Architecture Tradeoff Analysis Method) from the Software Engineering Institute (SEI) defines sensitivity points — decisions on which a quality attribute depends heavily — and tradeoff points — decisions where attributes pull in different directions. Encrypting a channel improves security and reduces performance; a database replica speeds up reads and complicates consistency. Before choosing, say out loud what you are paying.

When explicit architecture is needed

Explicit architecture is not a mandatory ritual but a response to the cost of mistakes:

  • needed: several teams work on one system, the system lives for years, availability and security requirements are strict
  • conventions are enough: a prototype, one team, a short lifespan
  • a sign of good timing: decisions are made while they can still be changed without a migration

The path is always the same: requirements and constraints become decisions, and decisions become structure; the structure follows from the requirements through recorded decisions (see the diagram below). A new requirement sends you back to the decisions.

Decisions are the bottleneck: there are many requirements but one structure, so decisions are recorded in ADRs to make them easy to revisit.

How it differs from neighbouring fields

FieldWhat it decidesWhere to read more
software architecturesystem parts, connections, deploymentthis reference
infrastructure and cloud architecturenodes, networks, availability, redundancythe infrastructure architecture reference
security architecturethreat models, defence, Zero Trustthe security architecture reference
enterprise architecturean organisation’s processes and systems, TOGAFthe section “Standards and their status”
code designclasses and functions within a boundarythe language and framework references

The boundaries overlap at the seams: for a software architect a message queue is a way to connect parts, for an infrastructure architect it is a node and a network. Specifications and project documents as part of the process are covered in the IT project management reference.

What you should know first

  • experience building at least one service: deployment, environment, database
  • HTTP and REST at the client and server level — the HTTP and REST reference
  • SQL and a relational database at the level of tables and queries — the SQL reference

Next: quality attributes are in “Quality attributes and non-functional requirements”, styles in “Architectural styles”, and recording decisions in “Architecture description: C4, arc42 and ADR”.

Section sources

the section is written from these pages

Cheat sheet

Quick-lookup tables: which style or pattern fits a task, what the terms mean, and which numbers to keep in mind when sizing a system. Each row is explained and justified in its own section of the reference.

Task → solution

The first two columns give typical situations and the direction of the solution; the third says where to find the details. Every solution has a price, so check your choice against the trade-offs in the section “Quality attributes and non-functional requirements”.

If you need…Look at…Section
To start a new product with a single teammodular monolithstyles
Several teams need independent releasesmicroservicesstyles
A change spans several servicessaga and transactional outboxintegration, data
Web and mobile clients with different needsBFF — backend for frontendintegration
A single entry point for clientsAPI gatewayintegration
Read and write loads differCQRSdata
A full history of state changesevent sourcingdata
A slow or unreliable dependencytimeout, retry with jitter, circuit breakerresilience
Load peaks and request spikesa queue as a bufferintegration, resilience
Replace a legacy system piece by piecestrangler figstyles
Show the system to a managerC4 model, levels 1–2documentation
Record a choice and its reasonsADRdocumentation

Terms in one line

The wording is minimal and leaves out caveats; precise definitions are in the topic sections.

TermWhat it is
Quality attributea measurable property: performance, availability, maintainability
ADRan architectural decision record: context, choice, consequences
C4 modelfour levels of description: context, containers, components, code
Bounded contexta part of the system with its own vocabulary and its own domain model
Aggregatea group of objects that is changed and saved as a single unit
Sagaa chain of local transactions with compensating actions on failure
Transactional outboxthe message is written to a table in the same transaction as the data
CQRSseparate models for writes and reads
Event sourcingstate is stored as a sequence of events and rebuilt by replaying them
CAP theoremduring a network partition, you give up either consistency or availability
PACELC theoreman extension of CAP: even without a partition, you choose between latency and consistency
Idempotencyrepeating a request does not change the result
Circuit breakeran automatic switch that stops requests to a failing dependency
Bulkheadcompartment isolation: one dependency’s resource pool cannot exhaust the others
Backpressurethe consumer tells the source how much it can take

Numbers worth knowing

Jeff Dean’s table “Numbers Everyone Should Know” (LADIS 2009) gives orders of magnitude measured in 2009. Hardware has got faster since then, but the ratios hold: memory is orders of magnitude faster than disk, and a trip across a continent costs more than anything that happens inside one machine. A more recent reference point for storage: the average latency of a network SSD for a 16 KiB operation is under 500 microseconds (io2 Block Express in the Amazon EBS volume types documentation).

OperationTime
L1 cache reference0.5 ns
Main memory reference100 ns
Read 1 MB from memory250 µs
Round trip within a data centre500 µs
Disk seek10 ms
Read 1 MB from disk20 ms
Packet round trip California → Netherlands → California150 ms

Availability

This is how much downtime a system can have for each availability target (data from Azure Well-Architected). Every extra nine costs money and redundancy, and a user on a smartphone with 99% reliability will not notice the difference between 99.99% and 99.999% (Google SRE), so the target is chosen deliberately rather than by “the more, the better”.

TargetDowntime per weekper monthper year
99%1.68 hours7.20 hours3.65 days
99.9%10.10 minutes43.20 minutes8.76 hours
99.95%5 minutes21.60 minutes4.38 hours
99.99%1.01 minutes4.32 minutes52.56 minutes
99.999%6 seconds25.90 seconds5.26 minutes

Formulas

Time-based availability is the share of healthy time over a period; according to Google SRE, for distributed systems the share of successful requests is clearer: successful requests in a day divided by all requests in that day. A system that returned 250 errors out of 2.5 million requests in a day meets a 99.99% target.

The availability of a chain of dependent components is the product of their availabilities: 99.95% × 99.99999% ≈ 99.95%. A long chain is rarely more reliable than its weakest link, so the target is calculated for the whole request path, not for a single service (Azure Well-Architected).

Little’s law relates the average number of requests in a system to the arrival rate and the average processing time: L = λW. Example: 200 requests per second at an average of 0.25 seconds means 50 requests are in the system at any moment. If processing time grows while the rate stays the same, the number of requests in the system grows by the same factor.

Section sources

the section is written from these pages

Quality attributes and non-functional requirements

A quality attribute is a measurable property of a system — performance, availability, maintainability — something the architecture either delivers or breaks. Non-functional requirements (NFRs) are requirements for such properties: for “fast and reliable” to become a requirement, it needs a number and conditions.

Features say what a system does; attributes say how well. A feature rarely determines the structure, but a goal such as “95% of requests faster than 300 ms at 500 RPS” rules out options immediately. Quality attributes sit at the start of the requirements pipeline: requirements and constraints become decisions, and decisions become structure (see the section “What software architecture is and how it works”).

The ISO/IEC 25010:2023 quality model

The ISO/IEC 25010:2023 standard defines a product quality model: nine characteristics, each divided into sub-characteristics. Go through the list and decide for each characteristic whether it matters in your system — the model keeps you from forgetting an aspect of quality.

CharacteristicWhat it meansExample sub-characteristic
Functional suitabilityfunctions meet stated and implied needsfunctional completeness
Performance efficiencyperformance relative to the resources usedtime behaviour
Compatibilityworking with other systems in the same environment and exchanging information with theminteroperability
Interaction capability (formerly usability)how well specified users can interact with the product to achieve their goals effectively and with satisfactionuser error protection
Reliabilityperforming functions under stated conditions for a stated periodavailability
Securityprotecting data according to access levelsconfidentiality
Maintainabilityhow easily the intended maintainers can modify the productmodularity
Flexibility (formerly portability)adapting to other environments and ways of usescalability
Safetyabsence of harm to people, business, software, property and the environmentfail safe

Quality attribute scenario

The model suggests which properties matter but does not produce verifiable requirements. The Software Engineering Institute (SEI) at Carnegie Mellon University proposed the quality attribute scenario: six parts that turn a wish into a measurable situation (this is how the Quality Attribute Workshops (QAW) described by the SEI in 2003 work).

PartQuestionExample
Source of stimuluswho or what disturbs the systemcustomers
Stimuluswhat happens2,000 checkouts per second
Artefactwhich part of the system is affectedorder service
Environmentunder what conditionspeak sale load
Responsehow the system should reactorder accepted and confirmed
Response measurehow to measure that the requirement is met99% of orders confirmed within 2 s

The parts answer the questions without which a requirement is underspecified: without the environment it is unclear what load the goal applies to, and without a response measure it is unclear what to check. Scenarios are gathered with stakeholders: participants propose situations, a vote selects the most important ones, and the top ones are refined to all six parts.

Worked example: a shop during a sale

A scenario for an online shop where a promotional email opens a sale, built from the six parts:

  1. source of stimulus — customers arriving from the promotional email;
  2. stimulus — 2,000 checkouts per second during the first 10 minutes;
  3. artefact — the order service;
  4. environment — peak sale load;
  5. response — the order is accepted and confirmed to the customer;
  6. response measure — 99% of orders confirmed within 2 s, with fewer than 0.1% errors.

The solutions follow from the wording: a queue in front of order processing will smooth the peak, a catalogue cache will take load off the database, and the order service will scale horizontally. See the sections “Scaling and performance” and “Resilience”.

Bad and good: how to verify a requirement

A requirement is verifiable when it contains a number, the conditions of measurement and the share that is enough. Examples modelled on arc42:

BadGood
“search must be fast”“95% of search requests complete in under 300 ms at 500 RPS”
“the system must be reliable”“service availability of 99.9% per month, measured as the share of successful requests”
“the system must be easy to extend”“a new payment method can be added in 5 person-days without changing existing code”

The technique works for any characteristic of the ISO/IEC 25010 model: a scenario and a response measure produce a verifiable requirement. With it the team can see whether enough has been done, and testers know what to measure.

SLI, SLO and SLA

For operational attributes — latency, availability, throughput — the Google SRE book offers a set of related concepts. The indicator answers “what do we measure”, the objective answers “to what value”, and the agreement answers “what happens if we miss it”.

TermWhat it isExampleConsequence of a breach
SLI, service level indicatora measurable quantity describing the level of serviceshare of requests faster than 300 msmeasures on its own, with no consequences
SLO, service level objectivea target for an SLI over a period99.9% of requests faster than 300 ms over 30 daysthe team investigates and reviews the objective
SLA, service level agreementa contract with consequencesan SLO plus compensation for downtimea penalty, a refund, termination

Google SRE’s test: if missing the target has no explicit consequences, it is an SLO; if it does (most often financial), it is an SLA. Objectives are set with a margin below users’ expectations, and an error budget is left — the share of failures that can be spent on releases. For objectives, error budgets and the “nines” of availability, see the reference “Infrastructure and cloud architecture”, section “Availability, SLA and SLO”.

Attributes conflict

Improving one attribute often worsens another; setting priorities is the architect’s job. Typical conflicts:

  • performance versus security: every token check and encryption layer costs milliseconds;
  • availability versus consistency: to always respond, a system tolerates temporary divergence between copies (CAP);
  • maintainability versus performance: an abstraction makes it easier to swap an implementation but adds calls on the hot path;
  • safety versus cost: full protection against rare accidents does not pay off in small systems.

No solution is optimal for every attribute at once, and every architectural trade-off is worth recording. Trade-offs are covered in the section “What software architecture is and how it works”, and the CAP theorem in “Data in a distributed system”.

Where requirements come from

Quality attributes are not the only input: constraints (budget, deadlines, team) and features sit alongside them. Non-functional requirements are gathered and written according to ISO/IEC/IEEE 29148; for how the standard is organised, see the section “Standards and their status”.

Section sources

the section is written from these pages

Architectural styles

An architectural style is a family of architectures with common traits: it constrains the shape of a system rather than listing technologies. A style describes the system as a whole; the solution to a single problem is a pattern. Choose a style based on the nature of the domain and the price you are prepared to pay.

A style defines which elements can appear in a system and how they are connected. When an architecture follows a style’s constraints, useful properties follow naturally: for microservices, independent deployment and fault isolation. The constraints also bring a cost: operational complexity, network calls, data consistency. The point is to understand why you adopt a style, not to reproduce its shape for the sake of purity.

The boundaries are the same; what differs is where they run: inside a process or across a network.

Monolith and modular monolith

A monolith is a single deployable application: one process handles HTTP requests, logic and data. For most new systems this is the right choice: almost all successful microservice stories began with a monolith that grew, while systems designed as microservices from scratch more often ran into trouble. While the boundaries are unclear, restructuring behaviour across services costs more than doing so inside one application.

A modular monolith keeps a single deployment but draws strict boundaries between modules: each module has its own interface and its own tables, and it does not read other modules’ tables. This tests the boundaries before you pay for the network. Once the boundaries have settled, a module can be split off into a service without rewriting its logic.

Layered and client-server

Layered (N-tier) architecture divides an application into layers: presentation, business logic, data access. A layer calls only the layers beneath it. The cost is horizontality: changing one rule touches several layers, so the style is poorly suited to frequent updates. The classic client-server scheme is a special case with two tiers.

SOA, ESB and microservices

The microservice style splits an application into a set of small, independently deployable services built around business capabilities: each service has its own database, its own release cycle and automated deployment. The term was discussed in May 2011 at an architects’ workshop near Venice; Lewis and Fowler’s definition was published on 25 March 2014.

Lewis and Fowler contrasted this with SOA built around an enterprise service bus (ESB) in the formula “smart endpoints and dumb pipes”: the logic lives in the services, and the channel only carries messages. A bus with routing, message transformation and business rules becomes a centre of coupling.

Event-driven architecture

Event producers do not know their consumers: they publish events to event channels, and consumers subscribe to them and react in near real time. A simple variant is Web-Queue-Worker: a web front end accepts requests and passes them through an asynchronous queue to a worker that does the resource-intensive work. The streaming variant keeps events in an event log and lets several consumers read it independently.

Serverless architecture

Code runs in response to events without you managing servers (serverless): the platform maintains the infrastructure, scales functions, and scales them to zero when idle. The cost is platform lock-in and runtime limits: caps on time and memory, a cold start of a new environment instead of a warm one, and a limited set of runtimes.

Pipeline

A pipeline (pipes and filters) divides a large task into a sequence of independent steps, called filters, connected by pipes. A filter receives a message, processes it and publishes the result to the next pipe; steps can be reordered, added and scaled individually without changing the filters themselves. The style is described both as a pipeline for processing a stream of messages and as a task with one input and one output broken into several sequential stages.

Which style when

StyleWhen it fitsWhat it costs
Monolitha new system whose boundaries are still unclearrisk of tangled dependencies as it grows
Modular monolithboundaries are tested within a single deploymentdiscipline: a module does not read other modules’ tables
Layered (N-tier)migrating a layered application, infrequent updatesa change touches several layers
Microservicesa complex domain, frequent updates, mature DevOpsoperations, network calls, eventual consistency
Event-drivenreal time, IoT, event streamsdelivery guarantees, event ordering, consistency
Web-Queue-Workera simple domain with resource-intensive processingwithout discipline, both ends grow out of control
Serverlessevent handling, load spikesplatform lock-in, runtime limits
Pipelinestream data processing, a sequence of stepsoverload at the slow step of the chain

Section sources

the section is written from these pages

Modularity and boundaries

A module is a part of a system with a hidden design and an explicit interface: the Orders module knows that the Warehouse module reserves goods, but not how it does so. Boundaries are drawn so that one part can be changed and tested without touching the others.

Two dimensions of a boundary come from early work on structured design. Cohesion is how far the responsibilities inside a module serve a single purpose: high cohesion keeps related changes in one place. Coupling is how far a change to one module forces a change in another; Fowler defines it briefly: if changing one module requires changing another, there is coupling. Coupling cannot be eliminated, because modules have to communicate, so it is kept under control and routed through explicit interfaces: Orders calls Warehouse, but does not read its tables.

Layers and the direction of dependencies

Classic layered architecture divides an application into layers: user interface, business logic and data access. A layer talks only to the one directly below it, and dependencies run from top to bottom. The price is that business logic, the most important part of the system, depends on data access details and often on the very existence of a database; testing it without a test database is hard.

Dependency inversion reverses the arrow: the core declares abstractions (interfaces) and the infrastructure implements them. The core no longer depends on the database or the framework, and the logic is tested by swapping the implementation. The same idea is known as Hexagonal Architecture, Ports and Adapters, Onion Architecture and Clean Architecture.

AspectClassic layersInverted dependencies
What it knows about the databaselogic depends on data access detailsthe core knows only an interface
Direction of dependenciestop to bottom: interface → logic → datatowards the centre: infrastructure → core
Testing business logicneeds a test databasean in-memory adapter instead of the database

Ports and adapters

Alistair Cockburn described this design in 2005 under the name Ports and Adapters. The application works without a user interface and without a database, so it can be checked with automated tests and run when the database is unavailable. A port is a purposeful conversation between the application and the outside world; its protocol is an API. For each technology, a separate adapter plugs into the port: a graphical interface, a batch run or a test harness on the inbound ports; an SQL database, a file or an in-memory store on the outbound ones. All the arrows in the diagram point towards the core: the adapter depends on the port, not the core on the adapter.

The adapter changes, the core does not: technologies plug in through ports.

MVC and MVVM

MVC (Model-View-Controller) and MVVM (Model-View-ViewModel) are presentation-layer patterns, not the architecture of a whole system: they organise the interface and its link to the data, but do not say where module boundaries lie. In MVC, the model holds data and rules, the view displays them and the controller handles input. In MVVM, the view is bound to the view model through data binding: the view knows about the view model, the view model knows about the model, and the model knows about nobody. The view model separates the interface from the data, so it can be tested without the interface.

In mobile development the same patterns pick up platform details: how an app’s architecture is organised on Android, and state with bindings in SwiftUI, are covered in the Android and iOS references.

Dependency injection

Dependency injection (DI) glues the core to the adapters: an object receives its dependencies from outside, usually through constructor parameters, rather than creating them itself. Fowler named the pattern on 23 January 2004, in place of the too general term Inversion of Control (IoC): a separate assembler object plugs implementations into fields and parameters, and DI containers automate this assembly. A dependency can be passed through a constructor, a setter or an interface.

In the example, the core is the PlaceOrder service: it knows the OrderRepository port and does not know what is behind it. PostgresOrderRepository is the outbound adapter for production, and InMemoryOrders is the test one: it keeps orders in a list.

pythonPort, adapter and service
from typing import Protocol # the Order, Cart and Connection types are defined alongside class OrderRepository(Protocol):    # port: the core knows only this interface    def add(self, order: Order) -> int: ...  class PostgresOrderRepository:    # adapter: the same port implemented with PostgreSQL    def __init__(self, conn: Connection) -> None:        self.conn = conn     def add(self, order: Order) -> int:        return self.conn.execute(            "INSERT INTO orders (total) VALUES (%s)"            " RETURNING id",            (order.total,),        ).fetchone()[0]  class PlaceOrder:    # the service receives the port through its constructor    def __init__(self, repo: OrderRepository) -> None:        self.repo = repo     def __call__(self, cart: Cart) -> int:        return self.repo.add(Order(total=cart.total()))
pythonTest: an in-memory adapter
class InMemoryOrders:    # test adapter: orders are kept in a list    def __init__(self) -> None:        self.orders: list[Order] = []     def add(self, order: Order) -> int:        self.orders.append(order)        return len(self.orders)  def test_place_order() -> None:    place_order = PlaceOrder(InMemoryOrders())    assert place_order(Cart(items=["book"])) == 1

Signs of bad boundaries

  • One change edits several modules: coupling has crossed the boundary.
  • A module knows the internals of its neighbour: its tables, fields and internal functions. The interface has stopped being a boundary.
  • Modules refer to each other in a circle: the cycle turns every edit into a series of follow-up edits that come back to the original module.

SOLID describes the design of classes inside a module, not the boundaries between modules; these principles are listed in the section “What software architecture is and how it works”.

Section sources

the section is written from these pages

Domain-driven design (DDD)

Domain-driven design (DDD) is Eric Evans’s approach: a system is built around a model of the problem domain, which developers create together with domain experts. The model also sets the boundaries: code is divided not by layers and tables but by parts of the business, each with its own language.

This is a short summary of the patterns in the book, based on the DDD Reference that Eric Evans publishes under the CC BY 4.0 licence; modern guides, such as the Azure Architecture Center materials, build on it too.

Strategic and tactical levels

Design in DDD works at two levels. The strategic level deals with the system as a whole: where the boundaries lie, which language each part uses and how the parts exchange data. The tactical level works inside a single boundary, with patterns for the model itself: entities, value objects, aggregates, repositories and domain events.

LevelPatternsQuestion it answers
Strategicbounded context, ubiquitous language, context mapWhere the boundaries lie and which language each part uses
Tacticalentities, aggregates, repositories, domain eventsHow the model is structured inside one context

Ubiquitous language

The ubiquitous language is a vocabulary that developers and experts create together within one context and use everywhere: in conversations, documents and code. A word from a conversation with an expert then points to the same class, and mismatches are noticed early: if the code has to translate an expert’s term into a “technical” one, the model is drifting away from the business.

A word lives within the bounds of one context. The sales department says “order”, and in the sales code the class is called the same; for delivery, the same thing is a “shipment”: it has to be packed and taken away.

Bounded context

A bounded context is a boundary inside which the model is consistent: every word has one meaning. In a large system, a single model for everything is unattainable: parts of the organisation use similar words in different senses. Fowler names “customer” as a typical example: in sales it is a buyer with an address and an order history, in support it is a requester with open tickets. These are not two records of one person but two models, each with its own fields and rules, with an explicit mapping set up between them.

One word, different models: an explicit mapping links them.

Context map

Relationships between contexts are described by a context map. The DDD Reference defines a standard set of relationships: it makes the agreement between teams explicit, instead of a verbal “we’ll sort out compatibility somehow”.

RelationshipEssence
Partnershipthe teams of two contexts share goals and coordinate changes together
Shared Kernela small shared part of the model; it can be changed only by agreement of both teams
Customer/Supplierthe supplier takes the consumer’s needs into account when planning
Conformistthe consumer accepts the supplier’s model as it is
Anticorruption Layera protective layer: the consumer translates the foreign model into its own
Open Host Servicethe supplier opens a common API for all of its consumers
Published Languagea published common language of exchange between contexts
Separate Waysno integration: the parts evolve separately

Aggregates and events

An aggregate is a group of entities and value objects gathered around a root. External references lead only to the root; the aggregate boundary is the boundary of one transaction, and consistency rules are checked inside it synchronously.

For example, an order with its lines is one aggregate: the Order root is responsible for it, and the total over the lines is recalculated in the same transaction as the change to the order’s contents. Do not confuse this with SQL aggregate functions: SUM and COUNT compute values in a query and have nothing to do with this pattern.

A domain event is a fact that has already happened: “something occurred”. According to the DDD Reference, events are normally immutable, since they are a record of the past, so they are conventionally named in the past tense: OrderPlaced, PaymentReceived. Publishing events between services, sagas and the outbox pattern are covered in the section “Service integration”.

pythonAn event and an aggregate in code
from dataclasses import dataclassfrom datetime import UTC, datetimefrom uuid import UUID, uuid4  # an event does not change after creation@dataclass(frozen=True)class OrderPlaced:    order_id: UUID    placed_at: datetime  class OrderLine:    # value object: has no identity of its own     def __init__(self, product_id: UUID, qty: int) -> None:        self.product_id = product_id        self.qty = qty  class Order:    # aggregate root: the lines and the total live inside it     def __init__(self, customer_id: UUID) -> None:        self.id = uuid4()        self.customer_id = customer_id        self.lines: list[OrderLine] = []        self.total = 0        self.events: list[OrderPlaced] = []     def add_line(        self, product_id: UUID, price: int, qty: int    ) -> None:        self.lines.append(OrderLine(product_id, qty))        self.total += price * qty     def place(self) -> None:        self.events.append(            OrderPlaced(self.id, datetime.now(UTC))        )

From model to services

The Azure Architecture Center materials turn the model into steps for dividing a system into services:

  1. Analyse the problem domain and its functions.
  2. Define the bounded contexts, one language in each.
  3. Within a context, find entities, aggregates and domain services.
  4. Map the aggregates and domain services to the system’s services.

Signs of a good boundary: a service does not extend beyond one context, there are no “chatty” calls between services, and each is deployed independently. If two services constantly talk to each other, it is a sign that the boundary is in the wrong place. Decomposition is an iterative process: if in doubt, start with larger services, because splitting one service is easier than moving functionality between several.

Migrating from a monolith piece by piece

The strangler fig is a migration approach that Fowler described after seeing strangler figs in Queensland: a seedling sprouts on a host tree, wraps around it and in time becomes self-supporting. The new system grows around the old one and takes over its functions one by one; when everything has been taken over, the old one is switched off. A complete rewrite from scratch almost always fails: the exact behaviour of the old system becomes known late, and users are not prepared to wait for new features.

Fowler first called it “Strangler Application” and later changed it to “Strangler Fig”, because the word “strangler” carries associations with violence and to keep the botanical metaphor.

Module boundaries and cohesion within a single application are covered in the section “Modularity and boundaries”; message delivery between services is covered in the section “Service integration”.

Section sources

the section is written from these pages

Service integration

Services communicate through synchronous calls, where the caller waits for a reply, and asynchronous messages, where the sender hands the message off and carries on. A failure in a synchronous chain propagates upwards; asynchronous messaging decouples services in time but requires idempotent consumers. A change spanning several services is carried out as a saga of local transactions: there is no automatic rollback, and cancellations are made with compensating transactions.

Synchronous call and asynchronous message

In a synchronous call (HTTP, gRPC), the calling service waits for the recipient’s reply, and work stands still while the recipient responds. The approach is familiar and well understood, but it requires the recipient to be available, and in a dependency chain where A calls B and B calls C, the latencies add up.

In asynchronous messaging, the sender puts a message on a channel and carries on; the recipient picks it up when it can. The recipient may be temporarily absent: messages wait for it. The decoupling is paid for in complexity: messages arrive twice, order is not guaranteed, and a reply to a message is a separate message with a correlation ID.

Ways to exchange messages

The same exchange can be built on different channels; the choice depends on whether a reply is needed, how many recipients there are and which ordering matters.

MethodProsConsWhen
RESTclear methods, caching, toolingwaits for a replypublic APIs, CRUD
gRPCcompact messages, contracts, streamswaits for a reply, binary formatinternal low-latency calls
Queue (point-to-point)load buffer; a recipient failure does not lose messagesno reply within the callbackground processing, load levelling
Publish-subscribe (pub/sub)every subscriber gets a copy; the sender does not know the subscriberssubscribers are independent; one subscriber receiving an event does not cancel it for the othersevents for several subscribers
Event logmessages are stored and can be read againstorage and ordering are the consumer’s concernaudit, state replay

REST is described in the HTTP and REST reference, in the section “Designing a REST API”; gRPC in the gRPC reference, in the section “Services and RPC types”. Delivery guarantees for an event log are covered in the Kafka reference, in the section “Delivery guarantees and transactions”.

Queue and publish-subscribe

In a point-to-point channel, exactly one recipient receives each message. If there are several recipients, the channel hands each message to just one of them, so several processes share the work without coordinating with each other (competing consumers).

In a publish-subscribe channel, every subscriber receives its own copy of the message. Subscribers do not know about the producer, and the producer does not know about them: the producer publishes an event, and the channel distributes the copies.

API gateway and BFF

An API gateway is a single entry point for all clients: it simply forwards some requests to the right service and handles others itself, querying several services and combining their responses. Access is also checked here, and the way the system is divided into services is hidden.

The BFF (backends for frontends) variant provides a separate gateway for each kind of client: one for the web app, one for mobile, one for external partners. A mobile client needs one compact response instead of six calls; the web needs a different one. The price is an extra network hop and one more component to operate.

Service mesh

Some of the work between services is the same for all of them: retries, circuit breaking, load balancing, mTLS and end-to-end tracing. A service mesh moves it out of the services’ code into a separate layer: a proxy intercepts the network traffic between the cluster’s services.

The proxy lives next to every service instance, as a sidecar container in a Pod; Pods and sidecars are covered in the Kubernetes reference, in the section “The Pod and its lifecycle”. The main options are Linkerd and Istio.

A mesh takes on complexity but also adds it: cluster setup becomes more complicated, every request goes through a proxy, and its processes run on every node. Before rolling a mesh out to production, test it under load.

Saga: transactions without a distributed rollback

A transaction spanning several services cannot be atomic: each service has its own database, and there is no shared COMMIT. A saga carries out a change as a sequence of local transactions; if one fails, the steps already done are undone with compensating transactions. A compensation is not a rollback: it is a new transaction that writes new data, and the developer designs it.

A saga can be coordinated in two ways. Choreography: each service publishes events about its steps, and the others react to them with their own transactions. Orchestration: an orchestrator, a separate object or service, tells the participants which steps to perform and collects the replies. Orchestration has fewer “who reacts to whom” links, but the orchestrator is an extra component with its own state.

OptionHow it worksProsCons
Choreographyservices publish events and react to each other’s eventsno central component, quick to startas the number of steps grows, the event flow is hard to trace
Orchestrationan orchestrator sets the steps and collects the repliesthe whole route of the saga is visiblebusiness logic may creep into the orchestrator

Let us walk through an order with payment and a warehouse under orchestration. The orchestrator runs the steps in order; when the warehouse cannot find the goods, compensations run instead of a rollback.

Steps 1–3 are orchestrator commands, the warehouse’s refusal is highlighted in red, and steps 4–5 are compensations.

The money has been returned, but along the way the customer may have seen “order accepted”: a saga provides no isolation, and parallel work on the same goods sees the intermediate state. The warehouse does not cancel the failed reservation, as there is nothing to cancel: the reservation was never created.

  1. Orders creates an order with the status “new”.
  2. Payment charges the money.
  3. Warehouse cannot find the goods and refuses the reservation.
  4. Payment refunds the charge.
  5. Orders cancels the order.

Transactional outbox

A message broker does not take part in a database transaction by itself. If a service sends a message in the middle of a transaction, it goes out even when the transaction is later rolled back: the order is not saved, but the message has already gone. If it is sent after the commit, the service may crash between the commit and the send, leaving an order with no message.

The transactional outbox solves this with a single database: the business record and the message are written in one local transaction to an outbox table. A separate process, the relay, reads the table and publishes the messages to the broker.

A message may go out twice: the relay can crash after publishing and before marking the message. So the consumer is idempotent and tracks the IDs of messages it has already processed; retries and idempotency are covered in the section “Resilience”.

sqlThe outbox table, PostgreSQL
CREATE TABLE outbox (    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,    aggregate_id bigint NOT NULL,    type         text NOT NULL,    payload      jsonb NOT NULL,    created_at   timestamptz NOT NULL DEFAULT now(),    published_at timestamptz); -- index for the relay: it selects unpublished rows in orderCREATE INDEX outbox_pending ON outbox (created_at)    WHERE published_at IS NULL;
sqlThe order and the message in one transaction
BEGIN;INSERT INTO orders (id, customer_id, total_cents, status)VALUES (1001, 77, 420000, 'new');INSERT INTO outbox (aggregate_id, type, payload)VALUES (1001, 'order.created',        '{"order_id": 1001, "total_cents": 420000}');COMMIT;

The relay reads unpublished rows in created_at order, publishes the messages to the broker and only then sets published_at. It can crash between publishing and marking, so the message goes out again, which is why the consumer is idempotent. There are two ways to implement the relay: polling the table and reading the transaction log.

Change contracts carefully

A contract is changed by extension, not replacement: a new field is added, the old one continues to be served for a while, and it is removed only once consumers have moved off it.

The reason is Hyrum’s law: with enough API users, someone depends on every observable behaviour of the system, whatever the contract promises. This includes behaviour that is not in the documentation. The law is examined in the section “Laws and principles”.

Section sources

the section is written from these pages

Data in distributed systems

When every service has its own database, there are no shared transactions: one service’s data is available to others only through its API, and a transaction touches only its own database. Integrity across services is assembled from events and compensations, and the consistency of copies is tuned to the cost of an error; the price paid is a window of stale data.

Database per service

The database-per-service pattern keeps data private: the database is part of the service’s implementation, and other services do not connect to it directly. In a relational DBMS there are three ways to own data, from cheapest to most expensive:

  • own tables: the service owns a set of tables in a shared database;
  • own schema (schema-per-service): a separate schema, with ownership made explicit;
  • own server (database-server-per-service): a separate database for workloads.

So that nobody bypasses the API and reads another service’s tables, each service gets its own DBMS user, with permissions granted only on its own objects. The price of the pattern is that there are no joins across databases: a list of orders with customer names is assembled by calling two APIs or from a view built from neighbours’ events.

ACID stays inside the database

Within a single database the guarantees are the same as before: ACID (atomicity, consistency, isolation, durability). Here C means that after a transaction the database does not violate its constraints: the total across two accounts does not change in a transfer. Isolation levels are covered in the SQL reference (“Transactions and isolation levels”) and the PostgreSQL reference (“Transactions, MVCC and locks”).

The C in ACID and the C in CAP are different things: in ACID, C is about database constraints; in CAP, it is about replica consistency. A database with ACID transactions can return a stale value from a replica, and a system that is “consistent” in the CAP sense can refuse a write during a network partition. Between services, a saga takes the place of an ACID transaction (see the section “Service integration”).

CQRS: write and read models

CQRS (Command Query Responsibility Segregation) is a technique first described by Greg Young; it builds on Command Query Separation: the model for changing data and the model for reading it are different. Writes are served by a domain model with invariants, reads by denormalised views.

In services with separate databases, CQRS settles the question of joins: a service subscribed to its neighbours’ events maintains a view with the JOINs it needs. According to Fowler, for most systems CQRS adds risky complexity; it is justified for complex domains and a heavy imbalance between reads and writes. Otherwise a reporting database does the job.

Event sourcing

Event sourcing stores every change of state as an event and rebuilds the state from the log. An account here is a log of “deposited 100” and “withdrawn 30”, from which a balance of 70 follows.

sqlPostgreSQL
-- the log: past records are never changed, only appended toINSERT INTO account_events (account_id, kind, amount)VALUES (42, 'deposited', 100), (42, 'withdrawn', 30); -- the state is a fold over the logSELECT sum(CASE kind WHEN 'deposited' THEN amount                     ELSE -amount END) AS balanceFROM account_eventsWHERE account_id = 42;

The log allows a complete rebuild of the state from scratch, a query for the state at any past date (“what the balance was on 1 October”) and replay of events into a new system or view. The price is working with the log: building projections for reading and changing their format as the domain evolves.

Replication and sharding

Copies and parts of the data are the two techniques by which a data store grows:

TechniqueWhyCost
Replication: copies of data on several nodesfault tolerance and offloading readscopies diverge: a window of stale data, conflict resolution
Sharding: data is split into parts by a keydata and write growth beyond a single nodequeries across several shards, data movement when the number of shards changes

The two techniques work together: each shard is usually replicated. Implementation is covered in the PostgreSQL (“Replication and high availability”), Redis (“Replication, Sentinel and Cluster”), ClickHouse (“Replication, shards and Keeper”) and Kafka (“Replication and fault tolerance”) references.

The CAP theorem

The CAP theorem was presented by Eric Brewer in a talk at PODC in 2000. Of the three properties (consistency, availability and partition tolerance), two are chosen during a partition: either the system responds but readers see stale data, or only the part with fresh data responds.

The proof by Gilbert and Lynch (2002) is built for linearizability: a reader sees the last written value. According to Abadi, a quorum protocol alone is not enough for such a guarantee, even with R + W > N. The classification is a guide, not a certificate.

PACELC: a choice even without a partition

Daniel Abadi’s PACELC (IEEE Computer, 2012) extends CAP: even without a network partition, a system chooses between latency and consistency. The formula: if there is a partition (P), then A or C; else (E), L or C.

SystemDuring a partitionWithout a partition
Dynamo, Cassandra, RiakPA: availabilityEL: low latency
VoltDB/H-Store, Megastore, BigTable, HBasePC: consistencyEC: consistency
MongoDBPAEC
PNUTSPCEL

Consistency models

In Werner Vogels’s classification, strong consistency means that after a write, any read returns the new value. Weak consistency guarantees this only under additional conditions; eventual consistency is a form of it: if there are no new writes, all reads will sooner or later return the last value. The time from the write to this guarantee is the inconsistency window; without failures, its upper bound is set by communication latency, load and the number of replicas. There are milder variants:

  • causal: whoever has seen the message about a write also sees the write;
  • read-your-writes: a reader sees their own write;
  • session: the same within a session;
  • monotonic read: having seen a newer value, a client does not see an older one.

On the server, the choice is quorums: N copies store the data, W acknowledge a write, and R are queried on a read. When W + R > N, the reading and writing copies overlap, so strong consistency is possible; when W + R ≤ N, a read may land on a copy without the latest write.

The choice is dictated by the cost of an error. A price in a shop window can update within seconds, so eventual consistency is enough. Charging money requires strong consistency: the buyer sees their own payment, and two operations on one account do not make the balance diverge. The architect is responsible for the choice and records it in an ADR; see the section “Architecture description: C4, arc42 and ADR”.

Section sources

the section is written from these pages

Resilience

Resilience is a system’s ability to survive the failure of some of its dependencies: a timeout stops callers waiting forever, a retry with a growing delay rides out a brief fault, and circuit breakers and bulkheads stop one failure from taking everything down. In a distributed system, failure is routine.

A cascading failure grows over time through positive feedback: one instance cannot cope with the load, its work shifts to its neighbours, and they run out of resources in turn. The most common cause is overload, so each technique below bounds either time or the number of requests at the bottleneck.

The eight fallacies

The list of eight assumptions took shape at Sun Microsystems: Peter Deutsch wrote down seven and James Gosling added the eighth. All of them turn out to be false sooner or later, and they cause major trouble. The techniques in this section follow from them:

  • the network is reliable — a timeout and a retry on every call;
  • latency is zero — make fewer network calls;
  • bandwidth is infinite — keep unnecessary data out of responses;
  • the network is secure — check trust at every hop (see the “Security architecture” reference);
  • topology doesn’t change — don’t hard-code addresses;
  • there is one administrator — agree rules across teams;
  • transport cost is zero — count the price of every call;
  • the network is homogeneous — verify protocols at the boundaries.

Timeouts and deadlines

A timeout is the limit on how long a client waits for a response. Without one, a hanging call holds a connection, a thread and memory until the process restarts, and running out of any resource knocks over its neighbours in a cascade.

In a chain of calls, the deadline is passed along: the client gave the request 30 s, the service spent 7 s on its part, so the next call has 23 s left. Work done after the deadline has passed is wasted because the client has already gone, so check the remaining time before each stage and abort a request that is late.

Choose the limit from the measured latency of the dependency, not from wishful thinking. For deadlines and how gRPC propagates them, see the gRPC reference, section “Deadlines, cancellation and retries”.

Retry with backoff

A retry survives a brief fault, but it also amplifies overload: the dependency is busy handling requests that will fail anyway. So the delay grows exponentially (exponential backoff) up to a cap, the number of attempts is limited, and retries happen at one layer only: in a stack of five call layers with three attempts each, a database failure multiplies the load by 243.

Without a random component — jitter — clients hit by the same network fault retry in waves: the delays coincide, and the load hits the dependency in sync again. Jitter spreads retries out over time.

pythonretry: three attempts, exponential delay with jitter
import randomimport time MAX_ATTEMPTS = 3BASE_DELAY = 0.1  # 100 msCAP_DELAY = 2.0 def call_with_retry(operation):    for attempt in range(MAX_ATTEMPTS):        try:            return operation()        except (TimeoutError, ConnectionError):            if attempt == MAX_ATTEMPTS - 1:                raise        # exponential delay with random jitter        ceiling = min(CAP_DELAY, BASE_DELAY * 2**attempt)        delay = random.uniform(0, ceiling)        time.sleep(delay)

A retry is safe only when the operation is idempotent: several identical calls give the same result as one. A read is idempotent by nature, while an operation with a side effect is retried only if the server recognises the repeat, using an idempotency key in the request. The idempotent HTTP methods — GET, PUT, DELETE — and the 429 and 503 codes with the Retry-After header are covered in the HTTP and REST reference, sections “HTTP methods” and “Status codes”.

Circuit breaker

A circuit breaker, described by Michael Nygard in “Release It!”, watches the errors of calls to one dependency and, once a threshold is exceeded, stops spending resources on it. Its states work like a breaker in a fuse box: it trips and cuts the power to let the line cool down.

The threshold, the length of the pause and the number of trial requests are tuning parameters.

Without a breaker, every request waits for the timeout of a hung dependency. With one, the system responds immediately and diverts traffic to a fallback path: a cache, a simplified response, another region. The error threshold, the pause length and the number of trial requests are set in configuration, separately for each dependency.

Bulkheads

A bulkhead is a technique borrowed from ship design: the hull is divided by partitions so that a breach floods one compartment rather than the whole ship. In code, these are separate resource pools for each dependency: a connection pool for the database, another for an external gateway, a thread limit for a group of calls.

When a dependency hangs, only its own pool is exhausted, and calls to other dependencies carry on without queuing for someone else’s resources. Groups of clients are isolated the same way: a heavy consumer gets its own service instance, and its spike doesn’t take throughput away from the rest.

yamla Pod manifest with its own resource limits
apiVersion: v1kind: Podmetadata:  name: paymentsspec:  containers:  - name: payments    image: payments:2.1    # bulkhead: its own resource limits    resources:      requests:        cpu: "250m"        memory: "64Mi"      limits:        cpu: "1"        memory: "128Mi"

Overload: limits, shedding, degradation

Rate limiting cuts off excess traffic before the server is overloaded: the per-client limit is set at the gateway or the load balancer. Load shedding means the server itself rejects some requests as it approaches its limit, instead of falling over completely. Graceful degradation goes further: it responds with a simplified result — search over a cache instead of the database, no suggestions or recommendations — but it still responds.

It is cheapest to refuse early: at the entrance first, then in the queue, and only then start the work — a response after the deadline has passed is of no use to anyone.

Queues and backpressure

A queue in front of slow processing smooths a peak, but a long queue is a trap: if processing takes 100 ms and the queue is 10 times longer than the pool of workers, a request at the tail waits a second before work even begins, and the memory for the queue runs out before the work does. Keep the queue short and reject new requests when there is no room.

Refusing when there is no room is exactly what backpressure is: the consumer tells the producer “slow down” not by asking but by declining to accept the excess. The producer — a client, another service or a broker — reduces its rate or retries later. An unbounded buffer only postpones the overload and costs more memory.

Techniques and their cost

TechniqueWhat it protects againstCost
Timeout and deadline propagationresources lost on a hung calllong but healthy operations get cut off
Retry with backoff and jittera brief dependency faultextra traffic, amplified overload
Idempotencya double effect on retrya retry key and server-side checks
Circuit breakerclients waiting, overload of neighboursmodal behaviour, harder to test
Bulkheadsresources captured by someone else’s failureresources sit idle in empty compartments
Shedding and degradationa server crashing under overloadvisible errors and simplified responses
Backpressurequeue and memory overflowdelays and refusals reach the producer

The techniques complement each other: a timeout bounds time, a retry survives a brief fault, a breaker stops the flow during a prolonged failure, bulkheads isolate, and shedding and backpressure protect the service itself. Where the line lies between surviving a fault and surviving the loss of a whole region is covered in the “Infrastructure and cloud architecture” reference, section “Availability, SLA and SLO”.

Section sources

the section is written from these pages

Scaling and performance

Scaling means increasing or decreasing resources to follow load: either a node is made more powerful (vertical scaling) or identical instances are added (horizontal scaling). A back-of-the-envelope estimate shows how many resources will be needed; growth relies on keeping state outside the instance, plus a cache and a queue.

Vertical and horizontal scaling

The Azure Well-Architected Framework (recommendation PE:05) defines scaling as the ability to change resources in step with demand: add them for a surge and remove them when traffic subsides. Vertical scaling (scale up) adds power to an existing node, while horizontal scaling (scale out) adds more identical nodes.

Resources grow in groups called scale units: for example, a hundred virtual machines, two queues and three data stores change together. The platform can do this automatically from load metrics such as CPU, memory and queue depth. Not every service allows scaling in: some permit scaling down only manually.

ApproachHowLimitCost
Vertical (scale up)the same node gets more CPUs and memorythe capacity of a single nodecapacity is sold in scale-unit steps, and the node remains a single point of failure
Horizontal (scale out)more nodes, with a load balancer sharing the trafficcommunication between nodes and shared statecode must not depend on a particular instance, and every instance costs money

Stateless instances

Horizontal scaling works only if instances are interchangeable. Twelve-factor processes are stateless and share nothing: anything that must survive a restart lives in a separate store, usually a database. A process’s memory and file system are fine as a cache for a single transaction, no longer: even a lone process loses its local state on restart. In return, any request can go to any instance.

The best-known state is the user session. Keeping it in process memory and pinning a visitor to one instance (sticky sessions) is something the twelve-factor authors explicitly call a violation of the rule. Session state is requested from a store with expiry, such as Redis or Memcached. Azure states the same ban as a requirement to remove client affinity: without it, the load balancer sends a request to any free instance.

How load balancers work is covered in the Nginx reference, section “Load balancing”; adding instances automatically in a cluster is in the Kubernetes reference, section “Resources and scaling”.

Cache and the cache-aside pattern

Reads usually dominate and are largely repetitive. In the cache-aside pattern, the application checks the cache first: on a hit, the answer comes straight from there; on a miss, it reads from the database, writes to the cache and responds to the reader. Writes go to the database and the cache key is invalidated — the cache picks up the fresh value on the next read.

The key’s time to live is chosen to suit the data: a short one sends load back to the database, a long one accumulates stale data; a cache that fills up evicts the least recently used keys (LRU). This is a cache inside the application; caching of HTTP responses is covered in the HTTP and REST reference, section “Caching”.

pythonthe cache-aside pattern, Python
import json import redis # db is the application's database access layerr = redis.Redis(host="cache", decode_responses=True)# key time to live, secondsTTL = 300  def get_product(product_id: int):    key = f"product:{product_id}"    cached = r.get(key)    if cached is not None:        # hit: serve from the cache        return json.loads(cached)    # miss: read the database and put the result in the cache    product = db.get_product(product_id)    r.set(key, json.dumps(product), ex=TTL)    return product  def update_product(product_id: int, **fields):    # write to the database first    db.update_product(product_id, **fields)    # invalidate the key: the fresh value arrives with the next read    r.delete(f"product:{product_id}")

The queue as a buffer

A peak that instances cannot digest at once is not rejected but put in a queue. The queue works as a buffer between intake and processing: consumers drain it at their own pace (queue-based load levelling). It decouples intake from processing, so instances are sized for the average load rather than the peak. A single queue for everything becomes a bottleneck itself, so Azure advises splitting the load across several queues.

Keep an eye on queue depth: if consumers consistently fail to keep up with the inflow, the queue just keeps growing, and latency with it. Competing consumers are covered in more detail in the “Service integration” section.

Data is scaled separately from compute, by replication and sharding, at the price of diverging copies. The approaches and their trade-offs are in the “Data in a distributed system” section.

Back-of-the-envelope estimate

Before any load arrives, it is estimated on the back of an envelope: a few multiplications give an order of magnitude, enough to see how much to ask of the infrastructure. Suppose an online shop expects a million active users a day, each making about 20 requests, an order weighs 2 KB, and 50 thousand orders are placed a day:

What we estimateCalculationResult
Requests per day1 million users × 20 requests20 million requests
Average rate20 million requests / 86,400 s≈ 230 RPS
Peak rateaverage × 5≈ 1,200 RPS
Order storage50,000 orders × 2 KB100 MB per day, ≈ 36.5 GB per year
Bandwidth at peak1,200 RPS × 20 KB≈ 24 MB/s, ≈ 190 Mbit/s

The numbers are approximate and a load test will check them, but they set the order of magnitude: how much bandwidth and disk to provision, how much memory for the cache and how many instances to keep for the peak. Little’s law shows where the number of concurrent requests comes from.

Two laws

Amdahl’s law limits the speedup S on N workers: S = 1 / ((1 − P) + P/N). Here P is the fraction of the work that can be done in parallel. An example from the NVIDIA guide: if 3/4 of a program’s time runs in parallel, the maximum speedup is 1/(1 − 3/4) = 4, however many workers are added.

This carries over to services directly: adding instances speeds up only the parallel part — the processing of independent requests. The sequential part, in the form of shared locks and a single data store, remains the ceiling. Scaling with a fixed problem size is called strong scaling; the first effort goes into increasing the parallel fraction, not into new instances.

Little’s law links the average number of requests in the system L, the arrival rate λ and the average time spent in the system W. The formula is L = λW (Little, 1961; Little and Graves, 2008). A peak of 1,200 RPS with an average response time of 0.2 s gives 240 requests in the system at once. That is how many connections the database pool keeps open, and how many threads the application is sized for. If the response time doubles at the same arrival rate, there will be twice as many requests in the system, and both the pool and the queues will have to be widened.

Latency orders of magnitude — from a memory access to a packet across a continent — are collected in this reference’s cheat sheet. How latency is measured under load and what the p95 and p99 percentiles show is covered in the “Load testing” reference, section “Metrics: latency, percentiles, RPS”.

Section sources

the section is written from these pages

Architecture description: C4, arc42 and ADR

An architecture description is what you use to present the architecture to stakeholders: diagrams, documents and decision records. The ISO/IEC/IEEE 42010:2022 standard sets requirements for the structure of a description, but not for the process, notation or tools: the form is chosen to suit the reader.

Viewpoint and view

The standard distinguishes the architecture itself from its description: what gets described is not the system but the way it is shown to stakeholders. A single description is assembled from views: a view is what one group of readers sees, and a viewpoint is the set of rules for building such a view. Operations reads the deployment view, developers read the component view. The arc42 template has the same ideas: sections on building blocks, runtime behaviour and deployment.

The C4 model: four levels of zoom

The C4 model was devised by Simon Brown for his architecture courses, as a simplification of UML ideas for teams that don’t use diagrams. It consists of four levels of static diagrams, four zoom levels on a system: context, containers, components, code. A container here is an application or a data store: a server-side web application, a mobile app, a database schema. For most development teams the top two levels are enough; the rest are drawn as needed.

A container in C4 is an application or a data store, not a Docker container.

Besides the four static levels there are three supplementary diagrams: a system landscape, a map of all the organisation’s systems; a dynamic diagram, showing how elements interact at runtime; and a deployment diagram, showing what the system runs on in a particular environment. The context diagram is shown to everyone, including non-technical readers, and components to architects and developers. Code diagrams are worth keeping only for the most important or complex components: usually the IDE generates them on demand.

The arc42 template

arc42 is an open, free template for describing architecture, in use since 2005. It answers two questions: what to document and how. It has 12 sections, each with a clear purpose, and the template can be tailored to the project.

No.SectionWhat it contains
1Introduction and goalsbasic requirements, above all quality goals
2Constraintsregulation and other external limits
3Context and scopeexternal systems and interfaces
4Solution strategykey ideas and approaches
5Building block viewcode structure, decomposition by level
6Runtime viewimportant runtime scenarios
7Deployment viewhardware, infrastructure, deployment
8Cross-cutting conceptsshared decisions: technologies, patterns, processes
9Architectural decisionsimportant decisions not described in other sections
10Quality requirementsquality tree and quality scenarios
11Risks and technical debtknown problems and risks
12Glossarythe project’s key terms

Recording decisions: ADR

A significant decision is recorded as an architectural decision recordADRarchitecture decision recordA document that captures one important architectural decision in a short template: the context, the chosen option and the consequences.Read more: ADR (ADR) — a format by Michael Nygard, described on 15 November 2011. It is a short text file of one or two pages with five parts: title, context, decision, status, consequences. Records are kept in the project repository in files named doc/arch/adr-NNN.md, numbered sequentially, and numbers are never reused. A reversed decision is not deleted but marked as superseded: the fact that the decision was once made is also part of the history.

markdowna sample ADR: context, decision, status, consequences
# ADR 7: A queue between order intake and processing ## Context A promotional mailing opens a sale: 2,000 checkouts per secondin the first 10 minutes. Synchronous processing can't hold the peakand sits idle for most of the day. ## Decision We separate order intake from processing with a queue (RabbitMQ).The number of workers scales with queue depth. ## Status Accepted. ## Consequences The peak is smoothed out, and an order is confirmed in milliseconds.The price: an order becomes visible later, and we need to monitorqueue depth and reprocess messages after a failure.

Decisions are recorded for future readers. A newcomer who meets an old decision with no explanation either accepts it blindly or reverses it blindly, and both are harmful, Nygard argues. A recorded decision can be discussed: the consequences of one ADR often become the context of the next.

HLD and LLD

Two levels of design document have taken root in teams: HLDHLDhigh-level designA document that describes a system at a high level: what parts it consists of, how they are connected to each other and to external systems, and where it runs.Read more: HLD (High-Level Design) and LLDLLDlow-level designA document that describes how one component of the system is built: modules and classes, database tables, API contracts and the algorithms of key operations.Read more: LLD (Low-Level Design). There is no single standard for them — they are the team’s working agreements, so settle their contents within the project.

DocumentWhat it containsWho reads itWhen it is written
HLDHLDhigh-level designA document that describes a system at a high level: what parts it consists of, how they are connected to each other and to external systems, and where it runs.Read more: HLDcomponents, the links between them, deployment, external systemsthe team, operations, the managerbefore development starts
LLDLLDlow-level designA document that describes how one component of the system is built: modules and classes, database tables, API contracts and the algorithms of key operations.Read more: LLDclasses, database schemas, API contracts, algorithmsthe developers of the componentafter the HLD, before the component is built

A full architecture document (SADSADsoftware architecture documentAn architecture document that records a system’s context, its major parts and the connections between them, key decisions and quality requirements.Read more: SAD) is assembled from the arc42 template or from the ISO/IEC/IEEE 42010 viewpoints. In practice a combination is often enough: C4 diagrams for structure, ADRs for decisions, and short sections on context and deployment.

When you need UML

UML is a modelling language, not a mandatory part of a description: for an overview of a system C4 is usually enough. UML diagrams are used for complex interactions — sequence diagrams show the order of calls between parts, deployment diagrams show what runs on what. The C4 model can be supplemented with state and timing diagrams when they are needed. The language revision is covered in the “Standards and their status” section.

Section sources

the section is written from these pages

Laws and principles

The laws and principles of architecture are observations by practitioners, not laws of nature: each has an author, a year and an occasion. They are useful as a reminder of a typical trap, and should be quoted from the primary source. Conway’s law ties architecture to the structure of teams — see the “IT project management” reference, section “Conway’s law and team structure”.

Conway’s law: an organisation designs systems that copy its communication structure. Melvin Conway, the paper “How Do Committees Invent?”, Datamation, April 1968. Fred Brooks gave it the name “Conway’s law” in “The Mythical Man-Month” (1975).

The point is that links between modules follow links between people: where two developers talk easily, their code gets coupled easily — through explicit calls and through implicit shared assumptions. So the modularity of a system and the division of people into teams are agreed together, and not only at the start: over the life of a product, architecture and organisation change hand in hand.

pythonan architect’s decision record
# architect for six teams in different cities, after Fowlerdecision = "six large subsystems, details to be settled later"rationale = "communication across cities and time zones is expensive"for city in ("america", "europe", "asia"):    print(f"{city}: its own subsystem, a narrow contract")
Conway’s law: the communication structure of an organisation is copied into the structure of the system.

Don’t fight Conway’s law; use it. There are three ways to deal with it: ignore it and end up with strain in the architecture; accept it and draw module boundaries so that they don’t contradict how teams communicate; or change the teams themselves, which is the inverse Conway manoeuvre.

The Inverse Conway Maneuver means changing team structure so that the desired architecture emerges by itself. The term was introduced by Jonny LeRoy and Matt Simons in the December 2010 issue of Cutter IT Journal; in the world of microservices it is used to form small, long-lived, full-cycle teams. On an existing system with a rigid architecture the manoeuvre doesn’t work instantly: friction first appears between the new team structure and the old code, so move in small steps.

Hyrum’s law: with a sufficient number of API users, it doesn’t matter what you promise in the contract, because somebody will come to depend on every observable behaviour of the system. It is an observation by Hyrum Wright (then at Google), named by Titus Winters.

Undocumented properties — response speed, field order, tolerance of extra whitespace — gradually become part of an unwritten contract. When there are many users, the interface “evaporates”: the implementation becomes the interface, and any change to its internals breaks someone’s expectations. So changes to an API between services are prepared in advance: keep the documented contract narrow and the internals free.

The robustness principle (Postel’s law): “be conservative in what you send, be liberal in what you accept”. Jon Postel formulated it in the IP specification (RFC 760, January 1980).

The idea was that a specification is imperfect, and a working protocol is better than a perfect text. Experience showed the other side: if implementations silently forgive other people’s mistakes, those mistakes become the de facto standard, and later implementations have to reproduce the bugs of earlier ones — this is called bug-for-bug compatibility. For example, some TLS servers dropped the connection if a ClientHello ended with an empty extension, and clients had to adapt. RFC 9413 (June 2023, Informational) describes this mechanism and proposes actively maintaining the protocol instead of being tolerant: clarify the specification and fix the implementations.

Technical debt: a metaphor by Ward Cunningham from his report on the WyCash system at OOPSLA 1992. Shipping code for the first time is like taking on a debt: a small speed-up now, to be repaid by rewriting; every minute spent working with unconsolidated code is interest.

The danger is not the debt itself but debt that is never repaid: without periodic consolidation and rework, the code becomes unmanageable, the team splits into narrow specialists, and the product becomes inflexible. For how to recognise and repay debt, see the “Common mistakes in approach” section.

A short list

Gall’s law: a complex system that works always evolves from a simple system that worked; a complex system designed from scratch never works and cannot be patched up to make it work (John Gall, “Systemantics”, 1975). The second-system effect: in the second design, the designer overloads the product with the lessons and embellishments of the first (Fred Brooks, “The Mythical Man-Month”, 1975).

KISS: don’t complicate a solution without need. YAGNI: don’t build in advance what you may never need. Both principles are applied without citing authors: the wording matters more than the history.

The strangler fig is the gradual replacement of an old system by a new one behind a facade proxy; see the “Domain-driven design (DDD)” section.

Law or principleAuthor and yearWhat to do in practice
Conway’s lawMelvin Conway, 1968Align module boundaries with teams; don’t expect the “right” architecture with a different communication structure
Inverse Conway manoeuvreJonny LeRoy, Matt Simons, 2010Form teams around the desired architecture; on a rigid old system, move in small steps
Hyrum’s lawHyrum Wright, name by Titus WintersFor any popular API, assume the contract is wider than the document; change the implementation carefully
Robustness principleJon Postel, RFC 760, 1980Send strictly according to the specification; accept strictly within its limits, and record and fix deviations
Technical debtWard Cunningham, 1992Take it on deliberately and repay it by reworking; make sure the interest doesn’t eat your speed
Gall’s lawJohn Gall, 1975Don’t design a complex system from scratch: grow it from a working simple one
Second-system effectFred Brooks, 1975Don’t carry everything accumulated into the second version: keep the scope under control
KISS and YAGNIno single authorDon’t complicate without need and don’t build in advance what you may not need

Further reading

  • Design and evolution of service interactions — see the “Software architecture” reference, section “Service integration”.
  • How to draw module boundaries that withstand Hyrum’s law — see the “Software architecture” reference, section “Modularity and boundaries”.
  • Why systems accumulate unwritten contracts and how to document them — see the “Software architecture” reference, section “Architecture description: C4, arc42 and ADR”.

Section sources

the section is written from these pages

Common mistakes

What hurts a team most often is not the choice of technology but a cost noticed too late. Typical examples are microservices adopted for future growth, a database shared by several services, and a style chosen because it is fashionable. Each of these mistakes has a recognisable symptom and a workable answer.

Microservices for future growth

The microservice premium is the price of a distributed system: automated deployment, monitoring, failure handling and eventual consistency. Fowler’s rule is not to consider microservices until the system can be run as a monolith; most systems should be a single monolithic application, with modularity kept inside it.

The premium is paid up front, while the complexity it was meant to address may never arrive. A team of 5 running 12 services bears the cost of distribution from day one. The spread is wide: Fowler has seen a team of 60 with 20 services and a team of 4 with 200 services.

Distributed monolith

Services that cannot be released independently form a distributed monolith: microservices in shape, a monolith in coupling. The Azure guidance lists the symptoms: chatty synchronous calls between services and dependencies that force two or more services to be deployed together. A chain of orders → warehouse → payment, where a payment release requires redeploying all three, is the typical picture.

Draw boundaries along bounded contexts: a service’s functionality should not span more than one context. If two services constantly call each other, they may be one service, so merge them back. When in doubt, make services larger: splitting one service is easier than moving functionality between existing ones. Where a call merely hands work on, a queue or an event is cheaper: in the Azure example, requests go into a queue and the delivery history is built from the delivery service’s events.

A database shared by several services

A shared database brings back the monolithic coupling you have just got rid of. The orders service and the customers service write to the same tables: a change to the credit-limit schema has to be agreed by both teams, which is development-time coupling. A long transaction in one service holds a table lock and slows another service’s query, which is runtime coupling. One database is also hard pressed to suit services with different storage needs.

The pattern that answers this is database per service: each service has its own database and gets other services’ data through the owner’s API or an event from it.

Big ball of mud

A big ball of mud is a system with no discernible structure: elements exchange data indiscriminately, almost all important data is shared or duplicated, and the structure is either undefined or blurred by successive patches. Brian Foote and Joseph Yoder described it at the PLoP (Pattern Languages of Programs) conference in 1997 and called it the most common architecture in practice, a de facto standard that is rarely discussed.

The causes are ordinary: deadlines burn, and architecture gives way to the urgent; work on it is invisible from outside; the team changes, taking its memory of decisions with it; the system grows through patches without rework. Foote and Yoder’s answer is not a heroic rewrite from scratch but constant refactoring, which is what holds entropy back. Carve out boundaries step by step (the strangler fig approach is covered in “Domain-driven design (DDD)”) and put together what changes at the same pace. Keep technical debt in view and pay it down on a schedule, before the interest eats the system.

A style chosen because it is fashionable

In 2015 Fowler observed that there is so much noise around microservices that teams adopt them too eagerly; the ThoughtWorks radar called this Microservice Envy. The question is not which style sounds good at conferences but whether it suits your system. Two things give you something to hold on to: quality attribute scenarios with a measurable bar, such as “the system handles 500 requests per second with latency under 200 ms” (see “Quality attributes and non-functional requirements”), and an architectural decision record (ADR) with the options considered, so it is visible what was rejected and why.

Vendor lock-in without an assessment

Vendor lock-in is not a yes-or-no matter but a scale: besides lock-in to a vendor, Gregor Hohpe lists lock-in to a product, its version, a platform and even the team’s skills. Escaping one lock-in creates another: Kubernetes is open, but its YAML manifests and versions are a lock-in too. Avoiding lock-in costs money: an abstraction layer adds complexity, and giving up a platform’s proprietary features undermines the point of moving to the cloud in the first place.

Hohpe compares the cost of switching to insurance: paying a huge premium for a zero deductible rarely pays off if switching is unlikely. His example: switching costs $50,000, the probability is 5%, and the expected saving is $2,500; investing in a zero switching cost exceeds that. Estimate both numbers and record the conclusion in an ADR.

Decisions without a record

The cheapest mistake to fix is the silent decision: a choice was made, the reasons stayed in the participants’ heads, and every new argument starts from scratch. Record significant decisions as ADRs: context, options, choice, consequences. Format and storage are covered in “Architecture description: C4, arc42 and ADR”.

MistakeSymptomWhat to do
Microservices for future growthdeployment and monitoring eat up time before the complexity has arrivedrun a monolith, keep modularity inside it
Distributed monolithreleasing one service forces its neighbours to be redeployed, calls run in chainsdraw boundaries along bounded contexts, merge the chatty pair
Shared databasea schema change has to be agreed by several teams, other services’ locks slow queriesdatabase per service, other services’ data through APIs and events
Big ball of muda change in one place breaks something unpredictable elsewherescheduled refactoring, boundaries step by step
Style chosen by fashionthe arguments are conferences and other people’s stories, not your own requirementsquality attribute scenarios and an ADR with options
Lock-in without an assessmentthe cost and probability of leaving the vendor are unknownestimate both numbers, record the decision in an ADR
Decisions without a recordthe argument about why a decision was made repeats with every team changean ADR for every significant choice

Section sources

the section is written from these pages

Standards and their status

Architecture description is set by ISO/IEC/IEEE 42010:2022 (which replaced the 2011 edition, itself the successor of IEEE 1471-2000), the product quality model by ISO/IEC 25010:2023, and requirements by ISO/IEC/IEEE 29148:2018. Frameworks add processes and diagrams on top of them: TOGAF for enterprise architecture and Well-Architected for reviewing cloud workloads.

Which documents are current

Every concept in this reference rests on a standard, and the status of each edition has been checked against the iso.org, standards.ieee.org, opengroup.org or omg.org page. The table shows that most work with standards relies on documents from 2017–2024: the editions are still young.

DocumentWhat it definesStatusReplaced or supplemented by
ISO/IEC/IEEE 42010:2022architecture description: viewpoints and viewscurrent edition, November 2022replaced ISO/IEC/IEEE 42010:2011
ISO/IEC/IEEE 42020:2019architecture processes: governance and enablingcurrent, under revisionnew edition in development (AWI 42020 draft)
ISO/IEC 25010:2023product quality model: nine characteristicscurrent edition, November 2023replaced ISO/IEC 25010:2011
ISO/IEC/IEEE 29148:2018requirements engineeringcurrent, confirmed in 2024a replacement is being prepared as a DIS draft
TOGAF Standard, 10th Editionenterprise architecture methodcurrent edition from The Open Groupsplit into Fundamental Content and Series Guides
ArchiMate 3.2enterprise architecture modelling languagecurrent standard from The Open Groupcomplements TOGAF
UML 2.5.1modelling language: class, sequence and deployment diagramscurrent OMG edition, December 2017replaced version 2.5 of 2015
AWS Well-Architected Frameworkquestionnaires for reviewing a cloud workloadedition of 6 November 2024sixth pillar, sustainability, added in November 2021
Azure Well-Architected Frameworkquestionnaires for reviewing a cloud workloadcurrent, updated continuouslyconsists of five pillars
Google Cloud Well-Architected Frameworkquestionnaires for reviewing a cloud workloadcurrent, updated continuouslysix pillars and cross-cutting perspectives

What to take from each

  • ISO/IEC/IEEE 42010:2022 is the vocabulary of description: the stakeholder (stakeholderstakeholderA person, group or organisation affected by a project or its outcome and able to influence it in turn.Read more: stakeholder), their concerns, viewpoints and views. The standard sets requirements for the structure of a description, not for the process or notation.
  • ISO/IEC 25010:2023 supplies the names of quality characteristics and subcharacteristics; how to use the model is covered in “Quality attributes and non-functional requirements”.
  • ISO/IEC/IEEE 29148:2018 sets requirements for the requirements themselves: engineering processes, the information to include and its format; the verifiability property is applied in “Quality attributes and non-functional requirements”.
  • TOGAF Standard, 10th Edition is a method for running enterprise architecture; in the 10th edition the stable part (Fundamental Content) is separated from the interchangeable guides (Series Guides).
  • Well-Architected Framework provides questionnaires a team uses to review a cloud workload before launch and in operation; each vendor has its own set of pillars.

Well-Architected pillars across three vendors

The pillars of the cloud frameworks almost coincide, with one difference: sustainability. The overlap makes it easier to carry a discussion from one cloud to another.

PillarAWSAzureGoogle Cloud
reliabilityyesyesyes
securityyesyesyes
costyesyesyes
operationsyesyesyes
performanceyesyesyes
sustainabilityyesnoyes

What changed in the latest editions

  • ISO/IEC 25010:2023 has nine characteristics instead of eight: usability became interaction capability, portability became flexibility, and safety was added. The 2011 edition was replaced by three documents, ISO/IEC 25002:2024, 25010:2023 and 25019:2023, and was withdrawn in March 2024.
  • ISO/IEC/IEEE 42010:2022 describes any entity: not only a system but also a software product, an enterprise and a product line.
  • ISO/IEC/IEEE 29148 has a third edition in the ballot: a DIS draft at stage 40.20, with voting open since September 2026; a replacement is expected once it is approved.
  • AWS Well-Architected Framework, edition of 6 November 2024: the guidance for five pillars was updated, with reliability reworked most extensively.
  • Google Cloud Well-Architected Framework is updated continuously: changes are published on the What’s new page.

Outdated documents that are still cited

Withdrawn documents still turn up in articles and old projects. Knowing what happened to them saves time: do not cite them in a new description.

DocumentReplaced byWithdrawn
IEEE 1471-2000ISO/IEC/IEEE 42010:20112011
ISO/IEC/IEEE 42010:2011ISO/IEC/IEEE 42010:2022November 2022
ISO/IEC 9126-1:2001ISO/IEC 25010:20112012
ISO/IEC 25010:2011ISO/IEC 25010:2023March 2024
IEEE 830-1998ISO/IEC/IEEE 29148:20112011

ISO/IEC/IEEE 42020:2019 (architecture processes) and 42030:2019 (architecture evaluation) are both under revision (stage 90.92), with new editions in development (AWI 42020 and AWI 42030 drafts): their provisions may change significantly.

Modelling languages: UML 2.5.1 was published by OMG in December 2017, and ArchiMate 3.2 is The Open Group’s standard for enterprise architecture. Both define a diagram notation, not a working process.

Further reading

  • For how quality models apply to requirements, see “Quality attributes and non-functional requirements”.
  • For how architecture description works in practice, see “Architecture description: C4, arc42 and ADR”.
  • For where the requirements standard sits in a project’s life cycle, see the reference “IT project management”.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Software architecture” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61