- Chapter
- Chapter 1 — Design at Multiple Scales
- Prerequisites
- Topics 1.1–1.2; Volume VI Topics 6.2–6.3
- You will be able to
- Define modules around business capabilities, design small stable public APIs, hide internal implementation using Java visibility, Spring Modulith and JPMS, keep dependencies acyclic and pointing towards stability, and verify module boundaries automatically
- Covers
- Dependency direction; Public API; Internal implementation
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Designing Modules Step by Step
- 4A. Deep Dive — Named Interfaces, Module Tests and JPMS
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
A module is a group of classes with a single purpose, a public API through which others use it, and an internal implementation others cannot touch. Module-level design decides module boundaries, what each module exposes, and which modules may depend on which.

| Concern | Module-level question |
|---|---|
| Boundary | Which capability or concept does this module own? |
| Public API | What is the smallest set of types others need? |
| Internal implementation | What can change freely without affecting others? |
| Dependency direction | Which modules may it use, and which may use it? |
2Why It Exists
As codebases grow beyond what one person can hold in their head, they need units larger than classes but smaller than deployable services. Without explicit modules, any class can use any other; dependencies tangle, cycles form and the codebase becomes a "big ball of mud". Modules — packages with enforced visibility, Maven modules, JPMS modules or Spring Modulith modules — give structure, allow teams to own areas, and are the natural first step before (or instead of) microservices.
3Core Concepts
3.1 Dependency direction

Module dependencies should form a directed acyclic graph (DAG) pointing from volatile (channels, UI, integrations) towards stable (domain core, shared kernel).
| Rule | Rationale |
|---|---|
| Acyclic Dependencies Principle | Cycles merge modules into one unit of change and release |
| Stable Dependencies Principle | Depend on modules more stable than yourself |
| Stable Abstractions Principle | Stable modules should be abstract (APIs, interfaces, events) |
| Feature modules don't depend on each other's internals | Only on published APIs or events |
| Shared kernel stays tiny | Everything depends on it; it must rarely change |
When two feature modules need each other, invert one direction (interface owned by the using module) or communicate via events:
// orders publishes; billing listens —
// billing depends on orders' event type, not vice versa
package com.shop.orders; // module: orders
public record OrderCompleted(OrderId orderId, CustomerId customer, Money total) {}
package com.shop.billing; // module: billing
@Component
class CreateInvoiceOnOrderCompleted {
private final Invoices invoices;
CreateInvoiceOnOrderCompleted(Invoices invoices) { this.invoices = invoices; }
@ApplicationModuleListener // Spring Modulith: async, transactional event listener
void on(OrderCompleted event) {
invoices.createFor(event.orderId(), event.customer(), event.total());
}
}3.2 Public API

The public API is the module's contract. Design it deliberately:
| API design rule | Example |
|---|---|
| Expose use-case operations, not entities | OrderService.place(PlaceOrder) returning OrderId |
| Exchange records/value objects, not JPA entities | OrderView(id, status, total) |
| Publish domain events for facts | OrderCompleted, OrderCancelled |
| Keep it small | A few services + DTOs + events |
| Document and version it | Javadoc; deprecation before removal |
| Test it as a contract | Module tests via API only (@ApplicationModuleTest) |
package com.shop.orders; // API package = module root (Spring Modulith)
public interface Orders { // public API
OrderId place(PlaceOrder command);
Optional<OrderView> find(OrderId id);
void cancel(OrderId id, CancellationReason reason);
}
public record PlaceOrder(CustomerId customer, List<LineRequest> lines) {}
public record OrderView(OrderId id, OrderStatus status, Money total, Instant placedAt) {}3.3 Internal implementation
Everything not in the API is internal: entities, repositories, mappers, helpers, adapters. Internals can be refactored, replaced or deleted without notice.
package com.shop.orders.internal; // internal package (hidden by Modulith)
@Service
class OrderManagement implements Orders { // package-private implementation class
private final OrderRepository repository;
private final ApplicationEventPublisher events;
…
}
@Entity
class OrderEntity { … } // never leaves the module
interface OrderRepository extends JpaRepository<OrderEntity, UUID> {}
| Hiding mechanism | Strength | Notes |
|---|---|---|
| Package-private classes | Compile-time within one package | Best with few, flat packages per module |
| Spring Modulith internal packages | Verified by ApplicationModules.verify() | Sub-packages are internal unless exposed as named interfaces |
| Maven/Gradle modules | Compile-time (classpath) | Separate artifacts; API module + impl module |
JPMS exports | Compile + runtime (strong encapsulation) | Non-exported packages inaccessible, even via reflection unless opened |
4How It Works Internally — Designing Modules Step by Step
1. Identify capabilities (ordering, billing, catalogue, shipping) — use domain language and change history, not technical layers.
2. Assign data ownership — each table/entity belongs to one module.
3. Draft APIs — use cases, views and events other modules need.
4. Decide dependency direction — draw the DAG; break needed cycles with events or inversion.
5. Hide internals — package-private, Modulith internal packages or JPMS.
6. Verify automatically — ApplicationModules.verify(), ArchUnit, module-level tests.
7. Document — generated diagrams (Modulith Documenter), ADRs for boundary decisions.
class ModularityTests {
ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
@Test
// cycles, internal access
void verifiesModularStructure() {
modules.verify();
}
@Test
// C4-style diagrams
void writeDocumentation() {
new Documenter(modules).writeDocumentation();
}
}4ADeep Dive — Named Interfaces, Module Tests and JPMS
Spring Modulith named interfaces let a module expose selected sub-packages:
@org.springframework.modulith.NamedInterface("spi")
package com.shop.payments.spi; // other modules may use this sub-package
@ApplicationModule(allowedDependencies = { "orders", "payments::spi" })
package com.shop.billing; // billing may use orders' API and payments' SPI onlyModule integration tests bootstrap only one module (and optionally its dependencies), proving the API works in isolation:
@ApplicationModuleTest // starts only the orders module
class OrdersModuleTests {
@Autowired Orders orders;
@Test
void placingAnOrderPublishesEvent(Scenario scenario) {
scenario.stimulate(() -> orders.place(samplePlaceOrder()))
.andWaitForEventOfType(OrderPlaced.class)
.toArriveAndVerify(e ->
assertThat(e.total()).isEqualTo(Money.inr("1200.00")));
}
}JPMS provides the strongest encapsulation — useful for libraries and platforms:
module com.shop.orders {
requires com.shop.shared;
requires spring.context;
exports com.shop.orders; // API only
// reflection for frameworks
opens com.shop.orders.internal to spring.core, org.hibernate.orm.core;
}| Mechanism | Use when |
|---|---|
| Spring Modulith | Spring Boot modular monoliths — best balance of enforcement and convenience |
| Maven/Gradle modules | Separately versioned or reused libraries; enforced compile boundaries |
| JPMS | Libraries/platforms needing strong encapsulation; less common in Spring apps due to reflection needs |
5APIs / Features / Syntax
| Feature | Purpose |
|---|---|
@ApplicationModule(allowedDependencies = …) | Declare allowed module dependencies |
@NamedInterface | Expose selected sub-packages |
ApplicationModules.verify() | Detect cycles and illegal access |
@ApplicationModuleListener | Transactional, asynchronous event listener between modules |
| Event publication registry | Reliable delivery of module events (outbox-like) |
@ApplicationModuleTest, Scenario | Module-scoped integration tests |
module-info.java (exports, opens, requires) | JPMS encapsulation |
6Practical Examples
6.1 Package-by-layer to package-by-module
controller, service, repository, dto packages were reorganised into orders, billing, catalog, customers modules; each module's internals moved into internal sub-packages. Modulith verification then revealed 14 illegal accesses to fix.
6.2 Shrinking an API
The customers module exposed its JPA entity to 6 modules. Replacing it with CustomerView and CustomerDirectory.find(id) let the team change the entity freely (splitting addresses into their own table) without touching other modules.
6.3 Worked example — modularising a Spring Boot monolith
| Step | Action | Result |
|---|---|---|
| 1 | Identify capabilities with domain experts and git change coupling | 6 modules: catalog, orders, payments, billing, shipping, customers |
| 2 | Move classes into module root packages (IDE Move Class) | Compiles; behaviour unchanged |
| 3 | Run ApplicationModules.verify() | 37 violations, 2 cycles |
| 4 | Break cycle orders ⇄ billing with OrderCompleted event | Cycle removed |
| 5 | Introduce API types (OrderView, CustomerView); move entities to internal packages | Violations → 9 |
| 6 | Fix remaining violations (payments SPI as named interface) | 0 violations; verification in CI |
| 7 | Generate module diagrams for documentation | Living architecture docs |
| Metric | Before | After |
|---|---|---|
| Package cycles | 2 large cycles | 0 |
| Classes visible across modules | ~420 | ~60 (APIs, events) |
| Change locality (commits touching one module) | 48% | 79% |
6.4 Worked example — designing an API for the payments module
| Candidate API element | Decision | Reason |
|---|---|---|
PaymentEntity | Internal | Persistence detail |
Payments.authorise(PaymentRequest) → PaymentResult (sealed) | Public | Use case other modules need |
Payments.refund(PaymentId, Money) | Public | Use case |
PaymentCaptured, PaymentFailed events | Public | Facts others react to |
RazorpayClient | Internal (adapter) | Vendor detail |
PaymentProvider SPI | Named interface spi | Other modules may contribute providers |
6.5 Worked example — enforcing direction with ArchUnit when not using Modulith
@ArchTest
static final ArchRule ordersInternalsStayInternal =
noClasses().that().resideOutsideOfPackage("com.shop.orders..")
.should().dependOnClassesThat()
.resideInAPackage("com.shop.orders.internal..");
// one such rule per module (or generated in a loop over module names)
@ArchTest
static final ArchRule noCycles =
slices().matching("com.shop.(*)..").should().beFreeOfCycles();Teams without Modulith combine a cycle rule with per-module rules that forbid access to ..internal.. packages from outside the module, achieving a similar effect.
7Common Problems & Mistakes
- Layer packages mistaken for modules — every feature touches every package.
- Exposing entities through module APIs.
- Cycles "just this once" — they spread.
- A giant common module everyone depends on.
- Modules without enforcement — boundaries erode within months.
- Too many tiny modules — coordination overhead without benefit.
8Performance & Production Considerations
| Aspect | Note |
|---|---|
| Monolith runtime | Modules are in-process — no network cost, shared transactions possible |
| Events between modules | Async listeners decouple latency; publication registry ensures delivery |
| Build times | Maven/Gradle modules allow incremental and parallel builds |
| Startup | Module tests start only needed beans — faster CI |
| Extraction later | Clean modules become services with minimal rework |
Treat module boundaries as a runtime concern as well as a structural one. Events delivered by @ApplicationModuleListener run asynchronously after the publishing transaction commits, so consumers see eventual consistency. The Spring Modulith event publication registry persists each publication, so incomplete ones can be resubmitted after a crash or a listener failure; purge completed entries on a schedule so the table does not grow without bound. Instrument modules individually: Spring Modulith's observability support creates spans for calls between modules, and Micrometer tags on module APIs show which capability drives latency or errors. Keep every table strictly owned by one module, because cross-module joins and shared transactions are what later block service extraction. Splitting Maven or Gradle modules also enables parallel, cached builds that keep CI fast.
9Architecture & Design Considerations
- Design modules around capabilities and data ownership, validated by change coupling.
- Keep APIs small and abstract; keep internals truly hidden.
- Enforce acyclic, stability-directed dependencies automatically.
- Prefer a modular monolith first; extract services only where independent deployment or scaling pays (Chapter 8).
10Interview Questions & Answers
What is a module?
A module is a group of classes with a single purpose that exposes a small public API and hides its internal implementation, so other code can use it without knowing or depending on how it works. In Java it can be a package with package-private internals, a Spring Modulith application module, a Maven or Gradle module, or a JPMS module. Following Parnas, a good module hides a design decision likely to change, such as how orders are stored or how payments are routed to a provider. Modules sit between classes and deployable services: they give teams ownership and structure within one codebase, and are a natural step before, or instead of, microservices.
Why should module dependencies be acyclic?
Because a cycle merges the modules involved into one unit of change. If orders depends on billing and billing depends on orders, you cannot understand, test, build, release or extract either one alone; a change in one can ripple back through the other, and the boundary exists only on paper. Acyclic dependencies form a directed graph, so modules can be built and tested bottom-up, and stable modules at the bottom can change rarely while volatile modules at the top change often. Cycles also spread, because once two modules are entangled, adding more cross-calls feels free. Spring Modulith's verify() and ArchUnit's beFreeOfCycles() enforce this automatically.
What belongs in a module's public API?
The smallest set of types other modules need to use its capability. That usually means a use-case interface such as Orders with place, find and cancel, command and view records such as PlaceOrder and OrderView, identifier value objects, and domain events such as OrderCompleted for facts others react to. It should not include JPA entities, repositories, mappers, adapters or framework types, because exposing them lets other modules depend on internals and freezes them. Every API element is a commitment, so it should be documented, tested as a contract through module tests, and evolved by deprecation before removal. Keeping it small is what lets internals change freely, such as splitting a table.
How can you hide internals in Java?
Java offers four mechanisms of increasing strength. Package-private classes are hidden at compile time, but only within one package, so they suit modules with few, flat packages. Spring Modulith treats sub-packages of a module as internal and checks access with ApplicationModules.verify() in a test, exposing selected sub-packages as named interfaces; it is the most convenient choice for Spring Boot modular monoliths. Separate Maven or Gradle modules enforce boundaries through the build classpath, often as API and implementation artifacts. JPMS exports give strong encapsulation at compile and run time, even against reflection unless packages are opened, which suits libraries but is awkward for reflection-heavy Spring and Hibernate applications.
How do you remove a dependency cycle between two modules?
There are two standard moves. First, invert one dependency: the module that uses something defines the interface it needs, and the other module implements it, so the compile-time arrow now points the other way. Second, decouple with events: instead of orders calling billing and billing calling orders, orders publishes OrderCompleted and billing listens, for example with Spring Modulith's @ApplicationModuleListener, so billing depends on orders' event type but orders knows nothing about billing. A third option, when the two modules are always changed together, is to accept that they are one capability and merge them. After breaking the cycle, add a verification test so it cannot return.
What does Spring Modulith verify?
ApplicationModules.of(ShopApplication.class) builds a model of the modules, treating each direct sub-package of the main application package as a module, and analyses the bytecode with ArchUnit. verify() fails when there are cycles between modules, when one module references types in another module's internal sub-packages instead of its API package or an exposed named interface, and when a module depends on modules outside the allowedDependencies declared in @ApplicationModule. Run as a normal unit test, it puts module boundaries into CI. The same model drives @ApplicationModuleTest, which bootstraps only one module and its dependencies, and the Documenter, which generates C4 and PlantUML module diagrams from the actual code structure.
How do you choose module boundaries?
I draw boundaries around business capabilities and data ownership, not technical layers. Working with domain experts, I identify capabilities such as catalogue, ordering, payments, billing and shipping, and assign each table or entity to exactly one module. Then I validate the candidates with evidence: Git change coupling should show that most commits touch a single module, and dependencies should form an acyclic graph pointing from volatile to stable modules. Team structure matters too, since a module ideally has one owning team. Boundaries that require constant cross-module calls or shared transactions are probably wrong. Finally I enforce them with Spring Modulith or ArchUnit and revisit them as the domain evolves.
Why start with a modular monolith?
Because it delivers most of the benefits attributed to microservices, such as clear ownership, enforced boundaries and independent evolution of modules, without the costs of distribution: network latency, partial failures, distributed transactions, eventual consistency, many pipelines and far more operational surface. Calls are in process, refactoring across modules is still a single IDE operation, and boundaries are cheap to correct while the team is still learning the domain. If the modules are clean, with small APIs, owned data and event-based collaboration, extracting one into a service later is largely mechanical. Extract only where independent deployment, scaling, technology choice or fault isolation clearly pays for the added complexity.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.