Define architecture quality beyond code quality, detect drift between intended and actual architecture, express architectural rules as executable fitness checks, measure coupling at module and service level, keep documentation useful with C4 and ADRs, and run lightweight architecture reviews and scorecards
Architecture quality is how well a system's large-scale structure — its modules, services, dependencies and data ownership — supports its quality goals, and how faithfully the implemented structure follows the intended one. Good code inside a tangled structure is still hard to maintain; architecture quality decides the reach of every change.
Figure 1 — Architecture quality dimensions
Dimension
Good looks like
Modularity
Capabilities in well-defined modules/services with small public APIs
Coupling
Few, explicit, stable dependencies; no cycles
Cohesion
Things that change together live together
Conformance
Code follows intended layering and boundaries
Data ownership
Each dataset owned by one module/service
Documentation
Current C4 views and decision records
Table 1 — Dimensions
Architecture-quality vocabulary
Meaning
Architecture erosion
Implementation violating intended architecture over time
Architecture drift
Implementation diverging from undocumented intent
Conformance checking
Automated verification of structural rules
Fitness function
Objective test of an architectural characteristic (Chapter 6)
ADR
Architecture decision record
Table 2 — Terms
2Why It Exists
Figure 2 — Intended vs actual architecture
Symptom of poor architecture quality
Cost
Every feature touches many modules/services
Coordination, slow delivery
Cycles between modules
Can't change or extract independently
Shared databases
Hidden coupling, risky schema changes
Nobody can draw the current architecture
Poor decisions, onboarding pain
Table 3 — Why it matters
3Core Concepts — Architecture Quality
3.1 Modular Structure
Level
Boundary
Package/module in a monolith
Spring Modulith application modules; internal packages
Service
Deployable unit with its own data
Domain/bounded context
Team ownership, ubiquitous language
Table 4 — Boundaries at several levels
3.2 Conformance
Figure 3 — Architecture fitness checks
Conformance is the gap between the architecture people believe they have and the one the code actually implements. Intended architecture lives in diagrams, ADRs and principles such as the domain has no framework dependencies or only the orders module writes the orders tables; implemented architecture is whatever the import statements, Spring beans, SQL grants and runtime calls really do. The gap opens one shortcut at a time, usually for good local reasons such as a deadline, and nobody notices until a change that should touch one module touches six. Conformance checking closes the gap by expressing each structural rule as an executable check. Static rules run in the unit-test phase: ArchUnit for layering, forbidden dependencies and cycles, and Spring Modulith for module boundaries and internal packages. Data rules run in infrastructure policy and database grants. Runtime rules use traces, for example failing a check when PayGrid cell A calls cell B or checkout calls loyalty synchronously. Each rule should link to the decision it enforces, so a violation explains itself, and legacy violations are frozen as a baseline so the build blocks only new ones.
3.3 Living Documentation
Figure 4 — C4 model levels
Artifact
Kept current by
C4 context/container diagrams
Structurizr DSL in repo, rendered in CI
Component views
Generated from Spring Modulith documenter
ADRs
Markdown in repo, reviewed in PRs
Service catalog
Backstage with ownership, APIs, dependencies
Table 5 — Documentation as code
4How It Works Internally — Measuring Architecture Quality
Measure
Source
Rule violations
ArchUnit/Modulith in CI
Cycles
ArchUnit slices, jdeps
Afferent/efferent coupling, instability
Package metrics (2.3)
Service call graph and fan-out
Traces (OpenTelemetry service graph)
Change coupling across services
Git history across repos
Shared data stores
Infrastructure inventory
Table 6 — Static, runtime and historical views
4ADeep Dive — Architecture Health Scorecard
Figure 5 — Architecture health score by service
Scorecard item
Weight
No rule violations / cycles
20
Owns its data (no shared DB)
20
API contracts versioned + contract-tested
15
Fan-out ≤ 5 synchronous dependencies
15
Docs current (C4, ADRs, runbook)
10
Supported framework versions
10
Change coupling with other services low
10
Table 7 — Composite score, reviewed quarterly
5APIs / Features / Syntax
JAVA
// ArchUnit: layering and no cycles, as tests that fail the build@AnalyzeClasses(packages = "com.shopnow.checkout")class ArchitectureTest {@ArchTeststaticfinal ArchRule layers = layeredArchitecture().consideringAllDependencies() .layer("Web").definedBy("..web..") .layer("Application").definedBy("..application..") .layer("Domain").definedBy("..domain..") .layer("Infrastructure").definedBy("..infrastructure..") .whereLayer("Web").mayNotBeAccessedByAnyLayer() .whereLayer("Application").mayOnlyBeAccessedByLayers("Web") .whereLayer("Domain") .mayOnlyBeAccessedByLayers("Application", "Infrastructure");@ArchTeststaticfinal ArchRule domainIsPure = noClasses().that().resideInAPackage("..domain..") .should().dependOnClassesThat() .resideInAnyPackage("org.springframework..", "jakarta.persistence..", "software.amazon..");@ArchTeststaticfinal ArchRule noCycles = slices().matching("com.shopnow.checkout.(*)..") .should().beFreeOfCycles();}
JAVA
// Spring Modulith: verify module boundaries and generate documentationclass ModularityTests { ApplicationModules modules = ApplicationModules.of(ShopCoreApplication.class);// fails on internal access/cycles@Testvoid verifiesModularStructure() { modules.verify(); }@Testvoid writesDocumentation() {new Documenter(modules) .writeModulesAsPlantUml() .writeIndividualModulesAsPlantUml(); }}
TEXT
// Structurizr DSL (C4) kept in the repo and rendered in CIworkspace { model { customer = person "Customer" shopnow = softwareSystem "ShopNow" { web = container "Web/App BFF" "Spring Boot 4" checkout = container "Checkout service" "Spring Boot 4" orders = container "Orders service" "Spring Boot 4" ordersDb = container "Orders DB" "Aurora PostgreSQL" } customer -> web "Uses" web -> checkout "REST" checkout -> orders "OrderPlaced (Kafka)" orders -> ordersDb "JDBC" } views { container shopnow { include * autolayout lr } }}
6Practical Examples
6.1 Erosion caught by the build
A developer injected OrderRepository into a checkout controller to "save time". The ArchUnit layering rule failed the PR; the change went through the application service instead. Before rules existed, 140 such shortcuts had accumulated in the legacy admin service.
6.2 Modular monolith health
ShopNow's shop-core (catalogue, pricing, promotions) runs as a Spring Modulith modular monolith. modules.verify() found 11 accesses to other modules' internal packages and 2 cycles; fixing them made it possible to extract promotions into its own service later without a rewrite.
6.3 Service call graph reveals coupling
The trace-derived service graph showed checkout synchronously calling 11 services per request. Architecture review consolidated reads into a checkout-view projection and moved notifications to events — fan-out dropped to 4.
6.4 Worked example — architecture review template
Section
Questions
Context
What problem, which quality attributes?
Boundaries
Which module/service owns what data?
Dependencies
New sync calls? Cycles? Shared data?
Contracts
Versioned? Contract tests?
Fitness
Which rules/tests enforce the design?
Decision
ADR link
Table 8 — Lightweight, repeatable review
6.5 Worked example — ADR
Field
Content
Title
ADR-031: Checkout reads prices via PricingPort, not DB
Status
Accepted (2026-03)
Context
Duplicated pricing (DEBT-042); price mismatches
Decision
All price reads through PricingPort; ArchUnit rule forbids pricing tables access
Consequences
+1 hop latency (≈ 3 ms); single source of truth
Table 9 — Decisions recorded with enforcement
6.6 Worked example — scorecard results
Service
Score
Main gap
catalog
91
—
checkout
86
fan-out 6
orders
72
shares DB with invoicing
legacy-admin
38
cycles, no contracts, EOL framework
Table 10 — Direction for investment
6.7 Worked example — interview whiteboard
Prompt
Answer outline
"How do you keep architecture quality from degrading?"
"Define intended structure explicitly — modules, layers, data ownership — and make it executable: ArchUnit and Spring Modulith rules in every build, cycle checks, contract tests, and runtime views from traces for service coupling. Keep documentation as code with C4/Structurizr and ADRs. Score services on a health scorecard quarterly and run lightweight architecture reviews for significant changes, feeding gaps into the debt register."
Table 11 — Structured answer
6.8 Worked example — conformance rule catalogue
Rule
Enforced by
Domain has no framework imports
ArchUnit
No access to other modules' internals
Spring Modulith
No cycles between packages/modules
ArchUnit slices
Controllers don't return entities
ArchUnit (7.2)
Only one module writes each table
DB grants + ArchUnit repository rule
Services don't share databases
Infra policy check
Table 12 — Rules shared via platform library
6.9 Worked example — change coupling across services
Service pair
% of changes released together
Action
orders ↔ invoicing
64%
Merge boundaries or introduce events
checkout ↔ pricing
12%
Acceptable
catalog ↔ search
48%
Search consumes catalogue events; contracts
Table 13 — Deploy-together frequency reveals poor boundaries (Chapter 4)
6.10 Worked example — documentation freshness
Artifact
Freshness rule
C4 container view
Generated from DSL on every merge
Module diagrams
Generated from code (Modulith)
ADRs
Required for decisions listed in review checklist
Runbooks
Reviewed after each incident
Table 14 — Generated where possible, reviewed where not
6.11 Worked example — PayGrid cell architecture conformance
Rule
Check
No cross-cell calls
Mesh policy + trace check (fail if cell A → cell B)
Control plane not on request path
Trace check
Ledger writes only via ledger module
ArchUnit + DB grants
Table 15 — Architecture rules for resilience (Volume IV) also checked
6.12 Worked example — architecture quality anti-patterns
Anti-pattern
Symptom
Big ball of mud
No discernible structure
Distributed monolith
Services that must deploy together
Anaemic boundaries
Modules with everything public
Architecture by PowerPoint
Diagrams nobody checks
Table 16 — Recognise them early
6.13 Worked example — extracting a module safely
Step
Quality check
1. Define module API
Modulith: no internal access
2. Remove cycles
ArchUnit slices
3. Own data
Tables accessed only by module
4. Events instead of calls
Modulith event publication registry
5. Extract to service
Contract tests; strangler routing
Table 17 — Quality first, extraction second
6.14 Worked example — architecture metrics trend
Metric
2024
2026
Services with shared DB
23
4
Rule violations in main branches
~600
0 (baseline frozen, new blocked)
Median sync fan-out
7
4
Services with current C4 docs
30%
95%
Table 18 — Measured improvement
7Common Problems & Mistakes
Mistake
Fix
Architecture only on slides
Executable rules
Rules added to legacy with thousands of violations
Freeze baseline, block new (ArchUnit FreezingArchRule)
Ignoring runtime coupling
Trace-based service graphs
Stale diagrams
Diagrams as code, generation
Reviews as gatekeeping
Lightweight reviews focused on decisions
Shared databases tolerated
Data ownership rules
Table 19 — Mistakes and fixes
8Performance & Production Considerations
Consideration
Practice
ArchUnit test time
Cache imported classes; run in unit phase
Boundary cost
Extra hop/indirection measured (ports cost little)
Extraction timing
Only when team/scale/deploy needs justify
Table 20 — Operating architecture quality
Architecture checks run on every build, so they must stay cheap. ArchUnit imports bytecode once per analysed package set and caches it across tests in the same JVM, so keep all rules for a module in one test class annotated with @AnalyzeClasses and restrict the import to production classes; a few hundred rules over a large service typically add seconds, not minutes. Spring Modulith verification is similar. Runtime conformance from traces needs a sampled but complete service graph, so derive it from tail-sampled traces plus span metrics rather than demanding full trace retention. Boundaries themselves have runtime cost only when they cross a process: a port or interface inside a modular monolith costs nanoseconds, whereas extracting a module into a service adds a network hop, serialisation and a new failure mode, typically a few milliseconds and a new SLO. That is why ShopNow extracts modules only when team ownership, independent scaling or deployment cadence justify it, and only after the module already passes its boundary rules inside the monolith.
9Architecture & Design Considerations
Guideline
Detail
Intent explicit and executable
Rules in build
Modular first, distribute when needed
Modular monolith → services
Data ownership is the key boundary
No shared schemas
Measure structure and runtime
Static + trace views
Table 21 — Design guidance
10Interview Questions & Answers
Q1L1 · BasicConcept
What is architecture quality?
Architecture quality is how well a system's large-scale structure, its modules, services, dependencies and data ownership, supports its quality goals, and how faithfully the implementation follows the intended structure. It sits above code quality: clean classes inside a tangled structure are still expensive to change, because architecture decides how far each change reaches. Its dimensions are modularity with small public APIs, low and explicit coupling without cycles, cohesion, conformance between intent and code, clear data ownership and current documentation. It is measured with rule violations, cycles, fan-out, change coupling and documentation freshness. At ShopNow a service that shared its database with invoicing scored 72 on the health scorecard, mostly because of that coupling.
Q2L1 · BasicConcept
What is architecture erosion?
Architecture erosion is the gradual divergence of the implemented system from its intended architecture, as individual changes violate the rules the design relied on. It happens one reasonable shortcut at a time: a controller injects a repository to save time, a module reaches into another module's internal package, a service reads another service's tables. Each shortcut looks harmless, but together they create cycles, hidden coupling and a structure nobody can draw, so changes touch many modules and extraction becomes a rewrite. ShopNow found about 140 such shortcuts in its legacy admin service before rules existed. The cure is to make intent executable with ArchUnit and Modulith checks so erosion fails the build immediately.
Q3L2 · IntermediateCode
How do you enforce layering in Java?
Enforce layering with ArchUnit rules that run as ordinary JUnit tests, so a violation fails the build like any other test. You annotate a test class with @AnalyzeClasses for the service's base package and declare a layeredArchitecture rule: define Web, Application, Domain and Infrastructure layers by package patterns, then state who may access whom, for example Web may not be accessed by any layer and Domain may only be accessed by Application and Infrastructure. Add a noClasses rule forbidding the domain package from depending on Spring, Jakarta Persistence or AWS SDK classes, and a slices rule requiring freedom from cycles. Share common rules through a platform library so every service applies them consistently.
Q4L2 · IntermediateInternals
What does Spring Modulith verify?
Spring Modulith verifies that a Spring Boot application is structured as well-bounded application modules. By convention each direct sub-package of the main application package is a module, and its sub-packages are internal unless explicitly exposed as named interfaces. Calling verify() on ApplicationModules.of(Application.class) in a test fails when one module accesses another's internal types, when there are cycles between modules or, where a module declares its allowed dependencies, when it uses any other. It also supports module-level integration tests with @ApplicationModuleTest, an event publication registry for reliable events between modules, and a Documenter that generates C4 and PlantUML diagrams from the code, keeping documentation aligned with reality.
Q5L3 · Senior EngineerScenario
How do you add rules to a legacy codebase?
Freeze the existing violations as a baseline and block only new ones. If you add strict rules to a codebase with hundreds of violations, every build fails and teams either disable the rules or ignore them. ArchUnit's FreezingArchRule wraps a rule and records current violations in a violation store committed to the repository; afterwards the build fails only on violations not in the store, and fixed violations are removed automatically so the baseline can only shrink. Combine it with targeted refactoring of the hotspots that change most, track the baseline count as a metric, and agree a date for each team to reduce it. ShopNow brought main-branch violations from about 600 to zero this way.
Q6L3 · Senior EngineerInternals
How do you measure runtime coupling?
Measure runtime coupling from what services actually do in production, mainly distributed traces. OpenTelemetry traces produce a service graph showing which services call which, synchronously or via messaging, with request rates, error rates and latency on each edge; from it you derive synchronous fan-out per request and dependency depth. ShopNow found checkout calling 11 services per request and reduced it to four. Complement traces with delivery coupling from git and deploy history: the percentage of changes that must be released together reveals boundaries that look separate but are not, such as orders and invoicing deploying together 64% of the time. Shared databases, found from the infrastructure inventory, are the third, often hidden, form.
Q7L4 · Technical ArchitectDesign
How do you keep documentation current?
Keep documentation current by generating it from sources that change with the system, and reviewing it where it cannot be generated. Write C4 context and container diagrams as code in Structurizr DSL in the repository, rendered in CI on every merge, so a new container appears in the same pull request that adds it. Generate component and module views from the code with the Spring Modulith Documenter. Keep ADRs as Markdown next to the code, reviewed in pull requests, and require one for decisions listed in the review checklist. Use a service catalogue such as Backstage for ownership, APIs and dependencies, and review runbooks after every incident. Measure freshness on the scorecard.
Q8L4 · Technical ArchitectDesign
What's in an architecture scorecard?
An architecture health scorecard combines a handful of weighted, objectively measurable items into one score per service, reviewed quarterly to direct investment. ShopNow's version gives 20 points for having no rule violations or cycles, 20 for owning its data without a shared database, 15 for versioned and contract-tested APIs, 15 for synchronous fan-out of five or fewer, 10 for current C4 diagrams, ADRs and runbooks, 10 for supported framework versions and 10 for low change coupling with other services. Most items are collected automatically from CI, traces and repository history. The score is used comparatively to find where help is needed, such as legacy-admin at 38, not to punish teams.
Q9L5 · Solution ArchitectConcept
Why is data ownership central?
Data ownership is central because shared data creates coupling that bypasses every other boundary. Two services that read and write the same tables are coupled through the schema: a column change in one can break the other, neither can change storage technology independently, and transactions and locks interact invisibly. Clean module APIs and separate deployments then give a false sense of independence. When each dataset has exactly one owning module or service, others must go through its API or consume its events, so contracts become explicit and versioned. ShopNow enforces it with database grants, an ArchUnit repository rule and an infrastructure check, and reduced services with shared databases from 23 to four.
Q10L5 · Solution ArchitectTrade-off
When should a module become a service?
A module should become a service only when a concrete need justifies the cost of distribution, and only after its boundary is already clean. Good reasons are independent ownership by a separate team, very different scaling or resource needs, a different deployment cadence, a different availability or compliance tier, or a different technology. Extraction adds network latency, partial failure, data consistency problems and operational overhead, so it should not be done for fashion. First make the module pass Spring Modulith verification, remove cycles, give it sole ownership of its tables and replace direct calls with events. Then extract it with contract tests and strangler routing, as ShopNow did with promotions.