Architecture Decisions: Trade-offs, ADRs, Second-Order Effects, 'No Perfect Architecture'
"It's better to avoid either blind acceptance or blind reversal." — Michael Nygard, Documenting Architecture Decisions, 15 November 2011
Summary: Architecture is a stream of decisions under uncertainty; there is no perfect architecture, only the least-worst set of trade-offs for a context, written down with its consequences and guarded by tests so that the next person can keep it or reverse it on purpose. Focus: What makes a decision architectural, one-way versus two-way doors, a repeatable trade-off analysis, second- and third-order effects, decision timing (last responsible moment, options, cost of delay), ADRs in depth (Nygard, MADR, Y-statements, lifecycle, storage, review, anti-patterns), RFC processes at team scale, technical debt and sacrificial architecture as deliberate choices, fitness functions, and four worked decisions with full ADRs and Go and Laravel tests. Learning goal: Given a real decision on your project, classify its reversibility, run a scored trade-off analysis, list its second- and third-order effects, write an ADR a stranger can understand in two years, and add one automated test that fails when the decision is silently broken.
This is the third chapter of AR 01. What Software Architecture Is says architecture is "the decisions that are hard to change"; Kruchten's 4+1 views shows how to describe the structures those decisions create. This page teaches how to make and record the decisions themselves. The next chapter, From Requirements to Architecture, takes the decision drivers used here and derives them from requirements; Quality Attributes defines the "-ilities" we score against. The design-side view of ADRs and reversibility is in Architecture vs Design; here we go deep.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why decisions need a method at all | Why it exists |
| Nygard, Bezos's doors, Poppendieck, Fowler, Richards and Ford, MADR | Where it comes from |
| What counts as an architecture decision | Architecture decision |
| One-way and two-way doors | Reversibility |
| A trade-off method that is not "it depends" | Trade-off analysis |
| Microservices → sagas, events → UX, caching → stale reads | Second-order effects |
| When to decide | Decision timing |
| ADR templates, lifecycle, storage, review, anti-patterns | ADRs |
| Rust RFCs, Uber, Oxide RFDs, advice process | RFCs at team scale |
| Debt you take on purpose; code you plan to throw away | Technical debt, Sacrificial architecture |
| Tests that guard decisions | Fitness functions |
| Tactics, ATAM, sensitivity points | Tactics and ATAM |
| Anchoring, sunk cost, confirmation bias | Biases |
| Scoring matrix, ADR tooling, failure messages | Mechanics |
| Four full ADRs: PostgreSQL vs MongoDB, REST vs events, monolith vs modular, Go vs PHP | Worked decisions |
| Decisions enforced as tests | Go, Laravel |
| Paralysis, HiPPO, stale ADRs, drift | Solving the classic problems |
| How much process for which decision | Choosing |
| Monolith to distributed system | In architecture |
| Write three ADRs and three fitness tests | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Architecture decision | A choice that is significant, costly to reverse or cross-cutting | "Orders live in PostgreSQL" | Big choices are made in a chat thread and forgotten |
| One-way door (Type 1) | A decision you cannot easily walk back through | Public API shape used by partners | Treated casually, it locks you in for years |
| Two-way door (Type 2) | A decision you can reverse cheaply | Which retry library to use | Treated heavily, it slows everything down |
| Trade-off analysis | Scoring options against the qualities that matter | Score PostgreSQL vs MongoDB on 6 characteristics | "It depends" without saying on what |
| Second-order effect | The consequence of the consequence | Microservices → no shared transaction → sagas | Surprise work lands on another team |
| Last responsible moment | Decide when waiting longer would remove a good option | Pick the broker when the first async flow is built | Decide too early on guesses, or too late by default |
| ADR | A short, numbered record of one decision and why | 0003-async-events-orders-notifications.md | Blind acceptance or blind reversal later |
| RFC / RFD | A proposal circulated for comment before deciding | Rust RFC with a final comment period | Cross-team decisions surprise the teams |
| Fitness function | An automated check that a decision still holds | A test that fails if domain imports database/sql | The decision erodes one pull request at a time |
| Deliberate technical debt | A shortcut taken knowingly with a payback plan | "Ship with one shared schema, split in Q3" | Debt nobody chose, interest nobody tracks |
| Sacrificial architecture | Building something you expect to replace | Version 1 sized for 10x, not 100x | Over-engineering, or shame when it is replaced |
The laws in one table.
| Statement | Source | What it means for you |
|---|---|---|
| "everything in software architecture is a trade-off" | Mark Richards, InfoQ podcast (the first law from Fundamentals of Software Architecture) | A proposal with no cons has not been analysed |
| "why is more important than how" | Richards (the second law), same podcast | Record the reasons, not only the diagram |
| Find "the least worst combination" of forces | Neal Ford, Tech Lead Journal #120 | Aim for least-worst, not best |
| "never use a one-size-fits-all decision-making process" | Jeff Bezos, 2016 shareholder letter | Heavy process only for one-way doors |
| Delay commitment until "the moment at which failing to make a decision eliminates an important alternative" | Mary and Tom Poppendieck, quoted by Jeff Atwood | Decide late, but not by default |
| ADRs are "numbered sequentially and monotonically" and superseded, not deleted | Nygard 2011 | The log is history; never rewrite it |
Four decisions, worked on this page.
| Decision | Chosen | Main thing given up | Second-order effect we must pay for | Guard |
|---|---|---|---|---|
| Monolith vs modular monolith vs microservices | Modular monolith | Independent deploy per team | Boundaries must be policed by tests | TestModulesTalkThroughAPIOnly, Pest arch() |
| PostgreSQL vs MongoDB for orders | PostgreSQL | Schema-free documents, built-in sharding | Migrations discipline; JSONB for the flexible part | Driver-import test; CHECK constraints |
| Sync REST vs async events | Events via outbox | Immediate consistency of notifications | Idempotent consumers, DLQ, "pending" states | TestNotificationsDependsOnEventsOnly |
| Go vs PHP for a service | Depends on the service; worked: Go for the webhook ingester, PHP for the back office | Single-language team | Two toolchains, two hiring profiles | CI matrix, ownership in CODEOWNERS |
Why it exists
Every system ends up with an architecture; the only question is whether the decisions behind it were made on purpose. Decisions differ in how expensive they are to reverse and how many people they touch, and they all have hidden costs that appear later and elsewhere. A decision method exists for three reasons: to spend care where reversal is expensive, to surface costs before they surprise someone, and to leave a record so the next person neither worships nor bulldozes the decision.
| Deciding by instinct | Deciding with a method |
|---|---|
| Fast for the first decision | Slightly slower for each important decision |
| Strong opinions win ("HiPPO": highest-paid person's opinion) | Criteria agreed before options are compared |
| Only first-order effects are seen | Second- and third-order effects are listed |
| Reasons live in one head; they leave with that person | Reasons live in the repository, next to the code |
| Every decision gets the same treatment | Process scales with reversibility and blast radius |
| Erosion is noticed in production | Erosion fails a test in CI |
The analogy we reuse on this page: choosing where to live. Renting a flat for a year is a two-way door: if you hate the street, you move. Buying a house with a 25-year mortgage is a one-way door: walking back costs fees, time and money. Sensible people spend an evening on the first decision and months on the second, visit the street at night (a spike), write down why they chose it (an ADR), and know that a cheap house far from work costs them two hours a day in commuting forever (a second-order effect). There is no perfect house; there is the least-worst one for your family, budget and job.
Three common misunderstandings, up front
- "There is a best architecture and experts know it." Richards and Ford's first law says the opposite: every option buys some qualities with others. Ford's corollary on Tech Lead Journal: "if you think you found something that doesn't have trade-offs, it probably just means you haven't figured out what those trade-offs are yet."
- "ADRs are approvals." An ADR is a record of reasoning, written by the people who decide; it is not a form an architecture board signs. Turning it into a gate makes teams stop writing them (see anti-patterns).
- "Deciding later is always better." Waiting has a price (cost of delay), and beyond the last responsible moment "decisions are made by default". Late is good only up to that moment.
Where it comes from
Alexandrian patterns and forces, 1970s. Nygard's ADR format is "similar to an Alexandrian pattern" because both balance forces; the vocabulary of "forces" and "context" comes from Christopher Alexander's pattern language.
SEI, quality attributes, tactics and ATAM. The Software Engineering Institute's Architecture Tradeoff Analysis Method (ATAM) turns business drivers into quality attribute scenarios and analyses "trade-offs, sensitivity points, and risks" (Wikipedia, secondary). Bachmann, Bass and Klein's 2003 reports describe tactics, design decisions aimed at one quality attribute, and note that "Applying tactics results in the addition of new responsibilities", the formal version of a second-order effect.
Lean, 2003. Mary and Tom Poppendieck's Lean Software Development introduced the last responsible moment; we read it as quoted by Jeff Atwood (secondary).
Fowler, Technical Debt Quadrant, 14 October 2009. Debt can be "reckless" or "prudent", "deliberate" or "inadvertent"; "The prudent debt example is deliberate because the team knows they are taking on a debt".
Nygard, 15 November 2011. Documenting Architecture Decisions proposed short, numbered records with Title, Context, Decision, Status and Consequences, kept in the repository.
Fowler, Sacrificial Architecture, 20 October 2014. "often the best code you can write now is code you'll discard in a couple of years time", with eBay's Perl → C++ → Java history and Jeff Dean's "design for ~10X growth, but plan to rewrite before ~100X".
Bezos, 2015 and 2016 shareholder letters. Type 1 (one-way door) and Type 2 (two-way door) decisions, the "70% of the information" rule and "disagree and commit".
Uber RFCs and Rust RFCs, 2010s. Rust requires "substantial" changes to go through an RFC with a final comment period; Gergely Orosz describes Uber's RFC process scaling "from tens of engineers to the low thousands".
Richards and Ford, 2020 and 2021. Fundamentals of Software Architecture coined the two laws; Software Architecture: The Hard Parts (with Sadalage and Dehghani) is built around trade-off analysis, every chapter ending in an ADR. We quote the authors from interviews, not from the books, which we did not have.
MADR 4.0.0, 17 September 2024; Fowler's ADR bliki, 24 March 2026. MADR (Markdown Architectural Decision Records) 4.0.0 includes a "Confirmation" section asking how compliance "can/will be confirmed", explicitly mentioning fitness functions. Fowler's bliki entry adds the "inverted pyramid" style and recording "the confidence level of the decision".
Year Idea What changed in practice
1 1977 Alexander: patterns balance forces "Context" and "forces" as vocabulary
2 - SEI ATAM Trade-offs, sensitivity points, risks
3 2003 Poppendieck: last responsible moment Decide late, but not by default
4 2003 Bachmann, Bass, Klein: tactics Each tactic adds responsibilities
5 2009 Fowler: technical debt quadrant Deliberate, prudent debt is a decision
6 2011 Nygard: ADRs Decisions recorded in the repo
7 2014 Fowler: sacrificial architecture Planned replacement is not failure
8 2015 Bezos: one-way and two-way doors Process scales with reversibility
9 2020 Richards and Ford: laws of architecture Everything is a trade-off; why over how
10 2024 MADR 4.0.0 with "Confirmation" ADRs link to fitness functions
11 2026 Fowler's ADR bliki Inverted pyramid, confidence levelThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, what provides it, and the fix.
Architecture decision Must-know
In plain words: an architecture decision is a choice that many things will depend on, that costs a lot to undo, or that cuts across several parts of the system.
Common misunderstanding: "Architecture decisions are about technology." Many are not: data ownership, team boundaries, consistency guarantees, what to build versus buy. And many technology choices are not architectural: a JSON library behind an interface is a two-way door.
Definition: Nygard records decisions that are "architecturally significant": "those that affect the structure, non-functional characteristics, dependencies, interfaces, or construction techniques". adr.github.io defines an architectural decision as "a justified design choice that addresses a functional or non-functional requirement that is architecturally significant" and an architecturally significant requirement (ASR) as one with "a measurable effect on the architecture and quality" of the system. Ford adds a test: an architecture decision is "one where all the possibilities have serious trade-offs associated with" them. Three practical markers:
| Marker | Question | Example |
|---|---|---|
| Significant | Does it change a quality attribute (availability, latency, security, cost)? | Synchronous call from checkout to fraud scoring |
| Costly to reverse | Would undoing it take more than a sprint or touch stored data? | Choosing MongoDB, then moving to PostgreSQL |
| Cross-cutting | Do several modules, teams or clients depend on it? | Event envelope format, authentication scheme |
Moment What happens Was it a decision?
1 Week 1 Dev adds Redis "just for sessions" Yes, implicitly (new runtime dependency)
2 Week 6 Three features cache data in the same Redis Yes, implicitly (shared infrastructure)
3 Week 20 Redis eviction drops sessions under load Consequence of 1 + 2, nobody chose it
4 Week 21 Postmortem: "who decided Redis is a cache AND a session store?" Nobody; it accumulatedReal scenario: a team adds a cron job that reads another module's tables "temporarily"; a year later four reports depend on that schema and the owning module cannot rename a column. A Laravel app grows DB::connection('legacy') calls in twelve places. A Go service starts calling a partner API synchronously inside a database transaction; when the partner slows down, connection pools drain.
What provides it:
| Practice | What it gives |
|---|---|
| A short "is this architectural?" checklist in the PR template | Implicit decisions become visible |
| ADR log in the repository | A place to put the visible decision |
CODEOWNERS on docs/decisions/ and on boundary code | The right people see changes |
| Fitness functions | The decision stays true after the meeting |
Fix / how to use it: when a PR adds a runtime dependency, a new datastore, a new network call between modules, or changes a public contract, stop and write an ADR (half a page is fine).
One-way and two-way doors: reversibility Must-know
In plain words: before deciding, ask "if this is wrong, how do we get out, and how much will it cost?" Cheap exits deserve fast decisions; expensive exits deserve slow ones.
Common misunderstanding: "Important decisions need careful process; the rest can be skipped." The mistake that hurts most is the opposite. Bezos: "As organizations get larger, there seems to be a tendency to use the heavy-weight Type 1 decision-making process on most decisions, including many Type 2 decisions. The end result of this is slowness, unthoughtful risk aversion, failure to experiment sufficiently".
Definition: from the 2015 letter:
"Some decisions are consequential and irreversible or nearly irreversible – one-way doors – and these decisions must be made methodically, carefully, slowly, with great deliberation and consultation. [...] But most decisions aren't like that – they are changeable, reversible – they're two-way doors." — Jeff Bezos, 2015 Letter to Amazon Shareholders
The 2016 letter adds that "most decisions should probably be made with somewhere around 70% of the information you wish you had" and "disagree and commit". Reversibility has two axes: cost to reverse (time, data migration, client changes) and blast radius (teams, services and external clients affected).
Step Two-way door: retry library One-way door: public order API v1
1 Day 0 Dev opens a PR with library X Proposal ADR + RFC to partner teams
2 Day 1 Review, merge, deploy behind a flag Spike: two clients built against draft
3 Day 7 Library leaks goroutines: revert PR Comments: pagination, idempotency keys
4 Day 7 Total cost: one day Week 4: accepted; contract tests published
5 - - Year 2: 40 partners; change needs v2 + 12 months deprecationReal scenario: the primary database engine, the tenancy model (shared schema vs schema per tenant), event schemas consumed by other teams, the identity of entities (UUID vs bigint exposed in URLs), and the split into services are one-way doors. Feature-flagged UI, internal helper APIs, logging libraries, and a Redis key layout with TTLs are two-way doors.
What provides it (turning one-way doors into two-way ones):
| Technique | How it lowers cost to reverse | Example |
|---|---|---|
| Port and adapter (interface) | Swap the implementation behind it | app.Store in the Go example; PostgreSQL adapter is one package |
| Feature flag | Turn behaviour off without deploying | New checkout flow at 5% of traffic |
| Expand / contract migrations | Old and new schema live side by side | Add column, dual-write, backfill, switch reads, drop |
| Strangler fig | Replace a system route by route | Strangler Fig |
| Versioned contracts | Old clients keep working | orders.order_placed.v1 beside v2 |
| Spike / prototype | Learn before committing | One-week PostgreSQL vs MongoDB load test |
Fix / how to use it: classify every decision on the matrix first. For one-way doors, spend the time; for two-way doors, let one person decide in a PR. When a decision is a one-way door, look for an adapter, flag or versioning scheme that makes it two-way before you debate it.
Trade-off analysis: "it depends", done rigorously Must-know
In plain words: list what matters, list the options, score each option on each thing that matters, weigh, and pick the option whose weaknesses you can live with. Say "it depends on X and Y" and then measure X and Y.
Common misunderstanding: "Trade-off analysis is a pros-and-cons list." A list does not tell you which pros matter more, and it lets the author leave out inconvenient cons. Ford on InfoQ: "If a tech leader, developer or another architect brings me a solution that's all pros, I push back".
Definition: a structured comparison of options against architecture characteristics (Richards: "those -ilities – scalability, performance – those characteristics that are orthogonal to the actual domain functionality") plus constraints (budget, skills, deadlines, regulation). Richards: "You can't make an architectural decision without knowing those architectural characteristics." Ford's goal is "the least worst solution, not the best solution". The method on this page:
| Step | What you do | Output | Trap to avoid |
|---|---|---|---|
| 1 Frame | Write the question; classify the door | One sentence + reversibility | Solving a different problem than the one asked |
| 2 Drivers | List characteristics and constraints, MECE (mutually exclusive, collectively exhaustive) | 4-8 drivers with weights | Overlapping drivers counted twice ("speed" and "latency") |
| 3 Options | At least three, including "do nothing" or "defer" | Option list | A favourite plus two straw men |
| 4 Score | Each option per driver, -2..+2, with evidence | Matrix | Scores without evidence; one person scoring alone |
| 5 Weigh | Weighted sum, then sensitivity check: does the winner change if a weight moves by 1? | Ranked options | Treating the number as truth |
| 6 Record | ADR: context, decision, consequences, rejected options | ADR file | Recording only the winner |
| 7 Guard | Fitness function + review-by date | Test, calendar entry | Decision erodes silently |
T Architect Product owner
1 t0 "Credit applications: sync or async?"
2 t1 Drivers: availability 3, consistency 2, latency 1
3 t2 Sync: never loses an application? No: rejects when scoring is down
4 t3 Async: always accepts, decision arrives later
5 t4 "Is it more important to always accept, or to answer instantly?" "Always accept."
6 t5 ADR-0012 accepted: async with status page; consequence: "pending" UXRichards gives exactly this example on InfoQ: bringing technical trade-offs to a business question such as "is it more important that we be able to always accept a credit application regardless, or that the credit application process is guaranteed to be started, pick one."
Real scenario: choosing between orchestration and choreography for a refund flow; between a shared library and a duplicated module; between one Kafka topic per event type or per aggregate; between Laravel Octane and PHP-FPM for an API with 2 ms of business logic.
What provides it:
| Tool | When | Note |
|---|---|---|
| Weighted decision matrix (Pugh matrix) | 3-5 options, 4-8 drivers | Shown in Mechanics |
| Quality attribute scenarios | When "fast" or "available" is vague | See Quality Attributes |
| ATAM workshop | Large, high-stakes systems | See Tactics and ATAM |
| Spike | When a score has no evidence | Time-boxed, throwaway code |
| MADR "Pros and Cons of the Options" | Recording the analysis | "Good, because", "Bad, because", "Neutral, because" |
Fix / how to use it: never present one option. Write the drivers and weights before the options, have two people score independently, and record the rejected options in the ADR.
Second- and third-order effects Must-know
In plain words: the first effect of a decision is the one you wanted. The second is what that effect causes, often in another team's backlog. The third is what that causes, usually in operations, support or UX.
Common misunderstanding: "Consequences are the pros and cons we listed." Pros and cons are usually first-order. Nygard asks for "All consequences [...] not just the 'positive' ones", and notes that "The consequences of one ADR are very likely to become the context for subsequent ADRs": second-order effects are the next decisions you will be forced to make.
Definition: an n-th order effect is a consequence reached by following n causal links from the decision. The SEI tactics work says it formally: "Applying tactics results in the addition of new responsibilities that must be treated by every reasoning framework". Every new responsibility needs an owner.
| Decision | 1st order (wanted) | 2nd order | 3rd order | Who pays |
|---|---|---|---|---|
| Split orders and payments into microservices | Independent deploys | No shared transaction → distributed transactions → sagas | Compensations, semantic locks, a dashboard for stuck sagas, on-call runbooks | Both teams, SRE, support |
| Event-driven integration | Decoupled teams, absorbs spikes | Eventual consistency: data lags by ms to minutes | UI shows "pending"; support needs a tool to see where an order is; idempotent consumers, DLQ | Frontend, support, every consumer |
| Cache product pages in Redis | 10x fewer DB reads | Invalidation on every write path | Stale reads after price changes; stampede on expiry; versioned keys and TTL jitter (Caching) | Every team writing product data |
| Read replicas for reporting | Primary offloaded | Replica lag | "I saved it but it's not there": read-your-writes routing (Replication) | Backend, QA |
| Multi-tenant shared schema | Cheap onboarding | Every query needs tenant_id | Row-level security, noisy neighbours, per-tenant export tooling | Every developer, forever |
| Choose MongoDB for flexibility | No migrations for new fields | Schema lives in application code | Readers must handle every historical shape; data quality checks | Every reader, analytics |
Week Decision: "notifications listens to OrderPlaced instead of being called"
1 0 Orders no longer waits for the mail server (1st order, wanted)
2 1 Consumer can see the event twice (at-least-once) -> inbox table needed (2nd)
3 2 Event can arrive before the order row is visible on a replica -> read from primary (2nd)
4 4 Support asks "did the customer get the mail?" -> processed_events must be queryable (3rd)
5 6 A malformed event blocks the queue -> DLQ + an owner for the DLQ (3rd)Real scenario: Fowler's Microservice Trade-Offs (1 July 2015) lists the second-order costs of microservices directly: "Distribution: Distributed systems are harder to program, since remote calls are slow and are always at risk of failure", "Eventual Consistency: [...] everyone has to manage eventual consistency", "Operational Complexity: You need a mature operations team".
What provides it:
| Technique | How |
|---|---|
| "And then what?" chain | For each first-order effect, ask "and then what?" twice; write each answer as a row |
| Ask the neighbours | Send the draft ADR to the teams who receive the 2nd- and 3rd-order work (that is what an RFC is for) |
| Pre-mortem | "It is a year later and this decision failed. Why?" Each answer is a candidate effect |
| Consequences template | Columns: effect, order, owner, mitigation, accepted? |
Fix / how to use it: every ADR on this page carries a second-order effects table. If an effect has no owner, the decision is not finished.
Decision timing: last responsible moment, options, cost of delay Important
In plain words: decide as late as you safely can, because you will know more; but not later, because waiting also costs, and at some point the decision makes itself.
Common misunderstanding: "Last responsible moment means procrastinate." Atwood: "Making decisions at the Last Responsible Moment isn't procrastination". The other misunderstanding is "decide everything in sprint zero": early decisions are made on the least information.
Definition: the Poppendiecks (as quoted by Atwood): "delay commitment until the last responsible moment, that is, the moment at which failing to make a decision eliminates an important alternative. If commitments are delayed beyond the last responsible moment, then decisions are made by default". Options thinking treats a design that keeps choices open (an interface, a feature flag) as buying an option: it costs a little now and lets you choose later. Cost of delay (Don Reinertsen, via Wikipedia, secondary) is "a way of communicating the impact of time on the outcomes we hope to achieve"; CD3 is cost of delay divided by duration, used to order work.
Week Broker decision for a new product (RabbitMQ vs Kafka)
1 1 No async flow exists yet. Deciding now = guessing. Too early
2 3 Outbox table written; relay publishes to an interface. Option bought cheaply
3 6 First consumer needs replay of 30 days -> Kafka fits better. Information arrives
4 7 Decide. Next week three consumers start coding against it. Last responsible moment
5 10 Not decided: each team picked its own (Redis, SQS, RabbitMQ). Decided by defaultReal scenario: the database engine must be chosen before the first migration, but the sharding strategy can wait until data volume is measured; the API style for internal calls can wait until the second service exists; the multi-region strategy can wait until a customer contract requires it, but the ID scheme that makes multi-region possible (globally unique IDs) is cheap to choose now.
What provides it:
| Tool | Buys | Cost |
|---|---|---|
| Interface / port | Engine or vendor choice later | One indirection |
| Outbox table with a pluggable relay | Broker choice later | A table and a poller |
| UUIDv7 / ULID IDs | Later sharding or multi-region | Larger keys than bigint |
| Feature flags | Rollout and rollback decisions later | Flag debt; remove them |
| A walking skeleton | Real measurements before committing | A week |
Fix / how to use it: for each pending decision write "decide by" (the event that would remove an option) next to it in the decision backlog; review the backlog in planning.
ADRs: Architecture Decision Records Must-know
In plain words: one short file per decision, in the repository, written for a developer who joins in two years and asks "what were they thinking?"
Common misunderstanding: "ADRs are documentation we write after the fact." Fowler's 2026 bliki: "perhaps even more valuable, the act of writing them helps to clarify thinking, particularly with groups of people." Write the ADR while deciding; status "proposed" exists for that.
Definition: Nygard 2011: "An architecture decision record is a short text file in a format similar to an Alexandrian pattern. [...] Each record describes a set of forces and a single decision in response to those forces." Five parts: Title ("short noun phrases"), Context ("the forces at play, including technological, political, social, and project local", "value-neutral"), Decision ("in full sentences, with active voice. 'We will …'"), Status ("proposed", "accepted", "deprecated" or "superseded"), Consequences ("All consequences should be listed here, not just the 'positive' ones"). Length: "one or two pages". Rules: "ADRs will be numbered sequentially and monotonically. Numbers will not be reused." and "If a decision is reversed, we will keep the old one around, but mark it as superseded."
The three common templates:
| Template | Sections | Best for |
|---|---|---|
| Nygard | Title, Status, Context, Decision, Consequences | Most teams; start here |
| MADR 4.0.0 | Optional front matter (status, date, decision-makers, consulted, informed), Context and Problem Statement, Decision Drivers, Considered Options, Decision Outcome, Consequences, Confirmation, Pros and Cons of the Options, More Information | Decisions where rejected options matter; links to fitness functions via "Confirmation" |
| Y-statement (Zdun et al.) | One sentence: In the context of <use case>, facing <concern> we decided for <option> to achieve <quality>, accepting <downside>. | Summary line at the top of a longer ADR; decision logs in a table |
MADR's front matter distinguishes consulted ("with whom there is a two-way communication") and informed ("with whom there is a one-way communication"), a RACI-like split that answers "who was asked?" later.
Lifecycle:
| Status | Meaning | Who changes it | Typical trigger |
|---|---|---|---|
| Proposed | Under discussion, open PR | Author | Draft written |
| Accepted | Agreed and in force | Decision makers on merge | Review consensus |
| Rejected | Considered and not chosen (MADR lists it) | Decision makers | Better option found |
| Deprecated | No longer relevant, nothing replaces it | Owner | The concern disappeared (feature removed) |
| Superseded by ADR-N | Replaced by a newer decision | Author of ADR-N | Context changed |
Fowler 2026: "Once an ADR is accepted, it should never be reopened or changed - instead it should be superseded. That way we have a clear log of decisions and how long they governed the work."
Storing and linking. Nygard used doc/arch/adr-NNN.md; Fowler names doc/adr as "A common choice"; MADR suggests docs/decisions/NNNN-title-with-dashes.md ("we assume that there won't be more than 9,999 ADRs in one repository"); adr-tools uses doc/architecture/decisions (adr init doc/architecture/decisions). Link both ways: the ADR names the packages and tests that implement it, and the code names the ADR (// ADR-0003 in the Go and PHP files on this page). Fowler notes the limit: "Storing them in a product repository won't work for ADRs that cover a broader ecosystem than a single code base"; cross-repo decisions go in a shared decisions repository or the RFC system.
Day ADR-0003 "Async events between orders and notifications"
1 1 Author opens PR: docs/decisions/0003-async-events.md, Status: Proposed
2 2 Reviewers from notifications and SRE comment: "who owns the DLQ?"
3 3 Consequences updated: DLQ owned by notifications, alert at 1 message
4 4 Merged with Status: Accepted, Review-by: 2027-06-01; archtest added in same PR
5 400 Notifications moves to its own service; ADR-0011 supersedes 0003; 0003 gets
"Superseded by ADR-0011", nothing else editedReviewing an ADR (checklist):
| Check | Question |
|---|---|
| Problem | Is the question stated so someone outside the team understands it? |
| Drivers | Are the drivers MECE and weighted? Are constraints separated from wishes? |
| Options | Are there at least two serious alternatives, plus "do nothing"? |
| Evidence | Does each important score cite a spike, a benchmark, a doc or an incident? |
| Consequences | Are negative and second-order effects listed with owners? |
| Confidence | Is the confidence level stated (Fowler recommends it)? |
| Reversal | Is there a revisit trigger or review-by date? |
| Confirmation | Is there a fitness function or review step that will notice a violation? |
ADR anti-patterns
| Anti-pattern | Symptom | Fix |
|---|---|---|
| ADR as approval form | Teams wait weeks for a board; ADRs written after the fact to satisfy it | The deciding team writes and merges; the board reads and comments (advice process) |
| Stale ADR | Accepted ADR contradicts the code | Review-by date; adrlint reports stale ADRs; fitness tests |
| Rewriting history | Accepted ADR edited to match a new decision | Supersede; keep the old file |
| Novel | 12 pages, nobody reads it | One page; link the spike; "inverted pyramid" |
| Sales pitch | Only pros; rejected options missing | MADR's "Considered Options" and "Bad, because" |
| Everything is an ADR | 300 ADRs, 280 of them two-way doors | Only architecturally significant decisions; small ones in PR descriptions |
| Retroactive justification | Context written to fit a decision already shipped | Fine for archaeology, but label it "recorded after the fact" |
| Orphan ADR | Nobody knows who owns it | decision-makers front matter; CODEOWNERS |
Fix / how to use it: add docs/decisions/ with a template and 0001-record-architecture-decisions.md (the decision to use ADRs, as adr-tools does), lint the folder in CI with the Go adrlint, and require an ADR link in PRs that touch boundaries.
RFCs at team scale: Rust, Uber, Oxide Important
In plain words: an RFC is an ADR's bigger sibling: a proposal circulated before the decision to everyone affected, with a defined comment period. ADRs record; RFCs consult.
Common misunderstanding: "RFCs are for open source only." Gergely Orosz on Uber: the process "both works and scales really well, from a handful of engineers to teams of thousands", and "Larger tech companies, like Google, Facebook, Microsoft or Amazon all came up with something that resembles some level of RFC process. Google calls it design docs".
Definition and three real processes:
| Process | Trigger | Steps and states | Distinctive rule |
|---|---|---|---|
| Rust RFCs | "Some changes though are 'substantial', and we ask that these be put through a bit of a design process and produce a consensus" | PR to rust-lang/rfcs → discussion → motion for final comment period (FCP) with a disposition (merge, close, postpone) → FCP → merged or closed; "postponed" label | "The FCP lasts ten calendar days"; all sub-team members sign off before FCP; accepted RFCs "should not be substantially changed" |
| Uber RFCs (per Orosz) | Any planned project with architecture impact | Template → sent to domain mailing lists (backend, mobile, web) → anyone comments → "Development only starts after the RFC is approved" | Templates evolved from repeated reviewer questions ("How will this be tested?") |
| Oxide RFDs | Any idea, "timely rather than polished" (quoting IETF RFC 3) | Six states: prediscussion, ideation, discussion, published, committed, abandoned | Discussion happens in the PR that integrates the RFD |
| ADR + advice process (Fowler 2026) | A decision by one team affecting others | Author seeks advice, decides, records advice summary in the ADR | "the act of writing them is used to elicit expertise and alignment" |
Day RFC "Move order events to Kafka" (cross-team, one-way door)
1 0 Author: problem, drivers, 3 options, recommendation, open questions
2 1 Sent to backend + data + SRE lists; RFC state: discussion
3 5 Data team: "we need 30-day replay" (new driver, changes scores)
4 9 Motion for final comment period: disposition = merge
5 19 FCP closes quietly; RFC accepted; ADR-0014 written in each affected repoReal scenario: a payments team wants to change the idempotency-key header used by six client teams; a platform team proposes a new service template; a company moves from one shared PostgreSQL cluster to database per service.
Fix / how to use it: use an RFC when the decision crosses team boundaries or is a one-way door for others; finish every RFC with ADRs in the repositories it affects, so the decision lives next to the code.
Technical debt as a deliberate decision Important
In plain words: taking a shortcut on purpose, knowing you will pay interest on it, can be a good architecture decision, if you write it down and plan the payback.
Common misunderstanding: "All technical debt is bad code." Fowler: "the useful distinction isn't between debt or non-debt, but between prudent and reckless debt", and "The prudent debt to reach a release may not be worth paying down if the interest payments are sufficiently small - such as if it were in a rarely touched part of the code-base."
Definition: Fowler's Technical Debt Quadrant (14 October 2009) crosses reckless / prudent with deliberate / inadvertent:
| Quadrant | Typical sentence | Architecture example | Response |
|---|---|---|---|
| Deliberate, prudent | "We must ship now and deal with consequences" | One shared schema for two modules until launch | ADR with payback trigger and owner |
| Deliberate, reckless | "We don't have time for design" | No module boundaries "for now" | Stop; this is not a decision, it is avoidance |
| Inadvertent, prudent | "Now we know how we should have done it" | Order and invoice should have been separate aggregates | New ADR; refactor with the next feature |
| Inadvertent, reckless | "What's layering?" | Controllers that write to five modules' tables | Fitness tests first, then refactor |
Sprint Deliberate, prudent debt: shared schema (ADR-0006)
1 1 ADR-0006: orders and invoicing share schema "app"; trigger: second team joins
2 8 Second team joins (trigger fired) -> ticket "split schema" scheduled
3 9 Expand: create schema invoicing, dual-write
4 10 Contract: switch reads, revoke grants; ADR-0009 supersedes 0006Fix / how to use it: every deliberate debt gets an ADR with "accepting" in its Y-statement, an interest estimate (days per feature), and a trigger that schedules payback.
Sacrificial architecture Good to know
In plain words: sometimes the right version 1 is one you expect to throw away when you succeed, because the architecture for 100x load would be too slow and expensive to build for 1x.
Common misunderstanding: "Planned replacement means low quality is fine." Fowler: "Knowing your architecture is sacrificial doesn't mean abandoning the internal quality of the software." Good modularity is what lets you sacrifice modules instead of the whole system: "as a system grows it's more effective to sacrifice individual modules - which you can only do if you have good module boundaries."
Definition: Fowler, Sacrificial Architecture (20 October 2014): "often the best code you can write now is code you'll discard in a couple of years time." His examples: eBay began "as a set of perl scripts built over a weekend in 1995", was rebuilt in C++ in 1997 and in Java in 2002; at Google "the explicit rule is to design a system for ten times its current needs", and Jeff Dean's footnote "design for ~10X growth, but plan to rewrite before ~100X".
| Signal | Sacrificial is reasonable | Build to last |
|---|---|---|
| Product-market fit | Unknown | Proven |
| Expected growth | Orders of magnitude | Linear |
| Cost of a rewrite | One team, months | Many teams, years, data migrations |
| What you keep | Data, contracts, lessons about boundaries | Everything |
Fix / how to use it: state it in an ADR ("this module is sized for 10x; rewrite trigger at 5x"), keep data and external contracts stable, and invest in module boundaries so the sacrifice is local.
Fitness functions as decision guards Must-know
In plain words: a fitness function is a test (or a metric with a threshold) that fails when the system stops honouring a decision.
Common misunderstanding: "Fitness functions are only for performance." Any characteristic that can be checked qualifies: dependency direction, no shared database, p99 latency, event schema compatibility, licence policy, ADR freshness.
Definition: Thoughtworks Technology Radar: "An architectural fitness function, as defined in Building Evolutionary Architectures, provides an objective integrity assessment of some architectural characteristics, which may encompass existing verification criteria, such as unit testing, metrics, monitors, and so on." MADR 4.0.0's "Confirmation" section asks: "Is there any automated or manual fitness function? If so, list it and explain how it is applied."
| Decision | Fitness function | Kind | Where on this page |
|---|---|---|---|
| Dependency rule (domain imports no infrastructure) | Parse imports (Go), Pest arch() (Laravel) | Atomic, triggered in CI | Go, Laravel |
Modules talk through api packages only | Import-graph test | Atomic, CI | TestModulesTalkThroughAPIOnly |
| No shared database | Lint of connection strings and DB::connection() names | Atomic, CI | TestNoSharedDatabase, NoSharedDatabaseTest.php |
| Events only between orders and notifications | Import test forbidding orders/* and net/http | Atomic, CI | TestNotificationsDependsOnEventsOnly |
| ADR log is healthy | adrlint: names, statuses, dangling supersedes, review dates | Atomic, CI | cmd/adrlint |
| p99 checkout < 300 ms | Load test threshold or SLO alert | Holistic, continuous | SLOs |
PR Change Result
1 #412 orders/domain imports database/sql "to save time" archtest FAIL: ADR-0001 violated
2 #413 notifications calls orders over HTTP archtest FAIL: ADR-0003 violated
3 #414 notifications.env points at payments DB archtest FAIL: ADR-0004 violated
4 #415 ADR-0003 status set to "Approved by CTO" adrlint FAIL: status not in lifecycleFix / how to use it: an accepted ADR without a guard is a wish. Add the guard in the same PR that merges the ADR, and name the ADR in the failure message so the developer knows where to read the reasons.
Tactics and ATAM: sensitivity and trade-off points Good to know
In plain words: a tactic is a small, named design move that improves one quality (add a cache, introduce a queue, replicate), and each tactic usually hurts another quality. ATAM is a workshop method to find those tensions in a whole architecture.
Common misunderstanding: "Tactics are free improvements." Bachmann, Bass and Klein (SEI, 2003): applying the tactic "apply scheduling strategy" "results in the responsibility 'schedule units of concurrency'", which must then be assigned to a module. Each tactic adds responsibilities: second-order effects by construction.
Definition: in ATAM (SEI), stakeholders turn business drivers into quality attribute scenarios, then analyse architectural approaches to find sensitivity points (a decision that strongly affects one quality), trade-off points (a decision that affects several qualities in opposite directions), risks and non-risks (Wikipedia summary, secondary).
| Tactic (Bass et al. families) | Improves | Usually costs | Trade-off point? |
|---|---|---|---|
| Introduce concurrency / async queue | Performance, availability | Consistency, debuggability | Yes |
| Maintain multiple copies (cache, replica) | Performance, availability | Consistency, cost | Yes |
| Encrypt data | Security | Performance, operability | Yes |
| Use an intermediary (gateway, broker) | Modifiability | Latency, a new failure point | Yes |
| Restrict dependencies (layers, modules) | Modifiability, testability | Some performance, indirection | Usually mild |
| Heartbeat / health check | Availability | Network and code overhead | Mild |
Fix / how to use it: when a proposal says "we'll add X to improve Y", ask "which quality does X cost, and which new responsibility does it add?" That answer belongs in Consequences.
Biases in architecture decisions Good to know
In plain words: architects are people; the same thinking shortcuts that fool everyone fool us. A process mostly exists to protect the decision from our own brains.
Common misunderstanding: "Experienced architects are objective." Kahneman's Thinking, Fast and Slow (2011) argues "that people have too much confidence in human judgment" (Wikipedia summary, secondary); experience makes fast intuition stronger, not less biased.
Definition (brief): System 1 is "fast, instinctive and emotional"; System 2 is "slower, more deliberative, and more logical" (same source). The biases that show up in architecture reviews:
| Bias | How it shows up | Counter-measure |
|---|---|---|
| Anchoring | The first option presented sets the frame | Write drivers and weights before options |
| Confirmation bias | Searching only for evidence that the favourite works | Assign someone to argue the strongest alternative |
| Sunk cost | "We've invested a year in this service mesh" | Score options on future cost only |
| Availability | Last incident dominates ("Kafka burned us once") | Ask for data across incidents, not one story |
| Bandwagon / résumé-driven | "Everyone uses Kubernetes" | Require a driver the option satisfies |
| Overconfidence | No confidence level, no revisit date | Fowler: record "the confidence level of the decision" |
| HiPPO | Highest-paid person's opinion ends debate | Independent scoring; "disagree and commit" is explicit, not silent |
Fix / how to use it: independent scoring, a devil's advocate, a pre-mortem, and Bezos's "disagree and commit" ("Look, I know we disagree on this but will you gamble with me on it?") recorded in the ADR when consensus is impossible.
Mechanics
The weighted decision matrix Must-know
Scale: -2 (strongly hurts) to +2 (strongly helps), evidence required for any ±2. Weight: 1 (nice) to 3 (critical). Score = Σ weight × score. Then the sensitivity check: change each weight by ±1; if the winner changes, the decision is close and the ADR must say so (low confidence, earlier review date).
| Driver (weight) | Option A | Option B | Option C | Evidence column |
|---|---|---|---|---|
| Consistency of order + payment (3) | +2 | -1 | 0 | Spike results, doc links |
| Team skills (2) | +1 | -1 | +2 | Survey of the team |
| Operational cost (2) | 0 | -2 | +1 | Vendor pricing |
| Time to first release (1) | +1 | 0 | +2 | Estimate |
| Weighted sum | 9 | -9 | 8 | A wins narrowly over C |
| Sensitivity: skills weight 3 | 10 | -10 | 10 | Tie: low confidence, review in 6 months |
ADR tooling and layout
| Tool | Command / location | Note |
|---|---|---|
| adr-tools (npryce) | adr init doc/architecture/decisions, adr new Implement as Unix shell scripts, adr new -s 9 Use Rust for performance-critical functionality | -s 9 marks ADR 9 as superseded by the new one |
| MADR | npm install madr && mkdir -p docs/decisions && cp node_modules/madr/template/* docs/decisions/ | Templates: full, minimal, bare; markdownlint config included |
| Folder | docs/decisions/NNNN-title-with-dashes.md | Subfolders per area are allowed; numbers then unique per folder only |
| Lint | go run ./cmd/adrlint docs/decisions (this page) | Fails CI on bad names, statuses, dangling supersedes, stale reviews |
| Ownership | CODEOWNERS: /docs/decisions/ @arch-guild | Reviewers see every new ADR |
| Publishing | A build task renders ADRs into the docs site | Fowler: "We can use a build task to publish them" |
Linking decisions to code
// Package domain holds the order rules. ADR-0001 (dependency rule): this
// package imports nothing from infrastructure.
package domain Link direction Mechanism Example on this page
1 ADR -> code "Confirmation" names the test and packages ADR-0001 -> shop/archtest/dependency_test.go
2 code -> ADR Package comment names the ADR // ADR-0003 in notify.go, OrderPlaced.php
3 test failure -> ADR Failure message names the ADR "ADR-0004 violated: notifications and payments share ..."
4 PR -> ADR PR template field "Decision record:" #412 links ADR-0001Failure messages you will actually see
| Where | Message | Meaning |
|---|---|---|
go test ./shop/archtest | ADR-0001 violated: ../orders/domain/order.go imports database/sql | Dependency rule broken |
go test ./shop/archtest | ADR-0001 violated: ... imports .../shop/orders/domain (use .../shop/orders/api) | Cross-module reach-in |
go test ./shop/archtest | ADR-0004 violated: notifications and payments share database pg-shared.internal:5432/payments | Shared database |
go run ./cmd/adrlint | 0003-x.md: superseded by ADR-0011, which does not exist | Broken decision log |
go run ./cmd/adrlint | 0001-x.md: stale, review was due 2026-01-01 | Decision nobody re-checked |
| Go compiler | use of internal package ... not allowed | Go's own boundary (Go 1.4 internal/ rule) |
| Pest | a failed arch() expectation naming the class and the forbidden namespace (wording depends on the Pest version; not verified here) | Laravel boundary broken |
| PostgreSQL | ERROR: permission denied for table orders (SQLSTATE 42501) | A service used another service's database role correctly denied |
Worked decisions: four ADRs
The worked system: Shop, an online store for one country, one product team of six (three Laravel developers, two Go developers, one SRE), launching in four months. Modules: orders, payments, catalog, notifications. Each decision below has a scored analysis, the full ADR, and a second-order effects table.
Decision 1: monolith vs modular monolith vs microservices Must-know
| Driver (weight) | Layered monolith | Modular monolith | Microservices |
|---|---|---|---|
| Time to first release (3) | +2 | +1 | -2 |
| Operational simplicity for 1 SRE (3) | +2 | +2 | -2 |
| Ability to split later (2) | -1 | +2 | +2 |
| Independent deploy per team (1) | -1 | -1 | +2 |
| Modifiability inside a boundary (2) | -1 | +2 | +2 |
| Weighted sum | 7 | 16 | -2 |
# ADR-0001: Modular monolith with an enforced dependency rule
## Status
Accepted
Review-by: 2027-06-01
## Context
One team of six ships a new shop in four months with one SRE. The domain
boundaries (orders, payments, catalog, notifications) are our best guess and
will move. Microservices would add distribution, eventual consistency and
operational load we cannot staff (Fowler, MicroservicePremium). A plain
layered monolith ships fastest but makes a later split expensive.
## Decision
We will build one deployable per language runtime, organised as modules.
Each module exposes an `api` package (Go) or `Contracts` namespace (Laravel);
other modules use nothing else. Domain code imports no infrastructure.
## Consequences
Good: one deploy, one database cluster, in-process calls, simple debugging.
Bad: one release train; a slow test suite slows everyone.
Second order: boundaries erode unless tested -> archtest and Pest arch() run
in CI. Splitting a module into a service later means replacing in-process
calls with network calls (see ADR-0003 for how events prepare for that).
Revisit when a second team owns a module or a module needs its own scaling.
## Confirmation
shop/archtest/dependency_test.go, tests/Architecture/DependencyRuleTest.php| Effect | Order | Owner | Mitigation |
|---|---|---|---|
Boundaries can be crossed with one import | 2nd | Tech lead | Fitness tests in CI |
| Shared test suite gets slow | 2nd | Team | Per-module test targets |
| Later split needs network contracts | 3rd | Future service owner | Contracts package and events from day one |
Deep dive: Modular Monolith, Monolith vs Microservices vs Modular.
Decision 2: PostgreSQL vs MongoDB for orders Must-know
| Driver (weight) | PostgreSQL | MongoDB |
|---|---|---|
| Atomic order + lines + outbox (3) | +2: ACID transactions, constraints | +1: multi-document transactions exist (since 4.0 on replica sets), single-document atomicity is the natural model |
| Reporting and ad-hoc SQL for finance (2) | +2 | -1: aggregation pipeline, BI connector needed |
| Flexible per-product attributes (1) | +1: jsonb column with GIN index | +2: native documents |
| Horizontal write scaling beyond one node (1) | -1: needs Citus or app-level sharding | +2: built-in sharding |
| Team skills (2) | +2 | 0 |
| Managed offering in our cloud (1) | +2 | +1 |
| Weighted sum | 17 | 6 |
-- PostgreSQL: the decision expressed in the schema (ADR-0002).
CREATE TABLE orders (
id uuid PRIMARY KEY,
customer_id uuid NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0),
placed_at timestamptz NOT NULL,
attributes jsonb NOT NULL DEFAULT '{}' -- the flexible part, on purpose
);
CREATE TABLE order_lines (
order_id uuid NOT NULL REFERENCES orders(id),
sku text NOT NULL,
qty int NOT NULL CHECK (qty > 0),
price_cents bigint NOT NULL CHECK (price_cents >= 0),
PRIMARY KEY (order_id, sku)
);
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
-- ADR-0004: one login role per service, no grants across services.
CREATE ROLE orders_app LOGIN;
GRANT SELECT, INSERT, UPDATE ON orders, order_lines, outbox TO orders_app;# ADR-0002: PostgreSQL for the orders module
## Status
Accepted
## Context
Orders, their lines and the outbox row must commit atomically. Finance runs
ad-hoc SQL. Product attributes vary per category. Expected volume: 20k
orders/day, well inside one PostgreSQL primary. The team knows SQL; nobody
has run MongoDB in production.
## Decision
We will store orders in PostgreSQL 17 (managed), with variable attributes in
a jsonb column. We will not shard; we will revisit at 10x volume.
## Consequences
Good: transactions, constraints, SQL for finance, one engine to operate.
Bad: schema migrations for every structural change (expand/contract).
Neutral: jsonb keeps flexibility for attributes only.
Second order: migrations need a zero-downtime process; reporting load needs
a replica before peak season (replica lag -> read-your-writes rule).
Confidence: high. Rejected: MongoDB (sharding not needed, team skills).| Effect | Order | Owner | Mitigation |
|---|---|---|---|
| Every structural change is a migration | 2nd | Orders team | Zero-downtime migrations |
| Reporting load on the primary | 2nd | SRE | Read replica; route finance there |
| Replica lag surprises users | 3rd | Backend | Read-your-writes after checkout (Replication) |
| Engine lock-in | 2nd | Tech lead | Store port (app.Store) keeps the domain engine-free |
The honest other side: if orders were a catalog of heterogeneous documents read by key, written in bursts across regions, MongoDB's document model and sharding would win; see Choosing a Database and MongoDB in Depth.
Decision 3: synchronous REST vs asynchronous events between orders and notifications Must-know
| Driver (weight) | Sync REST call | Async event via outbox |
|---|---|---|
| Checkout availability when mail provider is down (3) | -2: checkout fails or waits | +2: checkout unaffected |
| Customer sees confirmation immediately (1) | +2 | +1: seconds of lag |
| Simplicity to build and debug (2) | +2 | -1: relay, broker, inbox, DLQ |
| Future split into services (2) | -1: temporal coupling stays | +2: already a contract |
| Weighted sum | -1 | 9 |
Sync REST (rejected) Async via outbox (chosen)
1 POST /orders POST /orders
2 BEGIN; INSERT order BEGIN; INSERT order; INSERT outbox; COMMIT
3 POST notifications/send (timeout 2 s) 201 Created (p99 unaffected by mail)
4 mail provider slow -> 2 s added to checkout relay -> broker -> notifications (seconds later)
5 provider down -> retry? rollback order? both bad provider down -> retries, then DLQ; order is safe# ADR-0003: Asynchronous OrderPlaced event from orders to notifications
## Status
Accepted
## Context
Checkout must stay available when the mail provider fails (two outages last
quarter, 40 min each). Customers tolerate a confirmation mail a few seconds
late. Notifications may become a separate service (ADR-0001 revisit trigger).
## Decision
We will publish orders.order_placed.v1 through a transactional outbox. The
notifications module consumes it, deduplicates by event_id, and never calls
or imports orders code. Contracts live in contracts/events.
## Consequences
Good: checkout is independent of mail; the boundary is service-ready.
Bad: at-least-once delivery -> duplicate mails are possible in rare crashes.
Second order: inbox table, DLQ with an owner (notifications), alert at 1
message in DLQ, "confirmation pending" text on the order page.
Third order: support needs to look up processed_events by order id.
## Confirmation
TestNotificationsDependsOnEventsOnly; Pest arch() "notifications knows orders
only through its event contract".| Effect | Order | Owner | Mitigation |
|---|---|---|---|
| Duplicate delivery | 2nd | Notifications | Idempotent consumer / inbox |
| Poison messages | 2nd | Notifications | DLQ + alert |
| Confirmation may lag | 3rd | Frontend | "Confirmation on its way" copy |
| Event schema is now a public contract | 2nd | Orders | Versioned type names; additive changes only (schema evolution) |
More on the general choice: Service Communication, Outbox, Event-Driven Architecture.
Decision 4: Go vs PHP (Laravel) for a service Important
There is no honest global answer; the answer depends on the service. Two services in Shop:
| Driver (weight) | Back office (CRUD, forms, reports) in Laravel | Back office in Go | Webhook ingester (10k req/s bursts, tiny logic) in Laravel | Ingester in Go |
|---|---|---|---|---|
| Delivery speed for this workload (3) | +2: Eloquent, validation, queues, auth scaffolding | -1 | +1 | +1 |
| Resource use at peak (2) | 0 | +1 | -1: PHP-FPM process per request; Octane helps | +2: goroutines, one static binary |
| Team skills (2) | +2 (3 devs) | +1 (2 devs) | +2 | +1 |
| Operational fit (1) | +1: same as main app | 0 | 0: Octane adds long-lived-process concerns | +1 |
| Weighted sum, back office | 11 | 0 | - | - |
| Weighted sum, ingester | - | - | 5 | 9 |
# ADR-0005: Go for the payment webhook ingester; Laravel stays for the back office
## Status
Accepted
## Context
Payment provider webhooks arrive in bursts of 10k req/s during sales. Each
request validates a signature and appends a row; no business logic. The
back office is CRUD-heavy and changes weekly. Three developers are fluent in
Laravel, two in Go.
## Decision
We will write the ingester in Go (net/http, database/sql) and keep the back
office in Laravel 13. Both share the events contract, not code.
## Consequences
Good: ingester runs on two small instances; back office keeps Laravel speed.
Bad: two toolchains, two CI pipelines, two dependency update streams.
Second order: on-call needs Go and PHP skills; bus factor for Go is two.
We accept this; revisit if the Go developers drop below two.| Effect | Order | Owner | Mitigation |
|---|---|---|---|
| Two build pipelines | 2nd | SRE | Shared CI templates, one container base policy |
| On-call needs both skills | 2nd | Team lead | Pairing, runbooks per service |
| Shared logic tempts a shared library across languages | 3rd | Architects | Share contracts (JSON schema), not code |
| Hiring profile widens | 3rd | Management | Explicit in the ADR so it is a choice |
Go
The Go module enforces three accepted ADRs as tests and lints the decision log. It uses only the standard library: go/parser for imports, net/url for connection strings, testing/fstest for the linter tests.
Example
The domain package (ADR-0001: no infrastructure imports):
// Package domain holds the order rules. ADR-0001 (dependency rule): this
// package imports nothing from infrastructure: no database/sql, no net/http,
// no adapter packages. The archtest package enforces it.
package domain
import (
"errors"
"time"
)
// ErrEmptyOrder is returned when an order has no lines.
var ErrEmptyOrder = errors.New("order has no lines")
// Line is one product in an order; money is integer cents.
type Line struct {
SKU string
Qty int
PriceCents int64
}
// Order is the aggregate stored in PostgreSQL (ADR-0002).
type Order struct {
ID string
CustomerID string
Lines []Line
TotalCents int64
PlacedAt time.Time
}
// NewOrder validates the lines and computes the total.
func NewOrder(id, customerID string, lines []Line, now time.Time) (Order, error) {
if len(lines) == 0 {
return Order{}, ErrEmptyOrder
}
var total int64
for _, l := range lines {
if l.Qty <= 0 || l.PriceCents < 0 {
return Order{}, errors.New("invalid line " + l.SKU)
}
total += int64(l.Qty) * l.PriceCents
}
return Order{ID: id, CustomerID: customerID, Lines: lines, TotalCents: total, PlacedAt: now}, nil
}The use case writes the order and the event in one transaction (ADR-0002, ADR-0003):
// Package app is the orders use-case layer. It depends on domain and on the
// ports below; adapters (postgres, HTTP) implement the ports.
package app
import (
"context"
"encoding/json"
"time"
"academy/architecture-decisions-tradeoffs/shop/contracts/events"
"academy/architecture-decisions-tradeoffs/shop/orders/domain"
)
// Tx is the unit of work: the order and its outbox row commit together.
type Tx interface {
SaveOrder(ctx context.Context, o domain.Order) error
AppendOutbox(ctx context.Context, eventType string, payload []byte) error
}
// Store opens a transaction and runs fn inside it.
type Store interface {
InTx(ctx context.Context, fn func(Tx) error) error
}
// PlaceOrder implements ADR-0003: no synchronous call to notifications;
// the OrderPlaced event is written to the outbox in the same transaction.
type PlaceOrder struct {
Store Store
Now func() time.Time
NewID func() string
}
// Handle validates, stores and records the event atomically.
func (p PlaceOrder) Handle(ctx context.Context, customerID string, lines []domain.Line) (domain.Order, error) {
o, err := domain.NewOrder(p.NewID(), customerID, lines, p.Now())
if err != nil {
return domain.Order{}, err
}
payload, err := json.Marshal(events.OrderPlacedV1{
EventID: p.NewID(), OrderID: o.ID, CustomerID: o.CustomerID,
TotalCents: o.TotalCents, OccurredAt: o.PlacedAt,
})
if err != nil {
return domain.Order{}, err
}
err = p.Store.InTx(ctx, func(tx Tx) error {
if err := tx.SaveOrder(ctx, o); err != nil {
return err
}
return tx.AppendOutbox(ctx, events.Type, payload)
})
return o, err
}The PostgreSQL adapter, the only orders package that may import database/sql:
// Package postgres is the orders adapter for PostgreSQL (ADR-0002).
// It is the only orders package allowed to import database/sql.
package postgres
import (
"context"
"database/sql"
"academy/architecture-decisions-tradeoffs/shop/orders/app"
"academy/architecture-decisions-tradeoffs/shop/orders/domain"
)
// Store implements app.Store on a *sql.DB that points at the orders database.
type Store struct{ DB *sql.DB }
type tx struct{ tx *sql.Tx }
// InTx runs fn in one READ COMMITTED transaction and commits if fn succeeds.
func (s Store) InTx(ctx context.Context, fn func(app.Tx) error) error {
t, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(tx{t}); err != nil {
_ = t.Rollback()
return err
}
return t.Commit()
}
func (t tx) SaveOrder(ctx context.Context, o domain.Order) error {
_, err := t.tx.ExecContext(ctx,
`INSERT INTO orders (id, customer_id, total_cents, placed_at) VALUES ($1, $2, $3, $4)`,
o.ID, o.CustomerID, o.TotalCents, o.PlacedAt)
if err != nil {
return err
}
for _, l := range o.Lines {
if _, err := t.tx.ExecContext(ctx,
`INSERT INTO order_lines (order_id, sku, qty, price_cents) VALUES ($1, $2, $3, $4)`,
o.ID, l.SKU, l.Qty, l.PriceCents); err != nil {
return err
}
}
return nil
}
func (t tx) AppendOutbox(ctx context.Context, eventType string, payload []byte) error {
_, err := t.tx.ExecContext(ctx,
`INSERT INTO outbox (event_type, payload) VALUES ($1, $2)`, eventType, payload)
return err
}The public surface of orders and the event contract:
// Package api is the only orders package other modules may import (ADR-0001).
package api
import (
"context"
"academy/architecture-decisions-tradeoffs/shop/orders/domain"
)
// OrderSummary is what other modules may know about an order.
type OrderSummary struct {
ID string
TotalCents int64
}
// Reader is the read-only facade other modules call in-process.
type Reader interface {
Summary(ctx context.Context, orderID string) (OrderSummary, error)
}
// FromDomain maps the aggregate to the public shape.
func FromDomain(o domain.Order) OrderSummary {
return OrderSummary{ID: o.ID, TotalCents: o.TotalCents}
}// Package events is the published language between modules (ADR-0003).
// Consumers depend on this contract, never on the producer's packages.
package events
import "time"
// OrderPlacedV1 is emitted after the order transaction commits.
// Additive changes only; a breaking change becomes OrderPlacedV2.
type OrderPlacedV1 struct {
EventID string `json:"event_id"`
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
TotalCents int64 `json:"total_cents"`
OccurredAt time.Time `json:"occurred_at"`
}
// Type is the routing key / topic name for the event.
const Type = "orders.order_placed.v1"The consumer, which knows only the contract and is idempotent:
// Package notifications reacts to OrderPlaced (ADR-0003). It imports the
// event contract only, never the orders module, and it is idempotent because
// the outbox relay delivers at least once.
package notifications
import (
"context"
"encoding/json"
"fmt"
"academy/architecture-decisions-tradeoffs/shop/contracts/events"
)
// Mailer sends one message; Seen records processed event IDs (inbox table).
type Mailer interface {
Send(ctx context.Context, customerID, body string) error
}
// Seen is the dedup store (inbox table keyed by event ID).
type Seen interface {
Has(ctx context.Context, eventID string) (bool, error)
Mark(ctx context.Context, eventID string) error
}
// Handler consumes orders.order_placed.v1.
type Handler struct {
Mailer Mailer
Seen Seen
}
// Handle decodes, deduplicates and sends the confirmation.
func (h Handler) Handle(ctx context.Context, raw []byte) error {
var e events.OrderPlacedV1
if err := json.Unmarshal(raw, &e); err != nil {
return fmt.Errorf("decode %s: %w", events.Type, err)
}
seen, err := h.Seen.Has(ctx, e.EventID)
if err != nil || seen {
return err
}
body := fmt.Sprintf("Order %s confirmed: %d.%02d EUR", e.OrderID, e.TotalCents/100, e.TotalCents%100)
if err := h.Mailer.Send(ctx, e.CustomerID, body); err != nil {
return err // not marked: the broker redelivers
}
// Process, then mark: a crash between the two lines sends one duplicate
// mail, which ADR-0003 accepts as a consequence.
return h.Seen.Mark(ctx, e.EventID)
}Decision guard 1: the dependency rule and module boundaries (ADR-0001, ADR-0003):
// Package archtest turns accepted ADRs into tests that fail the build.
// ADR-0001: modular monolith with a dependency rule.
// - domain packages import no infrastructure;
// - a module imports another module only through its api package;
//
// ADR-0003: notifications learns about orders through events only.
package archtest
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strings"
"testing"
)
const mod = "academy/architecture-decisions-tradeoffs/shop/"
// imports maps every non-test .go file under root to its import paths.
func imports(t *testing.T, root string) map[string][]string {
t.Helper()
out := map[string][]string{}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), p, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, im := range f.Imports {
out[filepath.ToSlash(p)] = append(out[filepath.ToSlash(p)], strings.Trim(im.Path.Value, `"`))
}
return nil
})
if err != nil {
t.Fatal(err)
}
return out
}
// moduleOf returns "orders" for ".../shop/orders/app" and "" otherwise.
func moduleOf(importPath string) string {
rest, ok := strings.CutPrefix(importPath, mod)
if !ok {
return ""
}
return strings.SplitN(rest, "/", 2)[0]
}
func TestDomainImportsNoInfrastructure(t *testing.T) {
banned := []string{"database/sql", "net/http", "os", mod + "orders/postgres", mod + "orders/app", mod + "orders/api"}
for file, imps := range imports(t, "../orders/domain") {
for _, imp := range imps {
for _, b := range banned {
if imp == b || strings.HasPrefix(imp, b+"/") {
t.Errorf("ADR-0001 violated: %s imports %s", file, imp)
}
}
}
}
}
func TestModulesTalkThroughAPIOnly(t *testing.T) {
for file, imps := range imports(t, "..") {
self := moduleOf(mod + strings.TrimPrefix(file, "../"))
for _, imp := range imps {
other := moduleOf(imp)
if other == "" || other == self || other == "contracts" {
continue
}
if !strings.HasPrefix(imp, mod+other+"/api") {
t.Errorf("ADR-0001 violated: %s imports %s (use %sapi)", file, imp, mod+other+"/")
}
}
}
}
func TestNotificationsDependsOnEventsOnly(t *testing.T) {
for file, imps := range imports(t, "../notifications") {
for _, imp := range imps {
if moduleOf(imp) == "orders" || imp == "net/http" {
t.Errorf("ADR-0003 violated: %s imports %s (consume %s instead)", file, imp, mod+"contracts/events")
}
}
}
}Decision guard 2: no shared database (ADR-0004), a lint of the connection strings the deploy pipeline ships:
package archtest
// ADR-0004: no shared database. Every service config must point at a database
// that no other service uses, with a login role named after the service.
// Sharing a server (cluster) is allowed; sharing a database is not.
// The lint reads config/*.env, the same files the deploy pipeline ships.
import (
"bufio"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
type dsn struct {
service, user, target string
}
func readEnv(t *testing.T, path string) map[string]string {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
kv := map[string]string{}
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if k, v, ok := strings.Cut(line, "="); ok {
kv[k] = v
}
}
if err := sc.Err(); err != nil {
t.Fatal(err)
}
return kv
}
func TestNoSharedDatabase(t *testing.T) {
files, err := filepath.Glob("../../config/*.env")
if err != nil || len(files) == 0 {
t.Fatalf("no service configs found: %v", err)
}
owner := map[string]string{} // host:port/dbname -> service
for _, f := range files {
kv := readEnv(t, f)
u, err := url.Parse(kv["DATABASE_URL"])
if err != nil {
t.Fatalf("%s: bad DATABASE_URL: %v", f, err)
}
d := dsn{service: kv["SERVICE"], user: u.User.Username(), target: u.Host + u.Path}
if d.user != d.service+"_app" {
t.Errorf("ADR-0004 violated: %s logs in as %q, want %q", f, d.user, d.service+"_app")
}
if prev, taken := owner[d.target]; taken {
t.Errorf("ADR-0004 violated: %s and %s share database %s", prev, d.service, d.target)
}
owner[d.target] = d.service
}
}# ADR-0004: each service owns its database and its role.
SERVICE=orders
DATABASE_URL=postgres://orders_app@pg-orders.internal:5432/orders?sslmode=verify-fullSERVICE=payments
DATABASE_URL=postgres://payments_app@pg-shared.internal:5432/payments?sslmode=verify-fullSERVICE=notifications
DATABASE_URL=postgres://notifications_app@pg-shared.internal:5432/notifications?sslmode=verify-fullDecision-log guard: adrlint keeps ADRs alive (statuses, supersede links, review dates):
package main
import (
"bufio"
"fmt"
"io/fs"
"regexp"
"sort"
"strings"
"time"
)
var (
fileRe = regexp.MustCompile(`^(\d{4})-[a-z0-9-]+\.md$`)
supersededRe = regexp.MustCompile(`(?i)^superseded by ADR-(\d{4})`)
reviewRe = regexp.MustCompile(`(?i)^review-by:\s*(\d{4}-\d{2}-\d{2})`)
statuses = []string{"proposed", "accepted", "rejected", "deprecated", "superseded"}
required = []string{"## Status", "## Context", "## Decision", "## Consequences"}
)
// Lint returns one human-readable problem per line; an empty slice means OK.
func Lint(fsys fs.FS, now time.Time) ([]string, error) {
entries, err := fs.ReadDir(fsys, ".")
if err != nil {
return nil, err
}
numbers := map[string]string{}
var problems []string
type pending struct{ file, target string }
var links []pending
for _, e := range entries {
name := e.Name()
if e.IsDir() || !strings.HasSuffix(name, ".md") || name == "README.md" || strings.HasPrefix(name, "template") {
continue
}
m := fileRe.FindStringSubmatch(name)
if m == nil {
problems = append(problems, fmt.Sprintf("%s: name must match NNNN-title-with-dashes.md", name))
continue
}
if prev, dup := numbers[m[1]]; dup {
problems = append(problems, fmt.Sprintf("%s: number %s already used by %s", name, m[1], prev))
}
numbers[m[1]] = name
body, err := fs.ReadFile(fsys, name)
if err != nil {
return nil, err
}
status, review, missing := scan(string(body))
for _, h := range missing {
problems = append(problems, fmt.Sprintf("%s: missing section %q", name, h))
}
word := strings.ToLower(strings.Fields(status + " ?")[0])
if !contains(statuses, word) {
problems = append(problems, fmt.Sprintf("%s: status %q is not one of %v", name, status, statuses))
}
if s := supersededRe.FindStringSubmatch(status); s != nil {
links = append(links, pending{name, s[1]})
}
if word == "accepted" && review != "" {
due, err := time.Parse("2006-01-02", review)
if err == nil && now.After(due) {
problems = append(problems, fmt.Sprintf("%s: stale, review was due %s", name, review))
}
}
}
for _, l := range links {
if _, ok := numbers[l.target]; !ok {
problems = append(problems, fmt.Sprintf("%s: superseded by ADR-%s, which does not exist", l.file, l.target))
}
}
sort.Strings(problems)
return problems, nil
}
// scan returns the first line under "## Status", the Review-by date and
// the required headings that are absent.
func scan(body string) (status, review string, missing []string) {
seen := map[string]bool{}
inStatus := false
sc := bufio.NewScanner(strings.NewReader(body))
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if strings.HasPrefix(line, "## ") {
seen[line] = true
inStatus = line == "## Status"
continue
}
if m := reviewRe.FindStringSubmatch(line); m != nil {
review = m[1]
}
if inStatus && line != "" && status == "" {
status = line
}
}
for _, h := range required {
if !seen[h] {
missing = append(missing, h)
}
}
return status, review, missing
}
func contains(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}package main
import (
"strings"
"testing"
"testing/fstest"
"time"
)
const good = `# ADR-0001: Modular monolith for the shop
## Status
Accepted
Review-by: 2027-06-01
## Context
One team of six, one product, unknown boundaries.
## Decision
We will build one deployable with enforced module boundaries.
## Consequences
Simple operations; boundaries must be policed by tests.
`
func TestLint(t *testing.T) {
now := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC)
cases := []struct {
name string
fs fstest.MapFS
want string // substring of the only problem, "" for OK
}{
{"ok", fstest.MapFS{"0001-modular-monolith.md": {Data: []byte(good)}}, ""},
{"bad name", fstest.MapFS{"ADR1.md": {Data: []byte(good)}}, "name must match"},
{"missing section", fstest.MapFS{"0001-x.md": {Data: []byte(strings.Replace(good, "## Consequences", "## Notes", 1))}}, `missing section "## Consequences"`},
{"unknown status", fstest.MapFS{"0001-x.md": {Data: []byte(strings.Replace(good, "Accepted", "Approved by CTO", 1))}}, "is not one of"},
{"dangling supersede", fstest.MapFS{"0001-x.md": {Data: []byte(strings.Replace(good, "Accepted", "Superseded by ADR-0009", 1))}}, "does not exist"},
{"stale", fstest.MapFS{"0001-x.md": {Data: []byte(strings.Replace(good, "2027-06-01", "2026-01-01", 1))}}, "stale"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := Lint(c.fs, now)
if err != nil {
t.Fatal(err)
}
if c.want == "" && len(got) != 0 {
t.Fatalf("want no problems, got %v", got)
}
if c.want != "" && (len(got) != 1 || !strings.Contains(got[0], c.want)) {
t.Fatalf("want one problem containing %q, got %v", c.want, got)
}
})
}
}// Command adrlint checks a decision log (docs/decisions by default) so that
// ADRs stay a living record instead of a graveyard:
// - file names follow NNNN-title-with-dashes.md, numbers unique;
// - Status, Context, Decision and Consequences sections exist;
// - status is one of the lifecycle states;
// - "superseded by ADR-NNNN" points at a file that exists;
// - accepted ADRs past their "Review-by:" date are reported as stale.
//
// Usage: go run ./cmd/adrlint [dir]
package main
import (
"fmt"
"os"
"time"
)
func main() {
dir := "docs/decisions"
if len(os.Args) > 1 {
dir = os.Args[1]
}
problems, err := Lint(os.DirFS(dir), time.Now())
if err != nil {
fmt.Fprintln(os.Stderr, "adrlint:", err)
os.Exit(2)
}
for _, p := range problems {
fmt.Println(p)
}
if len(problems) > 0 {
os.Exit(1)
}
fmt.Println("adrlint: decision log OK")
}The Go angle
- The compiler is a fitness function.
internal/directories (Go 1.4) make some boundaries impossible to cross; import cycles are compile errors. The import test covers what the compiler cannot: "domain must not importdatabase/sql" is legal Go. - Consumer-side interfaces keep doors two-way.
app.Storeis defined where it is used; swapping PostgreSQL for another engine changes one package. - Static analysis scales the idea. The same rules can be written as
go/analysisanalyzers and run withgo vet -vettool, or asdepguardrules in golangci-lint, so that they show in editors. - One binary per service makes the "Go vs PHP" second-order effects concrete: no runtime to install, but a separate build pipeline.
Laravel
Laravel 13 with Pest: the same decisions as Pest architecture tests and a feature test over config/database.php.
Example
The domain (plain PHP, ADR-0001) and the use case (ADR-0002, ADR-0003):
<?php
namespace App\Modules\Orders\Domain;
use InvalidArgumentException;
// ADR-0001 dependency rule: Domain uses plain PHP only, no Eloquent, no
// facades, no HTTP. tests/Architecture/DependencyRuleTest.php enforces it.
final class Order
{
/** @param list<array{sku: string, qty: int, price_cents: int}> $lines */
private function __construct(
public readonly string $id,
public readonly string $customerId,
public readonly array $lines,
public readonly int $totalCents,
) {}
/** @param list<array{sku: string, qty: int, price_cents: int}> $lines */
public static function place(string $id, string $customerId, array $lines): self
{
if ($lines === []) {
throw new InvalidArgumentException('order has no lines');
}
$total = 0;
foreach ($lines as $line) {
if ($line['qty'] <= 0 || $line['price_cents'] < 0) {
throw new InvalidArgumentException("invalid line {$line['sku']}");
}
$total += $line['qty'] * $line['price_cents'];
}
return new self($id, $customerId, $lines, $total);
}
}<?php
namespace App\Modules\Orders\Application;
use App\Modules\Orders\Contracts\Events\OrderPlaced;
use App\Modules\Orders\Domain\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
// ADR-0002: orders live in PostgreSQL on the 'orders' connection.
// ADR-0003: no synchronous call to notifications; an event after commit.
final class PlaceOrder
{
/** @param list<array{sku: string, qty: int, price_cents: int}> $lines */
public function handle(string $customerId, array $lines): Order
{
$order = Order::place((string) Str::uuid(), $customerId, $lines);
DB::connection('orders')->transaction(function () use ($order) {
DB::connection('orders')->table('orders')->insert([
'id' => $order->id,
'customer_id' => $order->customerId,
'total_cents' => $order->totalCents,
'placed_at' => now(),
]);
DB::connection('orders')->table('order_lines')->insert(array_map(
fn (array $l) => ['order_id' => $order->id] + $l,
$order->lines,
));
// Dispatched only after this transaction commits.
OrderPlaced::dispatch((string) Str::uuid(), $order->id, $order->customerId, $order->totalCents);
});
return $order;
}
}The event contract; ShouldDispatchAfterCommit is Laravel's built-in way to "only dispatch an event after the active database transaction has committed":
<?php
namespace App\Modules\Orders\Contracts\Events;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
// ADR-0003: the published contract between orders and its consumers.
// ShouldDispatchAfterCommit: listeners never see an order that rolled back.
final class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable;
public const TYPE = 'orders.order_placed.v1';
public function __construct(
public readonly string $eventId,
public readonly string $orderId,
public readonly string $customerId,
public readonly int $totalCents,
) {}
}The queued, idempotent listener in notifications:
<?php
namespace App\Modules\Notifications\Listeners;
use App\Modules\Orders\Contracts\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
// ADR-0003: runs on a queue worker, at least once. Idempotent through an
// inbox table keyed by event id on the notifications connection.
final class SendOrderConfirmation implements ShouldQueue
{
public int $tries = 5;
/** @var list<int> */
public array $backoff = [10, 60, 300];
public function handle(OrderPlaced $event): void
{
$inbox = DB::connection('notifications')->table('processed_events');
if ($inbox->where('event_id', $event->eventId)->exists()) {
return; // duplicate delivery
}
// Send the mail here (Mail::to(...)->send(...)); logged for the example.
Log::info('order confirmation', ['order' => $event->orderId, 'total_cents' => $event->totalCents]);
// Process, then mark: a crash in between causes one duplicate mail.
DB::connection('notifications')->table('processed_events')
->insertOrIgnore(['event_id' => $event->eventId, 'processed_at' => now()]);
}
}One connection per module (ADR-0004):
<?php
// Excerpt of config/database.php. ADR-0004: one connection per module, each
// pointing at its own database with its own login role.
use Illuminate\Support\Str;
$pgsql = fn (string $prefix) => [
'driver' => 'pgsql',
'url' => env("{$prefix}_DB_URL"),
'host' => env("{$prefix}_DB_HOST", '127.0.0.1'),
'port' => env("{$prefix}_DB_PORT", '5432'),
'database' => env("{$prefix}_DB_DATABASE", Str::lower($prefix)),
'username' => env("{$prefix}_DB_USERNAME", Str::lower($prefix).'_app'),
'password' => env("{$prefix}_DB_PASSWORD", ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => env("{$prefix}_DB_SSLMODE", 'prefer'),
];
return [
'default' => env('DB_CONNECTION', 'orders'),
'connections' => [
'orders' => $pgsql('ORDERS'),
'payments' => $pgsql('PAYMENTS'),
'notifications' => $pgsql('NOTIFICATIONS'),
],
// Module name => connection it owns; read by NoSharedDatabaseTest.
'owners' => [
'Orders' => 'orders',
'Payments' => 'payments',
'Notifications' => 'notifications',
],
'migrations' => ['table' => 'migrations', 'update_date_on_publish' => true],
];Decision guard 1: dependency rule (Pest arch(), not->toUse, toOnlyBeUsedIn):
<?php
// ADR-0001 (modular monolith, dependency rule) and ADR-0003 (events only
// between orders and notifications) as Pest architecture tests.
// https://pestphp.com/docs/arch-testing
arch('domain is plain PHP')
->expect('App\Modules\Orders\Domain')
->not->toUse([
'Illuminate\Database',
'Illuminate\Support\Facades',
'Illuminate\Http',
'App\Modules\Orders\Application',
]);
arch('notifications knows orders only through its event contract')
->expect('App\Modules\Notifications')
->not->toUse([
'App\Modules\Orders\Domain',
'App\Modules\Orders\Application',
'Illuminate\Support\Facades\Http',
]);
arch('order contracts are the only public surface')
->expect('App\Modules\Orders\Application')
->toOnlyBeUsedIn('App\Modules\Orders');Decision guard 2: no shared database:
<?php
// ADR-0004: no shared database. Each module owns one connection; no two
// connections may resolve to the same host, port and database, and each
// module's code may only name its own connection.
use Illuminate\Support\Facades\File;
it('gives every module its own database', function () {
$seen = [];
foreach (config('database.owners') as $module => $name) {
$c = config("database.connections.{$name}");
$key = "{$c['host']}:{$c['port']}/{$c['database']}";
expect(isset($seen[$key]))->toBeFalse("{$module} shares {$key} with ".($seen[$key] ?? ''));
expect($c['username'])->toBe("{$name}_app");
$seen[$key] = $module;
}
});
it('lets module code name only its own connection', function () {
foreach (config('database.owners') as $module => $own) {
$dir = app_path("Modules/{$module}");
if (! File::isDirectory($dir)) {
continue;
}
foreach (File::allFiles($dir) as $file) {
preg_match_all("/DB::connection\\('([a-z_]+)'\\)/", $file->getContents(), $m);
foreach ($m[1] as $used) {
expect($used)->toBe($own, "{$file->getRelativePathname()} in {$module} uses '{$used}'");
}
}
}
});The Laravel angle
- Facades make boundaries easy to cross:
DB::table('payments')works from any module. That is why the connection-name lint exists: the framework will not stop it. ShouldDispatchAfterCommitandShouldQueueare the in-process half of ADR-0003: listeners never see a rolled-back order and run on a worker. For a real broker, the same contract travels through an outbox relay (see Outbox).- Pest
arch()presets (arch()->preset()->php(),->security()) cover generic rules; decision-specific rules like the ones above are what ADRs add. - Octane vs PHP-FPM is itself an ADR-worthy choice: Octane keeps the app in memory (faster) and adds long-lived-process concerns (state leaking between requests).
Solving the classic problems
Analysis paralysis
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Classify the door first | Two-way doors: one person, one PR | Most decisions become fast | Needs trust |
| Time-box | "Decide by Friday; if tied, author picks" | Ends debates | Occasionally a worse pick |
| 70% rule | Bezos: decide with ~70% of the information | Speed | Requires fast correction |
| Spike | One week of code answers the disputed score | Evidence replaces opinion | A week |
Decision by the loudest voice (HiPPO)
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Drivers before options | Agree weights first, in writing | Anchoring reduced | One extra meeting |
| Independent scoring | Each reviewer scores alone, then compare | Hidden disagreement surfaces | Effort |
| Disagree and commit | Record dissent in the ADR | Fast, honest | Requires a culture that allows it |
Decisions forgotten or stale
| Solution | How | Advantage | Cost |
|---|---|---|---|
| ADR in the repo, next to code | docs/decisions/ | Visible in code review | Discipline |
Review-by dates + adrlint | CI fails on stale ADRs | Decisions are re-checked | Noise if dates are unrealistic |
| Revisit triggers | "Revisit when a second team owns a module" | Re-evaluation tied to events | Someone must notice the event |
Decision drift: code no longer matches the decision
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Fitness functions | Tests above | Drift caught in the PR | Writing and maintaining tests |
| Language mechanisms | Go internal/, PHP final, private packages | Free enforcement | Coarse |
| Database permissions | One role per module; GRANT only own tables | Enforced even for raw SQL | Migration effort |
ADRs turned into bureaucracy
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Advice process | Deciding team decides after seeking advice | Speed and ownership | Needs trust in teams |
| One-page limit | Link spikes instead of pasting them | ADRs are read | Some detail moves elsewhere |
| ADR only for significant decisions | Use the reversibility matrix | Fewer, better ADRs | Judgment calls |
Reversing a decision safely
Step Reversing ADR-0002 (PostgreSQL -> another engine for one table), as an example
1 1 Write ADR-0015 "Proposed", status of 0002 unchanged
2 2 Add adapter behind app.Store; dual-write behind a flag
3 3 Backfill and compare; switch reads at 5%, 50%, 100%
4 4 Stop dual-write; ADR-0015 Accepted; ADR-0002 "Superseded by ADR-0015"Choosing: how much process for which decision
| Situation | Process | Artifact | Guard | Reason |
|---|---|---|---|---|
| Two-way door, one team | One person decides in a PR | PR description | Normal tests | Speed matters more than perfection |
| Two-way door, many teams (log format) | Announce, then decide | Short ADR | Lint | Cheap to change, but people must know |
| Expensive, one team (language for a service) | Scored analysis + spike | ADR | CI, ownership | Team lives with it for years |
| One-way door, one product (primary DB) | Scored analysis + spike + review | ADR with confidence level | Fitness tests, review-by | Hard to reverse |
| One-way door, many teams (event platform) | RFC with comment period, then ADRs | RFC + ADRs in each repo | Contract tests | Others pay the second-order costs |
| Deliberate debt | Explicit decision with payback trigger | ADR ("accepting ...") | Tracking ticket | Debt is only prudent if planned |
| Expected rewrite (sacrificial) | State the 10x limit | ADR | Load test at 5x | Avoid both over-engineering and shame |
| You cannot decide yet | Buy an option (interface, flag) and set a decide-by date | Decision backlog entry | Calendar | Last responsible moment |
In architecture: from a single process to a distributed system
The kind of decisions changes with scale; the method does not.
Monolith: one process, one database
How it shows up: few decisions are one-way doors: the database engine, the framework, the ID scheme, the public URL structure. Most others are two-way, because a refactoring tool can move code.
Example (simple): a Laravel blog: one ADR for the database (SQLite in production with Litestream, or PostgreSQL), one for hosting. That is enough.
Example (production-shaped): Shop before ADR-0001: a layered Laravel app with controllers, services and Eloquent models. The decision worth writing is "how will we split later?", because the answer (modules now, or a rewrite later) is cheap today and expensive in a year.
Modular monolith: boundaries inside one deployable
How it shows up: decisions move from "which technology" to "where is the boundary and what crosses it". Each boundary is an ADR plus a fitness test; database schemas or roles per module make the decision visible to the database.
-- PostgreSQL: one schema and one role per module; grants are the ADR in SQL.
CREATE SCHEMA orders; CREATE SCHEMA payments;
CREATE ROLE orders_app LOGIN; CREATE ROLE payments_app LOGIN;
GRANT USAGE ON SCHEMA orders TO orders_app;
GRANT USAGE ON SCHEMA payments TO payments_app;
-- No GRANT on payments.* to orders_app: a reach-in fails with SQLSTATE 42501.Example: Shop with ADR-0001 to ADR-0004 as in this page; archtest and Pest guard them.
Microservices: decisions cross team and network boundaries
What changes: many decisions become one-way doors for other teams (API contracts, event schemas), so RFCs replace hallway conversations. Every split carries the second-order costs Fowler lists (distribution, eventual consistency, operational complexity).
Flow after notifications becomes its own service (ADR-0011 supersedes ADR-0003)
1 orders-svc POST /orders -> BEGIN; INSERT order; INSERT outbox; COMMIT
2 relay outbox row -> broker topic orders.order_placed.v1
3 notif-svc consume -> inbox check -> send mail -> mark processed -> ack
4 notif-svc failure x5 -> DLQ; alert owner (notifications team)
5 archtest moves to notif-svc repo: no import of orders code is possible anyway;
new guard = consumer contract test against the v1 schemaExample: a payments split adds a saga (reserve → charge → confirm, with compensations): each step and compensation is a decision recorded in the saga's ADR (Saga); Data Ownership explains why TestNoSharedDatabase becomes essential.
Distributed data: replicas, caches and multi-region
| Decision | Second-order effect | Third-order effect | Guard |
|---|---|---|---|
| Read replicas | Replica lag | Read-your-writes routing rules in code | Test that post-write reads use the primary |
| Redis cache in front of catalog | Invalidation on every write | Stale prices, stampedes on expiry | Versioned keys; alert on hit ratio |
| Multi-region active-passive | Failover runbooks | Data loss window (RPO) is now a business decision | Game days (Backup and DR) |
| Multi-region active-active | Conflicts on concurrent writes | Conflict resolution rules per entity | Conflict metrics |
| Event log as source of truth | Replays, schema evolution | Storage and retention cost | Schema registry compatibility check |
Scaling path: 1×, 10×, 100×
| Scale | Typical decisions | Process | Guards |
|---|---|---|---|
| 1× (one team) | DB engine, framework, module layout | ADRs in the repo, a handful | Import tests, internal/ |
| 10× (several teams) | Boundaries, async vs sync, data ownership | ADRs + advice process; RFC for cross-team | Fitness tests in CI, DB roles, contract tests |
| 100× (many teams, many services) | Platforms, event backbone, multi-region, sacrificial rewrites (Dean's "rewrite before ~100X") | RFC process with comment periods, architecture guild reads all RFCs | Holistic fitness functions (SLOs), schema registry, dependency dashboards |
Lab: three ADRs, three fitness tests
You will write three ADRs for Shop, then make each one fail a test when violated. Everything runs offline with Go 1.24+.
Setup.
cd docs/snippets/architecture/architecture-decisions-tradeoffs/go
go vet ./...
go test ./...
# ok academy/architecture-decisions-tradeoffs/cmd/adrlint
# ok academy/architecture-decisions-tradeoffs/shop/archtestStep 1: write the decision log. Create a scratch folder /tmp/shop-decisions with three files using the templates from Worked decisions: 0001-modular-monolith.md, 0003-async-events-orders-notifications.md, 0004-no-shared-database.md. Each must have Status, Context, Decision, Consequences, a second-order effects table and a Review-by: line. Then:
go run ./cmd/adrlint /tmp/shop-decisions
# adrlint: decision log OKExpected: OK. Now change one status to Approved and run again: status "Approved" is not one of [proposed accepted rejected deprecated superseded], exit code 1.
Step 2: break ADR-0001 (dependency rule). Add "database/sql" to the imports of shop/orders/domain/order.go and use it (var _ *sql.DB). Run go test ./shop/archtest. Expected: ADR-0001 violated: ../orders/domain/order.go imports database/sql. Revert.
Step 3: break ADR-0003 (events only). In shop/notifications/notify.go import academy/architecture-decisions-tradeoffs/shop/orders/domain and reference domain.ErrEmptyOrder. Expected: two failures, ADR-0001 violated (not via api) and ADR-0003 violated (consume contracts/events instead). Revert.
Step 4: break ADR-0004 (no shared database). In config/notifications.env change /notifications? to /payments?. Expected: ADR-0004 violated: notifications and payments share database pg-shared.internal:5432/payments. Note that payments and notifications already share the server pg-shared.internal: the ADR allows a shared server, not a shared database. Revert.
Step 5: supersede a decision. Write 0005-notifications-as-a-service.md with Status Proposed, then set ADR-0003's status to Superseded by ADR-0006 (a number that does not exist). Expected adrlint error: superseded by ADR-0006, which does not exist. Fix it to ADR-0005.
Step 6: second-order effects. For your ADR-0003, list three effects per order (1st, 2nd, 3rd) and name an owner for each. Expected: at least the inbox table, the DLQ owner and the support lookup appear.
| Measure | Before the lab | After |
|---|---|---|
| Decisions written down | 0 | 3 ADRs, linted |
| Decisions that fail CI when violated | 0 | 3 |
| Second-order effects with an owner | 0 | ≥ 6 |
Step 7 (Laravel, optional). Copy the PHP files into a Laravel 13 app with Pest, add ORDERS_DB_*, PAYMENTS_DB_*, NOTIFICATIONS_DB_* to .env, run ./vendor/bin/pest tests/Architecture. Expected: all pass; adding DB::connection('payments') inside app/Modules/Orders fails "lets module code name only its own connection".
Common misconceptions
| Belief | Reality |
|---|---|
| There is a perfect architecture | Everything is a trade-off; aim for the least-worst combination for your context |
| Best practices settle architecture questions | Best practices are context-free; decisions are not. InfoQ's summary of Ford and Richards: "Software architecture is the stuff you can't Google." |
| A pros-and-cons list is a trade-off analysis | Without weights, evidence and rejected options it is advocacy |
| All decisions deserve the same rigour | Bezos: one-size-fits-all process causes "slowness, unthoughtful risk aversion" |
| Deciding late is always better | Past the last responsible moment, decisions are "made by default" |
| ADRs are approvals | They record reasoning; approval boards kill them |
| Accepted ADRs should be updated as things change | Supersede; never rewrite history (Nygard, Fowler) |
| ADRs are written after the fact | Writing them clarifies thinking during the decision (Fowler 2026) |
| Consequences means "pros and cons" | Include negative, neutral and second-/third-order effects with owners |
| Technical debt is always a failure | Deliberate, prudent debt is a valid decision with a payback plan |
| A rewrite means the first architecture failed | Sacrificial architecture: eBay's discarded versions carried its growth |
| Fitness functions are performance tests | Any checkable characteristic: dependencies, data ownership, contracts, ADR health |
| Microservices remove decisions | They multiply them and push their costs to other teams |
Cheat sheet
| Topic | Remember |
|---|---|
| Architecture decision | Significant, costly to reverse, or cross-cutting |
| First law | Everything in software architecture is a trade-off; no cons means not analysed |
| Second law | Why is more important than how: record reasons |
| Doors | Type 1 one-way: slow, careful; Type 2 two-way: fast, one person |
| 70% | Decide with ~70% of the information if you can correct fast |
| Method | Frame → drivers (MECE, weighted) → options (incl. do nothing) → score → weigh + sensitivity → ADR → guard |
| Second-order | Ask "and then what?" twice; every effect gets an owner |
| Timing | Last responsible moment; buy options (interfaces, flags); know the cost of delay |
| ADR (Nygard) | Title, Status, Context, Decision, Consequences; 1-2 pages; numbered, never reused |
| MADR 4.0.0 | Drivers, Considered Options, Outcome, Consequences, Confirmation, Pros and Cons |
| Y-statement | In the context of, facing, we decided for, to achieve, accepting |
| Lifecycle | Proposed → Accepted / Rejected → Deprecated / Superseded by N; never edit accepted |
| Storage | docs/decisions/NNNN-title.md, Markdown, reviewed in PRs, linked to code |
| RFC | Consult before deciding across teams; Rust FCP 10 days; Oxide 6 states |
| Debt quadrant | Reckless/prudent × deliberate/inadvertent; prudent-deliberate needs an ADR |
| Sacrificial | Design for ~10x, plan to rewrite before ~100x; keep modules and data clean |
| Fitness function | A test or threshold that fails when a decision is broken; name the ADR in the message |
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 — Name the three markers of an architecture decision and give an example of each. Must-know
Answer
Answer: Significant (changes a quality attribute: sync call to fraud scoring), costly to reverse (database engine), cross-cutting (event envelope format used by all teams). See Architecture decision.
2 — What did Bezos say goes wrong when organisations use Type 1 process for Type 2 decisions? Good to know
Answer
Answer: "slowness, unthoughtful risk aversion, failure to experiment sufficiently, and consequently diminished invention." See Reversibility.
3 — Give two techniques that turn a one-way door into a two-way door. Important
Answer
Answer: Any two of: ports and adapters, feature flags, expand/contract migrations, the strangler fig, versioned contracts, spikes. See Reversibility.
4 — Why must drivers be weighted before options are listed? Important
Answer
Answer: To avoid anchoring and confirmation bias: weights chosen after seeing options tend to favour the favourite. MECE drivers also prevent double counting. See Trade-off analysis and Biases.
5 — Trace microservices to its third-order effect. Good to know
Answer
Answer: Microservices → no shared transaction (distributed transactions) → sagas with compensations → semantic locks, stuck-saga dashboards, on-call runbooks and new skills. See Second-order effects.
6 — Define the last responsible moment and the risk on each side of it. Important
Answer
Answer: "the moment at which failing to make a decision eliminates an important alternative". Before it you decide on guesses; after it decisions "are made by default". See Decision timing.
7 — List Nygard's five ADR sections and two of his rules. Important
Answer
Answer: Title, Context, Decision, Status, Consequences. Rules: numbered sequentially and monotonically, numbers never reused; reversed decisions are kept and marked superseded; one or two pages; stored in the repository. See ADRs.
8 — What does MADR's "Confirmation" section add, and why does it matter? Good to know
Answer
Answer: How compliance with the decision "can/will be confirmed", e.g. an automated fitness function or a review. It links the record to a guard, which is what stops drift. See Fitness functions.
9 — When do you use an RFC rather than only an ADR? Must-know
Answer
Answer: When the decision crosses team boundaries or is a one-way door for others; the RFC consults before deciding (Rust's FCP, Uber's mailing lists, Oxide's discussion state), then ADRs record the result in each affected repo. See RFCs.
10 — Which quadrant of Fowler's technical debt model is a legitimate architecture decision, and what must its ADR contain? Good to know
Answer
Answer: Deliberate and prudent. The ADR states what is accepted, the estimated interest, a payback trigger and an owner. See Technical debt.
11 — In the lab, why does payments and notifications sharing pg-shared.internal pass TestNoSharedDatabase? Good to know
Answer
Answer: ADR-0004 forbids sharing a database, not a server; the key is host, port and database name. Sharing a server is a cost decision; sharing tables is a coupling decision. See Go and Lab.
12 — Go vs PHP: why can the same team rationally choose both? Must-know
Answer
Answer: Because the trade-off depends on the workload: the CRUD back office scores higher in Laravel (delivery speed, team skills), the bursty webhook ingester in Go (resource use at peak). The ADR records the second-order cost: two toolchains and on-call skills. See Decision 4.
Glossary
| Term | Meaning |
|---|---|
| Architecture decision (AD) | A justified choice addressing an architecturally significant requirement |
| Architecturally significant requirement (ASR) | A requirement with a measurable effect on architecture and quality |
| ADR | Architecture decision record: one short file per decision with context, decision, status, consequences |
| Decision log | The collection of ADRs of a project |
| MADR | Markdown Architectural Decision Records; template v4.0.0 (2024) with Decision Drivers, Considered Options, Confirmation |
| Y-statement | One-sentence decision format: context, concern, decision, quality, downside accepted |
| Proposed / Accepted / Rejected / Deprecated / Superseded | ADR lifecycle states |
| adr-tools | Command-line tool (adr init, adr new, adr new -s) for Nygard-style ADRs |
| RFC | Request for Comments: a proposal circulated for comment before a decision |
| RFD | Request for Discussion (Oxide); states prediscussion, ideation, discussion, published, committed, abandoned |
| Final comment period (FCP) | Rust's last 10-day window before an RFC is merged or closed |
| Advice process | The deciding person seeks advice from those affected, then decides and records it |
| One-way door (Type 1) | Consequential, irreversible or nearly irreversible decision |
| Two-way door (Type 2) | Changeable, reversible decision |
| Disagree and commit | Committing to a decision despite disagreement, made explicit |
| Blast radius | How many teams, services and clients a decision affects |
| Trade-off analysis | Scoring options against weighted architecture characteristics and constraints |
| Architecture characteristic | An "-ility" orthogonal to domain functionality (scalability, availability, security) |
| MECE | Mutually exclusive, collectively exhaustive: drivers that neither overlap nor leave gaps |
| Weighted decision matrix (Pugh matrix) | Table of options × drivers with weights and scores |
| Sensitivity check | Changing weights to see whether the winner changes |
| Least-worst | Ford's framing: pick the option whose weaknesses hurt least, not a "best" one |
| Second-/third-order effect | A consequence of a consequence, one or two causal steps removed |
| Last responsible moment | The moment after which not deciding eliminates an important alternative |
| Options thinking | Paying a small cost now (interface, flag) to keep a choice open |
| Cost of delay / CD3 | Value lost per unit of waiting; CD3 divides it by duration to rank work |
| Spike | Time-boxed experiment that produces evidence for a score |
| Technical debt quadrant | Fowler's reckless/prudent × deliberate/inadvertent grid |
| Sacrificial architecture | An architecture built knowing it will be replaced as the system grows |
| Fitness function | Objective, automated check of an architectural characteristic |
| Tactic | A design decision aimed at one quality attribute (Bass et al.) |
| ATAM | SEI's Architecture Tradeoff Analysis Method |
| Sensitivity point / trade-off point | A decision that strongly affects one quality / several qualities in opposite directions |
| Dependency rule | Inner layers (domain) do not depend on outer ones (infrastructure) |
| Database per service | Each service owns its data; others use its API or events |
| Bounded Context | DDD's boundary of one model; Fowler: DDD divides large models "into different Bounded Contexts" (Bounded Context) |
| Outbox | Writing an event in the same transaction as the state change, published later |
| Anchoring, sunk cost, confirmation bias | Cognitive biases that distort architecture decisions |
| HiPPO | Highest-paid person's opinion deciding instead of analysis |
References
- Michael Nygard, "Documenting Architecture Decisions", 15 November 2011
- ADR GitHub organization, Architectural Decision Records and ADR Templates (Y-statement)
- MADR, About MADR (4.0.0, 17 September 2024) and the template
- Nat Pryce, adr-tools README
- Martin Fowler, "Architecture Decision Record", 24 March 2026; "Technical Debt Quadrant", 14 October 2009; "Sacrificial Architecture", 20 October 2014; "Bounded Context", 15 January 2014; "Microservice Trade-Offs", 1 July 2015; "Microservice Premium"
- Jeff Bezos, 2015 Letter to Shareholders (PDF) and 2016 Letter to Shareholders
- Thomas Betts with Neal Ford and Mark Richards, InfoQ podcast: Software Architecture: The Hard Parts
- Tech Lead Journal #120, Neal Ford: Software Architecture from Fundamentals to the Hard Parts
- Jeff Atwood, "The Last Responsible Moment" (quotes Poppendieck, Lean Software Development, 2003; secondary)
- Wikipedia (secondary): Cost of delay, Architecture tradeoff analysis method, Thinking, Fast and Slow
- Bachmann, Bass, Klein, Preliminary Design of ArchE (CMU/SEI-2003-TR-021), September 2003; Bass, Clements, Kazman, Software Architecture in Practice, 4th ed. (publisher page)
- Thoughtworks Technology Radar, Architectural fitness function; Thoughtworks, Fitness function-driven development
- Rust, RFC process README; Oxide, RFD 1: Requests for Discussion; Gergely Orosz, "Scaling Engineering Teams via RFCs: Writing Things Down"
- Chris Richardson, Database per service
- Laravel 13: Events (ShouldDispatchAfterCommit), Database; Pest: Architecture testing; Go: Go 1.4 release notes (internal packages)