8.16 Modules with Spring Modulith¶
4.2 states how modules
meet without naming a technology; this page states how that is carried out with Spring Modulith
and jMolecules. Each package directly below net.lauper.feecheck is a Spring Modulith application
module — ModularityTest.modulesVerify asserts the eight of them — and each carries its own onion
rings (8.15). The build has spring-modulith-api and the insight
starter, and in the tests spring-modulith-core and spring-modulith-docs
(backend/app/build.gradle.kts, ADR-0009 point 10). Spring Modulith's events are the one
event backbone between the modules, into and out of the case engine, and to other deployables
(8.16.3).
8.16.1 How modules meet¶
| Kind | jMolecules | Spring / Spring Modulith | Where | Status |
|---|---|---|---|---|
| Published application service | @Service (org.jmolecules.ddd.annotation) on the application service |
the package published with @NamedInterface("application") on its package-info.java; the application service is a bean through an @Bean method (DocumentExtractionService in ExtractionConfiguration) or built on beans by the inbound adapter that needs it (DocumentIntakeService in CaseController and CasePushController); the caller receives it by constructor |
intake.application (DocumentIntakeService), extraction.application (DocumentExtractionService); called by cases and consumer |
built; for a stage's work replaced by a request and its reply (8.16.3), planned |
| Published domain types | @ValueObject on the records, e.g. Rendition, ExtractionResult; a port is a plain interface |
@NamedInterface("domain") on the ring's package-info.java |
intake.domain, extraction.domain, cases.domain |
built |
| Domain event | @DomainEvent on an immutable record in the publishing module's published package |
published with Spring's ApplicationEventPublisher inside the transaction of the change it reports, kept by Spring Modulith's event publication registry (the outbox), delivered to application-module listeners; an event another deployable needs is selected for externalization by its type and carried by Spring Cloud Stream (8.16.3). It contradicts ADR-0009 (docs/adr/adr-0009-async-intake-pubsub-bucket-firestore.md) §3 point 9 ("no Spring Modulith events", "no outbox"); its record is pending |
the event in the publishing module's domain ring; the bridge to the case engine and the inbound adapter in cases.infrastructure |
planned (ADR pending) |
| Enforcement | OnionArchitectureTest: the jMolecules rules for rings and DDD building blocks, and modulesMeetOnlyThroughPublishedTypes, the published types type by type |
ModularityTest: ApplicationModules.verify() — no cycle between modules, no use of a package a module does not publish |
backend/app/src/test/java/net/lauper/feecheck/ |
built (8.15.5) |
From the package-info.java of each published ring, DocumentIntakeService.java,
DocumentExtractionService.java, ExtractionConfiguration.java, CaseController.java,
CasePushController.java, OnionArchitectureTest.java and ModularityTest.java.
8.16.2 Published types and named interfaces¶
Modulith treats only a module's base package as its public surface. A module that offers a type from one of its rings to the others declares that ring
a named interface, with @NamedInterface on its package-info.java; everything else in the module
is internal, and a use of it from another module fails verify() (the Javadoc of
ModularityTest). modulesMeetOnlyThroughPublishedTypes stays the finer fence and narrows those
packages type by type (from 5.2.1).
| Module | Ring published | Named interface | Used by (from its package-info.java and the imports) |
|---|---|---|---|
intake |
domain | domain |
extraction (the rendition), the case component (the converter port), the queue's consumer (the rendition, the conversion result, the converter port) |
intake |
application | application |
the case component, which converts through the upload application service, and the queue's consumer, which does the same for a delivered case |
extraction |
domain | domain |
the case component, which keeps the result, the queue's consumer, which reads the result's verdicts, and the MCP server, which lists the claim schema and the verdicts |
extraction |
application | application |
the case component and the queue's consumer, which extract through the application service |
cases |
domain | domain |
the queue's consumer, which claims the case and moves it through the store ports |
A new use across components therefore needs both: the ring declared a @NamedInterface, and the
type added to modulesMeetOnlyThroughPublishedTypes. A bean in a published package cannot be
final, because the insight starter's per-module tracing subclasses it (CLAUDE.md).
With the stage work on events (8.16.3) a stage module publishes its request and reply events and the types they carry instead of its application service, the queue's consumer dissolves, and this table changes with it; whether the named interface then sits on the package or on each published type is decided when that code is built.
8.16.3 Events¶
Spring Modulith events are the one event backbone — for the case engine (6.1) and for the modules the engine does not run — and Spring Cloud Stream carries the ones another deployable or a downstream system needs, with the broker chosen by configuration. Where each environment sends and receives them is 7.1.5.
Kinds of interaction¶
| Kind | Example | Mechanism | Status |
|---|---|---|---|
| Case step — one plan item following another inside a case | Convert document completed → Extract attributes enabled | the engine's own Sentry, in the engine's transaction; not an event on the queue | planned |
| Stage work — the case needs a stage done and waits for the answer | the case requests the extraction; extraction answers |
a request event answered by a reply event, correlated by case ID and request ID; one request per stage module until a person or another module is next (6.1.2); an external worker task per stage is the exception, used by no stage | planned |
| Fact into a case — something outside starts or continues a case | a document arrives from another channel | a Spring Modulith event that cases hands to the engine's Event Registry; a CMMN event listener correlates it |
planned |
| Fact out of a case | ContractRecorded, FindingsPublished |
a CMMN send event task; an outbound channel adapter in cases publishes it as a Spring Modulith event inside the engine's transaction |
planned; that Flowable calls the adapter inside the command's transaction is checked first (RISK-3) — if it does not, the event is published from a plan-item lifecycle listener inside the command instead |
| Fact between modules, no case involved | reporting, notifications, master-data sync | a Spring Modulith event and an application-module listener | planned |
flowchart LR
subgraph be["«deployable» Backend"]
direction LR
subgraph cs["«module» cases"]
fl["«library»<br/>Flowable CMMN engine"]
br["«adapter»<br/>Event Registry bridge"]
ia["«adapter»<br/>Inbound push adapter"]
end
ex["«module»<br/>extraction"]
in["«module»<br/>intake"]
ot["«module»<br/>other modules"]
ob[("«outbox»<br/>event publication registry")]
end
scs["«library»<br/>Spring Cloud Stream"]
ps["«container»<br/>Event broker · Pub/Sub"]
fl <-.-> br
br -. "ExtractionRequested" .-> ex
ex -. "AttributesExtracted" .-> br
br -. "ConversionRequested" .-> in
in -. "DocumentConverted" .-> br
br -. "FindingsPublished" .-> ob
ot <-.-> ob
ob -. "externalized" .-> scs -.-> ps
ps -. "push" .-> ia
ia -.-> br
classDef person fill:#ffe8b0,stroke:#9a6b00,color:#000
classDef built fill:#b7e4c7,stroke:#2d6a4f,color:#000
classDef planned fill:#c6dcff,stroke:#1168bd,stroke-dasharray:4 3,color:#000
class ex,in built
class fl,br,ia,ot,ob,scs,ps planned
style be fill:none,stroke:#666
style cs fill:none,stroke:#666
| Colour | Meaning |
|---|---|
| green | built |
| blue, dashed border; dotted arrows | planned |
Every event in the diagram passes through the outbox; only the arrows the diagram would otherwise crowd are drawn there.
| Element | Responsibility | Status |
|---|---|---|
| Flowable CMMN engine | runs the case and its child cases from the CMMN models: Sentries, stage tasks, event and timer listeners, human tasks (6.1, 8.18) | planned (ADR pending) |
| Event Registry bridge | the outbound channel adapter that publishes a send event task's event as a Spring Modulith event, and the listener that hands a reply or a fact to the engine's Event Registry | planned |
| Inbound push adapter | the push endpoint of the event broker: checks the push's OIDC token, reads the versioned contract out of the push envelope, and hands the event on — to the Event Registry, or to the local listeners; it answers the push only when that is done (rule 10) | planned; it replaces the queue's push endpoints of the consumer module |
intake, extraction |
each stage module listens for its own requests and answers with its replies; it knows neither the case nor the engine | the work built (called directly); the request listener planned |
| Other modules | listen for and publish facts between modules that no case is involved in — reporting, notifications, master-data sync | planned |
| Event publication registry | Spring Modulith's outbox: every event is stored in the transaction of the change it reports and delivered after the commit | built under the two database profiles: spring-modulith-starter-jdbc, table event_publication from migration V3, the staleness monitor and the scheduled resubmission of rule 7 under a PostgreSQL advisory lock (spec 458 (docs/specs/458-event-publication-registry.md)); off without a database profile, where events go only to in-memory listeners. No module publishes an event yet; the ADR is pending |
| Spring Cloud Stream | carries externalized events outbound to the broker through ZenWave's externalizer (io.zenwave360.sdk:spring-modulith-events-scs, MIT; built for Spring Modulith 2.1, Spring Boot 4.1, Spring Cloud 2025.1 and Jackson 3); the broker is a binder chosen by configuration. Inbound is the push adapter, not Spring Cloud Stream. If the library needs a change or stalls, its few classes are copied into FeeCheck |
planned (ADR pending) |
| Event broker | FeeCheck's own container (5.2.7): Pub/Sub in production, reached through Spring Cloud GCP's Pub/Sub binder | planned (ADR pending) |
A worker deployment — the same image, configured to run only the stage modules' request
listeners, with its own push adapter and outbox and no case engine — is not in the PoC
(ADR-0009 (docs/adr/adr-0009-async-intake-pubsub-bucket-firestore.md) §5). With one,
requests are externalized and the backend's own listeners for them are switched off by the
same configuration (rule 10).
Choreography or orchestration¶
The two ways to coordinate work that more than one module does:
- Choreography. Each participant reacts to the previous one's event and publishes its own; no participant holds the whole flow.
- Orchestration. One participant, the orchestrator, knows the flow, asks each participant for its part and waits for the answer.
The kinds of interaction above use both, each where it fits:
| Interaction | Style | Status |
|---|---|---|
| Case step, stage work | orchestration: the case engine runs the case from its CMMN model and asks each stage module by request and reply. The stage modules know neither the case nor each other (4.2, 6.1.2) | planned; the work is built, and the case module calls each stage module's application service directly (8.16.1) |
| Fact into a case, fact out of a case | the boundary between the two: the case reacts to a fact from outside, and publishes its own facts without knowing who listens | planned |
| Fact between modules, no case involved | choreography: a module publishes, and whoever needs the fact listens | planned |
| The intake's queue | neither: one point-to-point hand-off from the upload to the queue's consumer (ADR-0009 (docs/adr/adr-0009-async-intake-pubsub-bucket-firestore.md)) |
built |
The reasons the case is orchestrated are those for a case engine in 8.18.3: people deciding in an unpredictable order, gates nobody may skip, and a case state the screen can show. That table's last column, logic written by hand, is what a choreographed case would be: listeners, timers, correlation and a state field, each written and tested by hand.
Stage work by request and reply¶
case: stage task "Extract attributes" sends the request (engine transaction)
→ ExtractionRequested(caseId, requestId, renditionRef) → outbox
extraction: listener on ExtractionRequested (after the commit)
claim requestId in its own short transaction — already claimed or done? → stop
run the use case on the rendition (no transaction open)
store the result, mark requestId done, publish the reply (one transaction)
→ AttributesExtracted(caseId, requestId, resultRef) or ExtractionRejected(caseId, requestId, cause)
cases: the reply → Event Registry → the event listener in the stage task, correlated by caseId and requestId
→ milestone Answered → the stage task completes → Sentries → the next request
no reply before the reply deadline → the stage task is terminated → the case is Failed (6.1.1)
The sketch shows the case engine's target; as built, cases publishes the extraction's reply,
in the transaction that saves the extraction (event catalogue).
The stage module depends on nothing of cases; cases depends on the stage modules' published
event types, which are the stage's API. Long work — a conversion, a model call — runs in the stage's
listener with no transaction open. A model that fails is not a failure: the extraction answers with
its defined fallback (8.7).
Rules¶
- A fact is named in the past tense (
DocumentConverted); a request names what is asked (ExtractionRequested) and is answered by a fact or a rejection (ExtractionRejected). A person's wish is a command to the case API;TaskRetriedandCaseReleasedrecord its result. - Every event is published through the event publication registry in the transaction of the change it reports — for the case, the engine's command, in the same PostgreSQL database (8.3). Two replies, or a reply and a timer, on one case at once meet the engine's optimistic locking; the loser's delivery is retried.
- Only an event another module or system consumes is published API (
@NamedInterface). - Thin: event ID, type, version, case ID, time, references to stored results; non-sensitive control data where a Sentry needs it. Never contract content — NFR-4 holds on the wire too.
- An event is selected for externalization by its type in
EventExternalizationConfiguration, not by an annotation on the domain type, so the domain ring keeps no Spring code (4.3); it is mapped to a versioned contract…V1, append-only, with the routing evaluated on the mapped contract (routeMapped()), which therefore carries the case ID. Listeners in the same deployable keep the domain event; a consumer in another deployable reads only the fields it needs. - At least once, every consumer idempotent: a consumer of long work claims the request ID in its own short transaction before the work, and marks it done in the transaction that stores the result; a claim older than its lease may be taken again. The key is a stable ID in the payload — never the broker's message ID, which a resubmit from the outbox changes; one store per consumer, in the database.
- Failed and incomplete publications are resubmitted by FeeCheck's own scheduled job through Spring Modulith's resubmission API, run by one instance at a time under a database lock; the staleness monitor marks a publication stuck beyond its age as failed. Republishing on restart stays off, because several instances start at once. The completion mode keeps completed rows, which a scheduled purge removes.
- Ordering only where a consumer needs it: request and reply are correlated by request ID and need
none. A topic whose consumers need a case's sequence — the facts out to downstream systems — uses
the case ID as ordering key, with message ordering on its subscription and the publishers on one
regional endpoint,
europe-west6(7.1.2); Pub/Sub orders per key within one topic and one subscription only. - A changed payload is a new version, never a silent change. A retry never replays a past event: it sends a new request with a new ID, and a late reply to the old one finds no waiting listener.
- One consumer per request: without a worker, a request stays in the deployable and its listener runs there; with a worker, the request is externalized and only the worker listens for it. The inbound push adapter takes only externalized events, and it handles each one completely inside the push request — Cloud Run allocates CPU only while a request is served, so work left running after the answer would stall and an early acknowledgement would lose the retry. Deduplication (6) stays the safety net.
- Operations: the outbox table is purged on a schedule; alerts on the backlog of incomplete publications and on the age of the oldest unacknowledged message; a dead-letter topic per subscription, with the Pub/Sub service agent's IAM roles; the push adapter keeps the OIDC token check (8.8); Spring Cloud GCP's task scheduler kept apart from the application's; the publisher's retry settings set as a complete group; a failed publish with an ordering key pauses that key until the transport resumes it.
Event catalogue¶
| Event | Kind | Published by | Consumed by | Status |
|---|---|---|---|---|
DocumentCheckRequested / DocumentChecked, DocumentBlocked |
stage request / reply | cases / intake |
intake / cases |
planned |
ClassificationRequested / DocumentClassified |
stage request / reply | cases / intake |
intake / cases |
planned |
ConversionRequested / DocumentConverted, ConversionRejected |
stage request / reply | cases / intake |
intake / cases |
planned; the conversion runs on a bare case ID on the queue |
ExtractionRequested / AttributesExtracted, ExtractionRejected |
stage request / reply | cases / cases, in the transaction that saves the extraction, because the extraction is the case component's aggregate (8.11.3, 8.3) |
extraction / cases |
planned; the extraction runs on a person's request |
ReconciliationRequested / FindingsCreated, ReconciliationRejected |
stage request / reply | cases / reconciliation |
reconciliation / cases |
planned |
AssessmentRequested / FindingsCommented |
stage request / reply | cases / the module that makes the model calls |
that module / cases |
planned |
DocumentReceived, from a channel other than the upload |
fact into a case | the channel's module | cases |
planned |
ContractRecorded |
fact out of a case | cases |
whoever needs it | planned |
FindingsPublished |
fact out of a case | cases |
downstream systems over Pub/Sub (ADR-0009 (docs/adr/adr-0009-async-intake-pubsub-bucket-firestore.md)) |
planned |
The case engine on the backbone¶
| Concept | With Flowable | Status |
|---|---|---|
| Case model | the CMMN models of spec 15 (docs/specs/15-workflow-module.md), deployed from the repository with the event and channel definitions; a child case is a CaseTask in the same engine, with the case's ID as its business key, so the business state of 6.1.1 is kept for the parent case; a customer's model per tenant (W-8) |
planned |
| Stage request out | a stage task: a sub-stage with a send event task, an event listener for the reply that reaches a required milestone, and the rejection and the reply deadline as its exit criteria (6.1.2) | planned |
| Reply or fact in | the Event Registry bridge, then a CMMN event listener | planned |
| Missing reply | a timer event listener per stage task, one generous default overridden in the model where needed, the value taken from measured run times | planned |
| Retry | the case port's retry a task starts the failed stage task again through the engine's change of plan-item state; the new request carries a new request ID | planned |
| Human task | Flowable's human task with a candidate group (W-7); the completing identity recorded by FeeCheck | planned |
| Business state and audit trail | FeeCheck's own record beside the engine's plan items (6.1.1) and FeeCheck's own append-only audit trail (spec 15 §2) | planned |
| Port | a thin port in cases.domain — start a case, read it, complete a human task, retry a task — spec 15 §5's CaseRuntime, CaseTasks and CaseJobs, with one adapter, Flowable's; no CaseStep |
planned |
| Persistence | the engine's tables, the case, the business state and the outbox in one PostgreSQL database under one transaction manager (8.3) | planned |
| Offline build | Flowable embedded on H2 in memory; PostgreSQL in a container only in the integration tests | planned |