Skip to content

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 forGo to
The definitions and the nesting in a few tablesEverything in one minute
Why the three words are kept apartWhy the distinction exists
Garlan and Shaw, Fielding, Gamma, Bass, Richards and FordWhere it comes from
Style, pattern, tactic, partitioning, quantum, one block eachThe concepts
Every style with when to use it and its chapterThe styles catalogue
Hexagonal, CQRS, saga, gateway, outbox and friendsThe patterns catalogue
Stars for deployability, elasticity, cost, simplicityCharacteristic ratings
Combining styles in one systemHybrid styles
How a style constrains a feature, step by stepMechanics
Style drift, distributed monolith, hype-driven choiceSolving the classic problems
One ordering system in three styles (folders and code)Go, Laravel
Picking a style from characteristicsChoosing
Monolith to distributed, with examplesIn architecture
A measurable exerciseLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three words. Every row is unpacked in the concepts.

TermIn plain wordsScopeExampleChosen
Architecture styleThe overall shape of a family of systems: what kinds of parts exist, how they may talk, what is forbiddenWhole systemLayered, event-driven, microservicesOnce, early; costly to reverse
Architectural patternA named, reusable answer to one recurring problem inside a contextA part of the system, crossing several componentsSaga, outbox, API gateway, CQRS, hexagonalPer problem, when the problem appears
TacticOne design decision aimed at one quality attributeOne mechanismRetry, timeout, cache, heartbeat, rate limitPer quality scenario
Design pattern (GoF)A solution at class levelA few classesAdapter, Strategy, DecoratorIn code, see Design Patterns
Architecture characteristicA quality the system must have ("-ility")Whole systemElasticity, deployability, testabilityFrom 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 itTactics those patterns bundle
MicroservicesAPI gateway, saga, outbox, database per service, circuit breaker, sidecarTimeout, retry with backoff, idempotency key, health check, bulkhead
Event-drivenBroker topology, mediator topology, event sourcing, CQRSAcknowledgment, dead-letter queue, replay, partitioning
LayeredRepository, service layer, MVCInput validation at the boundary, caching in the data layer
Modular monolithFacade per module, anti-corruption layer, in-process eventsSchema ownership, architecture fitness test

The styles at a glance (full text in the catalogue):

StyleDeployed asPartitioned byStrongest atWeakest at
LayeredOne unitTechnical layersCost, simplicityScale, evolvability
Modular monolithOne unitDomain modulesCost, evolvability, testabilityIndependent scaling
MicrokernelOne unit (plugins inside)Core plus plug-insExtensibility, customisationScale
Pipeline (pipe-and-filter)One or several unitsProcessing stepsSimplicity, composabilityInteractive workloads
Client-serverTwo or more tiersRole (requester or provider)Centralised control, familiarityServer is a bottleneck and single point
Peer-to-peerMany equal nodesNone (every node both)Resilience, no central costConsistency, discovery
Service-basedA few coarse servicesDomainBalance of agility and costFine-grained elasticity
Event-drivenMany decoupled processorsEvent typesPerformance, scale, fault toleranceSimplicity, testability
Space-basedReplicated processing units plus data gridProcessing unitsElasticity under spikesSimplicity, cost, testing
Orchestration-driven SOAEnterprise services plus a busTechnical, enterprise-wideReuse (the goal)Agility, cost
MicroservicesMany small servicesBounded contextsDeployability, elasticity, evolvabilityCost, simplicity, performance
Serverless / FaaSFunctions on a platformFunction / eventPay per use, no servers to runLatency control, vendor lock-in
Cell-basedMany identical full-stack cellsCustomer or key rangeBlast-radius controlCross-cell queries, cost
Lambda / KappaBatch plus speed layers, or one logData flowLarge-scale analyticsOperational 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 wordsKeeping 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 fightThe name tells the scale of the decision
A pattern is imposed system-wide because it was fashionableA pattern is applied where its problem exists
Style choice is made by accident, one library at a timeStyle choice is a recorded decision (ADR)
ARCHITECTURE STYLEcomponents + connectors + constraints (what is allowed)ARCHITECTURAL PATTERNreusable solution to a recurring problem in contextTACTICone design decision for one quality attributeretry, timeout, heartbeat, cache, rate limit,replicate, idempotency key, bulkheadmicroservices, layered, event-drivensaga, outbox, API gateway, CQRSStyle: shapes the wholesystem, chosen oncePattern: packagesseveral tacticsTactic: smallest unit,trade-off per quality

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 ​

  1. "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.
  2. "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).
  3. "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 ​

text
     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 ratings

Garlan 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).

text
     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 latency

Real 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.

text
     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 time

Real 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.

text
     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 changes

Real 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).

text
     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                Hours

Real 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).

text
     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 team

Real 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".

text
     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, serialisation

Real 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.

text
     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 monolith

Real 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.

Architecture stylesMonolithic: one deployment unitDistributed: many deployment unitsLayeredModular monolithMicrokernelPipelineClient-serverPeer-to-peerService-basedSOAMicroservicesEvent-drivenSpace-basedServerless / FaaSCell-basedLambdaKappa (big data)Pipeline and microkernelcan also be deployed asseveral units: thebranch is the usualshape, not a law.Real systems are hybrids: a service-based core with an event-driven edge,microservices with a pipeline inside one service, and so on.

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.

PatternProblem it solvesTypical stylesOwner chapter
Hexagonal (ports and adapters)Domain code tied to HTTP, DB or UI; hard to test aloneAny; inside one service or moduleStructural patterns, Anti-corruption
Clean / onion architectureSame, with a strict inward dependency ruleAnySOLID DIP
Repository, unit of workPersistence details leak into business codeLayered, modularRepositories, Data Persistence
CQRSReads and writes need different models or scaleMicroservices, event-drivenEvent Sourcing and CQRS
Event sourcingNeed full history and replayEvent-drivenEvent Sourcing and CQRS
SagaA business transaction spans several servicesMicroservices, SOASaga
Transactional outboxAtomic DB update plus message publishAny with a brokerOutbox
Change data captureStream database changes without double writesEvent-driven, migrationsCDC
API gatewayMany clients, many services, one entry pointMicroservices, service-basedGateway, BFF, Mesh
Backend for frontend (BFF)One API cannot serve web, mobile, partners wellMicroservicesGateway, BFF, Mesh
Sidecar, service meshCross-cutting network concerns repeated in every serviceMicroservicesService Mesh
Service discoveryInstances move; callers need addressesMicroservicesService Discovery
Circuit breakerSlow or failing dependency drags callers downAny distributed styleCircuit Breaker
BulkheadOne failing part exhausts shared resourcesAny distributed styleBulkhead
Strangler figReplace a legacy system graduallyMigrationsMonolith vs Microservices vs Modular
Database per serviceServices coupled through one schemaMicroservicesData Ownership
Competing consumersScale message processing horizontallyEvent-drivenCompeting Consumers
MVC, MVP, MVVMPresentation mixed with logicClient-server, layeredMVC

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:

SourceWhat it cataloguesLevel
Garlan and Shaw 1994, Shaw and Garlan 1996Pipes and filters, data abstraction, event systems, layered, repositories, interpretersStyles
Buschmann et al., POSA 1996Layers, pipes and filters, blackboard, broker, MVC, microkernel, reflectionArchitectural patterns
Fowler, PoEAA 2002Domain model, transaction script, repository, data mapper, unit of work, lazy loadEnterprise patterns
Gamma et al. 199423 patterns: factory, adapter, strategy, observerDesign patterns
Hohpe and Woolf, EIP 2003Message channel, router, translator, aggregatorIntegration patterns, see Integration Styles
Richardson, microservices.ioDecomposition, data, communication, deployment, observabilityMicroservice patterns
Bass et al.Tactics for availability, performance, security, modifiability, testabilityTactics

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.

text
     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 core

Real 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.

1111152315211212523153313135331334234343433433554353512353333535111313312231155555124514LayeredPipelineMicrokernelService-basedEvent-drivenSpace-basedOrchestr. SOAMicroservicesDeployabilityElasticityEvolvabilityFault toleranceModularityOverall costPerformanceReliabilityScalabilitySimplicityTestability1 = weakest, 5 = strongest. For cost and simplicity, 5 means cheaper / simpler. Colours: red 1, amber 2, grey 3, green 4-5.
StylePartitioningQuantaDeploy-abilityElasticityEvolvabilityFault toleranceModularityOverall costPerfor-manceReliabilityScalabilitySimplicityTestability
LayeredTechnical111111523152
PipelineTechnical111212523153
MicrokernelBoth131313533133
Service-basedDomain1 or more42343434334
Event-drivenTechnical1 or more33554353512
Space-basedTechnical1 or more35333353511
Orchestration SOATechnical1 or more13133122311
MicroservicesDomainMany55555124514

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 tableWhat it means
Column of 1s for deployability to scalabilityMonolithic: one unit to deploy, scale, fail
Cost 5 and simplicity 5 togetherCheap and easy; you pay with agility
Cost 1 and simplicity 1 togetherPowerful and expensive; justified only by a measured need
Event-driven: simplicity 1, performance 5Fast but hard to follow and test end to end
Service-based: no 1s except elasticity 2The compromise style, few weaknesses
Space-based: elasticity 5, testability 1You 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.

HybridWhat it combinesWhy teams do itWatch for
Modular monolith core plus a few extracted servicesModular monolith, microservicesExtract only the module that needs independent scale (image processing, search)Two deployment models to operate
Service-based core with an event-driven edgeService-based, event-drivenCore is synchronous and consistent; notifications and integrations are asynchronousDual write; use outbox
Microservices with a pipeline inside one serviceMicroservices, pipelineAn ingestion service runs validate, enrich, write as filtersThe pipeline owns its failure semantics
Layered inside each microserviceMicroservices, layeredA service is small enough for three layers, no moreAnaemic layers; see Layered
CQRS read side as a separate serviceMicroservices, CQRSHeavy reads scale apart from writesStaleness, read-your-writes
Microkernel plus serverless plug-insMicrokernel, FaaSCustomer-written plug-ins run isolatedCold starts, security of plug-ins
Cells of microservicesCell-based, microservicesMany services per cell, many cellsRouter is a new critical component
Lambda inside an event-driven systemBig data, event-drivenStream for freshness, batch for correctnessTwo 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.

text
     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)
text
     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)
text
     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.

text
     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 folders

The remedy is the same as for any invariant: make the rule executable (see Solving).

The distributed premium, itemised.

New concern in a distributed styleFailure or costTactic or pattern that manages it
Remote call latency and timeoutsSlow dependency blocks callersTimeout, circuit breaker, bulkhead
Partial failureOrder saved, stock not reservedSaga, outbox, idempotency
Duplicate messagesCharged twiceIdempotent consumer, inbox
No cross-service transactionAtomicity lostLocal transactions plus compensation
Data duplicationStale copiesEvents, CDC, ownership rules
Service discovery and routingWrong address, outage on deployDiscovery, load balancing
Contract and version skewDeploy order mattersConsumer-driven contracts, expand/contract
ObservabilityOne request touches ten servicesDistributed tracing, correlation IDs
Security between servicesInternal network is not trustedmTLS, tokens, see mTLS
OperationsN pipelines, N dashboards, N on-call rotasPlatform team, standard templates

Solving the classic problems ​

ProblemWhat it looks likeSolutionHowAdvantageCost or limit
Hype-driven style choice"Everyone uses microservices"Characteristic-driven choiceRank 3 characteristics, score styles (Choosing), record an ADRChoice is defensible and reversibleNeeds real requirements
Style driftModules reach into each other's tablesExecutable architecture rulesGo internal/, Pest arch(), ArchUnit, schema grantsViolations fail the buildRules must be maintained
Distributed monolithServices deployed together, one shared databaseMerge back, or give each service its own dataSee Service BoundariesRemoves the premium without the benefitMigration work
Layer sinkholeLayers pass requests through unchangedOpen the layer deliberately, or move to domain modulesAllow controllers to read through a query objectFewer empty layersRule exceptions to document
Pattern overuseCQRS plus event sourcing for a CRUD adminName the problem firstPattern needs a one-sentence problem and a measured painLess accidental complexityDiscipline
Hybrid chaosThree styles, no dominant oneState the dominant styleADR: "dominant style: X; patterns inside: Y"Shared mental modelOccasional re-labelling
Big-bang rewriteRewrite in the "right" styleStrangler figRoute by route, behind a facadeAlways shippableTwo systems for a long time
Premature extractionA service per module on day oneModular monolith first, extract on evidenceKeep seams enforced, extract when scale or team size forces itCheap experimentsExtract later costs real work

Fitness tests for boundaries (Go and Pest) ​

sql
-- 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 ​

text
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.

go
// 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 ​

text
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.

go
// 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
}
go
// 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 ​

text
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 /reservations

The 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.

go
// 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:

go
// 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 ​

text
app/
  Http/Controllers/OrderController.php   # presentation
  Services/OrderService.php              # business, DB::transaction
  Repositories/OrderRepository.php       # persistence (query builder)
  Models/                                # Eloquent models
php
<?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 ​

text
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
<?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
<?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 ​

text
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
<?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.

SituationShortlistExtra techniqueReason
New product, 3 to 10 developers, domain unclearModular monolith (or layered if throwaway)Enforced module boundaries, ADRLowest 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 cadenceService-based, then selective microservicesStrangler fig, platform teamIndependent deploys at moderate cost
Spiky traffic with bounded hot data (ticket release)Space-based or event-driven plus cacheQueue-based load levelling, rate limitingElasticity, performance
Product with customer-specific featuresMicrokernelVersioned plug-in contractExtensibility
Data transformation, ETL, mediaPipelineBackpressure, idempotent stepsSimple, testable filters
Strict failure isolation per tenantCell-based on top of any styleRouter by tenant keyBlast radius
Rare or bursty workloads, small ops teamServerlessIdempotency, concurrency limitsPay per use
Large enterprise integrating legacy systemsSOA or integration hubCanonical model (Message Transformation)Reuse across existing apps
Analytics on very large event streamsKappa or LambdaReplayable log, CDCThroughput, reprocessing
Regulated payments component inside a larger appService-based (one isolated service)Separate database, audit logAudit scope isolation

Quick filters:

QuestionIf yesIf no
Do parts need independent scaling you have measured?Allow a distributed style for those partsStay in one deployable
Do separate teams need to release without coordinating?Domain partitioning, consider servicesModules are enough
Is the team below ~10 developers and the domain unclear?Modular monolithRevisit
Do you have tracing, CI/CD per service, on-call for each?Microservices are survivableDo not split yet
Is a single database transaction a real need?Keep that data in one unitEvents 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.

QuestionAnswer in a layered monolith
AtomicityOne local transaction covers stock and order
Failure modesThe process is up or down; no partial failure between components
CostLowest: one pipeline, one dashboard
Where it starts to hurtMany 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."

QuestionAnswer in a modular monolith
OwnershipEach module owns its tables; others use its contract or events
Schema sharingOne database server, separate schemas; cross-schema joins forbidden by rule and by grants
TransactionsPossible across modules (same database), used sparingly so extraction stays possible
ExtractionA 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.

text
     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 stock

Production 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.

QuestionAnswer in microservices
AtomicityNone across services; saga, outbox, idempotency
DataDatabase per service (Data Ownership)
FailurePartial failure is normal; timeouts and retries are mandatory
CostHighest of the common styles: pipelines, tracing, on-call, contracts
PrerequisiteTeam 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)?

ComponentWhat can go wrongTactic
Read replica (Replication)Lag: order placed, "my orders" page emptyRead from primary after writes, or sticky read-your-writes
Cache (Caching)Stale price, stampedeTTL, invalidation on write, request coalescing
Multi-regionConflicting writes, high cross-region latencyHome-region per customer, consensus where needed (Distributed SQL)
Event consumersDuplicates, reorderingIdempotent 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 ​

LoadBakery situationStyle and structureNotable additions
1x (hundreds of orders/day)One web server, one databaseLayered or modular monolithBackups, one dashboard
10x (thousands/day, seasonal peaks)Two or three app servers behind a load balancerModular monolith, stateless app, read replica, cacheQueue for emails and invoices (first event-driven edge)
100x (Black Friday, many teams)Checkout and search must scale apartService-based or microservices for the hot parts; event-driven integrationGateway, outbox, tracing, rate limiting, per-service SLOs
1000x or globalRegional outages must not stop all salesCells or multi-region, serverless for spikesRouter 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:

bash
cd docs/snippets/architecture/styles-vs-patterns/go
go vet ./... && gofmt -l .     # expected: no output
  1. Run the three styles. go run ./layered, go run ./modular, go run ./microservice.
    • Expected: layered prints 200 {...}; modular prints order accepted: 2 x book and then rejected: place order: inventory: out of stock; microservice prints calls: 2 err: <nil> (first call failed with 503, the retry succeeded).
  2. Break the idempotency assumption. In microservice/main.go change the test server to count reservations per call without looking at Idempotency-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.
  3. Move a boundary. In modular/internal/orders/orders.go import the inventory package directly instead of using the Stock interface.
    • 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.
  4. Score styles. Run go run ./picker. Change the weights in main to 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.
  5. 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.
  6. 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 ​

BeliefReality
"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 ​

TopicWhat to remember
StyleVocabulary of components and connectors plus constraints (Garlan and Shaw); a coordinated set of constraints (Fielding)
PatternReusable solution to a recurring problem in context, with consequences
TacticOne design decision for one quality attribute response (Bass)
NestingStyle contains patterns; patterns package tactics
PartitioningTechnical (layers) versus domain (modules); prefer domain
Monolithic stylesLayered, pipeline, microkernel, modular monolith: one deployment unit
Distributed stylesService-based, event-driven, space-based, SOA, microservices, cells, serverless
Distributed premiumCost and risk of the network: timeouts, partial failure, duplicates, versions, ops
QuantumIndependently deployable unit with its own data; one shared database means one quantum
Default startModular monolith with enforced boundaries
Most flexible, most expensiveMicroservices: five stars on six characteristics, one on cost and simplicity
Best compromiseService-based
SpikesSpace-based, event-driven, serverless
Isolation of failureCell-based, bulkhead
EnforcementExecutable rules: Go internal/, Pest arch(), schema grants
HybridsName the dominant style; the rest are patterns inside it
Decision recordADR with level field: style, pattern, tactic

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Architecture styleA family of systems with shared vocabulary of components and connectors and constraints on combining them
Architectural patternA reusable solution to a recurring problem in context, recorded with its consequences
TacticA design decision aimed at one quality attribute response
Design patternA class-level reusable solution (GoF)
Enterprise patternA business-application pattern from Fowler's PoEAA, such as repository or unit of work
Architecture characteristicA quality the system must have (an "-ility"), also called quality attribute
Technical partitioningSplitting by technical role (layers)
Domain partitioningSplitting by business area (modules, bounded contexts)
Monolithic styleStyle deployed as one unit
Distributed styleStyle deployed as multiple units that communicate over a network
Distributed premiumThe extra cost and risk of a distributed system (Fowler's "microservice premium")
Architecture quantumAn independently deployable unit with high functional cohesion and its own data
Distributed monolithServices that must be deployed together or share a database
Layered architectureHorizontal layers with a downward-only dependency rule
Modular monolithOne deployable cut into domain modules with enforced boundaries
MicrokernelA minimal core plus plug-ins
Pipeline / pipe-and-filterA chain of independent steps connected by streams
Client-serverA requester and a provider separated by a network
Event-driven architectureComponents react to events; broker and mediator topologies
Space-based architectureReplicated processing units with a data grid instead of a central database
Service-based architectureA few coarse-grained domain services, often one database
SOAEnterprise services integrated through a central bus
MicroservicesIndependently deployable services organised around business capabilities, each owning its data
Serverless / FaaSFunctions run on demand by a platform
Cell-based architectureMany identical self-contained stacks serving slices of customers
Lambda architectureBatch layer plus speed layer, results merged
Kappa architectureA single streaming path with reprocessing from the log
Hexagonal architecturePorts and adapters isolating the domain from I/O
Strangler figGradual replacement of a legacy system behind a facade
OutboxWriting an event in the same transaction as the data change, relayed later
SagaA sequence of local transactions with compensations
ADRArchitecture decision record
Fitness testAn automated check that an architectural rule holds
Blast radiusThe part of the system affected by one failure

References ​

Built by Morteza Negahi