Skip to content

From Requirements to Architecture ​

"The ADD method is an approach to defining a software architecture in which the design process is based on the software's quality attribute requirements." — Wojcik, Bachmann, Bass, Clements, Merson, Nord, Wood, Attribute-Driven Design (ADD), Version 2.0, CMU/SEI-2006-TR-023, 2006

Summary: Architecture is not drawn from a feature list; it is derived, in small iterations, from the handful of requirements that are expensive to get wrong, using known tactics and patterns, and then checked with scenarios, spikes and fitness functions before anyone calls it done. Focus: The method that sits between "we have requirements" and "we have a candidate architecture": inputs, architecturally significant requirements (ASRs) and how to find them (QAW, interviews, utility tree), the eight ADD steps, tactics mapped to patterns, domain to components, choosing a style by characteristic fit, walking skeleton and tracer bullet, spikes, documenting and validating the candidate, and one full worked kata (Going Green) with ADRs plus a Go and Laravel walking skeleton. Learning goal: Given a requirements document, produce a ranked list of at most six drivers, a defensible style choice, a first set of modules and interfaces, a recorded set of decisions, and a validation plan, and say which of those could still be wrong.

This chapter owns the method. The definitions of quality attributes, ISO/IEC 25010, quality attribute scenarios and measurable NFRs live in Quality Attributes & Requirements; we link there and do not repeat them. What an architect is and why architecture exists is in What Is Software Architecture; how to record and weigh decisions is in Architecture Decisions & Trade-offs; how to draw the result is in Kruchten's 4+1 views; the numbers behind capacity are in Capacity Estimation; SLOs are in SLAs, SLOs, SLIs & Error Budgets.

Page map ​

If you are looking forGo to
The whole method in three tablesEverything in one minute
Why not just start coding the featuresWhy it exists
ADD, QAW, ATAM, katas, tracer bullets: who said whatWhere it comes from
What goes into the methodInputs
Which requirements matter and how to find themASRs, Finding ASRs, Domain concerns to characteristics
The eight ADD stepsADD
Tactics and the patterns that bundle themTactics catalogue
Turning a domain into componentsDomain to components
Picking a styleStyle fit
Walking skeleton, tracer bullet, spikeIterate and prototype, Risks and spikes
Capacity numbers as inputsCapacity inputs
Writing the candidate downDocumenting
Checking the candidateValidating
A complete exampleGoing Green kata
CodeGo, Laravel
Monolith to distributedIn architecture
ExerciseLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The method as a chain. Every row is unpacked later.

StageQuestion it answersOutputTypical tool
1. Gather inputsWhat must the system do, under which limits, for which business reasons?Functional requirements, constraints, quality attribute scenarios, business driversInterviews, QAW, event storming
2. Find the ASRsWhich few requirements change the structure if we get them wrong?Ranked list of at most 5 or 6 driversUtility tree, (importance, impact) grid
3. Choose tactics and patternsWhich known moves buy each driver?Pattern matrix with pros and consTactics catalogue, ADD step 4
4. Shape componentsWhere are the boundaries?Modules, responsibilities, interfacesBounded contexts, Conway's law check
5. Pick a styleWhich overall structure fits the drivers and the team?Style choice recorded in an ADRCharacteristic fit table
6. Prove the risky partsDo the risky assumptions hold?Walking skeleton, spikes, measurementsTracer bullet, load test, prototype
7. DocumentHow do others understand and challenge it?Views, ADRs, scenario listC4 or 4+1, ADR template
8. ValidateDoes it meet the scenarios, and will it keep meeting them?Risks list, fitness functions in CIATAM-lite, walkthroughs

The eight ADD steps (SEI report, CMU/SEI-2006-TR-023):

StepIn plain wordsDesign decision made?
1 Confirm there is sufficient requirements informationAre the requirements prioritised and testable enough to start?No
2 Choose an element of the system to decomposeWhich box do we open now? First time: the whole systemNo
3 Identify candidate architectural driversRank a second time by impact on the structure; take five or sixNo
4 Choose a design concept that satisfies the driversPick patterns and tactics, combine themYes
5 Instantiate elements and allocate responsibilitiesCreate the child elements; give each its jobYes
6 Define interfaces for instantiated elementsWhat each element provides and requiresYes
7 Verify and refine requirements, make them constraints for childrenCheck coverage; pass requirements downNo
8 Repeat steps 2 to 7 for the next elementOpen the next boxn/a

Ways to find ASRs, cheapest first.

TechniqueWho is neededTimeBest when
Read the document and ask "what if this is 10 times bigger or 10 times stricter"YouHoursAlways, as a first pass
Stakeholder interviews3 to 8 people, one at a timeDaysThe business drivers are unclear
Quality Attribute Workshop (QAW)5 to 30 stakeholdersOne to two daysMany stakeholders, conflicting assumptions
Utility treeArchitects plus product ownerA few hoursYou need ranking, not just a list
Characteristic extraction from domain words (Richards and Ford)Architect and domain expertAn hourKata-style or early design
Failure and incident review of the old systemOperatorsHoursA rewrite or a migration

Three common misunderstandings, up front ​

  1. "The architecture is the sum of all the requirements." No. Most requirements are cheap in any structure. A few drive the shape; ADD says to pick five or six.
  2. "We choose the style first (microservices!), then fit the requirements." That is resume-driven design. The style is an output of the drivers, the team and the risk, not an input.
  3. "A candidate architecture is a diagram." A diagram is one view. The candidate is the diagram plus the decisions behind it, the scenarios it was checked against and the risks that remain.

Why it exists ​

Without a method, architecture appears by accident: the first feature picks a framework, the second feature picks a table layout, and eighteen months later "we cannot add a country without touching everything". With a method, the few decisions that are expensive to change are made on purpose, with evidence, while the cost of changing them is still low. The QAW report puts the economics in one sentence:

"The earlier key quality attribute requirements are identified and prioritized, the more likely it is that the essential quality attributes will be built into the system." — Barbacci et al., Quality Attribute Workshops (QAWs), Third Edition, CMU/SEI-2003-TR-016

Feature-list thinkingDriver-led thinking
Every requirement has the same weightFive or six requirements shape the structure; the rest fit inside it
The style is chosen by fashion or familiarityThe style is chosen by fit to drivers, team size and risk
"Non-functional" is a late checklistQuality scenarios are inputs to the first design
Risks appear in productionRisks are named, ranked and spiked early
Design is one big documentDesign is a loop of small decisions, each with an ADR
Failure mode: big design up front, or no design at allFailure mode: analysis paralysis if the loop is never closed

The analogy we reuse on this page: an architect's brief for a house. The client says "four bedrooms, a garden, we host family every Christmas, and we have a limited budget". The architect does not start with window frames. She asks which of those sentences change the floor plan (hosting twenty people changes the plan; the colour of the door does not), makes the structural decisions first, builds a cardboard model, walks the client through it, and only then draws details. Software has the same order, with one gift: we can build a thin working model (a walking skeleton) cheaply.

Where it comes from ​

Conway, 1968. Melvin Conway's article in Datamation observed that organisations produce designs that copy their communication structure. Fowler quotes it: "Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure." (Fowler, Conway's Law, 20 October 2022.) It is why the team shape is an input to the method.

Pragmatic Programmers, 1999 and 2003. Hunt and Thomas named tracer bullets: "a skeletally thin system that does next to nothing, but does it from end to end, encompassing areas such as the database, any middleware, the application logic or business rules" (their article The Art in Computer Programming, Pragmatic Bookshelf). Tracer code is kept; a prototype is thrown away (they discuss the difference in an Artima interview, April 2003).

Cockburn, 1990s to 2000s. Walking skeleton is Alistair Cockburn's term for a tiny implementation of the system that performs a small end-to-end function. His page returned 404 when we fetched it, so the definition here is from secondary quotations; the idea is the same as tracer code, with the stress on automated build, deploy and test of the thin slice.

SEI methods, 2000 to 2006. The Software Engineering Institute produced a family: ATAM (evaluation, CMU/SEI-2000-TR-004, covered in the sibling chapter), the Quality Attribute Workshop (CMU/SEI-2003-TR-016, August 2003) to elicit scenarios before the architecture exists, and Attribute-Driven Design (ADD 2.0, CMU/SEI-2006-TR-023, November 2006) to design from the drivers. The ADD report says it can be used with the QAW "for gathering requirements for input to ADD" and with ATAM "to evaluate architectures that result from applying ADD". The report revises an earlier ADD; we read only version 2.0, so we do not describe version 1 or the later ADD 3.0 in detail.

Domain-Driven Design, 2003. Bounded contexts as the unit of model consistency; Fowler's bliki summary (15 January 2014) says "DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships."

Architecture katas, 2010s. Neal Ford and Mark Richards use short, vague business problems (the kata) as practice for architects; Going Green appears in Fundamentals of Software Architecture (O'Reilly, 2020) and on the companion site. Their method for characteristics (list drivers from domain words, rank them, keep the top few) is the "domain concerns to characteristics" step below. We could not open the book; the kata text comes from a public copy of the kata on GitHub that links to the companion site (references).

Microservice Premium and Monolith First, 2014 and 2015. Fowler's MicroservicePremium says "don't even consider microservices unless you have a system that's too complex to manage as a monolith." Monolith First (3 June 2015): "Almost all the cases where I've heard of a system that was built as a microservice system from scratch, it has ended up in serious trouble." Both are inputs to the style choice, not laws.

text
     Year   Idea                                       What it added to the method
1    1968   Conway's law                               Team structure is a design input
2    1999   Tracer bullets                             Prove the path end to end early
3    2000   ATAM                                       Evaluate against scenarios, name risks
4    2003   QAW                                        Elicit scenarios before the architecture exists
5    2006   ADD 2.0                                    Design loop driven by quality attributes
6    2014   MicroservicePremium, bounded contexts      Style has a price; boundaries come from the domain
7    2015   Monolith First                             Start simple, learn the boundaries

The concept catalogue ​

Inputs: requirements, constraints, scenarios, business drivers Must-know ​

In plain words: four kinds of input feed the method: what the system must do, what is already decided for us, how well it must do it, and why the business cares.

Common misunderstanding: "If the functional requirements are complete, we can design." The ADD report is clear that the inputs are "functional requirements, design constraints, and quality attribute requirements that system stakeholders have prioritized according to business and mission goals". Without priorities and quality targets you can only draw boxes.

Definition: the SEI report distinguishes functional requirements ("The system shall allow users to review account activity"), design constraints ("The system shall only interact with other systems via Publish/Subscribe") and quality attribute requirements ("availability: The system shall recover from a processor crash within one second"). It also says all three may be implied: "Given that Joe is the only resource available to handle the persistent storage aspects of the system and that Joe only has Oracle experience implies that Oracle must be used". We add a fourth, the business driver, because the QAW starts there.

InputExample (Going Green)Hidden form to look for
Functional requirement"Customers can get a quote ... either through the web or a kiosk"Two channels means one API contract, two clients
ConstraintTeam of six, PHP and Go skills, one cloud region (assumed)Skills are constraints too
Quality attribute scenario"A new device type is accepted in two working days""5 to 10 new types each month" implies modifiability
Business driver"A highly competitive business and a new line of business"Time to market, learning, low early cost
Stakeholder concernFinance: "no cheque is ever paid twice"Compliance, audit
Environment factKiosks in malls, patchy connectivity (assumed)Offline or degraded mode
text
     Source sentence in the brief                          Derived input
1    "5-10 new types of electronic each month"             QAS: add a device type in 2 days, no regression
2    "right to change the original quote"                  Functional: re-quote step; QAS: audit who changed what
3    "hundreds, hopefully thousands to millions" of users  Capacity range, not a number: estimate both ends
4    "new line of business"                                Business driver: learn fast, avoid irreversible bets

Real scenarios: a tender document with 400 numbered requirements of which 6 matter structurally; a regulator's sentence "all transactions are reviewable for seven years" that forces an immutable log; a CTO's "we only run on our private cloud" that removes a family of managed services.

Fix: write each quality requirement as a scenario (stimulus, response, response measure) using the template in Quality Attributes & Requirements; mark assumptions as assumptions and put them on the question list for stakeholders. ADD's own advice: "The architect should mark design decisions based on requirements known to be tentative and be prepared to back up and revise the process".

Architecturally significant requirements and architectural drivers Must-know ​

In plain words: an ASR is a requirement that, if you get it wrong, forces a costly structural change. The few you design around are the architectural drivers.

Common misunderstanding: "ASRs are the non-functional requirements." Some functional requirements are significant ("works offline", "every change is auditable"), and many quality requirements are not ("the page loads in 2 seconds at ten users").

Definition: ADD step 3 ranks requirements twice: once by stakeholders (importance) and once by the architect (impact on structure). With three levels each you get nine groups, "(H,H) (H,M) (H,L) (M,H) (M,M) (M,L) (L,H) (L,M) (L,L)", and "you should choose several (five or six) high-priority requirements as the focus". Those are candidate drivers; analysis may drop or add some, and what remains are the architectural drivers. The report's footnote adds a useful alarm: "If more than five or six requirements are ranked (H,H), this situation might signal a risk to the project and warrant renegotiation of the priorities."

Importance \ ImpactHigh impactMedium impactLow impact
High importance(H,H): design around it(H,M): check in the walkthrough(H,L): just do it
Medium importance(M,H): confirm importance(M,M): normal backlog(M,L): backlog
Low importance(L,H): ask "why is this high impact if nobody cares?"(L,M): backlog(L,L): drop

Real scenarios: "tenants must be isolated cryptographically" (H,H); "the logo can change per tenant" (H,L); "support 3 languages at launch" (M,L), but "right-to-left layout" can be (M,H) for the front-end framework.

Fix: keep the driver list on one page next to the diagram. When someone proposes a change, ask which driver it serves.

Finding ASRs: QAW, interviews and the utility tree Must-know ​

In plain words: you do not guess the drivers; you ask the people who care, in a structured way, and write down what they say as testable scenarios.

Common misunderstanding: "A workshop is a meeting to collect wishes." The QAW is a facilitated method with eight steps that ends in prioritised, refined scenarios, not a wish list.

Definition (QAW). The SEI report calls it "a facilitated, early intervention method used to generate, prioritize, and refine quality attribute scenarios before the software architecture is completed". Stakeholders "should number at least 5 and no more than 30". The steps, as printed in the report:

QAW stepWhat happensOutput
1 QAW presentation and introductionsFacilitators explain the methodShared expectations
2 Business/mission presentationA stakeholder presents goals and contextBusiness drivers
3 Architectural plan presentationArchitect shows what exists or is plannedKnown constraints
4 Identification of architectural driversFacilitators consolidate notes (15-minute caucus) and read backDriver list
5 Scenario brainstormingStakeholders propose scenarios in round-robinRaw scenarios
6 Scenario consolidationMerge similar ones so votes are not dilutedShorter list
7 Scenario prioritizationEach person gets votes equal to 30% of the scenarios, rounded to an even number, two passesRanked list
8 Scenario refinementThe top four or five get stimulus, source, artifact, environment, response, response measureRefined scenarios

Example from the report: "if 30 scenarios were generated, each stakeholder gets 30 x 0.3, or 9, votes rounded up to 10."

Stakeholder interviews do the same job for a small team: one person at a time, always two questions ("what would make this project a failure for you?" and "what is the worst thing that could happen in production?"), then read the answers back as scenarios. The utility tree (see Prioritising: utility tree and ATAM) turns the result into a ranked tree with (importance, difficulty) per leaf.

text
     Hour   Activity                                              Output
1    0:00   Business presenter: "new line of business, 4 months"  Driver: time to market
2    0:30   Architect: "assume one PostgreSQL, one queue"         Constraint
3    1:00   Brainstorm: 23 raw scenarios in round-robin           Raw list
4    2:00   Consolidate to 17; votes per person = 17 x 0.3 = 5.1 -> 6   Ranked list
5    3:00   Refine top 5 with response measures                   5 refined scenarios, 2 are (H,H)

Real scenarios: a payments team runs a half-day QAW and discovers that "refunds within 30 seconds" matters more to support than "checkout under 300 ms"; a data platform learns that "reprocess last 90 days" is a hidden availability driver.

Fix: record who said what, because a scenario with no owner is the first to be dropped under pressure.

Domain concerns to architecture characteristics Important ​

In plain words: business words hide quality needs: "millions of users" means scalability, "competitive" means agility, "money" means correctness and audit. Listing the matching characteristics is the fastest way to a first driver list.

Common misunderstanding: "More characteristics is better." Richards and Ford advise keeping only the few that matter, because each one costs and many conflict; the standard advice is a top three out of a longer candidate list. We could not read the book directly; this paraphrase also appears in secondary notes, so treat the number as a rule of thumb, not a quote.

Definition: read the requirements for domain concerns and map them. Explicit characteristics appear in the text; implicit ones (security, availability, observability) are needed for success but nobody wrote them down, so domain knowledge is required.

Domain concern in the briefCandidate characteristicKind
"Hundreds, hopefully thousands to millions" of usersScalability, elasticityExplicit
"5-10 new types each month", "each type has its own rules"Extensibility (modifiability), agilityExplicit
"Check", "right to change the original quote"Data integrity, auditabilityImplicit
"New line of business", "highly competitive"Time to market, feasibility, costExplicit
Kiosks in mallsAvailability under poor networks, usabilityImplicit
Personal electronics (data on devices)Security, privacyImplicit

Fix: rank, cut to three or four, and write one scenario per survivor. Everything else is "good enough" and gets no special structure.

The ADD loop in eight steps Must-know ​

In plain words: ADD opens one box at a time. For that box you take the few requirements that matter, choose patterns and tactics, create the child boxes, give them jobs and interfaces, check, and then open the next box.

Common misunderstanding: "ADD produces the whole architecture in one pass." It is recursive: "ADD follows a recursive design process that decomposes a system or system element by applying architectural tactics and patterns that satisfy its driving requirements", and it "essentially follows a 'Plan, Do, and Check' cycle". It stops when the drivers are met, not when every class is drawn.

PLANDOCHECK1Confirmrequirementsprioritised2Choose anelement todecompose3Identifycandidatedrivers4Choose designconcept: patterns+ tactics5Instantiate +allocateresponsibilities6Defineinterfaces(provides/requires)7 Verify and refinechildren meet the parent's requirements8 Repeat 2 to 7 for the next elementuntil every driver is metScenario walkthroughs, prototypes, fitness functions feed the check

Definition (steps 2 to 8 in detail).

StepSub-steps and rules from the reportOur shorthand
2 Choose elementFirst iteration: the system itself. Later: choose by (a) current knowledge, (b) risk and difficulty, (c) business criteria (incremental release, build or buy), (d) organisational criteria (skills, who decides)Open the riskiest box first
3 DriversSecond ranking by architecture impact; groups (H,H) to (L,L); take five or sixShort list
4 Design conceptSix sub-steps: identify design concerns; list alternative patterns with discriminating parameters; select with a pros and cons matrix; combine patterns; sketch views; resolve inconsistenciesPatterns plus tactics, with rationale
5 Instantiate and allocateCreate child instances; give responsibilities by type; allocate parent's responsibilities; create extra instances when quality properties differ; document in module, component-and-connector and allocation viewsBoxes and jobs
6 Interfaces"Interfaces describe the PROVIDES and REQUIRES assumptions that software elements make about one another"; include syntax, semantics, information exchanged, quality attributes, error handlingContracts, not just signatures
7 Verify and refineAll requirements of the parent allocated to a child; responsibilities become child functional requirements; refine child quality requirementsPass requirements down
8 RepeatReturn to step 2Next box

Step 4 has a rule worth memorising: "Ideally, you want to find a pattern that satisfies all of your candidate drivers; otherwise, pick a pattern that comes close and augment it with tactics. If you can't find a pattern that comes close, start with tactics." In step 5 the report lists "use cases that systems typically address", useful for finding forgotten responsibilities: one user doing two tasks at once, two users doing similar tasks at once, startup, shutdown, disconnected operation, failure of various elements, version upgrades.

text
     Iteration  Element opened      Drivers used                    Decision recorded
1    1          Whole system        Extensibility, payout safety    Modular monolith + plug-in rule packs (ADR-001, ADR-002)
2    2          Quoting module      Latency, reproducible quotes    Pure rule packs, versioned results (ADR-003)
3    3          Payout module       Never pay twice                 Outbox + idempotency key (ADR-004)
4    4          Inspection module   Re-quote and audit              Workflow with explicit states (ADR-005)

Real scenarios: an e-commerce platform opens "checkout" first because it is the riskiest; a data pipeline opens "ingest" because throughput is the first driver; a mobile team opens "sync" because offline is (H,H).

Fix: write the iteration log (as above). It is the cheapest evidence that the design was derived, not decorated.

Tactics catalogue and the patterns that bundle them Must-know ​

In plain words: a tactic is one small design move that pushes one quality in a known direction; a pattern is a bundle of several tactics plus structure. ADD step 4 matches drivers to patterns, and uses tactics to fill the gap.

Common misunderstanding: "Pick the pattern first." The report's own footnote says to look for a pattern that fits all drivers, otherwise take a close one and augment it with tactics, and if none is close start with tactics.

Definition: the table lists the standard tactic families from Bass, Clements and Kazman (we did not read the catalogue chapters in this session; the sibling chapter Tactics has a shorter table, and names should be checked against the book before quoting) and the patterns that package them, with the chapter where each is taught.

AttributeTactic (typical name)Pattern that bundles itCostTaught in
AvailabilityDetect faults (ping-echo, heartbeat, monitor), recover (redundancy, rollback, retry), prevent (removal from service)Active-passive failover, circuit breaker plus retryMoney, duplicate workError Handling & Fault Tolerance, Replication
AvailabilityRetry with backoff, circuit breaker, bulkheadResilience patternsRetry storms if unboundedService Communication
PerformanceReduce demand (cache, limit event rate), manage resources (queue, concurrency, scheduling)Cache-aside, CQRS read model, async queueStaleness, complexityStorage & Data Scaling
PerformanceReduce chattiness, batch, move data close to computeBFF, aggregated APICoupling to the consumerAPI Gateway, BFF & Service Mesh
ModifiabilityInformation hiding, restrict dependencies, use an intermediary, defer bindingLayering, plug-in registry (microkernel), ports and adaptersIndirectionMicrokernel / Plugin, Modular Monolith
SecurityAuthenticate, authorise, encrypt, audit, limit exposure, detect intrusionGateway auth, mTLS, row-level securityFriction, CPUSecurity by Design, Database Security
TestabilityControl and observe state: dependency injection, record and replay, sandboxHexagonal ports, test doublesMore typesDependency Inversion
UsabilityCancel, undo, aggregate, give feedback, adapt to the userCommand pattern, optimistic UIComplexity in the clientInteraction & Presentation
IntegrabilityOrchestrate, use an adapter, tailor interface, discoverAnti-corruption layer, message translatorMapping codeMessage Transformation
DeployabilityRoll back, canary, feature flags, automateBlue-green, immutable deploysPipeline workMonolith vs Microservices vs Modular
text
     Driver                                        Tactic chosen                      Pattern that carries it
1    "Quote p95 under 2 s at 200 requests/s"      Pure function, no remote calls     In-process rule pack
2    "New device type in 2 days"                   Defer binding, intermediary        Plug-in registry (microkernel)
3    "Never pay twice"                             Idempotency key, retry safe        Transactional outbox + idempotent consumer
4    "Quote reproducible years later"              Record the rule version            Versioned result (event-carried state)

Real scenarios: the same driver "survive a zone outage" is bought by redundancy (money), by queue buffering (staleness) or by degrading features (product cost); the matrix in step 4 makes the price visible.

Fix: use a pattern matrix: rows are drivers, columns are candidate patterns, cells are "pros and cons" (the report's Table 1). The Go snippet matrix/main.go turns it into numbers for conversation, not as an oracle.

From the domain to components: bounded contexts and Conway's law Important ​

In plain words: components should follow the seams of the business language and of the teams, not the technical layers.

Common misunderstanding: "Components are the nouns in the database." Nouns repeat across contexts: "customer" in Quoting is a name and an email; in Payout it is a payee with bank details and tax data. One shared Customer table couples everything.

Definition: a bounded context is the area where one model and one vocabulary are consistent (pointer: the DDD chapters). Conway's law (1968) says the design copies the communication structure, so one team per context is the cheapest alignment, and the opposite (the inverse Conway manoeuvre) shapes teams to get the architecture you want. This method uses them in step 5: instantiate one element per context, then check the allocation against the teams.

SignalSuggests a boundaryExample
Same word, different meaningSeparate contexts"Device" in Catalog (a type) vs Inspection (a physical unit)
Different rate of changeSeparate modulesRule packs change weekly; payout rules yearly
Different quality needsSeparate elements (ADD step 5, sub-step 4)Payout needs strict consistency; notifications do not
Different teams or ownersSeparate modules, maybe servicesFinance owns Payout
Different data lifetime or complianceSeparate schemaPayee bank details vs quote history
text
     Step   Action                                           Result
1    1      List the nouns and verbs in the kata             quote, device type, rule, box, inspect, pay, resell, recycle
2    2      Group by "same words, same people, same change"  Catalog, Quoting, Trade-in, Inspection, Payout, Disposition
3    3      Check the team: six people, three streams        Merge Notifications and Identity into platform, one owner
4    4      Draw the allowed dependencies                    Quoting -> Catalog; Inspection -> Trade-in; no cycles

Real scenarios: Shopify spent years componentising its Rails monolith into modules with enforced boundaries; their engineering post says they aim for a modular monolith and "are very deliberate about when to split functionality out into separate services" (references). Service boundaries in depth: Service Boundaries.

Fix: an element is only real if it has an owner, an interface and a data rule (who may read or write which tables).

Choosing a style by characteristic fit Must-know ​

In plain words: each architecture style is good at a few things and bad at others. Compare them with your drivers, not with fashion.

Common misunderstanding: "Microservices score highest on everything important." They score highest on independent deployment and team autonomy, and lowest on simplicity, cost and early speed. Fowler's MicroservicePremium: the "fulcrum of whether or not to use microservices is the complexity of the system you're contemplating".

Definition: the table rates common styles from 1 (poor) to 5 (excellent) on characteristics. The ratings are our synthesis of the style chapters and the Richards and Ford style-comparison idea (their book has a similar star chart; we have not copied it); they are a starting point to argue with.

StyleSimplicityCost (early)Time to marketExtensibilityElasticityFault isolationIndependent deployChapter
Layered monolith5552111Layered
Modular monolith4444221Modular Monolith
Microkernel / plug-in4445122Microkernel
Pipe and filter4443332Pipe and Filter
Service-based (a few coarse services)3334344SOA
Event-driven2334444Event-Driven Architecture
Microservices1125555Microservices

Combine, do not pick one: Going Green is a modular monolith whose Catalog is a microkernel and whose slow work is event-driven through an outbox. Styles versus patterns: Styles vs Patterns. The decision itself: Monolith vs Microservices vs Modular.

If the top drivers includeLean towardWarning
Time to market, small team, uncertain domainModular monolithEnforce boundaries or it becomes a big ball of mud
Extensibility by third parties or per-customer variationMicrokernelPlug-in contract must be versioned
Independent scaling or deployment of parts, many teamsService-based, then microservicesThe distributed-systems tax
Throughput over data in stagesPipe and filter, stream processingBack-pressure
Reacting to many independent eventsEvent-drivenEventual consistency, debugging

Real scenarios: Segment's engineering blog (2018) describes moving a pipeline back from microservices to a monolith: "Instead of enabling us to move faster, the small team found themselves mired in exploding complexity." That is a style chosen for a driver (isolation) that the team could not afford to operate.

Fix: write the choice as an ADR with the rejected alternatives (see the kata).

Iterate and prototype: walking skeleton and tracer bullet Must-know ​

In plain words: build the thinnest possible slice that goes from the user to the database and back out as an event, deploy it, and test it. Then grow it.

Common misunderstanding: "A skeleton is a throw-away prototype." Hunt and Thomas distinguish them: tracer code is kept and grows; a prototype explores one question and is discarded. A skeleton you throw away is just a prototype with a longer schedule.

Definition: a walking skeleton is a tiny end-to-end implementation, built with the real structure (modules, build, deploy, test pipeline), which "does next to nothing, but does it from end to end". The tracer bullet idea is the same stance: fire through the whole stack, watch where it lands, adjust. A prototype answers one question (can we render 10 000 rows? does this API return what we need?).

PrototypeWalking skeleton / tracer codeSpike
GoalLearn about a risk or a UIProve the architecture end to endAnswer one technical question
Kept?Thrown awayKept and grownThrown away (the learning is kept as an ADR)
Quality barLowProduction structure, tests and CILow
Typical sizeDaysOne to two weeksHours to days
OutputA decisionA running pipeline plus the first sliceA measurement
text
     Day   Slice                                             What it proves
1    1     HTTP POST /quotes -> service -> memory store      Wiring, tests run in CI
2    2     Swap memory store for PostgreSQL + outbox row     Local transaction, schema per module
3    3     Relay publishes outbox row to a log               Event path exists
4    4     Deploy to staging through the real pipeline       Build, config, health check
5    5     Add the second rule pack (camera)                 Extensibility driver holds: only a new file

Real scenarios: the first sprint of a greenfield product ends with one working "hello world" quote on staging; a team replacing a legacy system sends one real transaction through the new path before migrating the rest.

Fix: the skeleton must include the unpleasant parts (migrations, secrets, deploy, observability). See the code in Go and Laravel.

Risks and spikes Important ​

In plain words: every design rests on assumptions. List the ones that would hurt most if wrong and test them first, cheaply.

Common misunderstanding: "A risk list is a list of bad things." A useful entry has an assumption, an impact on a driver, a test and a deadline.

Definition: a risk here is an architecturally important decision that has not been made or is problematic (the sense used by ATAM in the sibling chapter). A spike is a time-boxed experiment that answers one question. ADD step 2 names risk as a reason to open an element first: "how difficult it will be to achieve the element's associated requirements" and "how familiar you are".

RiskDriverSpikeTime boxResult feeds
Rule packs cannot be added without a redeployExtensibilityLoad packs from a configuration list; add one in a branch1 dayADR-002
Kiosk network is unreliableAvailabilityReplay a kiosk session with 30% packet loss2 daysRetry policy and idempotency key
Cheque provider API is slowPayout correctnessCall sandbox 1 000 times1 dayTimeout and retry budget
Quote needs per-model data we do not haveQuote accuracyAsk the business for 20 sample prices2 daysData model of rule packs
Throughput claim "millions of users"ScalabilityEstimate with Capacity EstimationHalf a dayWhether to plan sharding

Fix: keep a risk burn-down: each iteration closes the top risk or explains why it remains.

Capacity inputs Important ​

In plain words: "millions of users" is not a number you can design for. Convert it into requests per second, bytes per day and peak factors, and keep the two ends of a range.

Common misunderstanding: "Capacity planning is for later." The shape (one database or sharded, synchronous or queued) depends on orders of magnitude, so a rough estimate belongs in the first iteration; precision does not.

Definition: use the method in Back-of-the-Envelope Capacity Estimation: users to daily actives to requests per second to peak; storage per record times retention. Mark every number as assumed.

Input (assumed)LowHighDerived
Registered users10 0005 000 000
Quotes per active user per month11
Monthly active share20%5%2 000 to 250 000 quotes per month
Peak factor (campaign day)1010
Quote rate (monthly quotes divided by 2.6 million seconds)about 0.001 to 0.1 requests per second on average; times the peak factor, 0.01 to 1
Quote record size1 KB1 KB2 MB to 250 MB per month

The result is the whole point: even the high end is about one request per second at peak for quoting, so a single PostgreSQL primary is far from the limit, and the real drivers are extensibility and payout correctness, not throughput. That is how a number removes a style (sharded microservices) from the shortlist.

Fix: when the estimate disagrees with the brief ("millions"), say so in the review: the brief is a hope, the estimate is a plan, and the architecture should be able to evolve to the hope.

Documenting the candidate Important ​

In plain words: write down the decisions, a few views, the scenarios and the open risks, in a form people can review in twenty minutes.

Common misunderstanding: "Documentation is the diagram." ADD says the output is "a system design in terms of the roles, responsibilities, properties, and relationships among software elements" documented in "Module, Component-and-Connector, and Allocation views". The decisions are the valuable part.

Definition: a minimum package:

ArtifactContentWhere taught
Context and container viewSystem, users, external systems, deployable units4+1 views
Module viewModules, allowed dependencies, data ownershipModular Monolith
Runtime viewOne sequence per top scenarioUML
Deployment viewNodes, databases, queues4+1 views
ADRsOne page per significant decision with alternatives and consequencesArchitecture Decisions
Driver list and scenariosThe reason for everything aboveThis page
Risk and assumption listWhat may be wrongThis page

Fix: link every ADR to the driver it serves; unlinked decisions are either drivers you forgot or decoration.

Validating the candidate: scenario walkthroughs, ATAM-lite, fitness functions Must-know ​

In plain words: pretend the scenario happens and trace it through the design on paper, then turn the checkable ones into tests that keep running.

Common misunderstanding: "Validation means a full ATAM." The full method has nine steps and many stakeholders, but the core (utility tree, rank scenarios, walk the top ones, name risks and trade-off points) fits in two hours for one system (sibling chapter).

Definition:

TechniqueHowCatchesCost
Scenario walkthroughFor each top scenario, trace stimulus to response through modules and name each decision it relies onMissing responsibilities, hidden couplingHours
ATAM-liteUtility tree plus walkthrough of the (H,H) leaves plus a list of risks, non-risks, sensitivity and trade-off pointsUnexamined drivers, trade-offsHalf a day
Spike or prototypeMeasure the risky thingWrong assumptionsDays
Fitness functionAn automated check of a quality (dependency rule, latency budget, schema rule) in CIDrift over timeHours to write
Review against the use cases ADD listsOne user two tasks, two users, startup, shutdown, disconnect, failure, upgradeForgotten responsibilitiesHours
text
     Step   Scenario: "Camera arrives cracked; inspector changes the quote"
1    1      Inspection records assessment (condition = cracked)       Inspection module
2    2      Inspection asks Catalog pack for new price at the pack version stored in the quote   Needs old pack version retained!
3    3      Trade-in moves to AwaitingCustomerDecision, event quote.revised   Outbox
4    4      Customer accepts in the web app within 14 days            Timer needed -> risk R4
5    5      Payout is created exactly once                           Idempotency key = trade-in id

The walkthrough found a missing responsibility at step 2 (keep old pack versions) and a risk at step 4 (a timer). That is the value.

Fitness functions (pointer to Fitness functions): code that fails the build when the structure drifts, such as the Go test arch_test.go and the Pest arch tests in Laravel.

Fix: keep one walkthrough per top scenario in the repository next to the ADRs and re-run them when a driver changes.

Anti-patterns of the method Good to know ​

In plain words: the usual ways this goes wrong.

Common misunderstanding: "More process means more safety." Process that never ends in a decision is waste.

Anti-patternSymptomCure
Resume-driven designThe style appears before the driversWrite the driver list first; justify the style from it
Big design up frontMonths of diagrams, no running codeOne iteration of ADD, then a walking skeleton
No design at allThe first framework choice is the architectureA day of driver work before the first sprint
Everything is a priority14 drivers (H,H)Renegotiate, as the ADD report advises for more than five or six
Ivory towerDecisions without the teamADRs reviewed in the pull request
Premature distributionNetwork calls between things that change togetherModular monolith first (Monolith First)
Unfalsifiable drivers"The system must be fast"Scenario with a response measure

Mechanics: the method as a procedure ​

Inputs: functional requirements, constraints, business drivers, stakeholder concernsdozens to hundreds of statements, most of them cheap to satisfy in any structureArchitecturally significant requirements (5 to 6 drivers)found by QAW, interviews, utility tree: (High importance, High impact)Quality attribute scenarios: stimulus, response, response measureeach driver becomes a testable sentenceTactics, then patterns that bundle themretry + breaker, cache, plug-in registry, outbox, queue, replicaStyle + candidate architecturevalidated by walkthroughs, spikes, fitness functionsfeedback: new risks reopen drivers

The procedure in one page.

#DoStop whenTypical size
1Collect inputs; mark assumptions; list questions for stakeholdersYou can state the business goal in one sentence1 page
2Build the driver list: candidate characteristics, then scenarios, then rank twiceAt most 5 or 6 (H,H)1 page
3Estimate capacity rangesYou know the order of magnitude per axis1 table
4Open the whole system (ADD 2 to 7): patterns, tactics, children, interfacesEvery driver has an owner element1 diagram, 3 to 6 ADRs
5Choose the riskiest child and repeatThe remaining children are routine1 to 3 more loops
6Build the walking skeleton and run the spikesEach top risk has an answer or a plan1 to 2 weeks
7Walk the scenarios, run ATAM-liteNo unexamined (H,H) scenarioHalf a day
8Write fitness functions for the rules you rely onCI fails when a rule is brokenA few tests
9Review at each quarter or on a driver changeDriver list is still true1 hour

Knobs with exact numbers (from the reports): QAW has 8 steps and 5 to 30 stakeholders; voting uses 30% of the number of scenarios, rounded to an even number, in two passes; the top four or five scenarios get refined; ADD step 3 selects five or six drivers and uses 9 groups for 3 by 3 ranking; ADD step 4 has six sub-steps; ADD step 5 announces six sub-steps (the report lists five numbered items in our copy); step 6 has three; step 7 has three.

Failure modes of the method.

FailureCauseFix
Drivers keep changingPriorities never agreed (ADD step 0, outside the method)Return unranked requirements to stakeholders
Every scenario ranked highNo cost attached to prioritiesGive each stakeholder limited votes (QAW)
Candidate cannot be testedResponse measures missingRewrite to the six-part scenario
Style chosen then drivers inventedProcess run backwardsRe-run step 3 honestly
Skeleton never gets the second sliceSkeleton treated as a demoMake slice two the sprint goal

Going Green: a full worked kata ​

This section runs the whole method on one kata so each step has numbers. Everything marked assumed is ours: the kata states only the lines quoted below, and a real architect would ask the stakeholders.

The kata and assumptions ​

The kata (Neal Ford and Mark Richards; text from a public copy that links to the companion site): "A large electronics store wants to get into the electronics recycling business and needs a new system to support it. Customers can send in their small personal electronic equipment (or use local kiosks at the mall) and possibly get money for their used equipment if it is in working condition." Users: "Hundreds, hopefully thousands to millions". Requirements:

#Requirement (verbatim from the kata)
R1"Customers can get a quote for used personal electronic equipment (phones, cameras, etc.) either through the web or a kiosk at a mall."
R2"Customers will receive a box in the mail, send in their electronic, and if it is in good working order receive a check."
R3"Once the equipment is received, it is assessed (inspected) to determine if it can be either recycled (destroyed safely) or sold (eBay, etc.)."
R4"The company anticipates adding 5-10 new types of electronic that they will accept each month."
R5"Each type of electronic has its own set of rules for quoting and assessment."

Additional context: a highly competitive, new line of business; types not received for a year are removed; the accepted list "changes often"; each item has its own inspection rules; "We have the right to change the original quote to the customer if the product isn't in the condition they said it was."

Assumption (ours)Why it mattersQuestion for stakeholders
Team of six engineers, PHP and Go skillsOperability, style choiceWho runs production?
First release in four monthsTime to marketIs a smaller first release acceptable?
Kiosks have a connection most of the time, short outages possibleAvailability of quotingDo kiosks need offline quoting?
Cheque payments via a provider API with idempotency keysPayout designWhich provider?
Customer has 14 days to accept a revised quoteWorkflow timersLegal minimum?

Step 1: driver list and scenarios ​

Domain words to characteristics (see above): extensibility, data integrity and auditability, time to market, scalability (range), availability of kiosks, security and privacy. Utility tree with (importance, difficulty):

Leaf scenario (response measure)Attribute(Imp, Diff)Driver?
S1: A product owner adds a new device type with its quote and inspection rules; one developer, two working days, no change to other types, all existing quote tests greenExtensibility(H,H)Yes
S2: A cheque is requested twice for the same trade-in (retry, double click, replay); exactly one cheque is issued, 100% of the timeData integrity(H,H)Yes
S3: A customer asks for a quote on web or kiosk; response in under 2 s at p95 at 10 requests per second peakPerformance(H,M)Check
S4: Six months later support asks "why was this price offered?"; the system shows inputs, rule pack version and who changed it, within one minuteAuditability(H,M)Yes (cheap if designed in)
S5: First production release in 4 months with six engineersTime to market(H,H)Yes (constraint on every other choice)
S6: A kiosk loses the network for 5 minutes mid-session; the customer's input is not lostAvailability(M,M)Later
S7: Personal data of customers is encrypted at rest and access is loggedSecurity(H,L)Standard practice
S8: Remove device types not received for a yearModifiability(L,L)No

Four drivers (S1, S2, S4 and S5) plus a performance check, below the "five or six" limit. Capacity (the table in Capacity inputs) shows peaks of about one request per second, so S3 is not a structural driver; it only forbids remote calls inside the quote path.

Step 2: tactics, patterns, style ​

DriverDesign concernTacticPattern consideredVerdict
S1Add behaviour without touching othersDefer binding, intermediary, restrict dependenciesPlug-in registry (microkernel), rules as data in a rules engine, microservice per devicePlug-in packs; rules-engine kept as an option
S2Duplicate requestsIdempotent operation, record outcomeIdempotency key, transactional outbox, sagaKey plus outbox
S4Reproduce historyRecord inputs and versionVersioned result, event logStore rule version with each quote
S5Fast first releaseReduce moving partsMonolith FirstOne deployable

Style scoring (Go matrix with weights extensibility 30, payout correctness 25, time to market 20, quote latency 15, operability 10):

StyleWeighted score (0 to 100)
Modular monolith + plug-in rule packs86.0
Layered monolith74.0
Service-based (4 coarse services)66.0
Microservices (per device type)52.0

The scores are conversation starters, not proof: change a weight and see whether the ranking flips; to test it, add an "independent deployment" driver to the matrix and raise its weight until the ranking flips; that weight is the price of the service split in this kata.

Step 3: components, interfaces, candidate ​

Web appquote, trackMall kioskquote, drop-offGoing Green platform: one deployable, 8 modules, in-process callsCatalog + rule packsdevice types, plug-insQuotingprice + rule versionTrade-inorder, box, statusInspectionassess, re-quotePayoutcheque, idempotentDispositionresell or recycleNotificationsemail, SMSIdentitycustomers, staffRule: modules talk through facades and events only (fitness-tested)ExternalCheque / payment providerShipping label providerMarketplace (eBay, ...)Email / SMS gatewayPostgreSQL: one schema per modulecatalog.* quoting.* tradein.* inspection.* payout.*outbox (same transaction as the state change)Queue + relayworkers, retries,dead letters
ModuleResponsibilityProvidesRequiresOwns data
CatalogAccepted device types, rule packs, pack versionsLookup(device), Accepted()nonecatalog.*
QuotingPrice a device, store versioned quoteRequestQuote(input), event quote.createdCatalogquoting.*
Trade-inOrder, label, box, status, customer acceptanceAccept(quote), state machineQuoting eventstradein.*
InspectionAssess, re-quote, route to resell or recycleAssess(box), event quote.revisedCatalog at the stored pack versioninspection.*
PayoutCreate the cheque exactly oncePay(tradeIn) (idempotent)Trade-in events, payment providerpayout.*
DispositionResell on marketplace or send to recyclingList(item)Inspection eventsdisposition.*
NotificationsEmail and SMS from eventsconsumes eventsEvent streamnone
IdentityCustomers and staff, rolesAuthenticatenoneidentity.*

Interface rule (ADD step 6): each module is called through a facade and communicates the rest by events; a module may read only its own schema (fitness-tested, see Go). The relation with the user-facing clients is a single HTTP API; the web app and the kiosk app are two clients of the same contract.

Step 4: the ADRs ​

The format follows Architecture Decisions: context, decision, alternatives, consequences, driver served.

ADR-001: Start as a modular monolith (Accepted). Context: S5 (four months, six people), uncertain domain boundaries. Decision: one deployable, eight modules with enforced dependencies, one PostgreSQL database, schema per module. Alternatives: microservices per device type (rejected: ops cost, S5), layered monolith (rejected: S1 needs a plug-in seam). Consequences: simple deploys and transactions; scaling is vertical first; a module can be extracted later because it already communicates through a facade and events. Evidence: Monolith First, capacity table.

ADR-002: Device types are rule packs behind a registry (Accepted). Context: S1 and R4/R5. Decision: a RulePack interface (pure quote function, version string); the registry is the microkernel core; adding a type adds one pack plus its tests. Alternatives: a generic rules engine with rules in a database (kept as a later option when product owners must edit rules without developers); one service per type (rejected: cost). Consequences: a deploy per new type (acceptable at 5 to 10 a month); packs must stay pure.

ADR-003: Every quote stores the rule pack version and inputs (Accepted). Context: S4 and "right to change the original quote". Decision: quoting.quotes.rule_version is mandatory; old pack versions stay loadable. Alternatives: recompute from current rules (rejected: not reproducible). Consequences: pack code is append-only in practice; storage grows by a few bytes per quote.

ADR-004: State change and event in one transaction; payout is idempotent (Accepted). Context: S2. Decision: the transactional outbox for events, idempotency key = trade-in id for the cheque request. Alternatives: publish after commit (rejected: lost events on crash), two-phase commit with the broker (rejected: availability). Consequences: duplicates are possible, so consumers deduplicate (Idempotent Consumers).

ADR-005: Inspection is an explicit state machine with a human-wait state (Accepted). Context: R3 and quote revision. Decision: states Received, Assessed, AwaitingCustomerDecision, Accepted, Rejected, Disposed; each transition emits an event; timers are database rows processed by a worker. Alternatives: a workflow engine (kept as an option). Consequences: a small worker and a timer table to operate.

Step 5: risks, spikes, validation ​

RiskSpike result (planned)Outcome
R-A Old pack versions must stay loadableKeep packs as files named by versionPacks registered by device@version; test fails if a version disappears
R-B Cheque provider has no idempotencyConfirm in sandboxIf absent, add our own ledger table with a unique key
R-C Kiosks lose connectivityReplay session with packet lossDecide on local retry in the kiosk client; deferred (S6 is (M,M))
R-D Timer for customer acceptanceWorker polls tradein.deadlinesAdded to ADR-005
R-E Marketplace API rate limitsRead the API docsQueue and retry in Disposition

Fitness functions to keep in CI: (1) Quoting must not import Inspection or Payout; (2) Catalog imports nothing from other modules; (3) every quoting.quotes row has rule_version; (4) quote latency test: pack call under 5 ms; (5) outbox lag alert: oldest unpublished row under 30 seconds.

Step 6: evolution path ​

TriggerMovePre-condition already in place
Marketplace listing blocks quoting during peaksExtract Disposition behind its event streamModule has own schema and events
Product owners need to edit rules dailyIntroduce a rules engine behind RulePackPure interface
Kiosks need offline modeLocal queue plus idempotency keysIdempotent API
Another country with different payout rulesNew Payout pack per countryPayout isolated
Team grows past three squadsOne squad per bounded context, consider extractionConway alignment checked in step 5

Go ​

The Go skeleton is a standard-library service (plus the pgx driver registration in main) with the structure of the chosen style: internal/catalog is the microkernel, internal/quoting is a module with a facade, internal/outbox relays events, internal/arch holds the fitness function. Schema: sql/schema.sql.

Walking skeleton: HTTP, service, database, event ​

The plug-in contract and the registry (the core knows packs only by interface):

go
// Package catalog owns the list of accepted device types and the rule pack
// (quoting rules) of each one. Adding a device type means adding one pack.
package catalog

import (
	"fmt"
	"sort"
)

// Input is what a customer tells us about a device.
type Input struct {
	Device    string `json:"device"`
	Model     string `json:"model"`
	Condition string `json:"condition"`
	StorageGB int    `json:"storage_gb"`
}

// RulePack is the plug-in contract: one pack per device type.
type RulePack interface {
	Device() string
	Version() string
	// Quote returns the offer in integer cents; it must be a pure function.
	Quote(in Input) (int64, error)
}

// Registry is the microkernel core: it knows packs only through the interface.
type Registry struct {
	packs map[string]RulePack
}

// NewRegistry builds a registry; a duplicate device type panics at start-up,
// which is the right time to find out.
func NewRegistry(packs ...RulePack) *Registry {
	r := &Registry{packs: make(map[string]RulePack, len(packs))}
	for _, p := range packs {
		if _, dup := r.packs[p.Device()]; dup {
			panic(fmt.Sprintf("catalog: duplicate rule pack for %q", p.Device()))
		}
		r.packs[p.Device()] = p
	}
	return r
}

// Lookup returns the pack for a device type.
func (r *Registry) Lookup(device string) (RulePack, bool) {
	p, ok := r.packs[device]
	return p, ok
}

// Accepted lists the device types we currently accept, sorted.
func (r *Registry) Accepted() []string {
	out := make([]string, 0, len(r.packs))
	for d := range r.packs {
		out = append(out, d)
	}
	sort.Strings(out)
	return out
}

Two packs, to prove that a second device type is only a new file:

go
package catalog

import "fmt"

// Smartphone is the first rule pack of the walking skeleton.
type Smartphone struct{}

func (Smartphone) Device() string  { return "smartphone" }
func (Smartphone) Version() string { return "smartphone@2026-11-01" }

// Quote starts from a base price per storage size and applies a condition factor.
func (Smartphone) Quote(in Input) (int64, error) {
	base := map[int]int64{64: 9000, 128: 14000, 256: 20000}[in.StorageGB]
	if base == 0 {
		return 0, fmt.Errorf("smartphone: unsupported storage %d GB", in.StorageGB)
	}
	factor, ok := map[string]int64{"working": 100, "cracked": 40, "dead": 10}[in.Condition]
	if !ok {
		return 0, fmt.Errorf("smartphone: unknown condition %q", in.Condition)
	}
	return base * factor / 100, nil
}

// Camera is the second pack; nothing else in the code base changes to add it.
type Camera struct{}

func (Camera) Device() string  { return "camera" }
func (Camera) Version() string { return "camera@2026-11-01" }

// Quote uses a flat price per condition.
func (Camera) Quote(in Input) (int64, error) {
	price, ok := map[string]int64{"working": 7000, "cracked": 2500, "dead": 500}[in.Condition]
	if !ok {
		return 0, fmt.Errorf("camera: unknown condition %q", in.Condition)
	}
	return price, nil
}

The module facade: price, version, save quote and event together:

go
// Package quoting turns a customer description into a priced, versioned quote
// and records an event in the same transaction as the quote.
package quoting

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"time"

	"academy/requirements-to-architecture/skeleton/internal/catalog"
)

// ErrNotAccepted means the device type is not on the accepted list.
var ErrNotAccepted = errors.New("device type not accepted")

// Quote is the aggregate persisted by this module.
type Quote struct {
	ID          string    `json:"id"`
	Device      string    `json:"device"`
	RuleVersion string    `json:"rule_version"`
	Cents       int64     `json:"cents"`
	Condition   string    `json:"condition"`
	CreatedAt   time.Time `json:"created_at"`
}

// Event is an outbox message written with the quote.
type Event struct {
	Type    string
	Key     string
	Payload []byte
}

// Store saves a quote and its event atomically.
type Store interface {
	Save(ctx context.Context, q Quote, ev Event) error
}

// Service is the module facade.
type Service struct {
	rules *catalog.Registry
	store Store
	now   func() time.Time
	newID func() string
}

// NewService wires the dependencies; now and newID are injectable for tests.
func NewService(rules *catalog.Registry, store Store) *Service {
	return &Service{rules: rules, store: store, now: time.Now, newID: randomID}
}

// RequestQuote prices the device and stores quote plus event.
func (s *Service) RequestQuote(ctx context.Context, in catalog.Input) (Quote, error) {
	pack, ok := s.rules.Lookup(in.Device)
	if !ok {
		return Quote{}, ErrNotAccepted
	}
	cents, err := pack.Quote(in)
	if err != nil {
		return Quote{}, err
	}
	q := Quote{
		ID: s.newID(), Device: in.Device, RuleVersion: pack.Version(),
		Cents: cents, Condition: in.Condition, CreatedAt: s.now().UTC(),
	}
	payload, err := json.Marshal(q)
	if err != nil {
		return Quote{}, err
	}
	ev := Event{Type: "quote.created", Key: q.ID, Payload: payload}
	if err := s.store.Save(ctx, q, ev); err != nil {
		return Quote{}, err
	}
	return q, nil
}

func randomID() string {
	b := make([]byte, 8)
	_, _ = rand.Read(b)
	return hex.EncodeToString(b)
}

The HTTP adapter (Go 1.22 method patterns) and the stores (PostgreSQL in one transaction, memory for tests):

go
package quoting

import (
	"encoding/json"
	"errors"
	"net/http"

	"academy/requirements-to-architecture/skeleton/internal/catalog"
)

// Routes registers the module's HTTP routes on a mux (Go 1.22+ patterns).
func (s *Service) Routes(mux *http.ServeMux) {
	mux.HandleFunc("POST /quotes", s.handleCreate)
}

func (s *Service) handleCreate(w http.ResponseWriter, r *http.Request) {
	var in catalog.Input
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16)).Decode(&in); err != nil {
		http.Error(w, "invalid json", http.StatusBadRequest)
		return
	}
	q, err := s.RequestQuote(r.Context(), in)
	switch {
	case errors.Is(err, ErrNotAccepted):
		http.Error(w, err.Error(), http.StatusUnprocessableEntity)
		return
	case err != nil:
		http.Error(w, err.Error(), http.StatusUnprocessableEntity)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	_ = json.NewEncoder(w).Encode(q)
}
go
package quoting

import (
	"context"
	"database/sql"
	"sync"
)

// SQLStore writes the quote and the outbox row in one transaction.
type SQLStore struct{ DB *sql.DB }

// Save implements Store.
func (s SQLStore) Save(ctx context.Context, q Quote, ev Event) error {
	tx, err := s.DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO quoting.quotes (id, device, rule_version, cents, condition, created_at)
		 VALUES ($1, $2, $3, $4, $5, $6)`,
		q.ID, q.Device, q.RuleVersion, q.Cents, q.Condition, q.CreatedAt); err != nil {
		return err
	}
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO outbox (event_type, event_key, payload) VALUES ($1, $2, $3)`,
		ev.Type, ev.Key, ev.Payload); err != nil {
		return err
	}
	return tx.Commit()
}

// MemoryStore is the in-process fake used by tests and the first spike.
type MemoryStore struct {
	mu     sync.Mutex
	Quotes []Quote
	Events []Event
}

// Save implements Store.
func (m *MemoryStore) Save(_ context.Context, q Quote, ev Event) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.Quotes = append(m.Quotes, q)
	m.Events = append(m.Events, ev)
	return nil
}

The outbox relay (FOR UPDATE SKIP LOCKED, at-least-once) and the composition root:

go
// Package outbox relays rows written in the business transaction to a publisher.
package outbox

import (
	"context"
	"database/sql"
	"log"
	"time"
)

// Publisher sends one event to the broker; at-least-once, so consumers dedupe by key.
type Publisher interface {
	Publish(ctx context.Context, eventType, key string, payload []byte) error
}

// LogPublisher is the skeleton's stand-in for a real broker client.
type LogPublisher struct{}

// Publish implements Publisher.
func (LogPublisher) Publish(_ context.Context, eventType, key string, payload []byte) error {
	log.Printf("publish %s key=%s %s", eventType, key, payload)
	return nil
}

// Run polls the outbox until ctx is cancelled. SKIP LOCKED lets several relays run.
func Run(ctx context.Context, db *sql.DB, pub Publisher, every time.Duration) error {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-t.C:
			if err := drain(ctx, db, pub); err != nil {
				log.Printf("outbox: %v", err)
			}
		}
	}
}

func drain(ctx context.Context, db *sql.DB, pub Publisher) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()
	rows, err := tx.QueryContext(ctx,
		`SELECT id, event_type, event_key, payload FROM outbox
		 WHERE published_at IS NULL ORDER BY id LIMIT 50 FOR UPDATE SKIP LOCKED`)
	if err != nil {
		return err
	}
	type row struct {
		id      int64
		typ     string
		key     string
		payload []byte
	}
	var batch []row
	for rows.Next() {
		var r row
		if err := rows.Scan(&r.id, &r.typ, &r.key, &r.payload); err != nil {
			_ = rows.Close()
			return err
		}
		batch = append(batch, r)
	}
	if err := rows.Close(); err != nil {
		return err
	}
	for _, r := range batch {
		if err := pub.Publish(ctx, r.typ, r.key, r.payload); err != nil {
			return err
		}
		if _, err := tx.ExecContext(ctx, `UPDATE outbox SET published_at = now() WHERE id = $1`, r.id); err != nil {
			return err
		}
	}
	return tx.Commit()
}
go
// Command api wires the modules of the modular monolith and serves HTTP.
package main

import (
	"context"
	"database/sql"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver

	"academy/requirements-to-architecture/skeleton/internal/catalog"
	"academy/requirements-to-architecture/skeleton/internal/outbox"
	"academy/requirements-to-architecture/skeleton/internal/quoting"
)

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Fatal("DATABASE_URL is required, e.g. postgres://postgres:secret@localhost:5432/greengreen")
	}
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Composition root: the only place that knows every module.
	rules := catalog.NewRegistry(catalog.Smartphone{}, catalog.Camera{})
	quotes := quoting.NewService(rules, quoting.SQLStore{DB: db})

	mux := http.NewServeMux()
	quotes.Routes(mux)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	go func() { _ = outbox.Run(ctx, db, outbox.LogPublisher{}, time.Second) }()

	srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	go func() { <-ctx.Done(); _ = srv.Shutdown(context.Background()) }()
	log.Printf("listening on %s, accepting %v", srv.Addr, rules.Accepted())
	if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatal(err)
	}
}

The test that makes it a walking skeleton (HTTP in, price and event out):

go
package quoting_test

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/requirements-to-architecture/skeleton/internal/catalog"
	"academy/requirements-to-architecture/skeleton/internal/quoting"
)

// The walking skeleton test: HTTP in, price out, quote and event stored.
func TestWalkingSkeleton(t *testing.T) {
	store := &quoting.MemoryStore{}
	svc := quoting.NewService(catalog.NewRegistry(catalog.Smartphone{}, catalog.Camera{}), store)
	mux := http.NewServeMux()
	svc.Routes(mux)

	body := `{"device":"smartphone","model":"X1","condition":"cracked","storage_gb":128}`
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/quotes", strings.NewReader(body)))

	if rec.Code != http.StatusCreated {
		t.Fatalf("status = %d, want 201: %s", rec.Code, rec.Body)
	}
	if len(store.Quotes) != 1 || store.Quotes[0].Cents != 5600 {
		t.Fatalf("quote = %+v, want 5600 cents", store.Quotes)
	}
	if len(store.Events) != 1 || store.Events[0].Type != "quote.created" {
		t.Fatalf("events = %+v, want one quote.created", store.Events)
	}
}

func TestUnknownDeviceIsRejected(t *testing.T) {
	svc := quoting.NewService(catalog.NewRegistry(catalog.Smartphone{}), &quoting.MemoryStore{})
	mux := http.NewServeMux()
	svc.Routes(mux)
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/quotes", strings.NewReader(`{"device":"toaster"}`)))
	if rec.Code != http.StatusUnprocessableEntity {
		t.Fatalf("status = %d, want 422", rec.Code)
	}
}

Style matrix as code ​

go
// Command matrix scores candidate architecture styles against weighted
// characteristics (ADD step 4: the pattern evaluation matrix).
package main

import (
	"fmt"
	"sort"
)

// Characteristic is one driver with a weight; weights should sum to 100.
type Characteristic struct {
	Name   string
	Weight int
}

// Style holds a 1 (poor) to 5 (excellent) rating per characteristic name.
type Style struct {
	Name    string
	Ratings map[string]int
}

// Score returns the weighted sum, normalised to 0..100.
func Score(s Style, drivers []Characteristic) float64 {
	total, max := 0, 0
	for _, d := range drivers {
		total += d.Weight * s.Ratings[d.Name]
		max += d.Weight * 5
	}
	return float64(total) * 100 / float64(max)
}

func main() {
	drivers := []Characteristic{
		{"extensibility", 30},
		{"payout-correctness", 25},
		{"time-to-market", 20},
		{"quote-latency", 15},
		{"operability-by-6-people", 10},
	}
	styles := []Style{
		{"layered monolith", map[string]int{"extensibility": 2, "payout-correctness": 4, "time-to-market": 5, "quote-latency": 4, "operability-by-6-people": 5}},
		{"modular monolith + plug-in rule packs", map[string]int{"extensibility": 5, "payout-correctness": 4, "time-to-market": 4, "quote-latency": 4, "operability-by-6-people": 4}},
		{"service-based (4 coarse services)", map[string]int{"extensibility": 4, "payout-correctness": 3, "time-to-market": 3, "quote-latency": 3, "operability-by-6-people": 3}},
		{"microservices (per device type)", map[string]int{"extensibility": 5, "payout-correctness": 2, "time-to-market": 1, "quote-latency": 2, "operability-by-6-people": 1}},
	}
	sort.Slice(styles, func(i, j int) bool { return Score(styles[i], drivers) > Score(styles[j], drivers) })
	for _, s := range styles {
		fmt.Printf("%5.1f  %s\n", Score(s, drivers), s.Name)
	}
}

Fitness function: the module rules in CI ​

go
// Package arch holds fitness functions: tests that fail the build when the
// structure drifts from the candidate architecture.
package arch

import (
	"go/parser"
	"go/token"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

const prefix = "academy/requirements-to-architecture/skeleton/internal/"

// allowed lists, per module, the sibling modules it may import.
var allowed = map[string][]string{
	"catalog": {},
	"quoting": {"catalog"},
	"outbox":  {},
	"arch":    {},
}

func TestModuleDependencies(t *testing.T) {
	fset := token.NewFileSet()
	for module, ok := range allowed {
		dir := filepath.Join("..", module)
		entries, err := os.ReadDir(dir)
		if err != nil {
			t.Fatalf("read %s: %v", dir, err)
		}
		for _, e := range entries {
			if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") || strings.HasSuffix(e.Name(), "_test.go") {
				continue
			}
			f, err := parser.ParseFile(fset, filepath.Join(dir, e.Name()), nil, parser.ImportsOnly)
			if err != nil {
				t.Fatal(err)
			}
			for _, imp := range f.Imports {
				path, _ := strconv.Unquote(imp.Path.Value)
				if !strings.HasPrefix(path, prefix) {
					continue
				}
				dep := strings.SplitN(strings.TrimPrefix(path, prefix), "/", 2)[0]
				if dep == module || contains(ok, dep) {
					continue
				}
				t.Errorf("%s imports %s: module %q may only use %v", e.Name(), dep, module, ok)
			}
		}
	}
}

func contains(list []string, s string) bool {
	for _, x := range list {
		if x == s {
			return true
		}
	}
	return false
}

The schema ​

sql
-- sql/schema.sql (excerpt): the outbox is the bridge from state change to event.
CREATE TABLE outbox (
    id           bigserial PRIMARY KEY,
    event_type   text        NOT NULL,
    event_key    text        NOT NULL,
    payload      jsonb       NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now(),
    published_at timestamptz
);
-- Fitness query: lag of the oldest unpublished event, should stay under 30 seconds.
SELECT coalesce(extract(epoch FROM now() - min(created_at)), 0) AS lag_seconds
FROM outbox WHERE published_at IS NULL;

The Go angle ​

QuestionGo answer
How do I enforce module boundaries?internal/ keeps outsiders away from the whole tree but does not separate sibling packages inside it, so add a test (go/parser, as in the snippet) or a tool such as go-arch-lint
Where are modules wired?In main, the composition root; no global registries
Plug-in registrationExplicit list in main; Go has no dynamic loading worth using in production, and an explicit list is greppable
How do I test the whole slice quickly?httptest plus an in-memory store behind the Store interface
Which layout?A package per module; avoid a top-level models or services package

Laravel ​

The same slice in Laravel 13 (PHP 8.4): modules are namespaces under app/Modules, registered through service providers listed in bootstrap/providers.php (the Laravel 13 provider documentation says "All user-defined service providers are registered in the bootstrap/providers.php file"). PHP was reviewed, not run.

Walking skeleton: route, controller, service, database, event ​

The Catalog public API (the only part other modules may use):

php
<?php

declare(strict_types=1);

namespace App\Modules\Catalog\Api;

/** Plug-in contract: one pack per device type; Quote must be a pure function. */
interface RulePack
{
    public function device(): string;

    public function version(): string;

    /** Offer in integer cents. @throws \InvalidArgumentException on unsupported input */
    public function quote(DeviceInput $input): int;
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Catalog\Api;

/** Public data shape of the Catalog module: what a customer tells us. */
final readonly class DeviceInput
{
    public function __construct(
        public string $device,
        public string $model,
        public string $condition,
        public int $storageGb = 0,
    ) {
    }
}

A pack and the registry (microkernel core):

php
<?php

declare(strict_types=1);

namespace App\Modules\Catalog\Packs;

use App\Modules\Catalog\Api\DeviceInput;
use App\Modules\Catalog\Api\RulePack;
use InvalidArgumentException;

final class SmartphonePack implements RulePack
{
    public function device(): string
    {
        return 'smartphone';
    }

    public function version(): string
    {
        return 'smartphone@2026-11-01';
    }

    public function quote(DeviceInput $input): int
    {
        $base = [64 => 9000, 128 => 14000, 256 => 20000][$input->storageGb]
            ?? throw new InvalidArgumentException("Unsupported storage {$input->storageGb} GB");
        $factor = ['working' => 100, 'cracked' => 40, 'dead' => 10][$input->condition]
            ?? throw new InvalidArgumentException("Unknown condition {$input->condition}");

        return intdiv($base * $factor, 100);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Catalog;

use App\Modules\Catalog\Api\RulePack;

/** Microkernel core: knows packs only through the RulePack interface. */
final class RuleRegistry
{
    /** @var array<string, RulePack> */
    private array $packs = [];

    /** @param iterable<RulePack> $packs */
    public function __construct(iterable $packs)
    {
        foreach ($packs as $pack) {
            $this->packs[$pack->device()] = $pack;
        }
    }

    public function lookup(string $device): ?RulePack
    {
        return $this->packs[$device] ?? null;
    }

    /** @return list<string> */
    public function accepted(): array
    {
        $names = array_keys($this->packs);
        sort($names);

        return $names;
    }
}

The Quoting facade with a local transaction that writes the quote and the outbox row (DB::transaction is documented on the Laravel database page):

php
<?php

declare(strict_types=1);

namespace App\Modules\Quoting;

use App\Modules\Catalog\Api\DeviceInput;
use App\Modules\Catalog\RuleRegistry;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;

/** Module facade: other modules and controllers call only this class. */
final class QuotingService
{
    public function __construct(private readonly RuleRegistry $rules)
    {
    }

    /** @return array{id: string, device: string, rule_version: string, cents: int} */
    public function requestQuote(DeviceInput $input): array
    {
        $pack = $this->rules->lookup($input->device)
            ?? throw new RuntimeException("Device type {$input->device} is not accepted");
        $cents = $pack->quote($input);

        $quote = [
            'id' => (string) Str::ulid(),
            'device' => $input->device,
            'rule_version' => $pack->version(),
            'cents' => $cents,
        ];

        // One local transaction: the state change and the outbox row commit together.
        DB::transaction(function () use ($quote, $input): void {
            DB::table('quoting.quotes')->insert($quote + [
                'condition' => $input->condition,
                'created_at' => now(),
            ]);
            DB::table('outbox')->insert([
                'event_type' => 'quote.created',
                'event_key' => $quote['id'],
                'payload' => json_encode($quote, JSON_THROW_ON_ERROR),
                'created_at' => now(),
            ]);
        });

        return $quote;
    }
}

The HTTP adapter and the module's service provider (composition root of the module):

php
<?php

declare(strict_types=1);

namespace App\Modules\Quoting\Http;

use App\Modules\Catalog\Api\DeviceInput;
use App\Modules\Quoting\QuotingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use InvalidArgumentException;
use RuntimeException;

final class QuoteController
{
    public function __construct(private readonly QuotingService $quoting)
    {
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'device' => ['required', 'string', 'max:40'],
            'model' => ['required', 'string', 'max:80'],
            'condition' => ['required', 'string', 'in:working,cracked,dead'],
            'storage_gb' => ['nullable', 'integer', 'min:0'],
        ]);

        try {
            $quote = $this->quoting->requestQuote(new DeviceInput(
                $data['device'], $data['model'], $data['condition'], (int) ($data['storage_gb'] ?? 0),
            ));
        } catch (RuntimeException|InvalidArgumentException $e) {
            return response()->json(['error' => $e->getMessage()], 422);
        }

        return response()->json($quote, 201);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Quoting;

use App\Modules\Catalog\Packs\SmartphonePack;
use App\Modules\Catalog\RuleRegistry;
use App\Modules\Quoting\Http\QuoteController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

/** Register in bootstrap/providers.php. The composition root of the module. */
final class QuotingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Adding a device type means adding one pack to this list.
        $this->app->singleton(RuleRegistry::class, fn () => new RuleRegistry([
            new SmartphonePack(),
        ]));
    }

    public function boot(): void
    {
        Route::middleware('api')->prefix('api')->group(function (): void {
            Route::post('/quotes', [QuoteController::class, 'store']);
        });
    }
}

Register it: bootstrap/providers.php returns [App\Providers\AppServiceProvider::class, App\Modules\Quoting\QuotingServiceProvider::class]. The migration creates one PostgreSQL schema per module and the outbox table:

php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

// PostgreSQL: one schema per module, one database for the whole monolith.
return new class extends Migration
{
    public function up(): void
    {
        DB::statement('CREATE SCHEMA IF NOT EXISTS quoting');

        Schema::create('quoting.quotes', function ($table): void {
            $table->string('id', 26)->primary();
            $table->string('device');
            $table->string('rule_version');
            $table->unsignedBigInteger('cents');
            $table->string('condition');
            $table->timestampTz('created_at');
        });

        Schema::create('outbox', function ($table): void {
            $table->id();
            $table->string('event_type');
            $table->string('event_key');
            $table->jsonb('payload');
            $table->timestampTz('created_at');
            $table->timestampTz('published_at')->nullable();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox');
        Schema::dropIfExists('quoting.quotes');
        DB::statement('DROP SCHEMA IF EXISTS quoting');
    }
};

Fitness functions with Pest ​

php
<?php

declare(strict_types=1);

// Pest architecture tests: fitness functions for the module boundaries.

arch('catalog does not depend on quoting')
    ->expect('App\Modules\Catalog')
    ->not->toUse('App\Modules\Quoting');

arch('quoting reaches catalog only through its public API and registry')
    ->expect('App\Modules\Quoting')
    ->not->toUse('App\Modules\Catalog\Packs');

arch('controllers never touch the database directly')
    ->expect('App\Modules\Quoting\Http')
    ->not->toUse('Illuminate\Support\Facades\DB');

arch('no debugging leftovers')
    ->expect(['dd', 'dump', 'var_dump'])
    ->not->toBeUsed();

test('quote request returns a versioned price', function (): void {
    $response = $this->postJson('/api/quotes', [
        'device' => 'smartphone', 'model' => 'X1', 'condition' => 'cracked', 'storage_gb' => 128,
    ]);

    $response->assertCreated()
        ->assertJsonPath('cents', 5600)
        ->assertJsonPath('rule_version', 'smartphone@2026-11-01');
    $this->assertDatabaseHas('outbox', ['event_type' => 'quote.created']);
});

The relay in Laravel is a scheduled or long-running command that selects unpublished rows FOR UPDATE SKIP LOCKED (DB::table('outbox')->whereNull('published_at')->orderBy('id')->limit(50)->lockForUpdate()->skipLocked() inside DB::transaction) and dispatches a queued job per row; queue internals: Laravel Queue Internals.

The Laravel angle ​

QuestionLaravel answer
Where do modules live?app/Modules/<Name> with a provider each; packages such as nwidart/laravel-modules exist, but a provider per module is enough to start
How to enforce boundaries?Pest arch tests (arch()->expect(...)->not->toUse(...)) and Deptrac in CI
Plug-in registrationA list in the module provider; tagged bindings with $this->app->tag(...) scale it
Transactions across modulesOne local database transaction while it is one database; after extraction, outbox and events
Walking skeleton speedphp artisan serve, SQLite in memory for the first slice, PostgreSQL by day two

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Everything is a priorityForced rankingQAW votes (30% of scenarios), (H,H) cap of five or sixHonest trade-offsUncomfortable conversation
Requirements are vague ("fast")Scenario rewriteSix-part scenario with response measureTestableNeeds stakeholder time
Nobody can say which requirements matterUtility treeRate (importance, difficulty)Shared rankingRatings are opinions; revisit
Style chosen by fashionCharacteristic fit table and ADRWeighted matrix, rejected alternatives recordedAuditable choiceWeights are subjective
Boundaries unclearBounded contexts and Conway checkGroup by language, change rate, teamFewer cross-module editsNeeds domain access
Design cannot be testedWalking skeletonOne slice, real pipelineEarly feedbackNeeds discipline to grow it
Fear of the unknownSpikesTime-boxed experimentsCheap answersEasy to over-run
Architecture driftsFitness functionsArch tests and CI queriesRules stay trueMaintenance of the tests
Decisions forgottenADRsOne page per decisionMemoryMust be kept short

"The brief says millions of users" ​

Do not design for "millions". Estimate (see Capacity inputs): ask what fraction is active and what each does. If the estimate says single-digit requests per second, record "scaling is vertical, plus a read replica when needed" and move on. Keep the ability to change: stateless application, schema per module, events.

"Everyone wants microservices" ​

Ask which driver they serve. If it is independent deployment for several teams, write it as a scenario ("Team A deploys Payout without Team B in under 15 minutes") and check whether the team count justifies it. If not, answer with the module rules and an evolution path (the kata's table).

Choosing ​

SituationRecommendationTechniqueReason
New product, uncertain domain, small teamModular monolith, walking skeleton in week oneADD with one iteration, ADRsLearn boundaries cheaply
Many (H,H) scenariosRenegotiate; split the system into subsystems and run ADD per subsystemStep 2 element choiceADD's own alarm
Quality requirement unclearQAW or interviewsScenario refinementCannot design for a wish
Big risk in one technologySpike firstTime boxCheapest evidence
Rewrite of an existing systemIncident review as an input, strangler pathADR per sliceReal data on failures
Regulated domainTreat audit as a driver from day oneVersioned records, immutable logRetrofitting is expensive
Many teams, independent release cadenceService-based or microservices after extractionConway checkAutonomy driver real
Short-lived systemLayered monolith, minimal documentationADR for one or two choicesCost of method matches value

In architecture: from a single process to a distributed system ​

The method is the same at every scale; what changes is which drivers appear and how expensive each tactic becomes. One everyday example (Going Green) and one production example (Shopify and Segment) per level.

Monolith: one process, one database ​

Going Green day one: one Go binary or one Laravel app, PostgreSQL, a worker for the outbox. Every driver is met in-process: S1 by a registry, S2 by a local transaction plus an idempotency key, S4 by a column. The architecture work is mostly not building things. Production note: Fowler's Monolith First says a monolith is where successful microservice stories started: "Almost all the successful microservice stories have started with a monolith that got too big and was broken up". Segment (2018) moved a pipeline back to a single service after microservices brought "exploding complexity".

Modular monolith and multiple databases ​

Going Green month six: eight modules, one database, schema per module, facades and events between modules, arch tests in CI. When the team grows to three squads each owns modules. If the Payout team needs its own database for compliance, the schema is already separate and cross-module reads are already forbidden, so the split is a connection-string change plus data migration. Production note: Shopify's engineering post (Sep 2020) describes making its Rails monolith modular, enforcing dependencies, and splitting out services only "for good reasons". See Modular Monolith.

Microservices: what survives a network boundary ​

Going Green year two: Disposition is extracted because marketplace calls were slow. What must be added: a contract for events (versioned), idempotent consumers, retries with backoff, an owner on call, tracing, a deployment pipeline of its own. The in-process call becomes a message; the shared transaction is gone, so a saga or an outbox plus compensation is needed. The method's check: does the driver that justified the extraction (independent scaling of listing) outweigh the "premium"? See Microservices Architecture, Service Boundaries, Data Ownership, Service Communication.

What was free in the monolithWhat it costs after extraction
A transaction across Trade-in and PayoutOutbox, idempotent consumers, sagas
A function callNetwork call, timeout, retry, version skew
One log, one debuggerDistributed tracing, correlation ids
One deployA pipeline and rollbacks per service

Distributed data: replicas, caches, multi-region ​

Going Green with a mall-kiosk fleet in several countries: quoting reads the catalog on every request, so the rule packs are cached in process (they are immutable per version, so there is no invalidation problem: a driver choice that made caching trivial). Reading the status of a trade-in from a replica can lag; the customer who just accepted a quote should see the new status ("read your writes"): route that session to the primary or show the state from the response. Multi-region adds the question of where Payout lives: one region owns the money. See Replication & Failover, Eventual Consistency, and the database replication chapter for lag and failover trade-offs.

Scaling path: 1x, 10x, 100x ​

ScaleGoing Green shapeWhat the method re-checks
1x (hundreds of users)One app, one PostgreSQL, one workerDrivers S1, S2, S4, S5
10x (tens of thousands)Two app instances behind a load balancer, read replica for status pages, managed queueLatency scenario S3, outbox lag
100x (millions)Extract Disposition and Notifications; cache rule packs; partition quoting.quotes by monthPeak factor, kiosk availability S6
BeyondRegional deployments, Payout in a home regionCAP trade-offs, compliance

Lab: from a brief to a walking skeleton ​

Setup (PostgreSQL 16 or later, Go 1.24 or later):

sql
CREATE DATABASE greengreen;
\c greengreen
\i docs/snippets/architecture/requirements-to-architecture/sql/schema.sql
text
     Exp   Do                                                                      Expected
1    1     cd docs/snippets/architecture/requirements-to-architecture/go && go test ./...   ok for arch and quoting packages
2    2     DATABASE_URL=postgres://localhost/greengreen go run ./skeleton/cmd/api  listening on :8080, accepting [camera smartphone]
3    3     curl -s -XPOST localhost:8080/quotes -d '{"device":"smartphone","model":"X1","condition":"cracked","storage_gb":128}'   201, cents 5600, rule_version smartphone@2026-11-01
4    4     Watch the server log                                                    publish quote.created key=<id> within one second
5    5     Add a third pack (Tablet) in packs.go and register it in main            One new type, no other file changed
6    6     In quoting/service.go import internal/outbox and run go test ./...       arch test fails: module rule enforced

Then do the paper part: take the kata brief, write four scenarios, rank them in a 3 by 3 grid, and write one ADR for the style. Time-box it to two hours and compare with the kata section above.

Common misconceptions ​

BeliefReality
"Architecture is decided once, up front"ADD is iterative and recursive; decisions are revisited when drivers change
"All NFRs drive the architecture"A few (five or six) do; most are met in any structure
"Functional requirements do not matter to architecture"Some are significant ("works offline", "audit every change")
"ADD needs complete requirements"The report says requirements may be incomplete; mark tentative decisions
"The utility tree is only for ATAM"It is the quickest way to rank drivers for design too
"Microservices are the safe, modern default"Fowler: don't consider them unless the system is too complex for a monolith
"A walking skeleton is a demo"It is production structure, kept and grown
"Fitness functions are for big companies"One import-rule test is enough to start
"A kata solution is the right answer"It is one defensible answer under stated assumptions
"Scores in a matrix prove the choice"They expose weights and assumptions; the ADR carries the reasoning

Cheat sheet ​

TopicWhat to remember
InputsFunctional requirements, constraints, quality scenarios, business drivers; all may be implied
ASRCostly to change, structure-shaping; aim for five or six
RankingImportance by stakeholders, impact by architect, 3 by 3 grid, take (H,H)
QAW8 steps, 5 to 30 stakeholders, votes 30% of scenarios, refine top 4 or 5
ADDPlan, Do, Check; 8 steps; recursive per element
Step 4Pattern matrix; pattern close then tactics; else tactics
Step 6Interface equals provides and requires, semantics, errors
TacticsPer attribute moves; patterns bundle them
ComponentsBounded contexts, Conway check, owner and data rule
StyleChoose by fit, combine, record in an ADR
SkeletonThin, end to end, deployed, kept
SpikeTime-boxed, answers one question, thrown away
CapacityConvert "millions" to requests per second and bytes, keep ranges
ValidationWalkthroughs, ATAM-lite, fitness functions
DocumentationViews plus ADRs plus drivers plus risks

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 — What are the inputs to ADD, and which of them may be only implied? Important ​

Answer

Answer: Functional requirements, design constraints and quality attribute requirements, prioritised by stakeholders. All three can be implied (the SEI report's example: Joe knows only Oracle, so Oracle is a constraint).

2 — How many architectural drivers does ADD ask you to select, and what does it say if more are (H,H)? Good to know ​

Answer

Answer: Five or six. More than that might signal a project risk and warrant renegotiating priorities.

3 — What are the eight QAW steps in order and how many votes does each stakeholder get? Good to know ​

Answer

Answer: Presentation and introductions, business/mission presentation, architectural plan presentation, identification of drivers, scenario brainstorming, consolidation, prioritization, refinement. Votes equal 30% of the consolidated scenarios, rounded to an even number, cast in two passes.

4 — What is the difference between a walking skeleton and a prototype? Must-know ​

Answer

Answer: A skeleton is thin but real, end to end, kept and grown; a prototype answers one question and is discarded.

5 — In ADD step 4, what do you do if no pattern satisfies all drivers? Important ​

Answer

Answer: Pick a pattern that comes close and augment it with tactics; if none is close, start with tactics.

6 — Why can a capacity estimate remove a style from the shortlist? Important ​

Answer

Answer: If peak load is a few requests per second, the elasticity and sharding that justify microservices are not needed, so the drivers that remain (extensibility, correctness) favour a simpler style.

7 — Name three fitness functions you would add for Going Green. Important ​

Answer

Answer: Quoting must not import Inspection or Payout; every quote row has a rule version; outbox lag under 30 seconds. Also a pack latency test.

8 — Which Going Green ADR makes "why was this price offered?" answerable, and how? Good to know ​

Answer

Answer: ADR-003: each quote stores the rule pack version and inputs; old versions stay loadable.

9 — Why does the walkthrough of "inspector changes the quote" find a missing responsibility? Important ​

Answer

Answer: Re-quoting needs the pack version stored in the original quote, so old pack versions must be kept; and acceptance needs a timer, which becomes a risk.

10 — When would you extract Disposition into a service? Important ​

Answer

Answer: When marketplace calls block or slow other work, and independent scaling or deployment is a real driver; it already has its own schema and events, so extraction is cheap.

Glossary ​

TermOne line
ADD (Attribute-Driven Design)SEI method that designs architecture from quality attribute drivers in a Plan-Do-Check loop
QAW (Quality Attribute Workshop)Facilitated workshop that produces prioritised, refined quality scenarios before the architecture exists
ATAMArchitecture Tradeoff Analysis Method; evaluates an architecture against scenarios
ASRArchitecturally significant requirement: costly to change, shapes structure
Architectural driverAn ASR selected as the focus of a design iteration
Quality attribute scenarioStimulus, source, artifact, environment, response, response measure
Utility treeTree from utility to attributes to scenarios rated by importance and difficulty
TacticA small design move that affects one quality attribute
PatternA named bundle of structure and tactics with known trade-offs
Discriminating parameterA property used to choose between patterns (restart time, number of dependencies)
Design conceptThe set of selected patterns and their relations in ADD step 4
Bounded contextArea in which one model and vocabulary are consistent
Conway's lawSystems copy the communication structure of the organisation
Inverse Conway manoeuvreShaping teams to obtain the desired architecture
Walking skeletonTiny end-to-end implementation with real structure, kept and grown
Tracer bulletThin end-to-end code that shows where the design lands; kept
PrototypeThrow-away experiment about one question
SpikeTime-boxed experiment answering one technical question
Fitness functionAutomated check that a quality or structure rule still holds
ADRArchitecture Decision Record: one page per significant decision
KataShort practice problem for architects (for example Going Green)
MicrokernelCore plus plug-ins registered through a contract
Transactional outboxEvent row written in the same transaction as the state change
Idempotency keyIdentifier that makes a repeated request safe
Risk (ATAM sense)Architecturally important decision not made or problematic
Sensitivity pointProperty critical to achieving a quality response
Trade-off pointProperty that is a sensitivity point for more than one attribute
Modular monolithOne deployable with enforced internal module boundaries
Monolith FirstFowler's advice to start with a monolith and extract services once boundaries are known

References ​

Fetched and saved under the scratchpad sources/requirements-to-architecture/; HTTP status 200 unless noted.

Built by Morteza Negahi