ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 8 · Architecture Quality Attributes
  4. Volume VI
  5. Architecture Quality
Book 8 · Volume VI — Maintainability, Modifiability & Testability · Topic 1.4

Architecture Quality

Clear boundaries, conformance between intent and code, and living documentation

12 min readStage 3 · Systems10 interview questions
Chapter
Chapter 1 — Maintainability
Prerequisites
Topics 1.1–1.3; Book 7 (application architecture)
You will be able to
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
Covers
Architecture quality
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts — Architecture Quality
  4. 4. How It Works Internally — Measuring Architecture Quality
  5. 4A. Deep Dive — Architecture Health Scorecard
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

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.

Architecture quality dimensions
Figure 1 — Architecture quality dimensions
DimensionGood looks like
ModularityCapabilities in well-defined modules/services with small public APIs
CouplingFew, explicit, stable dependencies; no cycles
CohesionThings that change together live together
ConformanceCode follows intended layering and boundaries
Data ownershipEach dataset owned by one module/service
DocumentationCurrent C4 views and decision records
Table 1 — Dimensions
Architecture-quality vocabularyMeaning
Architecture erosionImplementation violating intended architecture over time
Architecture driftImplementation diverging from undocumented intent
Conformance checkingAutomated verification of structural rules
Fitness functionObjective test of an architectural characteristic (Chapter 6)
ADRArchitecture decision record
Table 2 — Terms

2Why It Exists

Intended vs actual architecture
Figure 2 — Intended vs actual architecture
Symptom of poor architecture qualityCost
Every feature touches many modules/servicesCoordination, slow delivery
Cycles between modulesCan't change or extract independently
Shared databasesHidden coupling, risky schema changes
Nobody can draw the current architecturePoor decisions, onboarding pain
Table 3 — Why it matters

3Core Concepts — Architecture Quality

3.1 Modular Structure

LevelBoundary
Package/module in a monolithSpring Modulith application modules; internal packages
ServiceDeployable unit with its own data
Domain/bounded contextTeam ownership, ubiquitous language
Table 4 — Boundaries at several levels

3.2 Conformance

Architecture fitness checks
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

C4 model levels
Figure 4 — C4 model levels
ArtifactKept current by
C4 context/container diagramsStructurizr DSL in repo, rendered in CI
Component viewsGenerated from Spring Modulith documenter
ADRsMarkdown in repo, reviewed in PRs
Service catalogBackstage with ownership, APIs, dependencies
Table 5 — Documentation as code

4How It Works Internally — Measuring Architecture Quality

MeasureSource
Rule violationsArchUnit/Modulith in CI
CyclesArchUnit slices, jdeps
Afferent/efferent coupling, instabilityPackage metrics (2.3)
Service call graph and fan-outTraces (OpenTelemetry service graph)
Change coupling across servicesGit history across repos
Shared data storesInfrastructure inventory
Table 6 — Static, runtime and historical views

4ADeep Dive — Architecture Health Scorecard

Architecture health score by service
Figure 5 — Architecture health score by service
Scorecard itemWeight
No rule violations / cycles20
Owns its data (no shared DB)20
API contracts versioned + contract-tested15
Fan-out ≤ 5 synchronous dependencies15
Docs current (C4, ADRs, runbook)10
Supported framework versions10
Change coupling with other services low10
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 {
    @ArchTest
    static final 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");
 
    @ArchTest
    static final ArchRule domainIsPure = noClasses().that().resideInAPackage("..domain..")
            .should().dependOnClassesThat()
            .resideInAnyPackage("org.springframework..", "jakarta.persistence..",
                                "software.amazon..");
 
    @ArchTest
    static final ArchRule noCycles = slices().matching("com.shopnow.checkout.(*)..")
            .should().beFreeOfCycles();
}
JAVA
// Spring Modulith: verify module boundaries and generate documentation
class ModularityTests {
    ApplicationModules modules = ApplicationModules.of(ShopCoreApplication.class);
 
    // fails on internal access/cycles
    @Test void verifiesModularStructure() {
        modules.verify();
    }
 
    @Test void writesDocumentation() {
        new Documenter(modules)
                .writeModulesAsPlantUml()
                .writeIndividualModulesAsPlantUml();
    }
}
TEXT
// Structurizr DSL (C4) kept in the repo and rendered in CI
workspace {
  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

SectionQuestions
ContextWhat problem, which quality attributes?
BoundariesWhich module/service owns what data?
DependenciesNew sync calls? Cycles? Shared data?
ContractsVersioned? Contract tests?
FitnessWhich rules/tests enforce the design?
DecisionADR link
Table 8 — Lightweight, repeatable review

6.5 Worked example — ADR

FieldContent
TitleADR-031: Checkout reads prices via PricingPort, not DB
StatusAccepted (2026-03)
ContextDuplicated pricing (DEBT-042); price mismatches
DecisionAll 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

ServiceScoreMain gap
catalog91—
checkout86fan-out 6
orders72shares DB with invoicing
legacy-admin38cycles, no contracts, EOL framework
Table 10 — Direction for investment

6.7 Worked example — interview whiteboard

PromptAnswer 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

RuleEnforced by
Domain has no framework importsArchUnit
No access to other modules' internalsSpring Modulith
No cycles between packages/modulesArchUnit slices
Controllers don't return entitiesArchUnit (7.2)
Only one module writes each tableDB grants + ArchUnit repository rule
Services don't share databasesInfra policy check
Table 12 — Rules shared via platform library

6.9 Worked example — change coupling across services

Service pair% of changes released togetherAction
orders ↔ invoicing64%Merge boundaries or introduce events
checkout ↔ pricing12%Acceptable
catalog ↔ search48%Search consumes catalogue events; contracts
Table 13 — Deploy-together frequency reveals poor boundaries (Chapter 4)

6.10 Worked example — documentation freshness

ArtifactFreshness rule
C4 container viewGenerated from DSL on every merge
Module diagramsGenerated from code (Modulith)
ADRsRequired for decisions listed in review checklist
RunbooksReviewed after each incident
Table 14 — Generated where possible, reviewed where not

6.11 Worked example — PayGrid cell architecture conformance

RuleCheck
No cross-cell callsMesh policy + trace check (fail if cell A → cell B)
Control plane not on request pathTrace check
Ledger writes only via ledger moduleArchUnit + DB grants
Table 15 — Architecture rules for resilience (Volume IV) also checked

6.12 Worked example — architecture quality anti-patterns

Anti-patternSymptom
Big ball of mudNo discernible structure
Distributed monolithServices that must deploy together
Anaemic boundariesModules with everything public
Architecture by PowerPointDiagrams nobody checks
Table 16 — Recognise them early

6.13 Worked example — extracting a module safely

StepQuality check
1. Define module APIModulith: no internal access
2. Remove cyclesArchUnit slices
3. Own dataTables accessed only by module
4. Events instead of callsModulith event publication registry
5. Extract to serviceContract tests; strangler routing
Table 17 — Quality first, extraction second

6.14 Worked example — architecture metrics trend

Metric20242026
Services with shared DB234
Rule violations in main branches~6000 (baseline frozen, new blocked)
Median sync fan-out74
Services with current C4 docs30%95%
Table 18 — Measured improvement

7Common Problems & Mistakes

MistakeFix
Architecture only on slidesExecutable rules
Rules added to legacy with thousands of violationsFreeze baseline, block new (ArchUnit FreezingArchRule)
Ignoring runtime couplingTrace-based service graphs
Stale diagramsDiagrams as code, generation
Reviews as gatekeepingLightweight reviews focused on decisions
Shared databases toleratedData ownership rules
Table 19 — Mistakes and fixes

8Performance & Production Considerations

ConsiderationPractice
ArchUnit test timeCache imported classes; run in unit phase
Boundary costExtra hop/indirection measured (ports cost little)
Extraction timingOnly 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

GuidelineDetail
Intent explicit and executableRules in build
Modular first, distribute when neededModular monolith → services
Data ownership is the key boundaryNo shared schemas
Measure structure and runtimeStatic + 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.

Test your knowledge on this topic →Flashcards from this topic's 10 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.