How the Payments Platform uses Spring Modulith and 11 ArchUnit rules to keep four modules isolated in a single deployable, and what this design does not solve
Published: November 21, 2026
Reading time: 15 min
Keywords: modular monolith, clean architecture java, spring modulith, archunit, ports and adapters
Payments Platform in practice series
The project that became the Payments Platform started life as a trip-planning API with classic layered packages: controller, service, repository. The repository's first ADR records what that structure produced. A TripController of roughly 250 lines owned 17 endpoints across four domains. And a method called registerParticipantsToEvent() returned repository.findAll(): instead of the trip's participants, it returned every participant in the database.
That second bug is the kind no architecture diagram prevents. Any class could reach any repository, so one did. Fixing the code took minutes. Fixing the structure took the whole project, and that structural fix is what this article is about.
Today the java-clean-arch-sample repository is a payments platform with event sourcing, CQRS, a transactional outbox, a Stripe integration and observability. All of it runs in a single Spring Boot process. This first chapter explains why it is a monolith, how module boundaries are checked on every build, and what keeping that design costs. Every code excerpt comes from commit 5277f6c on main, with its file path.
Before the argument, the actual size of the thing, measured at commit 5277f6c:
| Metric | Value |
|---|---|
| Production / test Java files | 231 / 69 |
| Production / test lines of code | 12,060 / 8,823 |
| Modules | 4 (identity, payments, notifications, shared) |
| ADRs | 19 |
| Flyway migrations | 9 |
| Stack | Java 25, Spring Boot 3.5.16, Spring Modulith 1.4.14, ArchUnit 1.4.2, PostgreSQL 16, Redis 7, RabbitMQ 3.13 |
It is a sample, not a product running in production. That matters for everything that follows: decisions are explicit and gaps are recorded in ADRs, which makes it possible to discuss trade-offs with evidence instead of opinion. Where the project does not solve something, I will say so.
The rationale lives in ADR 0003, and it fits in one sentence from the document itself: "a payment and its outbox row must commit together".
When a payment is created, three things must happen atomically: the fact is written to the event store, the read projection is updated, and an integration event is recorded in outbox_events to be published to RabbitMQ later. If those writes share one local PostgreSQL transaction, atomicity is a COMMIT. If payments and notifications were separate services with separate databases, the same guarantee would require a coordination protocol, or accepting a dual write and the inconsistency window that comes with it.
The ADR lists the alternatives it rejected, and the table is worth reproducing because it shows the reasoning:
| Option | Why not now |
|---|---|
| Microservices per module | Distributed transactions or a dual write for the outbox. Operational cost without a measured bottleneck. |
| Several databases in one process | Loses the single commit that makes the outbox correct. |
Classic layered packages (controller, service, repository at the root) | The structure ADR 0001 rejected: no owner per aggregate, easy cross-reads. |
The phrase I would underline is "without a measured bottleneck". The decision is not an ideological stance against microservices. It says that until a module has a demonstrated need to scale, fail or deploy independently, the network between modules is cost with no return. The same ADR notes that extracting a service later is possible "along the event boundary", because the outbox payload is already the contract.
Three business modules and a shared kernel. Each owns its tables:
| Module | Package | Owns | Talks to others through |
|---|---|---|---|
identity | com.muse.payments.identity | users, refresh_tokens | Issues the JWT used by the other APIs |
payments | com.muse.payments.payments | payments | Writes integration events to outbox_events |
notifications | com.muse.payments.notifications | notifications | Learns about payments only through RabbitMQ |
shared | com.muse.payments.shared | outbox_events, processed_events, idempotency_keys, event store kernel | Common dependency, no payment business rules |
The most important detail in that table is the last column for notifications. The notifications module imports nothing from the payments domain. It learns that a payment was created the same way it would if it were a separate service: by consuming a message. Inside one process it would be trivial to inject the payments repository and read state directly. ADR 0003 forbids that explicitly: "In-process calls are not a substitute for the event path".
That discipline has an immediate cost, because notifications become eventually consistent even though they run in the same JVM. In exchange, the boundary between payments and notifications already has the shape it would have between two services. If extraction ever makes sense, the contract exists and is already tested.
Each module has four packages: domain, application, web and infrastructure. If you expect ports and adapters as package names, you will not find them. The roles exist, but the names follow the technical function:
| Logical layer | Location | Responsibility |
|---|---|---|
| Domain | */domain | Entities, value objects, state rules and repository contracts, in plain Java |
| Application | */application | Commands, queries, handlers, use cases and ports such as FraudScreeningPort, PaymentCachePort and OutboxPort |
| Inbound adapter | */web | Controllers that translate HTTP into commands and queries |
| Infrastructure | */infrastructure | JDBC, JPA, Redis, RabbitMQ, HTTP clients and Spring configuration |
The dependency rule is the Clean Architecture one: everything points inward. web and infrastructure may call application contracts and domain rules. The domain knows no framework. Nothing new so far. The difference is how this is enforced.
Free and paid products to turn ideas into a foundation you can actually ship.
13 products availableContinue exploring similar topics
The same payment has two findById methods: one rebuilds the aggregate from events, the other reads an indexed projection. That is what CQRS means in the Payments Platform, with no second database.
A BIGSERIAL sequence hands out numbers in order, but transactions commit out of order. If your async projection trusts global_position, it can lose events without a single error.
When the fraud provider goes down, the payment is held for review, never approved. How the Payments Platform fails closed, measures outbox and projection lag, and makes migrations and rebuilds verifiable.
A 47-point checklist to find bugs, security risks, and performance issues before launch.
Production-tested templates trusted by developers. Save weeks of setup on your next project.
An architecture rule that depends on code review lasts until the first Friday with a tight deadline. ADR 0001, from the trip-planner days, literally said slice rules were "enforced by review, documented here". That is the regime in which findAll() leaked data across trips.
In the Payments Platform, boundaries are tests. There are two complementary mechanisms.
The first is Spring Modulith. ModularityTest has three useful lines:
// src/test/java/com/muse/payments/ModularityTest.java:10-16
@Test
@DisplayName("Verify Spring Modulith module boundaries")
void verifyModularStructure() {
ApplicationModules modules = ApplicationModules.of(PaymentsApplication.class);
modules.verify();
new Documenter(modules).writeDocumentation();
}
ApplicationModules.of(...) treats each direct subpackage of com.muse.payments as a module, and verify() fails when a module reaches into another module's internal types or when modules form a cycle. The Documenter also generates module documentation from the real code, which beats a stale wiki diagram.
The second mechanism is ArchitectureTest, with 11 ArchUnit rules. The most important one is domain purity:
// src/test/java/com/muse/payments/ArchitectureTest.java:20-27
@ArchTest
static final ArchRule domain_should_not_depend_on_spring_or_jpa = classes()
.that().resideInAPackage("..domain..")
.should().onlyDependOnClassesThat().resideInAnyPackage(
"java..",
"com.muse.payments..domain.."
)
.as("Domain classes must be pure and depend only on JDK and domain packages");
Note that the rule is an allowlist. It does not say "the domain must not depend on Spring". It says the domain may only depend on the JDK and on other domain packages. The difference shows up the day someone adds a new library to pom.xml: a denylist would need updating, while the allowlist already blocks any new import.
The second rule I consider essential stops the application layer from knowing concrete adapters:
// src/test/java/com/muse/payments/ArchitectureTest.java:93-97
@ArchTest
static final ArchRule application_should_not_depend_on_infrastructure = noClasses()
.that().resideInAPackage("..application..")
.should().dependOnClassesThat().resideInAPackage("..infrastructure..")
.as("Application must not import infrastructure adapters");
The other nine cover narrower cases, and some reveal design decisions worth explaining:
no_field_injection: constructor injection only, so every class's dependencies are visible in its signature.domain_should_not_depend_on_resilience4j_or_http_clients and its application twin: Resilience4j and HTTP clients stay in infrastructure. Chapter 5 shows why that matters for the fraud policy.payments_application_should_not_depend_on_spring_security: payment authorization happens in the application handler with explicit rules, not in scattered Spring Security annotations. Chapter 2 shows the effect on the HTTP contract.event_store_adapters_should_stay_in_shared_infrastructure: only shared.infrastructure.eventstore may depend on the event store adapters. Business modules use the EventStore port, never the JDBC implementation.web_should_depend_on_application_or_shared_only: controllers import neither domain nor infrastructure from any module.That last rule has a recorded history. ADR 0014 explains that the notifications controller read the domain repository directly and serialized a domain object in its response, and that the authentication controller depended on a concrete infrastructure rate limiter. The fix introduced a ListNotificationsQueryHandler with a response record and an AuthRateLimitPort. The ArchUnit rule is what prevents the regression. The same ADR carves out a deliberate exception: @RestControllerAdvice may depend on domain exceptions, because that is exactly where a domain failure becomes an RFC 7807 response.
That exception deserves attention. Architecture rules without an escape valve end up switched off. A named exception, limited to one kind of class and justified in an ADR, keeps the rule useful without pretending every case is the same.
The Payment aggregate is plain Java. No @Entity, no @Component, no Jackson. A state transition looks like this:
// src/main/java/com/muse/payments/payments/domain/Payment.java:138-143
public void complete() {
if (this.status != PaymentStatus.PENDING) {
throw new ConflictException("Cannot complete payment in status: " + this.status);
}
raise(new PaymentCompletedEvent(this.id, this.userId));
}
The method checks the invariant and raises an event. It has no idea whether the event goes to a table, a queue or an in-memory test. raise comes from EventSourcedAggregate, a base class also written in plain Java that applies the event to state and increments the version. Chapter 3 covers that mechanism in detail.
The practical consequence is that payment business rules can be tested without a Spring context, a database or a container. PaymentTest and PaymentProviderSettlementTest, both in the domain package, import only JUnit, AssertJ and the domain itself: they instantiate the aggregate and check transitions. When the rule is "a payment held for review cannot be settled by a provider webhook", it is covered by a domain unit test. The integration test with a simulated Stripe (PspWebhookIT) exists, but it checks the wiring, not the rule.
This is the decision that sparks the most debate when I show the project. The payments table has a user_id column, and it does not reference users:
-- src/main/resources/db/migration/V3__payments.sql:1-18
CREATE TABLE payments (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
amount NUMERIC(19, 2) NOT NULL,
currency VARCHAR(3) NOT NULL,
description VARCHAR(255),
status VARCHAR(30) NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
version BIGINT NOT NULL DEFAULT 0,
screening_reason VARCHAR(500),
held_reason VARCHAR(500),
reviewer_id UUID,
reviewed_at TIMESTAMPTZ
);
CREATE INDEX idx_payments_user_created_at_id
ON payments (user_id, created_at DESC, id DESC);
There are two reasons. The first is about boundaries: a foreign key from payments to users makes one module's schema depend on another's. A migration in identity may suddenly need coordination with payments, and extracting either module later means untangling constraints. The second reason only appears after event sourcing, and I find it more interesting.
Migration V2__identity.sql created a foreign key from refresh_tokens.user_id to users.id. Both tables belong to the same module, so that key violates no boundary. It was still dropped in V7:
-- src/main/resources/db/migration/V7__independent_identity_projections.sql:1-3
-- Read models rebuild independently; rebuilding users must preserve token state.
-- Credentials are already a separate state table and are never truncated.
ALTER TABLE refresh_tokens DROP CONSTRAINT refresh_tokens_user_id_fkey;
Once users and refresh_tokens became projections of an event store, they gained a new property: they can be wiped and rebuilt from events. A foreign key between two projections prevents rebuilding one without touching the other. The comment in V9 repeats the argument for the webhook events table: "No FK to payments: the projection is rebuildable and truncation must not be blocked".
A note for anyone reading the repository: docs/architecture.md still describes the refresh_tokens foreign key as present. The migration is the source of truth. Documentation that drifts from the schema is a problem architecture tests do not catch, and I come back to it in the limitations.
Not having foreign keys has a concrete price. Referential integrity between payments.user_id and users.id becomes the application's job. A deleted user leaves payments with orphaned references, by design, and the sample has no cross-module referential consistency job. In payments that is usually acceptable, because financial history needs to outlive the user, but it is a decision to make on purpose rather than discover in production.
A modular monolith is not the free option. It trades one set of problems for another, and the costs are easier to accept once they are written down.
Isolation is at the code level, not at runtime. All four modules run in the same JVM and share the PostgreSQL connection pool. A slow query in notifications can exhaust connections that payments needs. No ArchUnit rule protects against that. Protection, where it exists, comes from bulkheads, pool limits and timeouts, and chapter 5 shows where the project applies each one.
A bad deploy takes down every module. ADR 0003 records this as an accepted consequence and lists the mitigations: readiness probes, migrations running as a separate Job, and rolling updates. The APP_MIGRATION_ONLY mode, detailed in chapter 5, exists because of it.
A bad migration affects everyone. One database, one public schema, one Flyway history. No cross-module foreign keys reduces coupling, but an ALTER TABLE that locks a large table locks the whole process.
The shared kernel can turn into a junk drawer. shared is open on purpose: event store, outbox, idempotency, security and RFC 7807 errors live there. The rule is that it holds no payment logic. But no test stops an arbitrary new class from landing in shared. The defense here is review, which is exactly the regime the project tried to leave behind.
Rules check packages, not contracts. ArchUnit guarantees that notifications does not import the payments domain. It does not guarantee that the JSON payload payments publishes stays compatible with what notifications consumes. That protection comes from elsewhere: the event type registry with stable names and schema versions, covered in chapter 3.
I would start most business systems with a single team as a modular monolith. But there are cases where it is the wrong choice:
On November 21, 2026, at commit 5277f6c, I ran the unit suite that includes the architecture rules:
mvn -B test -Dtest='ArchitectureTest,ModularityTest,PaymentTest,CreatePaymentUseCaseTest,IdempotencyServiceTest,EventSerializerTest,StripeWebhookSignatureTest,OutboxRelayBatchTest,PaymentProviderSettlementTest,ListPaymentsQueryHandlerTest'
Result: Tests run: 65, Failures: 0, Errors: 0, Skipped: 0, in 14.9 seconds, including the 11 ArchUnit rules and ApplicationModules.verify(). That proves the boundaries described here hold in the current code. The repository's full gate (scripts/ci-local.sh, which also validates Compose and the Kubernetes manifests) did not run in that session, so I am not claiming it passes.
"Why a modular monolith and not microservices?" comes up often in senior and staff interviews, and the weak answer is "because it is simpler". The answer I would expect from someone experienced covers four points:
Answering like that shows you made the decision rather than inherited a structure.
With boundaries in place, the next step is to look inside the payments module. In chapter 2 I show how the project separates reads and writes with two different repositories for the same aggregate, on a single PostgreSQL instance, and why another user's payment returns 404 instead of 403.
If your team is weighing whether to split a monolith or consolidate services and wants a second opinion grounded in code, that is the kind of architecture review I do at LEMON.DEV.
java-clean-arch-sample repository, commit 5277f6c (code, migrations, ADRs and tests checked on November 21, 2026).ArchitectureTest.java and ModularityTest.java.