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 for | Go to |
|---|---|
| The whole method in three tables | Everything in one minute |
| Why not just start coding the features | Why it exists |
| ADD, QAW, ATAM, katas, tracer bullets: who said what | Where it comes from |
| What goes into the method | Inputs |
| Which requirements matter and how to find them | ASRs, Finding ASRs, Domain concerns to characteristics |
| The eight ADD steps | ADD |
| Tactics and the patterns that bundle them | Tactics catalogue |
| Turning a domain into components | Domain to components |
| Picking a style | Style fit |
| Walking skeleton, tracer bullet, spike | Iterate and prototype, Risks and spikes |
| Capacity numbers as inputs | Capacity inputs |
| Writing the candidate down | Documenting |
| Checking the candidate | Validating |
| A complete example | Going Green kata |
| Code | Go, Laravel |
| Monolith to distributed | In architecture |
| Exercise | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The method as a chain. Every row is unpacked later.
| Stage | Question it answers | Output | Typical tool |
|---|---|---|---|
| 1. Gather inputs | What must the system do, under which limits, for which business reasons? | Functional requirements, constraints, quality attribute scenarios, business drivers | Interviews, QAW, event storming |
| 2. Find the ASRs | Which few requirements change the structure if we get them wrong? | Ranked list of at most 5 or 6 drivers | Utility tree, (importance, impact) grid |
| 3. Choose tactics and patterns | Which known moves buy each driver? | Pattern matrix with pros and cons | Tactics catalogue, ADD step 4 |
| 4. Shape components | Where are the boundaries? | Modules, responsibilities, interfaces | Bounded contexts, Conway's law check |
| 5. Pick a style | Which overall structure fits the drivers and the team? | Style choice recorded in an ADR | Characteristic fit table |
| 6. Prove the risky parts | Do the risky assumptions hold? | Walking skeleton, spikes, measurements | Tracer bullet, load test, prototype |
| 7. Document | How do others understand and challenge it? | Views, ADRs, scenario list | C4 or 4+1, ADR template |
| 8. Validate | Does it meet the scenarios, and will it keep meeting them? | Risks list, fitness functions in CI | ATAM-lite, walkthroughs |
The eight ADD steps (SEI report, CMU/SEI-2006-TR-023):
| Step | In plain words | Design decision made? |
|---|---|---|
| 1 Confirm there is sufficient requirements information | Are the requirements prioritised and testable enough to start? | No |
| 2 Choose an element of the system to decompose | Which box do we open now? First time: the whole system | No |
| 3 Identify candidate architectural drivers | Rank a second time by impact on the structure; take five or six | No |
| 4 Choose a design concept that satisfies the drivers | Pick patterns and tactics, combine them | Yes |
| 5 Instantiate elements and allocate responsibilities | Create the child elements; give each its job | Yes |
| 6 Define interfaces for instantiated elements | What each element provides and requires | Yes |
| 7 Verify and refine requirements, make them constraints for children | Check coverage; pass requirements down | No |
| 8 Repeat steps 2 to 7 for the next element | Open the next box | n/a |
Ways to find ASRs, cheapest first.
| Technique | Who is needed | Time | Best when |
|---|---|---|---|
| Read the document and ask "what if this is 10 times bigger or 10 times stricter" | You | Hours | Always, as a first pass |
| Stakeholder interviews | 3 to 8 people, one at a time | Days | The business drivers are unclear |
| Quality Attribute Workshop (QAW) | 5 to 30 stakeholders | One to two days | Many stakeholders, conflicting assumptions |
| Utility tree | Architects plus product owner | A few hours | You need ranking, not just a list |
| Characteristic extraction from domain words (Richards and Ford) | Architect and domain expert | An hour | Kata-style or early design |
| Failure and incident review of the old system | Operators | Hours | A rewrite or a migration |
Three common misunderstandings, up front
- "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.
- "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.
- "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 thinking | Driver-led thinking |
|---|---|
| Every requirement has the same weight | Five or six requirements shape the structure; the rest fit inside it |
| The style is chosen by fashion or familiarity | The style is chosen by fit to drivers, team size and risk |
| "Non-functional" is a late checklist | Quality scenarios are inputs to the first design |
| Risks appear in production | Risks are named, ranked and spiked early |
| Design is one big document | Design is a loop of small decisions, each with an ADR |
| Failure mode: big design up front, or no design at all | Failure 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.
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 boundariesThe 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.
| Input | Example (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 |
| Constraint | Team 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 concern | Finance: "no cheque is ever paid twice" | Compliance, audit |
| Environment fact | Kiosks in malls, patchy connectivity (assumed) | Offline or degraded mode |
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 betsReal 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 \ Impact | High impact | Medium impact | Low 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 step | What happens | Output |
|---|---|---|
| 1 QAW presentation and introductions | Facilitators explain the method | Shared expectations |
| 2 Business/mission presentation | A stakeholder presents goals and context | Business drivers |
| 3 Architectural plan presentation | Architect shows what exists or is planned | Known constraints |
| 4 Identification of architectural drivers | Facilitators consolidate notes (15-minute caucus) and read back | Driver list |
| 5 Scenario brainstorming | Stakeholders propose scenarios in round-robin | Raw scenarios |
| 6 Scenario consolidation | Merge similar ones so votes are not diluted | Shorter list |
| 7 Scenario prioritization | Each person gets votes equal to 30% of the scenarios, rounded to an even number, two passes | Ranked list |
| 8 Scenario refinement | The top four or five get stimulus, source, artifact, environment, response, response measure | Refined 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.
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 brief | Candidate characteristic | Kind |
|---|---|---|
| "Hundreds, hopefully thousands to millions" of users | Scalability, elasticity | Explicit |
| "5-10 new types each month", "each type has its own rules" | Extensibility (modifiability), agility | Explicit |
| "Check", "right to change the original quote" | Data integrity, auditability | Implicit |
| "New line of business", "highly competitive" | Time to market, feasibility, cost | Explicit |
| Kiosks in malls | Availability under poor networks, usability | Implicit |
| Personal electronics (data on devices) | Security, privacy | Implicit |
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.
Definition (steps 2 to 8 in detail).
| Step | Sub-steps and rules from the report | Our shorthand |
|---|---|---|
| 2 Choose element | First 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 Drivers | Second ranking by architecture impact; groups (H,H) to (L,L); take five or six | Short list |
| 4 Design concept | Six sub-steps: identify design concerns; list alternative patterns with discriminating parameters; select with a pros and cons matrix; combine patterns; sketch views; resolve inconsistencies | Patterns plus tactics, with rationale |
| 5 Instantiate and allocate | Create 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 views | Boxes 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 handling | Contracts, not just signatures |
| 7 Verify and refine | All requirements of the parent allocated to a child; responsibilities become child functional requirements; refine child quality requirements | Pass requirements down |
| 8 Repeat | Return to step 2 | Next 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.
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.
| Attribute | Tactic (typical name) | Pattern that bundles it | Cost | Taught in |
|---|---|---|---|---|
| Availability | Detect faults (ping-echo, heartbeat, monitor), recover (redundancy, rollback, retry), prevent (removal from service) | Active-passive failover, circuit breaker plus retry | Money, duplicate work | Error Handling & Fault Tolerance, Replication |
| Availability | Retry with backoff, circuit breaker, bulkhead | Resilience patterns | Retry storms if unbounded | Service Communication |
| Performance | Reduce demand (cache, limit event rate), manage resources (queue, concurrency, scheduling) | Cache-aside, CQRS read model, async queue | Staleness, complexity | Storage & Data Scaling |
| Performance | Reduce chattiness, batch, move data close to compute | BFF, aggregated API | Coupling to the consumer | API Gateway, BFF & Service Mesh |
| Modifiability | Information hiding, restrict dependencies, use an intermediary, defer binding | Layering, plug-in registry (microkernel), ports and adapters | Indirection | Microkernel / Plugin, Modular Monolith |
| Security | Authenticate, authorise, encrypt, audit, limit exposure, detect intrusion | Gateway auth, mTLS, row-level security | Friction, CPU | Security by Design, Database Security |
| Testability | Control and observe state: dependency injection, record and replay, sandbox | Hexagonal ports, test doubles | More types | Dependency Inversion |
| Usability | Cancel, undo, aggregate, give feedback, adapt to the user | Command pattern, optimistic UI | Complexity in the client | Interaction & Presentation |
| Integrability | Orchestrate, use an adapter, tailor interface, discover | Anti-corruption layer, message translator | Mapping code | Message Transformation |
| Deployability | Roll back, canary, feature flags, automate | Blue-green, immutable deploys | Pipeline work | Monolith vs Microservices vs Modular |
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.
| Signal | Suggests a boundary | Example |
|---|---|---|
| Same word, different meaning | Separate contexts | "Device" in Catalog (a type) vs Inspection (a physical unit) |
| Different rate of change | Separate modules | Rule packs change weekly; payout rules yearly |
| Different quality needs | Separate elements (ADD step 5, sub-step 4) | Payout needs strict consistency; notifications do not |
| Different teams or owners | Separate modules, maybe services | Finance owns Payout |
| Different data lifetime or compliance | Separate schema | Payee bank details vs quote history |
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 cyclesReal 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.
| Style | Simplicity | Cost (early) | Time to market | Extensibility | Elasticity | Fault isolation | Independent deploy | Chapter |
|---|---|---|---|---|---|---|---|---|
| Layered monolith | 5 | 5 | 5 | 2 | 1 | 1 | 1 | Layered |
| Modular monolith | 4 | 4 | 4 | 4 | 2 | 2 | 1 | Modular Monolith |
| Microkernel / plug-in | 4 | 4 | 4 | 5 | 1 | 2 | 2 | Microkernel |
| Pipe and filter | 4 | 4 | 4 | 3 | 3 | 3 | 2 | Pipe and Filter |
| Service-based (a few coarse services) | 3 | 3 | 3 | 4 | 3 | 4 | 4 | SOA |
| Event-driven | 2 | 3 | 3 | 4 | 4 | 4 | 4 | Event-Driven Architecture |
| Microservices | 1 | 1 | 2 | 5 | 5 | 5 | 5 | Microservices |
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 include | Lean toward | Warning |
|---|---|---|
| Time to market, small team, uncertain domain | Modular monolith | Enforce boundaries or it becomes a big ball of mud |
| Extensibility by third parties or per-customer variation | Microkernel | Plug-in contract must be versioned |
| Independent scaling or deployment of parts, many teams | Service-based, then microservices | The distributed-systems tax |
| Throughput over data in stages | Pipe and filter, stream processing | Back-pressure |
| Reacting to many independent events | Event-driven | Eventual 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?).
| Prototype | Walking skeleton / tracer code | Spike | |
|---|---|---|---|
| Goal | Learn about a risk or a UI | Prove the architecture end to end | Answer one technical question |
| Kept? | Thrown away | Kept and grown | Thrown away (the learning is kept as an ADR) |
| Quality bar | Low | Production structure, tests and CI | Low |
| Typical size | Days | One to two weeks | Hours to days |
| Output | A decision | A running pipeline plus the first slice | A measurement |
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 fileReal 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".
| Risk | Driver | Spike | Time box | Result feeds |
|---|---|---|---|---|
| Rule packs cannot be added without a redeploy | Extensibility | Load packs from a configuration list; add one in a branch | 1 day | ADR-002 |
| Kiosk network is unreliable | Availability | Replay a kiosk session with 30% packet loss | 2 days | Retry policy and idempotency key |
| Cheque provider API is slow | Payout correctness | Call sandbox 1 000 times | 1 day | Timeout and retry budget |
| Quote needs per-model data we do not have | Quote accuracy | Ask the business for 20 sample prices | 2 days | Data model of rule packs |
| Throughput claim "millions of users" | Scalability | Estimate with Capacity Estimation | Half a day | Whether 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) | Low | High | Derived |
|---|---|---|---|
| Registered users | 10 000 | 5 000 000 | |
| Quotes per active user per month | 1 | 1 | |
| Monthly active share | 20% | 5% | 2 000 to 250 000 quotes per month |
| Peak factor (campaign day) | 10 | 10 | |
| 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 size | 1 KB | 1 KB | 2 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:
| Artifact | Content | Where taught |
|---|---|---|
| Context and container view | System, users, external systems, deployable units | 4+1 views |
| Module view | Modules, allowed dependencies, data ownership | Modular Monolith |
| Runtime view | One sequence per top scenario | UML |
| Deployment view | Nodes, databases, queues | 4+1 views |
| ADRs | One page per significant decision with alternatives and consequences | Architecture Decisions |
| Driver list and scenarios | The reason for everything above | This page |
| Risk and assumption list | What may be wrong | This 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:
| Technique | How | Catches | Cost |
|---|---|---|---|
| Scenario walkthrough | For each top scenario, trace stimulus to response through modules and name each decision it relies on | Missing responsibilities, hidden coupling | Hours |
| ATAM-lite | Utility tree plus walkthrough of the (H,H) leaves plus a list of risks, non-risks, sensitivity and trade-off points | Unexamined drivers, trade-offs | Half a day |
| Spike or prototype | Measure the risky thing | Wrong assumptions | Days |
| Fitness function | An automated check of a quality (dependency rule, latency budget, schema rule) in CI | Drift over time | Hours to write |
| Review against the use cases ADD lists | One user two tasks, two users, startup, shutdown, disconnect, failure, upgrade | Forgotten responsibilities | Hours |
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 idThe 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-pattern | Symptom | Cure |
|---|---|---|
| Resume-driven design | The style appears before the drivers | Write the driver list first; justify the style from it |
| Big design up front | Months of diagrams, no running code | One iteration of ADD, then a walking skeleton |
| No design at all | The first framework choice is the architecture | A day of driver work before the first sprint |
| Everything is a priority | 14 drivers (H,H) | Renegotiate, as the ADD report advises for more than five or six |
| Ivory tower | Decisions without the team | ADRs reviewed in the pull request |
| Premature distribution | Network calls between things that change together | Modular monolith first (Monolith First) |
| Unfalsifiable drivers | "The system must be fast" | Scenario with a response measure |
Mechanics: the method as a procedure
The procedure in one page.
| # | Do | Stop when | Typical size |
|---|---|---|---|
| 1 | Collect inputs; mark assumptions; list questions for stakeholders | You can state the business goal in one sentence | 1 page |
| 2 | Build the driver list: candidate characteristics, then scenarios, then rank twice | At most 5 or 6 (H,H) | 1 page |
| 3 | Estimate capacity ranges | You know the order of magnitude per axis | 1 table |
| 4 | Open the whole system (ADD 2 to 7): patterns, tactics, children, interfaces | Every driver has an owner element | 1 diagram, 3 to 6 ADRs |
| 5 | Choose the riskiest child and repeat | The remaining children are routine | 1 to 3 more loops |
| 6 | Build the walking skeleton and run the spikes | Each top risk has an answer or a plan | 1 to 2 weeks |
| 7 | Walk the scenarios, run ATAM-lite | No unexamined (H,H) scenario | Half a day |
| 8 | Write fitness functions for the rules you rely on | CI fails when a rule is broken | A few tests |
| 9 | Review at each quarter or on a driver change | Driver list is still true | 1 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.
| Failure | Cause | Fix |
|---|---|---|
| Drivers keep changing | Priorities never agreed (ADD step 0, outside the method) | Return unranked requirements to stakeholders |
| Every scenario ranked high | No cost attached to priorities | Give each stakeholder limited votes (QAW) |
| Candidate cannot be tested | Response measures missing | Rewrite to the six-part scenario |
| Style chosen then drivers invented | Process run backwards | Re-run step 3 honestly |
| Skeleton never gets the second slice | Skeleton treated as a demo | Make 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 matters | Question for stakeholders |
|---|---|---|
| Team of six engineers, PHP and Go skills | Operability, style choice | Who runs production? |
| First release in four months | Time to market | Is a smaller first release acceptable? |
| Kiosks have a connection most of the time, short outages possible | Availability of quoting | Do kiosks need offline quoting? |
| Cheque payments via a provider API with idempotency keys | Payout design | Which provider? |
| Customer has 14 days to accept a revised quote | Workflow timers | Legal 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 green | Extensibility | (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 time | Data 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 peak | Performance | (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 minute | Auditability | (H,M) | Yes (cheap if designed in) |
| S5: First production release in 4 months with six engineers | Time 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 lost | Availability | (M,M) | Later |
| S7: Personal data of customers is encrypted at rest and access is logged | Security | (H,L) | Standard practice |
| S8: Remove device types not received for a year | Modifiability | (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
| Driver | Design concern | Tactic | Pattern considered | Verdict |
|---|---|---|---|---|
| S1 | Add behaviour without touching others | Defer binding, intermediary, restrict dependencies | Plug-in registry (microkernel), rules as data in a rules engine, microservice per device | Plug-in packs; rules-engine kept as an option |
| S2 | Duplicate requests | Idempotent operation, record outcome | Idempotency key, transactional outbox, saga | Key plus outbox |
| S4 | Reproduce history | Record inputs and version | Versioned result, event log | Store rule version with each quote |
| S5 | Fast first release | Reduce moving parts | Monolith First | One deployable |
Style scoring (Go matrix with weights extensibility 30, payout correctness 25, time to market 20, quote latency 15, operability 10):
| Style | Weighted score (0 to 100) |
|---|---|
| Modular monolith + plug-in rule packs | 86.0 |
| Layered monolith | 74.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
| Module | Responsibility | Provides | Requires | Owns data |
|---|---|---|---|---|
| Catalog | Accepted device types, rule packs, pack versions | Lookup(device), Accepted() | none | catalog.* |
| Quoting | Price a device, store versioned quote | RequestQuote(input), event quote.created | Catalog | quoting.* |
| Trade-in | Order, label, box, status, customer acceptance | Accept(quote), state machine | Quoting events | tradein.* |
| Inspection | Assess, re-quote, route to resell or recycle | Assess(box), event quote.revised | Catalog at the stored pack version | inspection.* |
| Payout | Create the cheque exactly once | Pay(tradeIn) (idempotent) | Trade-in events, payment provider | payout.* |
| Disposition | Resell on marketplace or send to recycling | List(item) | Inspection events | disposition.* |
| Notifications | Email and SMS from events | consumes events | Event stream | none |
| Identity | Customers and staff, roles | Authenticate | none | identity.* |
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
| Risk | Spike result (planned) | Outcome |
|---|---|---|
| R-A Old pack versions must stay loadable | Keep packs as files named by version | Packs registered by device@version; test fails if a version disappears |
| R-B Cheque provider has no idempotency | Confirm in sandbox | If absent, add our own ledger table with a unique key |
| R-C Kiosks lose connectivity | Replay session with packet loss | Decide on local retry in the kiosk client; deferred (S6 is (M,M)) |
| R-D Timer for customer acceptance | Worker polls tradein.deadlines | Added to ADR-005 |
| R-E Marketplace API rate limits | Read the API docs | Queue 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
| Trigger | Move | Pre-condition already in place |
|---|---|---|
| Marketplace listing blocks quoting during peaks | Extract Disposition behind its event stream | Module has own schema and events |
| Product owners need to edit rules daily | Introduce a rules engine behind RulePack | Pure interface |
| Kiosks need offline mode | Local queue plus idempotency keys | Idempotent API |
| Another country with different payout rules | New Payout pack per country | Payout isolated |
| Team grows past three squads | One squad per bounded context, consider extraction | Conway 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):
// 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:
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:
// 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):
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)
}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:
// 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()
}// 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):
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 := "ing.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{}), "ing.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
// 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
// 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/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
| Question | Go 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 registration | Explicit 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
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
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
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
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
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
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
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
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
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
| Question | Laravel 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 registration | A list in the module provider; tagged bindings with $this->app->tag(...) scale it |
| Transactions across modules | One local database transaction while it is one database; after extraction, outbox and events |
| Walking skeleton speed | php artisan serve, SQLite in memory for the first slice, PostgreSQL by day two |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Everything is a priority | Forced ranking | QAW votes (30% of scenarios), (H,H) cap of five or six | Honest trade-offs | Uncomfortable conversation |
| Requirements are vague ("fast") | Scenario rewrite | Six-part scenario with response measure | Testable | Needs stakeholder time |
| Nobody can say which requirements matter | Utility tree | Rate (importance, difficulty) | Shared ranking | Ratings are opinions; revisit |
| Style chosen by fashion | Characteristic fit table and ADR | Weighted matrix, rejected alternatives recorded | Auditable choice | Weights are subjective |
| Boundaries unclear | Bounded contexts and Conway check | Group by language, change rate, team | Fewer cross-module edits | Needs domain access |
| Design cannot be tested | Walking skeleton | One slice, real pipeline | Early feedback | Needs discipline to grow it |
| Fear of the unknown | Spikes | Time-boxed experiments | Cheap answers | Easy to over-run |
| Architecture drifts | Fitness functions | Arch tests and CI queries | Rules stay true | Maintenance of the tests |
| Decisions forgotten | ADRs | One page per decision | Memory | Must 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
| Situation | Recommendation | Technique | Reason |
|---|---|---|---|
| New product, uncertain domain, small team | Modular monolith, walking skeleton in week one | ADD with one iteration, ADRs | Learn boundaries cheaply |
| Many (H,H) scenarios | Renegotiate; split the system into subsystems and run ADD per subsystem | Step 2 element choice | ADD's own alarm |
| Quality requirement unclear | QAW or interviews | Scenario refinement | Cannot design for a wish |
| Big risk in one technology | Spike first | Time box | Cheapest evidence |
| Rewrite of an existing system | Incident review as an input, strangler path | ADR per slice | Real data on failures |
| Regulated domain | Treat audit as a driver from day one | Versioned records, immutable log | Retrofitting is expensive |
| Many teams, independent release cadence | Service-based or microservices after extraction | Conway check | Autonomy driver real |
| Short-lived system | Layered monolith, minimal documentation | ADR for one or two choices | Cost 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 monolith | What it costs after extraction |
|---|---|
| A transaction across Trade-in and Payout | Outbox, idempotent consumers, sagas |
| A function call | Network call, timeout, retry, version skew |
| One log, one debugger | Distributed tracing, correlation ids |
| One deploy | A 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
| Scale | Going Green shape | What the method re-checks |
|---|---|---|
| 1x (hundreds of users) | One app, one PostgreSQL, one worker | Drivers S1, S2, S4, S5 |
| 10x (tens of thousands) | Two app instances behind a load balancer, read replica for status pages, managed queue | Latency scenario S3, outbox lag |
| 100x (millions) | Extract Disposition and Notifications; cache rule packs; partition quoting.quotes by month | Peak factor, kiosk availability S6 |
| Beyond | Regional deployments, Payout in a home region | CAP trade-offs, compliance |
Lab: from a brief to a walking skeleton
Setup (PostgreSQL 16 or later, Go 1.24 or later):
CREATE DATABASE greengreen;
\c greengreen
\i docs/snippets/architecture/requirements-to-architecture/sql/schema.sql 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 enforcedThen 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Inputs | Functional requirements, constraints, quality scenarios, business drivers; all may be implied |
| ASR | Costly to change, structure-shaping; aim for five or six |
| Ranking | Importance by stakeholders, impact by architect, 3 by 3 grid, take (H,H) |
| QAW | 8 steps, 5 to 30 stakeholders, votes 30% of scenarios, refine top 4 or 5 |
| ADD | Plan, Do, Check; 8 steps; recursive per element |
| Step 4 | Pattern matrix; pattern close then tactics; else tactics |
| Step 6 | Interface equals provides and requires, semantics, errors |
| Tactics | Per attribute moves; patterns bundle them |
| Components | Bounded contexts, Conway check, owner and data rule |
| Style | Choose by fit, combine, record in an ADR |
| Skeleton | Thin, end to end, deployed, kept |
| Spike | Time-boxed, answers one question, thrown away |
| Capacity | Convert "millions" to requests per second and bytes, keep ranges |
| Validation | Walkthroughs, ATAM-lite, fitness functions |
| Documentation | Views plus ADRs plus drivers plus risks |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — 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
| Term | One 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 |
| ATAM | Architecture Tradeoff Analysis Method; evaluates an architecture against scenarios |
| ASR | Architecturally significant requirement: costly to change, shapes structure |
| Architectural driver | An ASR selected as the focus of a design iteration |
| Quality attribute scenario | Stimulus, source, artifact, environment, response, response measure |
| Utility tree | Tree from utility to attributes to scenarios rated by importance and difficulty |
| Tactic | A small design move that affects one quality attribute |
| Pattern | A named bundle of structure and tactics with known trade-offs |
| Discriminating parameter | A property used to choose between patterns (restart time, number of dependencies) |
| Design concept | The set of selected patterns and their relations in ADD step 4 |
| Bounded context | Area in which one model and vocabulary are consistent |
| Conway's law | Systems copy the communication structure of the organisation |
| Inverse Conway manoeuvre | Shaping teams to obtain the desired architecture |
| Walking skeleton | Tiny end-to-end implementation with real structure, kept and grown |
| Tracer bullet | Thin end-to-end code that shows where the design lands; kept |
| Prototype | Throw-away experiment about one question |
| Spike | Time-boxed experiment answering one technical question |
| Fitness function | Automated check that a quality or structure rule still holds |
| ADR | Architecture Decision Record: one page per significant decision |
| Kata | Short practice problem for architects (for example Going Green) |
| Microkernel | Core plus plug-ins registered through a contract |
| Transactional outbox | Event row written in the same transaction as the state change |
| Idempotency key | Identifier that makes a repeated request safe |
| Risk (ATAM sense) | Architecturally important decision not made or problematic |
| Sensitivity point | Property critical to achieving a quality response |
| Trade-off point | Property that is a sensitivity point for more than one attribute |
| Modular monolith | One deployable with enforced internal module boundaries |
| Monolith First | Fowler'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.
- Wojcik, Bachmann, Bass, Clements, Merson, Nord, Wood, Attribute-Driven Design (ADD), Version 2.0, CMU/SEI-2006-TR-023: https://www.sei.cmu.edu/documents/775/2006_005_001_14795.pdf (read in full; saved as
sei-add2.txt). - SEI, A Practical Example of Applying Attribute-Driven Design (ADD), Version 2.0: https://www.sei.cmu.edu/library/file_redirect/2007_005_001_14867.pdf/ (fetched, not quoted).
- Barbacci, Ellison, Lattanze, Stafford, Weinstock, Wood, Quality Attribute Workshops (QAWs), Third Edition, CMU/SEI-2003-TR-016: https://www.sei.cmu.edu/documents/716/2003_005_001_14249.pdf
- Kazman, Klein, Clements, ATAM, CMU/SEI-2000-TR-004: https://insights.sei.cmu.edu/documents/629/2000_005_001_13706.pdf (via the sibling chapter).
- Martin Fowler, Monolith First: https://martinfowler.com/bliki/MonolithFirst.html ; MicroservicePremium: https://martinfowler.com/bliki/MicroservicePremium.html ; Bounded Context: https://martinfowler.com/bliki/BoundedContext.html ; Conway's Law: https://martinfowler.com/bliki/ConwaysLaw.html
- Hunt and Thomas, The Art in Computer Programming (tracer bullets): https://media.pragprog.com/articles/other-published-articles/ArtInProgramming.pdf ; Artima interview Tracer Bullets and Prototypes: https://www.artima.com/articles/tracer-bullets-and-prototypes
- Going Green kata (public copy that links to the companion site): https://github.com/marckoch/going-green ; companion site: https://fundamentalsofsoftwarearchitecture.com/katas/kata?id=GoingGreen (JavaScript page, text not extractable); nealford.com/katas returned a GitHub Pages error when fetched.
- Software Architecture Guild, Architecture Characteristics: https://software-architecture-guild.com/guide/architecture/fundamentals/architecture-characteristics/ (secondary summary of explicit and implicit characteristics).
- Shopify Engineering, Under Deconstruction: The State of Shopify's Monolith (16 Sep 2020): https://shopify.engineering/shopify-monolith
- Segment, Goodbye Microservices: From 100s of problem children to 1 superstar: https://segment.com/blog/goodbye-microservices/
- Laravel 13 documentation, Database (
DB::transaction) and Service Providers (bootstrap/providers.php): https://laravel.com/docs/13.x/database , https://laravel.com/docs/13.x/providers (read through the raw docs repository because laravel.com serves a bot check). - Pest architecture testing: https://pestphp.com/docs/arch-testing
- Not read, cited from general knowledge and labelled above: Cockburn's Walking Skeleton page (404), Richards and Ford Fundamentals of Software Architecture (book not accessible), Bass, Clements, Kazman Software Architecture in Practice tactics chapters, Newman Building Microservices (not used for quotes), Conway's 1968 article (via Fowler).