Architecture Styles vs Architecture Patterns
"An architectural style, then, defines a family of such systems in terms of a pattern of structural organization. More specifically, an architectural style determines the vocabulary of components and connectors that can be used in instances of that style, together with a set of constraints on how they can be combined." — David Garlan and Mary Shaw, An Introduction to Software Architecture, CMU-CS-94-166, January 1994
Summary: A style is a family of systems that share a vocabulary and constraints, a pattern is a reusable solution to one recurring problem, a tactic is one decision that moves one quality attribute; this page is the map that places every style and the well-known patterns in one picture and tells you which chapter teaches each. Focus: The three definitions and how they nest, technical versus domain partitioning, monolithic versus distributed styles and the distributed premium, the styles catalogue (layered to cell-based and Lambda/Kappa), the architectural-patterns catalogue mapped to the chapters that own them, the characteristic ratings table, hybrids, a decision table, and one ordering system sketched in three styles in Go and Laravel. Learning goal: Given a system description or a requirement list, name the style (or hybrid) it uses, say which patterns and tactics live inside it, pick a style from the characteristics that matter, and know which chapter of this path to open next.
This is the map page of the group "AR 02 · Architecture Styles". It does not teach any single style in depth: Layered, Modular Monolith, Microkernel, Client-Server, Pipe-and-Filter, SOA, Microservices and Big Data each have their own chapter. Here you get the vocabulary, the comparison, and the rules for choosing. The decision between the three most common shapes is argued in Monolith vs Microservices vs Modular; the trade-off habit behind every choice is in Architecture Decisions; the quality attributes the ratings talk about are defined in Quality Attributes.
Page map
| If you are looking for | Go to |
|---|---|
| The definitions and the nesting in a few tables | Everything in one minute |
| Why the three words are kept apart | Why the distinction exists |
| Garlan and Shaw, Fielding, Gamma, Bass, Richards and Ford | Where it comes from |
| Style, pattern, tactic, partitioning, quantum, one block each | The concepts |
| Every style with when to use it and its chapter | The styles catalogue |
| Hexagonal, CQRS, saga, gateway, outbox and friends | The patterns catalogue |
| Stars for deployability, elasticity, cost, simplicity | Characteristic ratings |
| Combining styles in one system | Hybrid styles |
| How a style constrains a feature, step by step | Mechanics |
| Style drift, distributed monolith, hype-driven choice | Solving the classic problems |
| One ordering system in three styles (folders and code) | Go, Laravel |
| Picking a style from characteristics | Choosing |
| Monolith to distributed, with examples | In architecture |
| A measurable exercise | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three words. Every row is unpacked in the concepts.
| Term | In plain words | Scope | Example | Chosen |
|---|---|---|---|---|
| Architecture style | The overall shape of a family of systems: what kinds of parts exist, how they may talk, what is forbidden | Whole system | Layered, event-driven, microservices | Once, early; costly to reverse |
| Architectural pattern | A named, reusable answer to one recurring problem inside a context | A part of the system, crossing several components | Saga, outbox, API gateway, CQRS, hexagonal | Per problem, when the problem appears |
| Tactic | One design decision aimed at one quality attribute | One mechanism | Retry, timeout, cache, heartbeat, rate limit | Per quality scenario |
| Design pattern (GoF) | A solution at class level | A few classes | Adapter, Strategy, Decorator | In code, see Design Patterns |
| Architecture characteristic | A quality the system must have ("-ility") | Whole system | Elasticity, deployability, testability | From requirements, see Requirements to Architecture |
How the three nest. A style is the container, patterns are the recurring moves inside it, tactics are the single bolts inside a pattern.
| Style (container) | Patterns that commonly live in it | Tactics those patterns bundle |
|---|---|---|
| Microservices | API gateway, saga, outbox, database per service, circuit breaker, sidecar | Timeout, retry with backoff, idempotency key, health check, bulkhead |
| Event-driven | Broker topology, mediator topology, event sourcing, CQRS | Acknowledgment, dead-letter queue, replay, partitioning |
| Layered | Repository, service layer, MVC | Input validation at the boundary, caching in the data layer |
| Modular monolith | Facade per module, anti-corruption layer, in-process events | Schema ownership, architecture fitness test |
The styles at a glance (full text in the catalogue):
| Style | Deployed as | Partitioned by | Strongest at | Weakest at |
|---|---|---|---|---|
| Layered | One unit | Technical layers | Cost, simplicity | Scale, evolvability |
| Modular monolith | One unit | Domain modules | Cost, evolvability, testability | Independent scaling |
| Microkernel | One unit (plugins inside) | Core plus plug-ins | Extensibility, customisation | Scale |
| Pipeline (pipe-and-filter) | One or several units | Processing steps | Simplicity, composability | Interactive workloads |
| Client-server | Two or more tiers | Role (requester or provider) | Centralised control, familiarity | Server is a bottleneck and single point |
| Peer-to-peer | Many equal nodes | None (every node both) | Resilience, no central cost | Consistency, discovery |
| Service-based | A few coarse services | Domain | Balance of agility and cost | Fine-grained elasticity |
| Event-driven | Many decoupled processors | Event types | Performance, scale, fault tolerance | Simplicity, testability |
| Space-based | Replicated processing units plus data grid | Processing units | Elasticity under spikes | Simplicity, cost, testing |
| Orchestration-driven SOA | Enterprise services plus a bus | Technical, enterprise-wide | Reuse (the goal) | Agility, cost |
| Microservices | Many small services | Bounded contexts | Deployability, elasticity, evolvability | Cost, simplicity, performance |
| Serverless / FaaS | Functions on a platform | Function / event | Pay per use, no servers to run | Latency control, vendor lock-in |
| Cell-based | Many identical full-stack cells | Customer or key range | Blast-radius control | Cross-cell queries, cost |
| Lambda / Kappa | Batch plus speed layers, or one log | Data flow | Large-scale analytics | Operational complexity |
Why the distinction exists
When a team says "we use hexagonal architecture" and another says "we use microservices", they are not alternatives: one describes how the inside of a component is organised, the other describes how the system is cut into deployable parts. Keeping style, pattern and tactic apart stops comparisons of things at different levels, and it tells you who can change what: a tactic is a pull request, a pattern is a team decision, a style is a company decision.
| Mixing the words | Keeping them apart |
|---|---|
| "Should we use CQRS or microservices?" (a pattern against a style) | "Which style fits, and does a read/write split help inside it?" |
| Every discussion becomes a naming fight | The name tells the scale of the decision |
| A pattern is imposed system-wide because it was fashionable | A pattern is applied where its problem exists |
| Style choice is made by accident, one library at a time | Style choice is a recorded decision (ADR) |
The analogy we reuse on this page: a city. The style is the city plan: a strict grid with identical blocks (layered), a hub with districts that plug into it (microkernel), or independent neighbourhoods each with their own shops, school and clinic (microservices, or cells). A pattern is a recurring street solution: a roundabout where four streets meet, a one-way ring around a market. A tactic is a speed bump, a traffic light, a lamp post: one device for one purpose (safety, flow). You do not pick "roundabout versus grid": you pick a city plan and then decide where roundabouts help.
Three common misunderstandings, up front
- "Microservices, hexagonal and DDD are three competing architectures." They sit at different levels: microservices is a style (how the system is cut into deployables), hexagonal is a pattern for the inside of one component, DDD gives the vocabulary for drawing the cuts.
- "A pattern is a smaller style." A style restricts the whole system and defines its vocabulary; a pattern solves one problem and can appear in several styles (a circuit breaker lives in microservices, service-based and SOA alike).
- "The more patterns, the better the architecture." Each pattern is a cost: more concepts, more moving parts. The test is a real problem in this system that the pattern removes.
Where it comes from
Year Source What it gave us
1 1992 Perry & Wolf, Foundations for the study of Architecture = elements + form + rationale
software architecture
2 1994 Garlan & Shaw, Intro. to Software Arch. Style = vocabulary of components/connectors + constraints
3 1994 Gamma, Helm, Johnson, Vlissides (GoF) Design patterns at class level
4 1996 Buschmann et al., POSA vol. 1 Architectural patterns (layers, pipes and filters, broker...)
5 1996 Shaw & Garlan, Software Architecture (book) Style catalogue and case studies
6 2000 Fielding, doctoral dissertation REST derived by adding constraints to a "null style"
7 2002 Fowler, Patterns of Enterprise App. Arch. Enterprise patterns (repository, unit of work, ...)
8 2003 Bass, Clements, Kazman, 2nd ed. Tactics; "patterns package tactics"
9 2014 Lewis & Fowler, Microservices A style named and characterised
10 2015 Richards, Software Architecture Patterns Layered, event-driven, microkernel, microservices, space-based rated
11 2020 Richards & Ford, Fundamentals of Software Arch. Eight styles compared on star ratingsGarlan and Shaw, 1994. The paper (Carnegie Mellon technical report CMU-CS-94-166, also CMU/SEI-94-TR-21) treats an architecture as "a collection of computational components ... together with a description of the interactions between these components—the connectors", and defines a style as the quote at the top. Their questions for describing any style are still the best template: what is the structural pattern (components, connectors, constraints), what is the computational model, what are the essential invariants, where is it used, what are its advantages and disadvantages, what are its specialisations. Note that the same paper writes "architectural patterns, or styles" as synonyms: in the 1990s the words were not yet separated.
Perry and Wolf, 1992. Fielding summarises their model in his dissertation: "a software architecture as a set of architectural elements that have a particular form, explicated by a set of rationale", with the rationale capturing "the motivation for the choice of architectural style, the choice of elements, and the form". Style is already a named design choice there.
Fielding, 2000. In chapter 1 he defines the term operationally: "An architectural style is a coordinated set of architectural constraints that restricts the roles/features of architectural elements and the allowed relationships among those elements within any architecture that conforms to that style." He also notes that "a given architecture may be composed of multiple styles" and that "a hybrid style can be formed by combining multiple basic styles". In chapter 5 he derives REST by starting from the "Null style (...) simply an empty set of constraints" and adding client-server, stateless, cache, uniform interface, layered system and code-on-demand one at a time, studying "the impact of each constraint as it is added". This is the best demonstration of what "style = constraints" means.
Gamma et al. and POSA, 1994 and 1996. GoF patterns work at class level (Design Patterns). Buschmann, Meunier, Rohnert, Sommerlad and Stal's Pattern-Oriented Software Architecture volume 1 (1996) applied the pattern idea to the system level and named three kinds: architectural patterns (Layers, Pipes and Filters, Blackboard, Broker, MVC, Microkernel), design patterns and idioms. We did not fetch POSA, so the exact wording of its definition is not quoted here; the three-kind split is how the book is catalogued in its widely cited summaries (secondary).
Fowler, 2002. Patterns of Enterprise Application Architecture gives the enterprise-application layer of patterns: domain model, transaction script, repository, unit of work, data mapper, and so on. The online catalogue lists them with one-paragraph summaries; our Data Persistence in Design chapter uses several.
Bass, Clements and Kazman. In the second edition (2003) chapter 5 they write: "A tactic is a design decision that influences the control of a quality attribute response", "We call a collection of tactics an architectural strategy" and "An architectural pattern packages tactics". That is the nesting the diagram above shows: tactics inside patterns. (The edition we could read is the 2003 second edition on a university mirror; later editions refine the wording.)
Richards, 2015, and Richards and Ford, 2020. Mark Richards' free O'Reilly report Software Architecture Patterns (2015) called layered, event-driven, microkernel, microservices and space-based "architecture patterns" and rated each Low or High on agility, deployment, testability, performance, scalability and ease of development. The 2020 book Fundamentals of Software Architecture renamed the same family "architecture styles", added pipeline, service-based and orchestration-driven SOA, and replaced Low/High by one-to-five star ratings across more characteristics. Practitioners therefore use "style" and "pattern" loosely: this page follows the 2020 usage plus Bass's definitions.
Newman and the microservices literature, 2014 onwards. Lewis and Fowler (25 March 2014) describe "a particular way of designing software applications as suites of independently deployable services". Fowler's MicroservicePremium (13 May 2015) warns that the style "adds a premium to a project's cost and risk". Chris Richardson's microservices.io is organised exactly like this page: its first group is titled "Architectural style" (monolithic or microservice), and its other groups (service boundaries, collaboration, reliability, deployment, observability) are patterns.
The concepts, one by one
Each block: plain words, the common mistake, the precise definition, a timeline, scenarios, who provides it, and how to use it.
Architecture style Must-know
In plain words: A style is the overall shape of a kind of system: which kinds of parts exist, how they are allowed to connect, and what is forbidden. If you know the style, you can predict how a change will travel and how the system will fail.
Common misunderstanding: "A style is a technology or a framework." Laravel is not a style and neither is Kubernetes; a layered style can be built in Laravel, Spring or Go, and microservices can run without Kubernetes. The style lives in the constraints, not the tools.
Definition: Garlan and Shaw: the vocabulary of components and connectors plus the constraints on combining them. Fielding: "a coordinated set of architectural constraints". Each constraint buys a property and costs another one (statelessness buys scalability and visibility, costs repeated data per request).
Constraint added (Fielding's derivation) Property bought Price paid
1 Client-server Independent evolution of UI/data Network hop
2 Stateless Scalability, visibility Repeated data per request
3 Cache Fewer interactions, lower latency Stale reads
4 Uniform interface Simplicity, decoupling Less efficient than a tailored protocol
5 Layered system Intermediaries (proxies, gateways) Added latencyReal scenario: A start-up chooses "layered, one deployable, one PostgreSQL" because the team is five people; a payment platform chooses "service-based, 6 services" because audit scope must be isolated; a ticket seller chooses "event-driven plus in-memory grid" for the 100x spike on release day.
What provides it: Language and framework features enforce constraints only partly: Go internal/ packages, Laravel module providers, Java modules, ArchUnit and Pest arch() tests, API gateways and network policies (see Solving).
How to use it: Name the style in the first page of the architecture description, list its constraints as rules, and enforce at least the dependency rule automatically.
Architectural pattern Must-know
In plain words: A pattern is a proven answer to a problem you will meet again: "how do I update my database and publish an event without losing one of them?" is answered by the outbox pattern in any style that uses a broker.
Common misunderstanding: "Using a pattern means copying its diagram." A pattern is a problem-context-solution-consequences description. The consequences section is half the value: saga gives you consistency across services and costs you isolation and a compensation design.
Definition: A reusable solution to a recurring problem in a given context, recorded with its forces and consequences. Architectural patterns (Buschmann; Richardson) work at the component level and cross several classes; design patterns (GoF) work at class level; enterprise patterns (Fowler) sit in between for business applications.
Problem (context) Pattern Consequence you accept
1 Update DB and send event, atomically Transactional outbox A relay process; at-least-once delivery
2 One call spans several services' data Saga No isolation; compensations to design
3 Many clients, many services API gateway / BFF New hop; the gateway must be scaled
4 Slow dependency drags the caller down Circuit breaker A fallback path to design and test
5 Replace a legacy system gradually Strangler fig Two systems run in parallel for a long timeReal scenario: A checkout that writes an order and publishes OrderPlaced: without outbox, a crash between the two leaves either a ghost order or a missing event.
What provides it: Messaging chapters own the data-flow patterns (Outbox, Saga, Event Sourcing and CQRS); this section owns the structure patterns (Gateway, BFF, Mesh); system design owns the resilience patterns (Circuit Breaker, Bulkhead).
How to use it: Write the problem as a sentence first. If you cannot, you do not need the pattern.
Tactic Important
In plain words: A tactic is one small decision made to improve one quality: "add a timeout" improves availability under slow dependencies; "add a cache" improves latency; "add a heartbeat" improves fault detection.
Common misunderstanding: "Tactics are the same as patterns." A tactic addresses one quality attribute and has no structure of its own; a pattern bundles several tactics (a circuit breaker bundles fault detection, a state machine and a fallback) and brings new structure.
Definition: Bass et al.: "a design decision that influences the control of a quality attribute response". Tactic families exist per attribute (availability, performance, security, modifiability, testability, usability, energy efficiency in later editions). Tactics have side effects: redundancy for availability needs synchronisation, which costs performance.
Quality scenario Tactic chosen Side effect to manage
1 p99 under 300 ms when the DB is slow Timeout + cache read-through Stale data
2 Survive loss of one availability zone Replicate state, health check Replica lag, split brain
3 Block credential stuffing Rate limit per IP and account False positives for shared NAT
4 Deploy daily without downtime Expand/contract migrations Longer rollout of schema changesReal scenario: The Laravel Http::timeout(1)->retry(3, 100) call in the microservices excerpt is two tactics (timeout, bounded retry) that together form part of a larger pattern (circuit breaker plus fallback).
What provides it: Libraries (Go context deadlines, net/http client timeouts; Laravel HTTP client, queue retry settings), infrastructure (load balancers, service meshes) and database settings.
How to use it: Derive tactics from a measurable quality scenario (SLOs), and record the side effect next to the tactic.
How the three nest Must-know
In plain words: Style on the outside, patterns inside it, tactics inside the patterns. The style narrows which patterns make sense; the patterns decide which tactics you need.
Common misunderstanding: "Nesting means strict hierarchy." A pattern often appears in several styles, and a tactic often appears in several patterns. A circuit breaker (pattern) uses a timeout (tactic), and a plain layered application may use a timeout without any circuit breaker.
Definition: Style constrains the whole; pattern solves a recurring problem within the constraints; tactic is the smallest knob. A decision may be classified by its reversal cost: style (quarters), pattern (weeks), tactic (days).
Level Decision Who decides Reversal cost
1 Style Distributed, service-based, 6 services Architect + leads Quarters
2 Pattern Outbox for order events Team Weeks
3 Tactic Idempotency key on the reserve endpoint Developer, in review Days
4 Design Strategy for discount rules Developer HoursReal scenario: A team asked "should we adopt event sourcing?" first checks the level: it is a pattern (weeks to months, affects storage and reads), not a style, so it can be introduced in one bounded context without redesigning the system.
What provides it: The ADR template: "Decision level: style / pattern / tactic" as a field.
How to use it: When two options are compared, check they are at the same level; if not, split the question.
Technical versus domain partitioning Must-know
In plain words: You can cut a system by what the code does technically (UI, business rules, data access) or by what the business does (orders, inventory, payments). Technical cuts make one change touch every layer; domain cuts make one change touch one slice.
Common misunderstanding: "Domain partitioning means microservices." Modules inside one deployable are domain-partitioned too; microservices are one way to deploy a domain partition. Likewise technical partitioning does not have to be monolithic, but it usually is.
Definition: Richards and Ford call the top-level split technical or domain partitioning. Layered, pipeline and (in the book) orchestration-driven SOA partition by technical concern; modular monolith, service-based, microservices, event-driven (by event type) and space-based tend to partition by domain; microkernel mixes (a technical core and domain plug-ins).
Feature: "add gift wrapping to an order"
Technical partitioning Domain partitioning
1 presentation/OrderForm (edit) orders/ui (edit)
2 business/OrderService (edit) orders/rules (edit)
3 persistence/OrderRepository (edit) orders/store (edit)
4 database/orders table (edit) -- all in module "orders"
-> 4 folders, 3 teams to coordinate -> 1 module, 1 teamReal scenario: A shop with a layered Laravel app (app/Http, app/Services, app/Repositories) finds that every sprint touches all three folders for every story; moving to app/Modules/Orders, app/Modules/Inventory (modular monolith) makes pull requests local.
What provides it: Folder and package structure, plus a rule enforced by tests. Conway's law links partitioning to team structure (Service Boundaries).
How to use it: Prefer domain partitioning from the first day, even inside one deployable; add technical layers inside each module if you need them.
Monolithic versus distributed styles Must-know
In plain words: A monolithic style ships as one deployment unit; a distributed style ships as several that talk over a network. The network is the whole difference and it changes everything: calls can be slow, fail, or succeed without the reply arriving.
Common misunderstanding: "Distributed is the grown-up version of monolithic." Distribution is a cost you pay to get independent deployment or scaling. If you do not need either, you pay without receiving.
Definition: Richards and Ford split the styles into monolithic (layered, pipeline, microkernel, and the modular monolith as a variation) and distributed (service-based, event-driven, space-based, orchestration-driven SOA, microservices). Fowler's MicroservicePremium names the cost: microservices "introduce complexity on their own account", a premium on cost and risk; his guideline is "don't even consider microservices unless you have a system that's too complex to manage as a monolith".
Same call, two shapes Failure modes that appear
1 orders.Place -> inventory.Reserve (function call) exception, rollback (one transaction)
2 orders -> HTTP POST /reservations -> inventory timeout (did it reserve?), retry (twice?),
partial failure (order saved, reserve lost),
version skew, auth, serialisationReal scenario: Twilio Segment's team had split a pipeline into one service per destination; their own account lists shared-library version drift, one repo and queue per destination, and operator-scaled services as the cost, and in 2018 they merged "over 140 services into a single service" (see In architecture).
What provides it: Nothing removes the premium; sagas, idempotency, outbox, observability and discovery manage it (Service Communication, Data Ownership).
How to use it: Distribute only along a seam where you need independent deployment, scaling or fault isolation, and write that reason in the ADR.
Architecture characteristics and star ratings Important
In plain words: The "-ilities" are the qualities the business needs (can it scale, deploy daily, survive a crash). Each style has a natural strength profile; the ratings table says which style is a good starting point for which "-ility".
Common misunderstanding: "A five-star style guarantees the quality." The stars are the natural tendency of a typical implementation; a sloppy microservices system has poor fault tolerance, and a careful layered system can scale far.
Definition: Richards and Ford rate each style from one to five stars on characteristics including deployability, elasticity, evolvability, fault tolerance, modularity, overall cost, performance, reliability, scalability, simplicity and testability, and list the partitioning type and the number of architecture quanta. An architecture quantum is "an independently deployable artifact with high functional cohesion, which includes all the structural elements required for the system to function properly" (the definition in Software Architecture: The Hard Parts; paraphrased here, not fetched): one database shared by everything keeps the system at one quantum even if there are twenty services.
Architecture Quanta Why
1 Layered monolith 1 One deployable, one database
2 Modular monolith 1 Same
3 Microservices (DB each) many Each service deploys and owns its data
4 "Microservices" on one 1 Shared database couples deployment and data
shared database -> the distributed monolithReal scenario: A team asks for "99.99% and daily deploys"; the table shows both are strongest in service-based and microservices, and that the cost and simplicity stars are the price.
What provides it: See Characteristic ratings and Requirements to Architecture.
How to use it: Choose the top three characteristics for the system (not eight), then use the table to shortlist styles.
The styles catalogue
One block per style: what it is, the rule that defines it, when it fits, when it hurts, and the chapter that teaches it. The ratings are in one table.
The tree shows the usual deployment shape of each style; the sections below follow it from left to right.
Layered (n-tier) Must-know
In plain words: Stack the code in horizontal layers (presentation, business, persistence, database); each layer talks only to the one below. It is the default shape of most business applications, in Laravel as Controller -> Service -> Repository -> Model.
Common misunderstanding: "Layered means clean." Layers by themselves only separate technical concerns; the domain logic can still be a tangle inside the business layer, and a request for "add a field" still touches all layers. Richards' report says that without a formal architecture teams "resort to the de facto standard traditional layered architecture pattern".
Definition: Partitioning: technical. Constraint: closed layers (a request goes through the layer directly below) or open layers (may be skipped) by explicit exception. One quantum.
When it fits: Small teams and budgets, CRUD-heavy line-of-business systems, time to market, unknown domain. When it hurts: Fast independent change, scale of one part, large teams colliding in the same layers (the "sinkhole" anti-pattern: requests pass through layers that add nothing). Chapter: Layered Monolithic Architecture.
Modular monolith Must-know
In plain words: One deployable, but cut into modules by business area, each with a small public face and hidden insides (own tables, own rules). It keeps the monolith's cheap operations and the microservices' clean boundaries.
Common misunderstanding: "It is just a monolith with folders." Folders are not boundaries: a modular monolith needs enforced rules (no reaching into another module's tables or classes), checked automatically. Shopify's engineering post describes the work as "componentization" with tooling and a dependency graph that had to be untangled, not as a folder rename.
Definition: Partitioning: domain. Constraint: modules communicate through contracts (facades, interfaces, events); each module owns its data. One quantum. Fowler: "there's no reason why you can't make a single monolith with well defined module boundaries".
When it fits: Most new systems; teams of 3 to 100; domains still being discovered; a path to extract services later along proven seams. When it hurts: Independent scaling or deployment per module, polyglot needs. Chapter: Modular Monolith.
Microkernel (plug-in) Important
In plain words: A small core with the minimum to run, and plug-ins that add features, like an IDE, a browser with extensions, or an e-commerce platform with payment plug-ins.
Common misunderstanding: "A plug-in system needs a marketplace." Any internal feature that varies by customer or country (tax rules, shipping carriers) can be a plug-in behind a stable contract.
Definition: Core system plus plug-in components; plug-ins register through a contract, and the core never depends on a specific plug-in. Partitioning: both (technical core, domain plug-ins). Usually one quantum, can be several if plug-ins are remote.
When it fits: Product software with customer-specific variations, rule engines, tools. When it hurts: Scale and elasticity (the core is a single piece), plug-in versioning. Chapter: Microkernel / Plugin.
Pipeline (pipe-and-filter) Important
In plain words: Data flows through a chain of single-purpose steps (filters) joined by pipes: read, validate, transform, enrich, write. Unix shell pipelines, ETL jobs and image processors are the usual examples.
Common misunderstanding: "It is only for batch." Streaming pipelines (Kafka Streams, Flink, Unix pipes) process data continuously; the constraint is the one-directional flow and filters that do not share state, not the batch.
Definition: Garlan and Shaw: each component "has a set of inputs and a set of outputs", reads streams and produces streams; pipes connect outputs to inputs; constraints include no cycles and filters that are independent. Partitioning: technical. Strongest in simplicity and testability of each filter.
When it fits: ETL, compilers, media processing, request/response middleware chains (HTTP middleware is a pipeline). When it hurts: Interactive, stateful workloads. Chapter: Pipe-and-Filter.
Client-server Must-know
In plain words: Clients ask, servers answer. The server owns data and rules; the client owns presentation. Two-tier, three-tier, thin and thick client are variants.
Common misunderstanding: "Client-server is old; REST replaced it." REST is client-server with more constraints; Fielding lists "client-server" as the first constraint added to derive it, and the web is the largest client-server system there is.
Definition: Separation of concerns between a requesting component and a providing component, which Fielding says allows "components to evolve independently". Variants: tiers (presentation, application, data), thin/thick clients, BFF, push (WebSockets, SSE) on top.
When it fits: Nearly every networked application as the base layer. When it hurts: Offline use, heavy server load without caching, server as single point of failure. Chapter: Client-Server; the networking side is in The Client-Server Model.
Peer-to-peer Good to know
In plain words: Every node is both client and server; there is no central owner. BitTorrent, blockchain nodes and some chat systems work this way.
Common misunderstanding: "P2P means no servers at all." Most practical systems add bootstrap or tracker servers; pure P2P is rare.
Definition: Equal nodes, discovery by gossip or a distributed hash table, data replicated across peers; consistency is usually eventual. Partitioning: none. See Gossip Protocols, Consistent Hashing, CRDTs.
When it fits: Censorship resistance, bandwidth sharing, no central budget. When it hurts: Strong consistency, access control, discovery latency.
Event-driven Must-know
In plain words: Components react to events instead of calling each other. A producer announces "OrderPlaced" and does not know who listens.
Common misunderstanding: "Event-driven means Kafka." The style is about decoupling by events; the broker (RabbitMQ, Kafka, Redis Streams, SQS) is an implementation detail, and in-process event dispatchers (Laravel events) are event-driven too.
Definition: Two topologies in Richards and Ford: broker (no central coordinator; each processor publishes the next event, high decoupling, hard to see the overall flow) and mediator (a central orchestrator sequences steps; easier workflow control and error handling, more coupling). Partitioning: domain by event type. Strong in performance, scalability and fault tolerance, weak in simplicity and testability.
When it fits: Asynchronous workflows, high-throughput fan-out, integrations. When it hurts: Workflows that need an immediate consistent answer, debugging the whole path. Chapters: Event-Driven Architecture, Event Sourcing and CQRS, Saga, Stream Processing.
Space-based Good to know
In plain words: Remove the central database from the hot path: many identical processing units keep their data in memory and replicate it among themselves through a data grid; the database is updated asynchronously behind.
Common misunderstanding: "It is just a cache." A cache in front of a database still depends on that database for correctness; in space-based architecture the in-memory grid is the system of record for the hot data and the database is a slow backup.
Definition: Processing units, virtualised middleware (messaging grid, data grid, processing grid, deployment manager) and data pumps to a database. Richards' report says high scalability "comes from the fact that there is little or no dependency on a centralized database".
When it fits: Unpredictable spikes with a bounded working set (ticketing, auctions, online games). When it hurts: Large datasets that do not fit memory, testing at peak load ("achieving very high user loads in a test environment is both expensive and time consuming"). Related: Scaling Strategies, Caching.
Service-based Important
In plain words: A handful (often 4 to 12) of coarse-grained services, each a whole business area, usually sharing one database; a pragmatic middle between a monolith and microservices.
Common misunderstanding: "Service-based is half-baked microservices." It is a style on its own with its own sweet spot: independent deployment of large domain pieces, without the per-service database and without hundreds of network calls.
Definition: Few domain services, one UI (or a few), shared database allowed (with care: schema partitioning by service keeps coupling visible). In Richards and Ford's ratings it is the most balanced distributed style: good deployability, fault tolerance and testability at a lower cost than microservices.
When it fits: Teams moving from a monolith, systems where parts need different release cadence or isolation (payments, reporting). When it hurts: Elasticity of fine-grained functions, a shared schema nobody owns. Chapter: Monolith vs Microservices vs Modular.
Service-oriented architecture (SOA) Good to know
In plain words: The 2000s enterprise style: reusable business services in the middle, an enterprise service bus (ESB) routing and transforming messages, SOAP and WSDL contracts, shared across the whole company.
Common misunderstanding: "SOA and microservices are the same." Richards and Ford contrast them: SOA chases enterprise-wide reuse and sits on a central bus, with technical partitioning; microservices accept duplication to keep services independent and partition by domain.
Definition: Layers of enterprise, business, application and infrastructure services, orchestrated by the bus. The OASIS reference model defines the vocabulary; the W3C defines SOAP 1.2 and WSDL 1.1. In ratings it is the most expensive and least agile distributed style.
When it fits: Large enterprises integrating existing systems. When it hurts: Agility, cost, team autonomy. Chapter: SOA.
Microservices Must-know
In plain words: Many small services, each owning one business capability and its data, deployed independently by its own team, talking over the network.
Common misunderstanding: "Small services equal microservices." The test is independent deployability and data ownership. Services that must be deployed together, or that share one database, are a distributed monolith.
Definition: Lewis and Fowler: "suites of independently deployable services", organised "around business capabilities", with "decentralized control of languages and data". Partitioning: domain (bounded contexts). Ratings: five stars for deployability, elasticity, evolvability, fault tolerance, modularity and scalability; one star for cost and simplicity.
When it fits: Large systems with many teams, parts with very different load or release cadence, strong platform and DevOps maturity. When it hurts: Small teams, unclear domain, weak observability (the premium). Chapters: Microservices Architecture, Service Boundaries, Communication, Data Ownership, Discovery, Gateway, BFF, Mesh.
Serverless / Functions as a Service Important
In plain words: You write functions; the platform (AWS Lambda, Google Cloud Functions, Azure Functions, Cloudflare Workers) runs them on demand and bills per invocation. No servers to patch or scale.
Common misunderstanding: "Serverless has no servers and no ops." Servers exist; you do not manage them. You still own cold starts, timeouts, concurrency limits, idempotency and cost control.
Definition: Fowler: "application designs that incorporate third-party 'Backend as a Service' (BaaS) services, and/or that include custom code run in managed, ephemeral containers on a 'Functions as a Service' (FaaS) platform". It is event-driven by nature: an HTTP request, queue message or schedule triggers a function. Strong in elasticity and cost at low load; weak in latency control, long-running work and portability.
When it fits: Spiky or rare workloads, glue code, event handlers, prototypes. When it hurts: Steady high load (reserved servers are cheaper), long jobs, strict latency. Chapter: Serverless and Event-Driven Compute.
Cell-based Good to know
In plain words: Run many identical, fully self-contained copies (cells) of the whole stack, each serving a slice of customers. If one cell breaks, only its slice is affected.
Common misunderstanding: "A cell is a microservice." A cell is a complete copy of the workload (all services and data for its customers); microservices are different services. Cells are replication for isolation; microservices are decomposition.
Definition: The AWS Well-Architected whitepaper explains the idea with ship bulkheads: "vertical partition walls subdivide the ship's interior into self-contained, watertight compartments"; a router maps a partition key (customer, tenant, region) to a cell, with minimal cross-cell interaction. Strong in blast-radius control; weak in cross-cell queries and cost.
When it fits: Multi-tenant SaaS and platforms with strict availability goals. When it hurts: Small systems, cross-tenant reporting. Related: Bulkhead, Multi-Tenancy.
Big data: Lambda and Kappa Good to know
In plain words: Two shapes for analytics on huge data. Lambda runs a batch layer (accurate, slow) and a speed layer (fast, approximate) and merges them; Kappa uses a single streaming path over a replayable log.
Common misunderstanding: "Kappa replaced Lambda." Jay Kreps' 2014 article "Questioning the Lambda Architecture" argued the dual code paths are a maintenance burden and proposed reprocessing from the log; both remain in use depending on volume and tooling.
Definition: Lambda (Nathan Marz): batch layer, serving layer and speed layer, with the batch recomputation overriding the real-time view. Kappa (Kreps): stream processing only; reprocess by replaying the log from the start. Chapter: Big Data Architectures; data-flow pieces in Change Data Capture, Stream Processing.
The architectural patterns catalogue
These are the patterns people name when they talk about "architecture". The "Owner" column says which chapter teaches the mechanism; this page only places them.
| Pattern | Problem it solves | Typical styles | Owner chapter |
|---|---|---|---|
| Hexagonal (ports and adapters) | Domain code tied to HTTP, DB or UI; hard to test alone | Any; inside one service or module | Structural patterns, Anti-corruption |
| Clean / onion architecture | Same, with a strict inward dependency rule | Any | SOLID DIP |
| Repository, unit of work | Persistence details leak into business code | Layered, modular | Repositories, Data Persistence |
| CQRS | Reads and writes need different models or scale | Microservices, event-driven | Event Sourcing and CQRS |
| Event sourcing | Need full history and replay | Event-driven | Event Sourcing and CQRS |
| Saga | A business transaction spans several services | Microservices, SOA | Saga |
| Transactional outbox | Atomic DB update plus message publish | Any with a broker | Outbox |
| Change data capture | Stream database changes without double writes | Event-driven, migrations | CDC |
| API gateway | Many clients, many services, one entry point | Microservices, service-based | Gateway, BFF, Mesh |
| Backend for frontend (BFF) | One API cannot serve web, mobile, partners well | Microservices | Gateway, BFF, Mesh |
| Sidecar, service mesh | Cross-cutting network concerns repeated in every service | Microservices | Service Mesh |
| Service discovery | Instances move; callers need addresses | Microservices | Service Discovery |
| Circuit breaker | Slow or failing dependency drags callers down | Any distributed style | Circuit Breaker |
| Bulkhead | One failing part exhausts shared resources | Any distributed style | Bulkhead |
| Strangler fig | Replace a legacy system gradually | Migrations | Monolith vs Microservices vs Modular |
| Database per service | Services coupled through one schema | Microservices | Data Ownership |
| Competing consumers | Scale message processing horizontally | Event-driven | Competing Consumers |
| MVC, MVP, MVVM | Presentation mixed with logic | Client-server, layered | MVC |
Two points of vocabulary. First, Fowler writes that "for most systems CQRS adds risky complexity"; it is a pattern for particular situations, not a style and not a default. Second, the strangler fig name comes from strangler figs Fowler saw in Queensland rain forests in 2001; he wrote a short post a couple of years later (originally titled "Strangler Application"), and the current bliki entry is dated 22 August 2024: the new system grows around the old until the old can be removed.
Where the pattern vocabulary comes from per source:
| Source | What it catalogues | Level |
|---|---|---|
| Garlan and Shaw 1994, Shaw and Garlan 1996 | Pipes and filters, data abstraction, event systems, layered, repositories, interpreters | Styles |
| Buschmann et al., POSA 1996 | Layers, pipes and filters, blackboard, broker, MVC, microkernel, reflection | Architectural patterns |
| Fowler, PoEAA 2002 | Domain model, transaction script, repository, data mapper, unit of work, lazy load | Enterprise patterns |
| Gamma et al. 1994 | 23 patterns: factory, adapter, strategy, observer | Design patterns |
| Hohpe and Woolf, EIP 2003 | Message channel, router, translator, aggregator | Integration patterns, see Integration Styles |
| Richardson, microservices.io | Decomposition, data, communication, deployment, observability | Microservice patterns |
| Bass et al. | Tactics for availability, performance, security, modifiability, testability | Tactics |
Pattern spotlight: hexagonal and clean architecture Important
In plain words: Put the business rules in the middle and make everything else (HTTP, database, queue, UI) a replaceable adapter plugged into a port. Tests drive the core directly; production plugs real adapters in.
Common misunderstanding: "Hexagonal architecture needs six sides, and clean architecture needs exactly four rings." Cockburn says the hexagon is a drawing device, and Martin writes that "the circles are schematic" and "there's no rule that says you must always have just these four"; the only fixed rule is the direction of dependencies.
Definition: Cockburn's intent: "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." Martin's Dependency Rule: "source code dependencies can only point inwards". Both are the ports-and-adapters idea; onion architecture is the same idea with its own vocabulary. They are patterns for the inside of a component or module, usable in a layered, modular or microservice style.
Without ports (domain knows the world) With ports and adapters
1 OrderService -> Eloquent Order model OrderService -> OrderRepository (port, in core)
2 OrderService -> Stripe SDK OrderService -> PaymentGateway (port, in core)
3 test needs DB + network test passes fakes; prod passes StripeAdapter, EloquentRepository
-> arrows point outward -> all arrows point inward to the coreReal scenario: A pricing module that is tested with in-memory fakes in milliseconds and later extracted into a service: only the adapter changes from "in-process call" to "HTTP client". See Structural Patterns, SOLID DIP and the Go sketch in style 2, where orders owns the Stock port.
How to use it: Apply it inside the modules that hold real rules; skip it for thin CRUD, where it adds interfaces without removing a problem.
Characteristic ratings
The table gives approximate one-to-five ratings in our words. Verification note: the O'Reilly book chapters were not retrievable from this machine (access denied), so the numbers below are our reading of the ratings in Fundamentals of Software Architecture and should be checked against the book. What we did verify is the 2015 free report: it rates layered Low on agility, deployment, performance and scalability and High on testability and ease of development; event-driven High on agility, deployment, performance and scalability, Low on testability and ease of development; microkernel High on agility, deployment, testability and performance, Low on scalability and ease of development; microservices High on agility, deployment, testability, scalability and ease of development, Low on performance; space-based High on agility, deployment, performance and scalability, Low on testability and ease of development. The two sources agree in direction except for a few cells (for example layered testability), so treat each number as an ordering hint, not a measurement.
| Style | Partitioning | Quanta | Deploy-ability | Elasticity | Evolvability | Fault tolerance | Modularity | Overall cost | Perfor-mance | Reliability | Scalability | Simplicity | Testability |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Layered | Technical | 1 | 1 | 1 | 1 | 1 | 1 | 5 | 2 | 3 | 1 | 5 | 2 |
| Pipeline | Technical | 1 | 1 | 1 | 2 | 1 | 2 | 5 | 2 | 3 | 1 | 5 | 3 |
| Microkernel | Both | 1 | 3 | 1 | 3 | 1 | 3 | 5 | 3 | 3 | 1 | 3 | 3 |
| Service-based | Domain | 1 or more | 4 | 2 | 3 | 4 | 3 | 4 | 3 | 4 | 3 | 3 | 4 |
| Event-driven | Technical | 1 or more | 3 | 3 | 5 | 5 | 4 | 3 | 5 | 3 | 5 | 1 | 2 |
| Space-based | Technical | 1 or more | 3 | 5 | 3 | 3 | 3 | 3 | 5 | 3 | 5 | 1 | 1 |
| Orchestration SOA | Technical | 1 or more | 1 | 3 | 1 | 3 | 3 | 1 | 2 | 2 | 3 | 1 | 1 |
| Microservices | Domain | Many | 5 | 5 | 5 | 5 | 5 | 1 | 2 | 4 | 5 | 1 | 4 |
For cost and simplicity, 5 means cheap and simple. The modular monolith is not in the book's eight; by our reading it matches layered on cost and simplicity, beats it on modularity, evolvability and testability (3 to 4 each), and equals it on elasticity and scalability (1).
How to read the table:
| Pattern in the table | What it means |
|---|---|
| Column of 1s for deployability to scalability | Monolithic: one unit to deploy, scale, fail |
| Cost 5 and simplicity 5 together | Cheap and easy; you pay with agility |
| Cost 1 and simplicity 1 together | Powerful and expensive; justified only by a measured need |
| Event-driven: simplicity 1, performance 5 | Fast but hard to follow and test end to end |
| Service-based: no 1s except elasticity 2 | The compromise style, few weaknesses |
| Space-based: elasticity 5, testability 1 | You cannot easily reproduce the spike in a test |
Hybrid styles in practice
Fielding writes that "a given architecture may be composed of multiple styles" and that "a hybrid style can be formed by combining multiple basic styles". Almost every production system is a hybrid.
| Hybrid | What it combines | Why teams do it | Watch for |
|---|---|---|---|
| Modular monolith core plus a few extracted services | Modular monolith, microservices | Extract only the module that needs independent scale (image processing, search) | Two deployment models to operate |
| Service-based core with an event-driven edge | Service-based, event-driven | Core is synchronous and consistent; notifications and integrations are asynchronous | Dual write; use outbox |
| Microservices with a pipeline inside one service | Microservices, pipeline | An ingestion service runs validate, enrich, write as filters | The pipeline owns its failure semantics |
| Layered inside each microservice | Microservices, layered | A service is small enough for three layers, no more | Anaemic layers; see Layered |
| CQRS read side as a separate service | Microservices, CQRS | Heavy reads scale apart from writes | Staleness, read-your-writes |
| Microkernel plus serverless plug-ins | Microkernel, FaaS | Customer-written plug-ins run isolated | Cold starts, security of plug-ins |
| Cells of microservices | Cell-based, microservices | Many services per cell, many cells | Router is a new critical component |
| Lambda inside an event-driven system | Big data, event-driven | Stream for freshness, batch for correctness | Two code paths |
The rule for hybrids: state the dominant style (the one that sets the deployment model and the data ownership) and call the rest "patterns inside it". "We are service-based with an event-driven integration edge" is a sentence an ADR can hold; "we are everything" is not.
Mechanics: how a style acts on a feature
A style does its work through constraints. The same feature, "place an order and reserve stock", travels differently in each style.
LAYERED (1 process, 1 DB transaction)
1 POST /orders -> OrderController
2 -> OrderService.place() BEGIN
3 -> OrderRepository.decrementStock() UPDATE products ... WHERE stock >= qty
4 -> OrderRepository.insert() INSERT INTO orders ...
5 <- 201 Created COMMIT (all or nothing) MODULAR MONOLITH (1 process, 1 DB, 2 schemas)
1 POST /orders -> orders.PlaceOrder
2 -> inventory.ReservesStock.reserve() contract call, in process
3 -> orders.orders INSERT same transaction, own schema
4 <- 201 Created COMMIT (all or nothing) MICROSERVICES (2 processes, 2 databases)
1 POST /orders -> orders service order row saved as PENDING
2 -> POST inventory/reservations Idempotency-Key: reserve-42
3 <- timeout after 800 ms did inventory reserve? unknown
4 -> retry, same key inventory returns the first result
5 <- 201 reserved
6 orders -> order row CONFIRMED separate local transaction
7 if step 5 never arrives: saga timeout -> compensation (release, CANCELLED)What changed between the three is not the feature but the constraint set: layered allows one transaction across everything; the modular monolith allows one transaction but forbids touching another module's tables; microservices forbid both and replace the transaction with a protocol (idempotent calls, saga, outbox).
Style drift: how the constraint decays.
Month What the team did Resulting state
1 0 Modules with facades, rule in README Modular monolith on paper
2 3 A deadline: orders reads inventory.stock table Rule broken once, "temporary"
3 6 Three more such reads, none removed Boundary leaks both ways
4 9 Inventory schema change breaks Orders Coupling surfaces as an outage
5 12 Nobody dares to split or change A big ball of mud with foldersThe remedy is the same as for any invariant: make the rule executable (see Solving).
The distributed premium, itemised.
| New concern in a distributed style | Failure or cost | Tactic or pattern that manages it |
|---|---|---|
| Remote call latency and timeouts | Slow dependency blocks callers | Timeout, circuit breaker, bulkhead |
| Partial failure | Order saved, stock not reserved | Saga, outbox, idempotency |
| Duplicate messages | Charged twice | Idempotent consumer, inbox |
| No cross-service transaction | Atomicity lost | Local transactions plus compensation |
| Data duplication | Stale copies | Events, CDC, ownership rules |
| Service discovery and routing | Wrong address, outage on deploy | Discovery, load balancing |
| Contract and version skew | Deploy order matters | Consumer-driven contracts, expand/contract |
| Observability | One request touches ten services | Distributed tracing, correlation IDs |
| Security between services | Internal network is not trusted | mTLS, tokens, see mTLS |
| Operations | N pipelines, N dashboards, N on-call rotas | Platform team, standard templates |
Solving the classic problems
| Problem | What it looks like | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|---|
| Hype-driven style choice | "Everyone uses microservices" | Characteristic-driven choice | Rank 3 characteristics, score styles (Choosing), record an ADR | Choice is defensible and reversible | Needs real requirements |
| Style drift | Modules reach into each other's tables | Executable architecture rules | Go internal/, Pest arch(), ArchUnit, schema grants | Violations fail the build | Rules must be maintained |
| Distributed monolith | Services deployed together, one shared database | Merge back, or give each service its own data | See Service Boundaries | Removes the premium without the benefit | Migration work |
| Layer sinkhole | Layers pass requests through unchanged | Open the layer deliberately, or move to domain modules | Allow controllers to read through a query object | Fewer empty layers | Rule exceptions to document |
| Pattern overuse | CQRS plus event sourcing for a CRUD admin | Name the problem first | Pattern needs a one-sentence problem and a measured pain | Less accidental complexity | Discipline |
| Hybrid chaos | Three styles, no dominant one | State the dominant style | ADR: "dominant style: X; patterns inside: Y" | Shared mental model | Occasional re-labelling |
| Big-bang rewrite | Rewrite in the "right" style | Strangler fig | Route by route, behind a facade | Always shippable | Two systems for a long time |
| Premature extraction | A service per module on day one | Modular monolith first, extract on evidence | Keep seams enforced, extract when scale or team size forces it | Cheap experiments | Extract later costs real work |
Fitness tests for boundaries (Go and Pest)
-- Module ownership in PostgreSQL: each module gets a schema and a role.
CREATE SCHEMA orders;
CREATE SCHEMA inventory;
CREATE ROLE orders_app LOGIN;
CREATE ROLE inventory_app LOGIN;
GRANT USAGE ON SCHEMA orders TO orders_app;
GRANT ALL ON ALL TABLES IN SCHEMA orders TO orders_app;
GRANT USAGE ON SCHEMA inventory TO inventory_app;
GRANT ALL ON ALL TABLES IN SCHEMA inventory TO inventory_app;
-- orders_app has no privilege on inventory tables: a cross-module SELECT fails with
-- SQLSTATE 42501 (insufficient_privilege), so drift becomes visible in CI.
-- Cross-module data goes through a contract (a function call or an event), never a JOIN.The Go layout enforces the same rule at compile time (a package under internal/ cannot be imported from outside its parent tree), and the Pest test in the Laravel section enforces it for PHP namespaces.
Go: the same order system in three styles
All three sketches implement "place an order and reserve stock". Folder trees first, then one excerpt each.
Style 1: layered monolith
orders-layered/
main.go # wiring + HTTP server
handler/orders.go # presentation layer
service/orders.go # business layer
store/orders.go # persistence layer (database/sql)The sketch keeps the three layers in one file so the call chain is visible. Handler calls service, service calls store; nobody skips a layer.
// Style 1: layered monolith. One deployable, one database, horizontal layers
// (presentation -> business -> persistence). Every layer may only call the
// layer directly below it; technical partitioning.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
)
type Order struct {
ID int `json:"id"`
SKU string `json:"sku"`
Qty int `json:"qty"`
Total int `json:"total_cents"`
}
// ---- persistence layer -----------------------------------------------------
type OrderStore interface {
Save(ctx context.Context, o Order) (Order, error)
}
type memStore struct {
mu sync.Mutex
next int
rows map[int]Order
}
func (s *memStore) Save(_ context.Context, o Order) (Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.next++
o.ID = s.next
s.rows[o.ID] = o
return o, nil
}
// ---- business layer --------------------------------------------------------
var ErrInvalid = errors.New("invalid order")
type OrderService struct {
store OrderStore
price map[string]int
}
func (s *OrderService) Place(ctx context.Context, sku string, qty int) (Order, error) {
unit, ok := s.price[sku]
if !ok || qty <= 0 {
return Order{}, ErrInvalid
}
return s.store.Save(ctx, Order{SKU: sku, Qty: qty, Total: unit * qty})
}
// ---- presentation layer ----------------------------------------------------
type OrderHandler struct{ svc *OrderService }
func (h OrderHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var in struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
o, err := h.svc.Place(r.Context(), in.SKU, in.Qty)
if errors.Is(err, ErrInvalid) {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(o)
}
func main() {
store := &memStore{rows: map[int]Order{}}
svc := &OrderService{store: store, price: map[string]int{"book": 1200}}
mux := http.NewServeMux()
mux.Handle("POST /orders", OrderHandler{svc: svc})
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/orders", strings.NewReader(`{"sku":"book","qty":2}`))
mux.ServeHTTP(rec, req)
fmt.Println(rec.Code, strings.TrimSpace(rec.Body.String()))
}Style 2: modular monolith
orders-modular/
main.go # composition root: the only file that sees both modules
internal/orders/ # module: public Service, private rules, own tables
internal/inventory/ # module: public Facade, private ledger
migrations/orders/ # schema "orders"
migrations/inventory/ # schema "inventory"orders declares the small interface it needs (Stock); inventory exports a Facade that happens to satisfy it. The orders package does not import inventory, so the dependency can be replaced by a fake in tests or by an HTTP client later without touching orders.
// Package orders is a module that depends on inventory only through a
// small interface that it owns (consumer-side interface). It does not import
// the inventory package, so the dependency arrow is decided in main.
package orders
import (
"context"
"fmt"
)
// Stock is what orders needs from "somebody who holds stock".
type Stock interface {
Reserve(ctx context.Context, sku string, qty int) error
}
type Service struct{ stock Stock }
func NewService(s Stock) *Service { return &Service{stock: s} }
func (s *Service) Place(ctx context.Context, sku string, qty int) (string, error) {
if err := s.stock.Reserve(ctx, sku, qty); err != nil {
return "", fmt.Errorf("place order: %w", err)
}
return fmt.Sprintf("order accepted: %d x %s", qty, sku), nil
}// Style 2: modular monolith. Still one process and one deployable, but
// partitioned by domain; modules talk through facades, wired in one place.
package main
import (
"context"
"errors"
"fmt"
"academy/styles-vs-patterns/modular/internal/inventory"
"academy/styles-vs-patterns/modular/internal/orders"
)
func main() {
// Composition root: the only place that knows both modules.
inv := inventory.New(map[string]int{"book": 3})
svc := orders.NewService(inv)
ctx := context.Background()
for _, qty := range []int{2, 2} {
msg, err := svc.Place(ctx, "book", qty)
switch {
case errors.Is(err, inventory.ErrOutOfStock):
fmt.Println("rejected:", err)
case err != nil:
fmt.Println("error:", err)
default:
fmt.Println(msg)
}
}
}Style 3: microservices
orders-service/ # its own repo or module, its own database
cmd/orders/main.go
internal/api/ # HTTP handlers
internal/inventoryclient/ # the client below: timeout, retry, idempotency key
internal/outbox/ # events written in the same transaction as the order
inventory-service/ # separate deployable, separate database
cmd/inventory/main.go
internal/reservations/ # idempotent POST /reservationsThe call that was a function in style 2 now needs a deadline, a bounded retry on 5xx only, and an idempotency key so a retry cannot reserve twice.
// Style 3: microservices. The same "place order" call now crosses a network.
// The caller must add a timeout, a bounded retry and an idempotency key,
// because the remote call can be slow, fail, or succeed without the reply
// arriving. None of this exists in the in-process version.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"time"
)
type InventoryClient struct {
base string
http *http.Client
}
func NewInventoryClient(base string) *InventoryClient {
return &InventoryClient{base: base, http: &http.Client{Timeout: 800 * time.Millisecond}}
}
// Reserve calls the inventory service. key makes a retry safe: the server must
// treat two requests with the same key as one reservation.
func (c *InventoryClient) Reserve(ctx context.Context, key, sku string, qty int) error {
body, _ := json.Marshal(map[string]any{"sku": sku, "qty": qty})
var last error
for attempt := 0; attempt < 3; attempt++ {
if attempt > 0 {
time.Sleep(time.Duration(attempt) * 50 * time.Millisecond) // linear back-off, small on purpose
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/reservations", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Idempotency-Key", key)
resp, err := c.http.Do(req)
if err != nil {
last = err
continue
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
switch {
case resp.StatusCode < 300:
return nil
case resp.StatusCode >= 500:
last = fmt.Errorf("inventory: status %d", resp.StatusCode)
continue // retry server-side failures only
default:
return fmt.Errorf("inventory rejected: status %d", resp.StatusCode)
}
}
return fmt.Errorf("inventory unavailable after retries: %w", last)
}
func main() {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 { // first call fails, retry succeeds
http.Error(w, "boom", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
err := NewInventoryClient(srv.URL).Reserve(context.Background(), "order-42", "book", 2)
fmt.Println("calls:", calls.Load(), "err:", err)
}The Go angle
Go makes the styles concrete through packages: internal/ is a compiler-enforced boundary (since Go 1.4), unexported identifiers hide module internals, and small consumer-side interfaces keep the dependency arrows pointing the way the style wants. The standard library covers the distributed tactics (context deadlines, http.Client.Timeout, net/http/httptest for contract tests). A tiny scoring helper that encodes the ratings table, to make "choose by characteristics" an executable argument:
// A tiny decision aid: score each style against the characteristics you
// weighted as important. Ratings are an ordinal 1..5 reading of Richards &
// Ford's style analysis (see the heatmap on the page); weights are yours.
package main
import (
"fmt"
"sort"
)
var characteristics = []string{"deployability", "elasticity", "evolvability", "fault-tolerance", "modularity", "cost", "performance", "scalability", "simplicity", "testability"}
var ratings = map[string][]int{
"layered": {1, 1, 1, 1, 1, 5, 2, 1, 5, 2},
"pipeline": {1, 1, 2, 1, 2, 5, 2, 1, 5, 3},
"microkernel": {3, 1, 3, 1, 3, 5, 3, 1, 3, 3},
"service-based": {4, 2, 3, 4, 3, 4, 3, 3, 3, 4},
"event-driven": {3, 3, 5, 5, 4, 3, 5, 5, 1, 2},
"space-based": {3, 5, 3, 3, 3, 3, 5, 5, 1, 1},
"microservices": {5, 5, 5, 5, 5, 1, 2, 5, 1, 4},
}
type scored struct {
style string
score int
}
// Rank returns styles ordered by weighted score. weights maps a characteristic
// to its importance (0 = ignore, 3 = critical).
func Rank(weights map[string]int) []scored {
var out []scored
for style, r := range ratings {
total := 0
for i, c := range characteristics {
total += r[i] * weights[c]
}
out = append(out, scored{style, total})
}
sort.Slice(out, func(i, j int) bool {
if out[i].score != out[j].score {
return out[i].score > out[j].score
}
return out[i].style < out[j].style
})
return out
}
func main() {
// A 6-person team building an internal tool: cheap and simple wins.
team := map[string]int{"cost": 3, "simplicity": 3, "testability": 2, "deployability": 1}
// A ticket seller with 100x spikes: elasticity and scale dominate.
spikes := map[string]int{"elasticity": 3, "scalability": 3, "performance": 2, "fault-tolerance": 2, "cost": 1}
cases := []struct {
name string
weights map[string]int
}{{"internal tool", team}, {"ticket spikes", spikes}}
for _, c := range cases {
fmt.Println(c.name)
for _, s := range Rank(c.weights)[:3] {
fmt.Printf(" %-14s %d\n", s.style, s.score)
}
}
}Laravel: the same order system in three styles
Style 1: layered monolith
app/
Http/Controllers/OrderController.php # presentation
Services/OrderService.php # business, DB::transaction
Repositories/OrderRepository.php # persistence (query builder)
Models/ # Eloquent models<?php
namespace App\Services;
use App\Repositories\OrderRepository;
use Illuminate\Support\Facades\DB;
class OrderService
{
public function __construct(private readonly OrderRepository $repo) {}
/** @return array{id:int, sku:string, qty:int, total_cents:int} */
public function place(string $sku, int $qty): array
{
// One process, one database: a local transaction covers everything.
return DB::transaction(function () use ($sku, $qty) {
$unit = $this->repo->unitPrice($sku);
$this->repo->decrementStock($sku, $qty); // throws when stock would go negative
return $this->repo->insert($sku, $qty, $unit * $qty);
});
}
}Style 2: modular monolith
app/Modules/
Orders/
PlaceOrder.php # use case, depends on the Inventory contract
Http/ Models/ Database/ # module-private
Inventory/
Contracts/ReservesStock.php # public
Contracts/OutOfStock.php # public
Internal/StockLedger.php # private implementation
InventoryServiceProvider.php # binds contract to implementation
tests/ArchTest.php # Pest arch() rules<?php
namespace App\Modules\Orders;
use App\Modules\Inventory\Contracts\ReservesStock;
use Illuminate\Support\Facades\DB;
// Style 2, modular monolith: Orders talks to Inventory through its contract, in-process.
final class PlaceOrder
{
public function __construct(private readonly ReservesStock $stock) {}
public function __invoke(string $sku, int $qty, int $totalCents): int
{
return DB::transaction(function () use ($sku, $qty, $totalCents) {
$this->stock->reserve($sku, $qty); // same process, same transaction
return DB::table('orders.orders')->insertGetId([
'sku' => $sku, 'qty' => $qty, 'total_cents' => $totalCents,
]);
});
}
}The rule that makes it a modular monolith and not a folder rename:
<?php
// Pest architecture test: fails the build when a module reaches into another module's internals.
arch('orders only uses the inventory contracts')
->expect('App\Modules\Orders')
->not->toUse('App\Modules\Inventory\Internal');
arch('inventory does not depend on orders')
->expect('App\Modules\Inventory')
->not->toUse('App\Modules\Orders');Style 3: microservices
orders-service/ # Laravel app 1, database "orders"
app/Clients/InventoryClient.php # HTTP client with timeout, retry, idempotency key
app/Jobs/PublishOrderEvents.php # outbox relay
inventory-service/ # Laravel app 2, database "inventory"
app/Http/Controllers/ReservationController.php # idempotent endpoint<?php
namespace App\Clients;
use Illuminate\Support\Facades\Http;
// Style 3, microservices: the same call now crosses a network, so it needs a timeout, bounded
// retries and an idempotency key. Without them a retry can reserve stock twice.
final class InventoryClient
{
public function reserve(string $orderId, string $sku, int $qty): void
{
Http::baseUrl(config('services.inventory.url'))
->timeout(1)
->retry(3, 100, throw: false)
->withHeaders(['Idempotency-Key' => "reserve-{$orderId}"])
->post('/reservations', ['sku' => $sku, 'qty' => $qty])
->throw(); // 4xx/5xx after the last retry becomes a RequestException
}
}The Laravel angle
Laravel 13 gives each tactic a first-class API: Http::timeout(), Http::retry($times, $sleep, throw: false) (HTTP client docs), DB::transaction() for the local transaction, service providers as the composition root (the container binding is where a module chooses its implementation), and queues plus events for the event-driven edge. Pest's arch() tests (architecture testing) enforce module boundaries. The framework is style-neutral: the same Laravel app can be layered, modular or one of several services; what decides is the rules you enforce.
Choosing a style
Step 1: pick the three characteristics that matter most, with a number each (SLO, capacity). Step 2: shortlist from the ratings. Step 3: apply the filters below.
| Situation | Shortlist | Extra technique | Reason |
|---|---|---|---|
| New product, 3 to 10 developers, domain unclear | Modular monolith (or layered if throwaway) | Enforced module boundaries, ADR | Lowest cost, keeps seams for later; Fowler: "The majority of software systems should be built as a single monolithic application" |
| 30+ developers, release conflicts, parts with different cadence | Service-based, then selective microservices | Strangler fig, platform team | Independent deploys at moderate cost |
| Spiky traffic with bounded hot data (ticket release) | Space-based or event-driven plus cache | Queue-based load levelling, rate limiting | Elasticity, performance |
| Product with customer-specific features | Microkernel | Versioned plug-in contract | Extensibility |
| Data transformation, ETL, media | Pipeline | Backpressure, idempotent steps | Simple, testable filters |
| Strict failure isolation per tenant | Cell-based on top of any style | Router by tenant key | Blast radius |
| Rare or bursty workloads, small ops team | Serverless | Idempotency, concurrency limits | Pay per use |
| Large enterprise integrating legacy systems | SOA or integration hub | Canonical model (Message Transformation) | Reuse across existing apps |
| Analytics on very large event streams | Kappa or Lambda | Replayable log, CDC | Throughput, reprocessing |
| Regulated payments component inside a larger app | Service-based (one isolated service) | Separate database, audit log | Audit scope isolation |
Quick filters:
| Question | If yes | If no |
|---|---|---|
| Do parts need independent scaling you have measured? | Allow a distributed style for those parts | Stay in one deployable |
| Do separate teams need to release without coordinating? | Domain partitioning, consider services | Modules are enough |
| Is the team below ~10 developers and the domain unclear? | Modular monolith | Revisit |
| Do you have tracing, CI/CD per service, on-call for each? | Microservices are survivable | Do not split yet |
| Is a single database transaction a real need? | Keep that data in one unit | Events and sagas are acceptable |
In architecture: from a single process to a distributed system
One everyday example runs through this section: an online bakery that takes orders, tracks flour and cakes, and charges cards. One production example: Shopify's modular monolith and Twilio Segment's move from many services back to one, both described in the companies' own engineering posts.
Monolith (one process, one database)
Bakery: Day one, a Laravel app: OrderController -> OrderService -> OrderRepository, one PostgreSQL, one DB::transaction that decrements stock and inserts the order. Style: layered. Everything is atomic, the whole system fits in one head, deploys take a minute.
| Question | Answer in a layered monolith |
|---|---|
| Atomicity | One local transaction covers stock and order |
| Failure modes | The process is up or down; no partial failure between components |
| Cost | Lowest: one pipeline, one dashboard |
| Where it starts to hurt | Many developers editing the same layers; one slow report slows checkout |
The simplest correct usage: choose domain folders from the start (Orders, Inventory) even if you keep layers inside; it costs nothing and prepares the next step.
Modular monolith / multiple databases
Bakery: Orders, Inventory, Payments become modules, each with a facade and its own schema (orders, inventory, payments). Modules call each other through contracts; a fitness test blocks forbidden imports. Still one deployable and still one transaction when you want it, but the seams are real.
Production example, Shopify (September 2020 post): their Rails monolith was being "componentized". The post reports a call-graph tool (Wedge) that logged method calls across components during CI test runs to detect forbidden dependencies, and Sorbet, now their "go-to tool for expressing input and output contracts on component boundaries". They also write: "We are very deliberate about when to split functionality out into separate services, and we only do it for good reasons. That's because splitting a single monolithic application into a distributed system of services increases the overall complexity considerably."
| Question | Answer in a modular monolith |
|---|---|
| Ownership | Each module owns its tables; others use its contract or events |
| Schema sharing | One database server, separate schemas; cross-schema joins forbidden by rule and by grants |
| Transactions | Possible across modules (same database), used sparingly so extraction stays possible |
| Extraction | A module with a contract and its own schema can become a service later (strangler fig) |
Microservices
Bakery: Payments needs PCI isolation and independent scaling at holiday peaks, so it becomes a service with its own database; the order flow now crosses a network. The call that was payments.Charge() becomes an HTTP call with an idempotency key, and "order paid" becomes an event written to an outbox and consumed by Orders.
Orders service Payments service Broker
1 POST /orders - -
2 save order PENDING - -
3 outbox row: ChargeRequested (same transaction) -
4 relay publishes -----------------------------------> ChargeRequested
5 - consume (idempotent) <---
6 - charge card, save result -
7 - outbox row: Charged -
8 consume Charged <---------------------------------- Charged
9 order PAID - -
10 (failure) no Charged in 2 min -> saga timeout -> order CANCELLED, release stockProduction example, Twilio Segment (July 2018 post): their pipeline sent events to over a hundred customer destinations. A single queue suffered head-of-line blocking when one destination slowed, so they built a separate service and queue per destination, which fixed the isolation. Later the post lists the costs that came with it: one repository per destination, shared libraries whose versions diverged, per-service scaling that "became more art than science", and operational overhead that "increased linearly with each added destination". They consolidated "over 140 services into a single service". The lesson is not "microservices are bad": the split fixed a real isolation problem and then became expensive when the number of services kept growing.
| Question | Answer in microservices |
|---|---|
| Atomicity | None across services; saga, outbox, idempotency |
| Data | Database per service (Data Ownership) |
| Failure | Partial failure is normal; timeouts and retries are mandatory |
| Cost | Highest of the common styles: pipelines, tracing, on-call, contracts |
| Prerequisite | Team autonomy, CI/CD per service, observability, a platform |
Distributed data (replicas, caches, multi-region)
Bakery: The cake catalogue is read ten thousand times for each order. A read replica serves browsing; a cache holds the product pages; a CDN holds images. Now two new questions appear: how stale may a page be, and what does a customer see right after they place an order (read-your-writes)?
| Component | What can go wrong | Tactic |
|---|---|---|
| Read replica (Replication) | Lag: order placed, "my orders" page empty | Read from primary after writes, or sticky read-your-writes |
| Cache (Caching) | Stale price, stampede | TTL, invalidation on write, request coalescing |
| Multi-region | Conflicting writes, high cross-region latency | Home-region per customer, consensus where needed (Distributed SQL) |
| Event consumers | Duplicates, reordering | Idempotent consumer, partition key per order (Ordering) |
Style interplay: Cache and replica choices are tactics, available in every style; but in a distributed style the staleness is observable between services, not only to users. Segment's post reports a concrete side effect of merging services: with one service per destination "low traffic destinations only had a handful of processes, which meant their in-memory caches ... would stay hot", and after merging "that cache is spread thinly across 3000+ processes so it's much less likely" to hit. A style change moved the cache hit rate.
Scaling path: 1x, 10x, 100x
| Load | Bakery situation | Style and structure | Notable additions |
|---|---|---|---|
| 1x (hundreds of orders/day) | One web server, one database | Layered or modular monolith | Backups, one dashboard |
| 10x (thousands/day, seasonal peaks) | Two or three app servers behind a load balancer | Modular monolith, stateless app, read replica, cache | Queue for emails and invoices (first event-driven edge) |
| 100x (Black Friday, many teams) | Checkout and search must scale apart | Service-based or microservices for the hot parts; event-driven integration | Gateway, outbox, tracing, rate limiting, per-service SLOs |
| 1000x or global | Regional outages must not stop all sales | Cells or multi-region, serverless for spikes | Router by tenant, cross-cell reporting pipeline |
The principle: add structure only at the point a measured limit appears (Capacity Estimation), and write the reason in an ADR each time.
Lab: measure what a style changes
Use the Go snippets (no database needed) and your own laptop. Each experiment has expected output in comments.
Setup:
cd docs/snippets/architecture/styles-vs-patterns/go
go vet ./... && gofmt -l . # expected: no output- Run the three styles.
go run ./layered,go run ./modular,go run ./microservice.- Expected: layered prints
200 {...}; modular printsorder accepted: 2 x bookand thenrejected: place order: inventory: out of stock; microservice printscalls: 2 err: <nil>(first call failed with 503, the retry succeeded).
- Expected: layered prints
- Break the idempotency assumption. In
microservice/main.gochange the test server to count reservations per call without looking atIdempotency-Key. Make the first response succeed but sleep 1 s so the client times out and retries.- Expected: the server counts two reservations for one order. This is the duplicate that the key prevents; fix the server to remember keys and the count returns to one.
- Move a boundary. In
modular/internal/orders/orders.goimport theinventorypackage directly instead of using theStockinterface.- Expected: it compiles (Go allows it), which shows why the interface rule needs a test. Add a small test that parses imports (see Architecture vs Design for the pattern) and watch it fail.
- Score styles. Run
go run ./picker. Change the weights inmainto your own project (for example{"scalability": 3, "simplicity": 1}).- Expected: the ranking changes; write down which two styles tie and what extra fact would break the tie.
- Classify your system. On paper: partitioning (technical or domain), deployment units, quanta (count independently deployable things with their own data), dominant style, three patterns, three tactics.
- Expected: if you cannot name the dominant style in one word, the architecture is implicit; write the ADR.
- Cost the premium. For one internal call in your system list: timeout, retry rule, idempotency, trace ID, auth, contract test. Count the missing ones.
- Expected: each missing item is a failure mode you have not handled; this count is your distributed premium debt.
Common misconceptions
| Belief | Reality |
|---|---|
| "Style and pattern are synonyms" | Style constrains a whole system; a pattern solves one recurring problem. Even the 1994 paper wrote "patterns, or styles" before the terms separated, and Richards' 2015 report used "pattern" for what the 2020 book calls "style" |
| "Microservices are the modern default" | Fowler: the majority of systems should be a single monolith with good modularity; microservices pay off only above a complexity threshold |
| "A monolith cannot be modular" | A modular monolith has enforced module boundaries and own schemas; Shopify describes running one at large scale |
| "Event-driven means a message broker" | It means decoupling by events; the in-process dispatcher is event-driven too |
| "More stars is better" | The stars are trade-offs: microservices score 5 on six characteristics and 1 on cost and simplicity |
| "Hexagonal architecture is an alternative to microservices" | Hexagonal organises the inside of a component; microservices cut the system into deployables; they combine |
| "REST is an API format" | Fielding defines REST as an architectural style: a set of constraints (client-server, stateless, cache, uniform interface, layered, code on demand) |
| "SOA and microservices are the same" | SOA reuses services enterprise-wide through a central bus; microservices duplicate to stay independent and partition by domain |
| "Splitting into services makes code modular" | Network boundaries do not create good boundaries; a tangled monolith becomes a tangled distributed monolith |
| "You choose a style once" | Systems evolve; styles change along the scaling path and hybrids are normal (In architecture) |
| "Serverless means no ops" | You still own timeouts, cold starts, concurrency limits, idempotency and cost |
Cheat sheet
| Topic | What to remember |
|---|---|
| Style | Vocabulary of components and connectors plus constraints (Garlan and Shaw); a coordinated set of constraints (Fielding) |
| Pattern | Reusable solution to a recurring problem in context, with consequences |
| Tactic | One design decision for one quality attribute response (Bass) |
| Nesting | Style contains patterns; patterns package tactics |
| Partitioning | Technical (layers) versus domain (modules); prefer domain |
| Monolithic styles | Layered, pipeline, microkernel, modular monolith: one deployment unit |
| Distributed styles | Service-based, event-driven, space-based, SOA, microservices, cells, serverless |
| Distributed premium | Cost and risk of the network: timeouts, partial failure, duplicates, versions, ops |
| Quantum | Independently deployable unit with its own data; one shared database means one quantum |
| Default start | Modular monolith with enforced boundaries |
| Most flexible, most expensive | Microservices: five stars on six characteristics, one on cost and simplicity |
| Best compromise | Service-based |
| Spikes | Space-based, event-driven, serverless |
| Isolation of failure | Cell-based, bulkhead |
| Enforcement | Executable rules: Go internal/, Pest arch(), schema grants |
| Hybrids | Name the dominant style; the rest are patterns inside it |
| Decision record | ADR with level field: style, pattern, tactic |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — State the three definitions (style, pattern, tactic) and say who defined each. Good to know
Answer
Answer: Style: Garlan and Shaw (vocabulary of components and connectors plus constraints) and Fielding (a coordinated set of constraints). Pattern: a reusable solution to a recurring problem in a context (Buschmann, Richardson, Fowler). Tactic: Bass, Clements, Kazman, "a design decision that influences the control of a quality attribute response". See Where it comes from.
2 — How do style, pattern and tactic nest? Give one example of each for a checkout. Important
Answer
Answer: Style contains patterns, patterns package tactics. Checkout: style service-based, pattern outbox for order events, tactic idempotency key on the payment call. See How the three nest.
3 — What is the difference between technical and domain partitioning, and why does it matter for a change? Must-know
Answer
Answer: Technical partitioning groups code by layer, so a feature touches every layer; domain partitioning groups by business area, so a feature stays inside one module. See Technical versus domain partitioning.
4 — Why is "microservices on one shared database" not microservices? Must-know
Answer
Answer: Deployment is independent but data is shared, so schema changes couple all services and the system remains one architecture quantum: a distributed monolith. See Characteristics.
5 — Name three costs of the distributed premium and the tactic for each. Important
Answer
Answer: Partial failure (saga, outbox), duplicates (idempotency key, inbox), slow dependency (timeout, circuit breaker). See Mechanics.
6 — Which style has the best balance of deployability and cost among the distributed ones, and why? Important
Answer
Answer: Service-based: few coarse domain services, usually a shared database, good deployability, fault tolerance and testability without per-service data and hundreds of calls. See Service-based.
7 — How does Richards' 2015 report differ in vocabulary from the 2020 book? Good to know
Answer
Answer: 2015 calls layered, event-driven and the others "architecture patterns" with Low/High ratings; 2020 calls them "architecture styles" and uses one-to-five stars on more characteristics and eight styles. See History.
8 — What did Fielding's derivation of REST show about styles? Good to know
Answer
Answer: Starting from the null style (no constraints), each added constraint buys a property and costs another, so a style is best understood as a set of traded-off constraints. See Architecture style.
9 — When would you pick space-based over event-driven? Important
Answer
Answer: Unpredictable spikes on a bounded hot dataset where the central database is the bottleneck; elasticity and performance outrank simplicity and testability. See Space-based and Choosing.
10 — What do Segment and Shopify illustrate? Good to know
Answer
Answer: Segment split into per-destination services to isolate failures and later consolidated 140+ services because of operational overhead; Shopify kept a modular monolith and splits services only for good reasons. Both show that the style must follow the measured need. See In architecture.
11 — Why is a style only half-enforced by a language? Important
Answer
Answer: Go internal/ blocks imports across trees but not a deliberately wide interface, and PHP namespaces enforce nothing; add executable tests (Pest arch()) and database grants. See Solving.
Glossary
| Term | Meaning |
|---|---|
| Architecture style | A family of systems with shared vocabulary of components and connectors and constraints on combining them |
| Architectural pattern | A reusable solution to a recurring problem in context, recorded with its consequences |
| Tactic | A design decision aimed at one quality attribute response |
| Design pattern | A class-level reusable solution (GoF) |
| Enterprise pattern | A business-application pattern from Fowler's PoEAA, such as repository or unit of work |
| Architecture characteristic | A quality the system must have (an "-ility"), also called quality attribute |
| Technical partitioning | Splitting by technical role (layers) |
| Domain partitioning | Splitting by business area (modules, bounded contexts) |
| Monolithic style | Style deployed as one unit |
| Distributed style | Style deployed as multiple units that communicate over a network |
| Distributed premium | The extra cost and risk of a distributed system (Fowler's "microservice premium") |
| Architecture quantum | An independently deployable unit with high functional cohesion and its own data |
| Distributed monolith | Services that must be deployed together or share a database |
| Layered architecture | Horizontal layers with a downward-only dependency rule |
| Modular monolith | One deployable cut into domain modules with enforced boundaries |
| Microkernel | A minimal core plus plug-ins |
| Pipeline / pipe-and-filter | A chain of independent steps connected by streams |
| Client-server | A requester and a provider separated by a network |
| Event-driven architecture | Components react to events; broker and mediator topologies |
| Space-based architecture | Replicated processing units with a data grid instead of a central database |
| Service-based architecture | A few coarse-grained domain services, often one database |
| SOA | Enterprise services integrated through a central bus |
| Microservices | Independently deployable services organised around business capabilities, each owning its data |
| Serverless / FaaS | Functions run on demand by a platform |
| Cell-based architecture | Many identical self-contained stacks serving slices of customers |
| Lambda architecture | Batch layer plus speed layer, results merged |
| Kappa architecture | A single streaming path with reprocessing from the log |
| Hexagonal architecture | Ports and adapters isolating the domain from I/O |
| Strangler fig | Gradual replacement of a legacy system behind a facade |
| Outbox | Writing an event in the same transaction as the data change, relayed later |
| Saga | A sequence of local transactions with compensations |
| ADR | Architecture decision record |
| Fitness test | An automated check that an architectural rule holds |
| Blast radius | The part of the system affected by one failure |
References
- David Garlan and Mary Shaw, "An Introduction to Software Architecture", CMU-CS-94-166, January 1994 (university mirror of the CMU report); Mary Shaw and David Garlan, Software Architecture: Perspectives on an Emerging Discipline, Prentice Hall, 1996 (not fetched)
- Roy T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, 2000: chapter 1, chapter 5
- Len Bass, Paul Clements, Rick Kazman, Software Architecture in Practice, 2nd ed., chapter 5 (university mirror); later editions not fetched
- Mark Richards, Software Architecture Patterns, O'Reilly, 2015; Mark Richards and Neal Ford, Fundamentals of Software Architecture, O'Reilly, 2020 (chapters not retrievable, ratings table reproduced approximately, see note); Ford, Richards, Sadalage, Dehghani, Software Architecture: The Hard Parts, 2021 (quantum definition paraphrased)
- Buschmann, Meunier, Rohnert, Sommerlad, Stal, Pattern-Oriented Software Architecture vol. 1, Wiley, 1996 (not fetched); Martin Fowler, Catalog of Patterns of Enterprise Application Architecture; Gamma, Helm, Johnson, Vlissides, Design Patterns, 1994; Hohpe and Woolf, Enterprise Integration Patterns
- James Lewis and Martin Fowler, "Microservices", 25 March 2014; Martin Fowler, "Microservice Premium", 13 May 2015; "Monolith First"; "CQRS"; "Strangler Fig"; "Serverless Architectures"
- Chris Richardson, microservices.io pattern language, Microservice Architecture, Saga, Transactional outbox, API Gateway / BFF
- Alistair Cockburn, Hexagonal architecture; Robert C. Martin, The Clean Architecture, 2012
- Jay Kreps, Questioning the Lambda Architecture, 2 July 2014; Nathan Marz, How to beat the CAP theorem
- AWS Well-Architected, What is a cell-based architecture?
- Shopify Engineering, "Under Deconstruction: The State of Shopify's Monolith", 16 September 2020; Twilio Segment, "Goodbye Microservices: From 100s of problem children to 1 superstar", 10 July 2018
- Laravel 13: HTTP client; Pest: Architecture testing; Go: internal packages (Go 1.4)