Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why decisions need a method at allWhy it exists
Nygard, Bezos's doors, Poppendieck, Fowler, Richards and Ford, MADRWhere it comes from
What counts as an architecture decisionArchitecture decision
One-way and two-way doorsReversibility
A trade-off method that is not "it depends"Trade-off analysis
Microservices → sagas, events → UX, caching → stale readsSecond-order effects
When to decideDecision timing
ADR templates, lifecycle, storage, review, anti-patternsADRs
Rust RFCs, Uber, Oxide RFDs, advice processRFCs at team scale
Debt you take on purpose; code you plan to throw awayTechnical debt, Sacrificial architecture
Tests that guard decisionsFitness functions
Tactics, ATAM, sensitivity pointsTactics and ATAM
Anchoring, sunk cost, confirmation biasBiases
Scoring matrix, ADR tooling, failure messagesMechanics
Four full ADRs: PostgreSQL vs MongoDB, REST vs events, monolith vs modular, Go vs PHPWorked decisions
Decisions enforced as testsGo, Laravel
Paralysis, HiPPO, stale ADRs, driftSolving the classic problems
How much process for which decisionChoosing
Monolith to distributed systemIn architecture
Write three ADRs and three fitness testsLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
Architecture decisionA 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 throughPublic API shape used by partnersTreated casually, it locks you in for years
Two-way door (Type 2)A decision you can reverse cheaplyWhich retry library to useTreated heavily, it slows everything down
Trade-off analysisScoring options against the qualities that matterScore PostgreSQL vs MongoDB on 6 characteristics"It depends" without saying on what
Second-order effectThe consequence of the consequenceMicroservices → no shared transaction → sagasSurprise work lands on another team
Last responsible momentDecide when waiting longer would remove a good optionPick the broker when the first async flow is builtDecide too early on guesses, or too late by default
ADRA short, numbered record of one decision and why0003-async-events-orders-notifications.mdBlind acceptance or blind reversal later
RFC / RFDA proposal circulated for comment before decidingRust RFC with a final comment periodCross-team decisions surprise the teams
Fitness functionAn automated check that a decision still holdsA test that fails if domain imports database/sqlThe decision erodes one pull request at a time
Deliberate technical debtA shortcut taken knowingly with a payback plan"Ship with one shared schema, split in Q3"Debt nobody chose, interest nobody tracks
Sacrificial architectureBuilding something you expect to replaceVersion 1 sized for 10x, not 100xOver-engineering, or shame when it is replaced

The laws in one table.

StatementSourceWhat 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 podcastRecord the reasons, not only the diagram
Find "the least worst combination" of forcesNeal Ford, Tech Lead Journal #120Aim for least-worst, not best
"never use a one-size-fits-all decision-making process"Jeff Bezos, 2016 shareholder letterHeavy 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 AtwoodDecide late, but not by default
ADRs are "numbered sequentially and monotonically" and superseded, not deletedNygard 2011The log is history; never rewrite it

Four decisions, worked on this page.

DecisionChosenMain thing given upSecond-order effect we must pay forGuard
Monolith vs modular monolith vs microservicesModular monolithIndependent deploy per teamBoundaries must be policed by testsTestModulesTalkThroughAPIOnly, Pest arch()
PostgreSQL vs MongoDB for ordersPostgreSQLSchema-free documents, built-in shardingMigrations discipline; JSONB for the flexible partDriver-import test; CHECK constraints
Sync REST vs async eventsEvents via outboxImmediate consistency of notificationsIdempotent consumers, DLQ, "pending" statesTestNotificationsDependsOnEventsOnly
Go vs PHP for a serviceDepends on the service; worked: Go for the webhook ingester, PHP for the back officeSingle-language teamTwo toolchains, two hiring profilesCI 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 instinctDeciding with a method
Fast for the first decisionSlightly 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 seenSecond- and third-order effects are listed
Reasons live in one head; they leave with that personReasons live in the repository, next to the code
Every decision gets the same treatmentProcess scales with reversibility and blast radius
Erosion is noticed in productionErosion 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 ​

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

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

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

MarkerQuestionExample
SignificantDoes it change a quality attribute (availability, latency, security, cost)?Synchronous call from checkout to fraud scoring
Costly to reverseWould undoing it take more than a sprint or touch stored data?Choosing MongoDB, then moving to PostgreSQL
Cross-cuttingDo several modules, teams or clients depend on it?Event envelope format, authentication scheme
text
     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 accumulated

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

PracticeWhat it gives
A short "is this architectural?" checklist in the PR templateImplicit decisions become visible
ADR log in the repositoryA place to put the visible decision
CODEOWNERS on docs/decisions/ and on boundary codeThe right people see changes
Fitness functionsThe 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).

cost to reverse (hours, days, weeks, quarters)blast radius (one team to whole org)Cheap but widedecide fast, announce widelylog format, trace header name,lint rules, branch namingOne-way door (Type 1)ADR + RFC + spike, last responsible momentprimary database engine, service split,public API shape, event schema, tenancy modelTwo-way door (Type 2)decide in a pull request, revert if wrongretry library, internal helper API,feature-flagged UI changeExpensive but localspike + ADR, owned by one teamGo vs PHP for one new service,queue driver, ORM vs plain SQLadapters, flags, expand/contract,strangler: turn doors into two-way ones
text
     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 deprecation

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

TechniqueHow it lowers cost to reverseExample
Port and adapter (interface)Swap the implementation behind itapp.Store in the Go example; PostgreSQL adapter is one package
Feature flagTurn behaviour off without deployingNew checkout flow at 5% of traffic
Expand / contract migrationsOld and new schema live side by sideAdd column, dual-write, backfill, switch reads, drop
Strangler figReplace a system route by routeStrangler Fig
Versioned contractsOld clients keep workingorders.order_placed.v1 beside v2
Spike / prototypeLearn before committingOne-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:

1 Framequestion,door type2 Driverscharacteristics,constraints3 Optionsincl. "donothing"4 Scoreoption xcharacteristic5 Weighpick theleast-worst6 RecordADR withconsequences7 Guardfitness test,review-by datecontext changed or review date passed: run the loop again and supersede"It depends" done rigorously: say on what, score it, write it down, test it.
StepWhat you doOutputTrap to avoid
1 FrameWrite the question; classify the doorOne sentence + reversibilitySolving a different problem than the one asked
2 DriversList characteristics and constraints, MECE (mutually exclusive, collectively exhaustive)4-8 drivers with weightsOverlapping drivers counted twice ("speed" and "latency")
3 OptionsAt least three, including "do nothing" or "defer"Option listA favourite plus two straw men
4 ScoreEach option per driver, -2..+2, with evidenceMatrixScores without evidence; one person scoring alone
5 WeighWeighted sum, then sensitivity check: does the winner change if a weight moves by 1?Ranked optionsTreating the number as truth
6 RecordADR: context, decision, consequences, rejected optionsADR fileRecording only the winner
7 GuardFitness function + review-by dateTest, calendar entryDecision erodes silently
text
     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" UX

Richards 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:

ToolWhenNote
Weighted decision matrix (Pugh matrix)3-5 options, 4-8 driversShown in Mechanics
Quality attribute scenariosWhen "fast" or "available" is vagueSee Quality Attributes
ATAM workshopLarge, high-stakes systemsSee Tactics and ATAM
SpikeWhen a score has no evidenceTime-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.

Decision1st order2nd order3rd orderMicroservicessplit orders/paymentsno shared transaction:distributed transactionssagas withcompensating stepssemantic locks, stuck-sagadashboard, on-call runbook,new team skillsEvent-drivenasync between serviceseventual consistency(lag of ms to minutes)UX shows "pending",read-after-write gapscopy and design changes,support tooling, idempotentconsumers, DLQ ownershipCachingRedis in front of DBinvalidation logicon every write pathstale reads, stampedeon expiryversioned keys, TTL jitter,read-your-writes routing,cache metrics on dashboardsEach column is a new cost someone pays; the ADR's Consequences section lists at least columns 2 and 3.
Decision1st order (wanted)2nd order3rd orderWho pays
Split orders and payments into microservicesIndependent deploysNo shared transaction → distributed transactions → sagasCompensations, semantic locks, a dashboard for stuck sagas, on-call runbooksBoth teams, SRE, support
Event-driven integrationDecoupled teams, absorbs spikesEventual consistency: data lags by ms to minutesUI shows "pending"; support needs a tool to see where an order is; idempotent consumers, DLQFrontend, support, every consumer
Cache product pages in Redis10x fewer DB readsInvalidation on every write pathStale reads after price changes; stampede on expiry; versioned keys and TTL jitter (Caching)Every team writing product data
Read replicas for reportingPrimary offloadedReplica lag"I saved it but it's not there": read-your-writes routing (Replication)Backend, QA
Multi-tenant shared schemaCheap onboardingEvery query needs tenant_idRow-level security, noisy neighbours, per-tenant export toolingEvery developer, forever
Choose MongoDB for flexibilityNo migrations for new fieldsSchema lives in application codeReaders must handle every historical shape; data quality checksEvery reader, analytics
text
     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:

TechniqueHow
"And then what?" chainFor each first-order effect, ask "and then what?" twice; write each answer as a row
Ask the neighboursSend 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 templateColumns: 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.

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

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

ToolBuysCost
Interface / portEngine or vendor choice laterOne indirection
Outbox table with a pluggable relayBroker choice laterA table and a poller
UUIDv7 / ULID IDsLater sharding or multi-regionLarger keys than bigint
Feature flagsRollout and rollback decisions laterFlag debt; remove them
A walking skeletonReal measurements before committingA 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:

TemplateSectionsBest for
NygardTitle, Status, Context, Decision, ConsequencesMost teams; start here
MADR 4.0.0Optional 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 InformationDecisions 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:

DraftProposedAcceptedRejectedDeprecatedSuperseded by NPRagreednot chosen (kept)review-by date or contextchange: re-evaluateconcern gonereplacedreplacement ADR N links back and starts as a new draftAccepted ADRs are immutable in substance: fix typos, never rewrite the decision.
StatusMeaningWho changes itTypical trigger
ProposedUnder discussion, open PRAuthorDraft written
AcceptedAgreed and in forceDecision makers on mergeReview consensus
RejectedConsidered and not chosen (MADR lists it)Decision makersBetter option found
DeprecatedNo longer relevant, nothing replaces itOwnerThe concern disappeared (feature removed)
Superseded by ADR-NReplaced by a newer decisionAuthor of ADR-NContext 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.

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

Reviewing an ADR (checklist):

CheckQuestion
ProblemIs the question stated so someone outside the team understands it?
DriversAre the drivers MECE and weighted? Are constraints separated from wishes?
OptionsAre there at least two serious alternatives, plus "do nothing"?
EvidenceDoes each important score cite a spike, a benchmark, a doc or an incident?
ConsequencesAre negative and second-order effects listed with owners?
ConfidenceIs the confidence level stated (Fowler recommends it)?
ReversalIs there a revisit trigger or review-by date?
ConfirmationIs there a fitness function or review step that will notice a violation?

ADR anti-patterns ​

Anti-patternSymptomFix
ADR as approval formTeams wait weeks for a board; ADRs written after the fact to satisfy itThe deciding team writes and merges; the board reads and comments (advice process)
Stale ADRAccepted ADR contradicts the codeReview-by date; adrlint reports stale ADRs; fitness tests
Rewriting historyAccepted ADR edited to match a new decisionSupersede; keep the old file
Novel12 pages, nobody reads itOne page; link the spike; "inverted pyramid"
Sales pitchOnly pros; rejected options missingMADR's "Considered Options" and "Bad, because"
Everything is an ADR300 ADRs, 280 of them two-way doorsOnly architecturally significant decisions; small ones in PR descriptions
Retroactive justificationContext written to fit a decision already shippedFine for archaeology, but label it "recorded after the fact"
Orphan ADRNobody knows who owns itdecision-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:

ProcessTriggerSteps and statesDistinctive 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 impactTemplate → 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 RFDsAny idea, "timely rather than polished" (quoting IETF RFC 3)Six states: prediscussion, ideation, discussion, published, committed, abandonedDiscussion happens in the PR that integrates the RFD
ADR + advice process (Fowler 2026)A decision by one team affecting othersAuthor seeks advice, decides, records advice summary in the ADR"the act of writing them is used to elicit expertise and alignment"
text
     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 repo

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

QuadrantTypical sentenceArchitecture exampleResponse
Deliberate, prudent"We must ship now and deal with consequences"One shared schema for two modules until launchADR 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 aggregatesNew ADR; refactor with the next feature
Inadvertent, reckless"What's layering?"Controllers that write to five modules' tablesFitness tests first, then refactor
text
     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 0006

Fix / 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".

SignalSacrificial is reasonableBuild to last
Product-market fitUnknownProven
Expected growthOrders of magnitudeLinear
Cost of a rewriteOne team, monthsMany teams, years, data migrations
What you keepData, contracts, lessons about boundariesEverything

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

DecisionFitness functionKindWhere on this page
Dependency rule (domain imports no infrastructure)Parse imports (Go), Pest arch() (Laravel)Atomic, triggered in CIGo, Laravel
Modules talk through api packages onlyImport-graph testAtomic, CITestModulesTalkThroughAPIOnly
No shared databaseLint of connection strings and DB::connection() namesAtomic, CITestNoSharedDatabase, NoSharedDatabaseTest.php
Events only between orders and notificationsImport test forbidding orders/* and net/httpAtomic, CITestNotificationsDependsOnEventsOnly
ADR log is healthyadrlint: names, statuses, dangling supersedes, review datesAtomic, CIcmd/adrlint
p99 checkout < 300 msLoad test threshold or SLO alertHolistic, continuousSLOs
text
     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 lifecycle

Fix / 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)ImprovesUsually costsTrade-off point?
Introduce concurrency / async queuePerformance, availabilityConsistency, debuggabilityYes
Maintain multiple copies (cache, replica)Performance, availabilityConsistency, costYes
Encrypt dataSecurityPerformance, operabilityYes
Use an intermediary (gateway, broker)ModifiabilityLatency, a new failure pointYes
Restrict dependencies (layers, modules)Modifiability, testabilitySome performance, indirectionUsually mild
Heartbeat / health checkAvailabilityNetwork and code overheadMild

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:

BiasHow it shows upCounter-measure
AnchoringThe first option presented sets the frameWrite drivers and weights before options
Confirmation biasSearching only for evidence that the favourite worksAssign someone to argue the strongest alternative
Sunk cost"We've invested a year in this service mesh"Score options on future cost only
AvailabilityLast 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
OverconfidenceNo confidence level, no revisit dateFowler: record "the confidence level of the decision"
HiPPOHighest-paid person's opinion ends debateIndependent 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 AOption BOption CEvidence column
Consistency of order + payment (3)+2-10Spike results, doc links
Team skills (2)+1-1+2Survey of the team
Operational cost (2)0-2+1Vendor pricing
Time to first release (1)+10+2Estimate
Weighted sum9-98A wins narrowly over C
Sensitivity: skills weight 310-1010Tie: low confidence, review in 6 months

ADR tooling and layout ​

ToolCommand / locationNote
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
MADRnpm install madr && mkdir -p docs/decisions && cp node_modules/madr/template/* docs/decisions/Templates: full, minimal, bare; markdownlint config included
Folderdocs/decisions/NNNN-title-with-dashes.mdSubfolders per area are allowed; numbers then unique per folder only
Lintgo run ./cmd/adrlint docs/decisions (this page)Fails CI on bad names, statuses, dangling supersedes, stale reviews
OwnershipCODEOWNERS: /docs/decisions/ @arch-guildReviewers see every new ADR
PublishingA build task renders ADRs into the docs siteFowler: "We can use a build task to publish them"

Linking decisions to code ​

go
// Package domain holds the order rules. ADR-0001 (dependency rule): this
// package imports nothing from infrastructure.
package domain
text
     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-0001

Failure messages you will actually see ​

WhereMessageMeaning
go test ./shop/archtestADR-0001 violated: ../orders/domain/order.go imports database/sqlDependency rule broken
go test ./shop/archtestADR-0001 violated: ... imports .../shop/orders/domain (use .../shop/orders/api)Cross-module reach-in
go test ./shop/archtestADR-0004 violated: notifications and payments share database pg-shared.internal:5432/paymentsShared database
go run ./cmd/adrlint0003-x.md: superseded by ADR-0011, which does not existBroken decision log
go run ./cmd/adrlint0001-x.md: stale, review was due 2026-01-01Decision nobody re-checked
Go compileruse of internal package ... not allowedGo's own boundary (Go 1.4 internal/ rule)
Pesta failed arch() expectation naming the class and the forbidden namespace (wording depends on the Pest version; not verified here)Laravel boundary broken
PostgreSQLERROR: 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 monolithModular monolithMicroservices
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 sum716-2
markdown
# 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
EffectOrderOwnerMitigation
Boundaries can be crossed with one import2ndTech leadFitness tests in CI
Shared test suite gets slow2ndTeamPer-module test targets
Later split needs network contracts3rdFuture service ownerContracts 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)PostgreSQLMongoDB
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)+20
Managed offering in our cloud (1)+2+1
Weighted sum176
sql
-- 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;
markdown
# 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).
EffectOrderOwnerMitigation
Every structural change is a migration2ndOrders teamZero-downtime migrations
Reporting load on the primary2ndSRERead replica; route finance there
Replica lag surprises users3rdBackendRead-your-writes after checkout (Replication)
Engine lock-in2ndTech leadStore 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 callAsync 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-19
text
     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
markdown
# 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".
EffectOrderOwnerMitigation
Duplicate delivery2ndNotificationsIdempotent consumer / inbox
Poison messages2ndNotificationsDLQ + alert
Confirmation may lag3rdFrontend"Confirmation on its way" copy
Event schema is now a public contract2ndOrdersVersioned 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 LaravelBack office in GoWebhook ingester (10k req/s bursts, tiny logic) in LaravelIngester 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 app00: Octane adds long-lived-process concerns+1
Weighted sum, back office110--
Weighted sum, ingester--59
markdown
# 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.
EffectOrderOwnerMitigation
Two build pipelines2ndSREShared CI templates, one container base policy
On-call needs both skills2ndTeam leadPairing, runbooks per service
Shared logic tempts a shared library across languages3rdArchitectsShare contracts (JSON schema), not code
Hiring profile widens3rdManagementExplicit 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):

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

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

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

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

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

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

go
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
	}
}
ini
# ADR-0004: each service owns its database and its role.
SERVICE=orders
DATABASE_URL=postgres://orders_app@pg-orders.internal:5432/orders?sslmode=verify-full
ini
SERVICE=payments
DATABASE_URL=postgres://payments_app@pg-shared.internal:5432/payments?sslmode=verify-full
ini
SERVICE=notifications
DATABASE_URL=postgres://notifications_app@pg-shared.internal:5432/notifications?sslmode=verify-full

Decision-log guard: adrlint keeps ADRs alive (statuses, supersede links, review dates):

go
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
}
go
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)
			}
		})
	}
}
go
// 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 import database/sql" is legal Go.
  • Consumer-side interfaces keep doors two-way. app.Store is 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/analysis analyzers and run with go vet -vettool, or as depguard rules 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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.
  • ShouldDispatchAfterCommit and ShouldQueue are 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 ​

SolutionHowAdvantageCost / limitation
Classify the door firstTwo-way doors: one person, one PRMost decisions become fastNeeds trust
Time-box"Decide by Friday; if tied, author picks"Ends debatesOccasionally a worse pick
70% ruleBezos: decide with ~70% of the informationSpeedRequires fast correction
SpikeOne week of code answers the disputed scoreEvidence replaces opinionA week

Decision by the loudest voice (HiPPO) ​

SolutionHowAdvantageCost
Drivers before optionsAgree weights first, in writingAnchoring reducedOne extra meeting
Independent scoringEach reviewer scores alone, then compareHidden disagreement surfacesEffort
Disagree and commitRecord dissent in the ADRFast, honestRequires a culture that allows it

Decisions forgotten or stale ​

SolutionHowAdvantageCost
ADR in the repo, next to codedocs/decisions/Visible in code reviewDiscipline
Review-by dates + adrlintCI fails on stale ADRsDecisions are re-checkedNoise if dates are unrealistic
Revisit triggers"Revisit when a second team owns a module"Re-evaluation tied to eventsSomeone must notice the event

Decision drift: code no longer matches the decision ​

SolutionHowAdvantageCost
Fitness functionsTests aboveDrift caught in the PRWriting and maintaining tests
Language mechanismsGo internal/, PHP final, private packagesFree enforcementCoarse
Database permissionsOne role per module; GRANT only own tablesEnforced even for raw SQLMigration effort

ADRs turned into bureaucracy ​

SolutionHowAdvantageCost
Advice processDeciding team decides after seeking adviceSpeed and ownershipNeeds trust in teams
One-page limitLink spikes instead of pasting themADRs are readSome detail moves elsewhere
ADR only for significant decisionsUse the reversibility matrixFewer, better ADRsJudgment calls

Reversing a decision safely ​

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

SituationProcessArtifactGuardReason
Two-way door, one teamOne person decides in a PRPR descriptionNormal testsSpeed matters more than perfection
Two-way door, many teams (log format)Announce, then decideShort ADRLintCheap to change, but people must know
Expensive, one team (language for a service)Scored analysis + spikeADRCI, ownershipTeam lives with it for years
One-way door, one product (primary DB)Scored analysis + spike + reviewADR with confidence levelFitness tests, review-byHard to reverse
One-way door, many teams (event platform)RFC with comment period, then ADRsRFC + ADRs in each repoContract testsOthers pay the second-order costs
Deliberate debtExplicit decision with payback triggerADR ("accepting ...")Tracking ticketDebt is only prudent if planned
Expected rewrite (sacrificial)State the 10x limitADRLoad test at 5xAvoid both over-engineering and shame
You cannot decide yetBuy an option (interface, flag) and set a decide-by dateDecision backlog entryCalendarLast 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.

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

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

Example: 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 ​

DecisionSecond-order effectThird-order effectGuard
Read replicasReplica lagRead-your-writes routing rules in codeTest that post-write reads use the primary
Redis cache in front of catalogInvalidation on every writeStale prices, stampedes on expiryVersioned keys; alert on hit ratio
Multi-region active-passiveFailover runbooksData loss window (RPO) is now a business decisionGame days (Backup and DR)
Multi-region active-activeConflicts on concurrent writesConflict resolution rules per entityConflict metrics
Event log as source of truthReplays, schema evolutionStorage and retention costSchema registry compatibility check

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

ScaleTypical decisionsProcessGuards
1× (one team)DB engine, framework, module layoutADRs in the repo, a handfulImport tests, internal/
10× (several teams)Boundaries, async vs sync, data ownershipADRs + advice process; RFC for cross-teamFitness 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 RFCsHolistic 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.

bash
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/archtest

Step 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:

bash
go run ./cmd/adrlint /tmp/shop-decisions
# adrlint: decision log OK

Expected: 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.

MeasureBefore the labAfter
Decisions written down03 ADRs, linted
Decisions that fail CI when violated03
Second-order effects with an owner0≥ 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 ​

BeliefReality
There is a perfect architectureEverything is a trade-off; aim for the least-worst combination for your context
Best practices settle architecture questionsBest 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 analysisWithout weights, evidence and rejected options it is advocacy
All decisions deserve the same rigourBezos: one-size-fits-all process causes "slowness, unthoughtful risk aversion"
Deciding late is always betterPast the last responsible moment, decisions are "made by default"
ADRs are approvalsThey record reasoning; approval boards kill them
Accepted ADRs should be updated as things changeSupersede; never rewrite history (Nygard, Fowler)
ADRs are written after the factWriting 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 failureDeliberate, prudent debt is a valid decision with a payback plan
A rewrite means the first architecture failedSacrificial architecture: eBay's discarded versions carried its growth
Fitness functions are performance testsAny checkable characteristic: dependencies, data ownership, contracts, ADR health
Microservices remove decisionsThey multiply them and push their costs to other teams

Cheat sheet ​

TopicRemember
Architecture decisionSignificant, costly to reverse, or cross-cutting
First lawEverything in software architecture is a trade-off; no cons means not analysed
Second lawWhy is more important than how: record reasons
DoorsType 1 one-way: slow, careful; Type 2 two-way: fast, one person
70%Decide with ~70% of the information if you can correct fast
MethodFrame → drivers (MECE, weighted) → options (incl. do nothing) → score → weigh + sensitivity → ADR → guard
Second-orderAsk "and then what?" twice; every effect gets an owner
TimingLast 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.0Drivers, Considered Options, Outcome, Consequences, Confirmation, Pros and Cons
Y-statementIn the context of, facing, we decided for, to achieve, accepting
LifecycleProposed → Accepted / Rejected → Deprecated / Superseded by N; never edit accepted
Storagedocs/decisions/NNNN-title.md, Markdown, reviewed in PRs, linked to code
RFCConsult before deciding across teams; Rust FCP 10 days; Oxide 6 states
Debt quadrantReckless/prudent × deliberate/inadvertent; prudent-deliberate needs an ADR
SacrificialDesign for ~10x, plan to rewrite before ~100x; keep modules and data clean
Fitness functionA test or threshold that fails when a decision is broken; name the ADR in the message

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — 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 ​

TermMeaning
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
ADRArchitecture decision record: one short file per decision with context, decision, status, consequences
Decision logThe collection of ADRs of a project
MADRMarkdown Architectural Decision Records; template v4.0.0 (2024) with Decision Drivers, Considered Options, Confirmation
Y-statementOne-sentence decision format: context, concern, decision, quality, downside accepted
Proposed / Accepted / Rejected / Deprecated / SupersededADR lifecycle states
adr-toolsCommand-line tool (adr init, adr new, adr new -s) for Nygard-style ADRs
RFCRequest for Comments: a proposal circulated for comment before a decision
RFDRequest 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 processThe 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 commitCommitting to a decision despite disagreement, made explicit
Blast radiusHow many teams, services and clients a decision affects
Trade-off analysisScoring options against weighted architecture characteristics and constraints
Architecture characteristicAn "-ility" orthogonal to domain functionality (scalability, availability, security)
MECEMutually exclusive, collectively exhaustive: drivers that neither overlap nor leave gaps
Weighted decision matrix (Pugh matrix)Table of options × drivers with weights and scores
Sensitivity checkChanging weights to see whether the winner changes
Least-worstFord's framing: pick the option whose weaknesses hurt least, not a "best" one
Second-/third-order effectA consequence of a consequence, one or two causal steps removed
Last responsible momentThe moment after which not deciding eliminates an important alternative
Options thinkingPaying a small cost now (interface, flag) to keep a choice open
Cost of delay / CD3Value lost per unit of waiting; CD3 divides it by duration to rank work
SpikeTime-boxed experiment that produces evidence for a score
Technical debt quadrantFowler's reckless/prudent × deliberate/inadvertent grid
Sacrificial architectureAn architecture built knowing it will be replaced as the system grows
Fitness functionObjective, automated check of an architectural characteristic
TacticA design decision aimed at one quality attribute (Bass et al.)
ATAMSEI's Architecture Tradeoff Analysis Method
Sensitivity point / trade-off pointA decision that strongly affects one quality / several qualities in opposite directions
Dependency ruleInner layers (domain) do not depend on outer ones (infrastructure)
Database per serviceEach service owns its data; others use its API or events
Bounded ContextDDD's boundary of one model; Fowler: DDD divides large models "into different Bounded Contexts" (Bounded Context)
OutboxWriting an event in the same transaction as the state change, published later
Anchoring, sunk cost, confirmation biasCognitive biases that distort architecture decisions
HiPPOHighest-paid person's opinion deciding instead of analysis

References ​

Built by Morteza Negahi