ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 7 · Application Architecture & Distributed Systems
  4. Volume II
  5. Types of Monoliths
Book 7 · Volume II — Application Architecture Styles & Patterns · Topic 1.2

Types of Monoliths

Modular monolith, layered monolith and big ball of mud

9 min readStage 3 · Systems8 interview questions
Chapter
Chapter 1 — Monolithic Architecture
Prerequisites
Topic 1.1; Volume I Chapter 4
You will be able to
Distinguish modular, layered and big-ball-of-mud monoliths by structure and behaviour, build a modular monolith with Spring Modulith, recognise when a layered monolith has become a liability, diagnose a big ball of mud with dependency and change analysis, and plan an incremental path from mud to modular
Covers
Modular monolith; Layered monolith; Big ball of mud
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Comparing Types
  5. 4A. Deep Dive — From Mud to Modules
  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

Monoliths differ by their internal structure: a modular monolith is divided vertically into business-capability modules with enforced boundaries; a layered monolith is divided horizontally into technical layers; a big ball of mud has no meaningful structure at all.

Three kinds of monolith (TOC)
Figure 1 — Three kinds of monolith (TOC)
TOC typeDefinition
Modular monolithA single deployable composed of capability-aligned modules with explicit APIs, private internals, own data (schemas) and enforced dependency rules
Layered monolithA single deployable organised by technical layers (web, service, repository) across all features, typically sharing one data model
Big ball of mudA system whose structure has eroded into tangled, arbitrary dependencies — "haphazardly structured, sprawling, sloppy" (Foote & Yoder)
Table 1 — The three TOC types

2Why It Exists

Most teams start layered because frameworks encourage it; many drift toward mud under deadline pressure. Recognising the type you have, and the type you want, guides refactoring investments far better than a premature move to microservices.

The distinction matters because all three types look the same from outside: one artifact, one pipeline, one database. Architecture discussions often skip straight to "monolith versus microservices", when the more useful question is what kind of monolith you have. A layered monolith that is beginning to rot needs different work from a modular monolith that is simply growing, and a big ball of mud needs a rescue plan before any extraction is safe. Naming the type also sets expectations with management. Cost of change rises slowly in a well-enforced modular monolith but steeply in mud, so the type explains why delivery has slowed and which investment, enforcement, modularisation or extraction, will actually reverse it.

Cost of change over time
Figure 2 — Cost of change over time

3Core Concepts

3.1 Modular monolith

Modular monolith (TOC)
Figure 3 — Modular monolith (TOC)
JAVA
// Module API as a named interface; everything else in the module is internal
@org.springframework.modulith.NamedInterface("api")
package com.shop.pricing.api;
 
// Cross-module side effects via events persisted in the publication registry
@Service
class OrderService {
    private final ApplicationEventPublisher events;
    @Transactional
    public void confirm(OrderId id) {
        Order o = orders.get(id); o.confirm();
        events.publishEvent(new OrderConfirmed(id.value(), o.total()));
    }
}
Modular monolith propertyMechanism
Vertical capability modulesTop-level packages
Private internalsModulith internal packages
Explicit APIsNamed interfaces
Own dataSchema per module
Loose couplingEvents (@ApplicationModuleListener)
Enforcementverify() in CI
Table 2 — Building blocks

3.2 Layered monolith

Layered monolith (TOC)
Figure 4 — Layered monolith (TOC)
Layered monolith traitConsequence
web/, service/, repository/ packagesFeatures spread across all layers
One shared entity modelEverything joins everything
No module APIsAny service calls any service
Works for small appsDegrades as features grow
Table 3 — Layered monolith

3.3 Big ball of mud

Big ball of mud (TOC)
Figure 5 — Big ball of mud (TOC)
Mud symptomMeasurement
Cyclic dependencies everywhereSlice cycles (ArchUnit/Sonargraph)
God classesClasses > 2,000 lines, many dependencies
Change couplingFiles that always change together across packages
Fear of changeLow deploy frequency, high change failure rate
Knowledge silosOnly "old-timers" can change parts
Table 4 — Diagnosing mud

4How It Works Internally — Comparing Types

Comparing monolith types (TOC)
Figure 6 — Comparing monolith types (TOC)
Scenario: add loyalty discountModularLayeredMud
Files touched4 (pricing module)14 across layers30+ unpredictable
Teams involved12–3"whoever knows"
RiskLowMediumHigh
Table 5 — Change locality in practice

4ADeep Dive — From Mud to Modules

Improvement path
Figure 7 — Improvement path
StepTechnique
1 Find seamsDependency graph, change coupling, domain workshop
2 FreezeArchUnit FreezingArchRule — no new violations
3 Carve modulesMove packages by capability; introduce API types
4 Break cyclesEvents or extracted interfaces
5 Separate dataSchema per module; replace cross-module joins
6 EnforceModulith verify() blocking in CI
Table 6 — Incremental modularisation
JAVA
@ArchTest
static final ArchRule noNewCycles = FreezingArchRule.freeze(
        slices().matching("com.shop.(*)..").should().beFreeOfCycles());

5APIs / Features / Syntax

ToolPurpose
Spring Modulith ApplicationModulesDetect and verify modules
@ApplicationModule(allowedDependencies=…)Explicit dependency rules
@NamedInterfacePublished API packages
Event publication registryReliable in-process events
DocumenterModule diagrams & canvases
ArchUnit slices/layersRules for any structure
Table 7 — Tooling
JAVA
@ApplicationModule(allowedDependencies = { "pricing::api", "catalog::api" })
package com.shop.ordering;

6Practical Examples

6.1 Mud rescue

A 12-year-old insurance monolith had 1,400 cyclic package dependencies. Freezing violations, then carving eight capability modules over 9 months, reduced cycles to zero; deploy frequency rose from monthly to weekly.

6.2 Layered pain

A layered order system with 120 service classes needed three teams to coordinate on every feature. Re-slicing into capability modules (each with internal layers) gave each team a module and cut merge conflicts by 70%.

6.3 Worked example — package-by-layer vs by-feature

By layerBy feature (modular)
web/OrderControllerordering/web/OrderController
service/OrderServiceordering/OrderService
repository/OrderRepositoryordering/internal/OrderRepository
Table 8 — Same classes, different organisation

6.4 Worked example — module canvas (generated)

Fieldordering
Base packagecom.shop.ordering
APIOrderApi, OrderDto
Published eventsOrderPlaced, OrderConfirmed
Listens toPaymentCompleted
Dependenciespricing::api, catalog::api
Table 9 — Documenter output

6.5 Worked example — schema per module

SQL
CREATE SCHEMA ordering AUTHORIZATION shop_app;
CREATE SCHEMA pricing  AUTHORIZATION shop_app;
-- rule: no SQL references across schemas (tested)

6.6 Worked example — mud metrics dashboard

MetricValueTarget
Package cycles1,4000
God classes37< 5
Avg files per change18< 6
Table 10 — Measure mud to fix it

6.7 Worked example — module integration test

JAVA
@ApplicationModuleTest
class OrderingModuleTests {
    @Test
    void publishesOrderPlaced(Scenario scenario) {
        scenario.stimulate(() -> orders.place(sampleCommand()))
                .andWaitForEventOfType(OrderPlaced.class)
                .toArrive();
    }
}

6.8 Worked example — hybrid: layers inside modules

ModuleInternal layers
orderingweb / application / domain / infra
Table 11 — Layers still useful — inside capability modules

6.9 Worked example — when layered is fine

ContextOK?
Small CRUD app, one team✔
Growing domain, many teams✘ modularise
Table 12 — Fit depends on size

6.10 Worked example — extraction readiness

ModuleCouplingExtractable?
searchAPI only, events✔ easy
orderingcycles with pricing✘ fix first
Table 13 — Modular monolith enables extraction

6.11 Worked example — change coupling analysis

PairCo-changeDiagnosis
OrderService + PromoRules68%Boundary wrong
Table 14 — Git history shows real coupling

6.12 Worked example — mud causes

CauseCountermeasure
Deadline shortcutsDebt register, freeze rules
No architecture ownerArchitect + module owners
No enforcementCI rules
Table 15 — Mud is preventable

6.13 Worked example — team ownership per module

ModuleTeam
catalog, pricingMerch
ordering, paymentsCheckout
Table 16 — Modules enable ownership in one repo

6.14 Worked example — shared kernel inside monolith

Allowed sharedNot shared
Money, IDsOrder, Customer entities
Table 17 — Keep it tiny

6.15 Worked example — anti-corruption between modules

SituationApproach
Legacy module with messy modelAdapter in consumer module
Table 18 — ACL applies inside monoliths too

6.16 Worked example — build modularisation

OptionBenefit
Maven multi-module per capabilityCompile-time boundaries, faster builds
Single module + ModulithSimpler build, test-time checks
Table 19 — Choose enforcement level

6.17 Worked example — roadmap

QuarterGoal
Q1Freeze rules, map domains
Q2Carve 3 modules
Q3Remaining modules, schemas
Q4Verify blocking, consider extraction
Table 20 — Year-long modularisation

6.18 Worked example — naming smells

NameSuggests
CommonUtils, Manager, HelperCoincidental cohesion
PricingApi, OrderPlacedCapability thinking
Table 21 — Names reveal structure

6.19 Worked example — modular monolith vs microservices checklist

NeedModular monolithMicroservices
Team autonomy (≤ 4 teams)✔◆
Independent scaling◆✔
Simplicity✔✘
Table 22 — Choose deliberately

6.20 Worked example — measuring improvement

MetricBeforeAfter modularisation
Deploy frequencymonthlyweekly
Change failure rate28%12%
Onboarding to first PR3 weeks1 week
Table 23 — Evidence of value

6.21 Worked example — interview answer

TypeOne-liner
ModularVertical modules, enforced APIs
LayeredHorizontal layers, shared model
MudNo structure, tangled
Table 24 — Structured answer

7Common Problems & Mistakes

  • Assuming layered = well-structured.
  • Modules without enforcement decay into mud.
  • Shared entity model across modules.
  • Big-bang rewrites instead of incremental modularisation.
  • Jumping to microservices from mud (distributed mud).
  • Ignoring change-coupling evidence.

These mistakes share one root: structure that is assumed rather than enforced and measured. Teams believe tidy web, service and repository packages mean a healthy design, while features are coupled through a shared entity model. Others introduce modules but no CI checks, and within months developers import internal classes because it is quicker, so the modules decay into mud. A shared JPA model across modules is the most common leak, because one entity relationship couples two capabilities at both code and database level. Big-bang rewrites and jumps to microservices fail for the same reason: they replace a system before anyone understands its real boundaries. Change-coupling data from git history is the cheapest way to see those boundaries before acting.

8Performance & Production Considerations

AspectGuideline
StructureCapability modules with internal layers
EnforcementModulith verify, ArchUnit freeze
DataSchema per module
IntegrationAPIs + events
MeasurementCycles, change coupling, DORA metrics
Table 25 — Operational guidelines

9Architecture & Design Considerations

  • Target the modular monolith as the default monolith form.
  • Treat mud as technical debt with a repayment plan.
  • Use layers inside modules, not modules inside layers.
  • Make extraction a later option, not an escape from mud.

10Interview Questions & Answers

Q1L1 · BasicConcept

What types of monoliths exist?

Monoliths are classified by internal structure, since all three are a single deployable. A modular monolith is split vertically into business-capability modules, each with an explicit API, private internals, its own data and enforced dependency rules. A layered monolith is split horizontally into technical layers such as web, service and repository that run across every feature and usually share one data model. A big ball of mud, the term from Foote and Yoder, has no meaningful structure left: dependencies are tangled and cyclic, and changes ripple unpredictably. The type, not the deployment unit, decides maintainability. A modular monolith keeps change local and makes later extraction cheap, while mud makes every change expensive.

Q2L1 · BasicConcept

What is a modular monolith?

A modular monolith is one deployable application divided into modules that each own a business capability, such as ordering or pricing. Each module exposes a small published API, keeps its internal classes inaccessible to other modules and owns its data, typically in its own database schema. Modules talk through API calls or in-process events rather than reaching into each other's tables or classes. The crucial part is enforcement: in Spring Boot, Spring Modulith's verify() or ArchUnit rules fail the build when someone crosses a boundary. You get most of the design benefits of microservices, such as team ownership, without network calls, distributed transactions or many pipelines, and modules can be extracted later.

Q3L2 · IntermediateTricky

What's the weakness of a layered monolith?

The main weakness is that a layered monolith groups code by technical role instead of business capability, so every feature is spread across all layers. Adding a loyalty discount touches controllers, services, repositories and the shared entity model, often fourteen files, and several teams must coordinate. Because there are no module APIs, any service can call any other service and any repository can join any table, so coupling grows silently. The layers look tidy, which is why teams assume good structure, but they say nothing about which business parts depend on which. It works for small CRUD applications with one team; as the domain and team grow, it drifts toward mud.

Q4L2 · IntermediateScenario

How do you recognise a big ball of mud?

You recognise a big ball of mud from both structural and behavioural evidence. Structurally, dependency analysis with ArchUnit slices, Sonargraph or jQAssistant shows cyclic dependencies between most packages, and god classes of several thousand lines with dozens of collaborators. Change analysis of git history, for example with CodeScene, shows high change coupling: files in unrelated packages that always change together, and an average change touching many files. Behaviourally, delivery slows down: deployments are infrequent, the change failure rate is high, people are afraid to touch certain areas, and only a few long-serving engineers understand them. Measuring these numbers matters, because it turns a vague complaint into a baseline you can track while fixing it.

Q5L3 · Senior EngineerInternals

How does Spring Modulith help?

Spring Modulith makes module boundaries in a Spring Boot application explicit and testable. It treats each direct sub-package of the main application package as an application module, and by convention only the module's base package is its API; sub-packages are internal. @NamedInterface publishes extra API packages, and @ApplicationModule with allowedDependencies restricts which modules a module may use. ApplicationModules.of(App.class).verify() fails a test on cycles or access to another module's internals. For loose coupling it offers @ApplicationModuleListener and an event publication registry that persists events so incomplete deliveries are retried. @ApplicationModuleTest runs one module in isolation, and the Documenter generates module diagrams and canvases. Together these stop a modular monolith decaying into mud.

Q6L3 · Senior EngineerScenario

How do you start fixing mud without stopping delivery?

Start by stopping it getting worse, then improve incrementally alongside feature work. First freeze the current state: ArchUnit's FreezingArchRule records today's violations, such as package cycles, and fails the build only on new ones. Next find seams using a domain workshop, the dependency graph and change-coupling data, and pick one capability with clear value, ideally one being actively changed. Move its packages into a module, introduce API types, and break cycles with events or extracted interfaces. Then separate its data into its own schema and replace cross-module joins. Repeat module by module, and make Modulith verification blocking once a module is clean. Each step ships independently, so delivery continues and progress is measurable.

Q7L4 · Technical ArchitectTricky

Why not move straight from mud to microservices?

Because splitting a tangled codebase across the network does not remove the tangles; it turns them into remote calls. The cyclic dependencies, shared tables and hidden coupling of the mud become synchronous chains between services, shared databases and coordinated releases, which is a distributed monolith. You keep all the original coupling and add latency, partial failures, distributed transactions and much more operational cost. You also have to guess service boundaries without evidence, and wrong boundaries are far more expensive to fix across services than across packages. Modularising inside the monolith first lets you find and test boundaries cheaply. Afterwards, extracting a clean module with an API and its own schema is a manageable step.

Q8L5 · Solution ArchitectDesign

How would you plan modernisation of a large layered monolith?

I would plan it as an incremental modularisation with optional extraction at the end. First map business capabilities with domain experts and measure the current state: dependency cycles, change coupling, deploy frequency and change failure rate. Then freeze existing rule violations so no new coupling appears. Next carve capability modules one at a time, starting where change is frequent, each with internal layers, an explicit API, its own schema and events for cross-module side effects, and enforce them with Spring Modulith verification in CI. Team ownership follows modules. Only after modules are clean would I extract services, and only those with a concrete need such as independent scaling, release cadence or PCI isolation.

Test your knowledge on this topic →Flashcards from this topic's 8 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.