#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Builds the Spring Modulith 2.1 post HTML with correct code-block escaping for ankurm.com's house style: '&' -> '&', '<' -> '<', '>' stays literal. """ def esc(code: str) -> str: return code.replace("&", "&").replace("<", "<") def pre(lang: str, code: str) -> str: code = code.strip("\n") return f'
{esc(code)}'
REPO = "https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment"
def link(path, text=None):
return f'{text or path}'
callout_style = 'style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"'
def callout(lead, body):
return f'{lead} {body}' # --------------------------------------------------------------------------- # Diagrams (hand-written inline SVG) # --------------------------------------------------------------------------- DIAGRAM_MODULES = '''
Every modular monolith starts the same way: a clean diagram, a handful of packages
named after the business, and a promise that order will not reach into
inventory’s business. Six months and four developers later, somebody
adds exactly that reach — a repository field, a quick read, “it’s all
one database anyway” — and nothing stops them. The code compiles. The tests
that exist still pass. The diagram is now a lie, and nobody finds out until the day
someone tries to split the monolith and discovers the boundaries were never real.
Spring Modulith is Spring’s answer to that specific failure: not a framework for writing microservices-shaped code inside one deployable, but a verification tool that turns your package structure into a contract a test can enforce. This post builds a small, real order-fulfillment app with four modules, breaks the boundary between two of them on purpose, watches the actual test failure, fixes it, and then shows that the "fix" most people reach for first — routing the call through the public API instead of the internals — still fails, for a reason that matters more than the original mistake.
{VERSIONS_CALLOUT} ''' SEC_MODEL = f'''Spring Modulith does not introduce a new way to write Spring code. It looks at
packages you were probably going to create anyway and gives them meaning. The default
convention — and the one this post uses — is package by
feature: every direct sub-package of the package holding
@SpringBootApplication is a module. No XML, no registry, no annotation
required to declare one.
The demo app has four: order, inventory, shipping,
and notification, each a sub-package of
com.ankurm.modulithdemo. Inside each module, anything directly in the
module’s own package is that module’s public API —
fair game for other modules to depend on. Anything one level deeper, in an
internal sub-package, is exactly that: internal, and off-limits to
everyone else, regardless of whether the Java compiler marks it public.
Java’s own visibility modifiers stop at the package; Spring Modulith is the thing
that enforces the rest.
That diagram is not something I drew by hand and hoped matches the code. It is the
real output of Spring Modulith’s own Documenter, reading this
repository’s bytecode and generating a PlantUML component diagram and a
per-module canvas — see the accordion near the end of this post for the raw
PlantUML and the full captured transcript. Every arrow is a "listens to"
relationship the tool found by inspecting @ApplicationModuleListener
method parameters, not something I asserted.
Notice the direction. inventory and notification both
point at order, and notification also points at
shipping. order points at nothing. That is not an accident of
this particular app; it is the whole design goal, and it is the thing that gets broken
in the next section.
The diagram above is only worth anything if something fails the build the moment it stops being true. That something is two lines:
{SNIPPET_MODULARITY_TEST}{link("src/test/java/com/ankurm/modulithdemo/ModularityTests.java", "ModularityTests.java")}
ApplicationModules.of(Application.class) scans the bytecode reachable
from the application’s main package and builds the module model described above.
verify() walks every type dependency it finds — constructor
parameters, fields, method bodies, the lot — and throws
org.springframework.modulith.core.Violations, a RuntimeException,
the moment one of them crosses a module boundary it should not. Put it in a JUnit test
and it becomes a build-breaking architecture check that runs on every commit, with zero
ArchUnit rules to hand-write.
The app itself needs nothing special to make this work. Here is the whole bootstrap class:
{SNIPPET_APPLICATION}{link("src/main/java/com/ankurm/modulithdemo/Application.java", "Application.java")}
— @Modulithic is optional (it names the system for the generated
documentation) but ApplicationModules.of() works with a plain
@SpringBootApplication class just as well.
The Maven coordinates for all of this are one BOM import and two starters — one for the main app, one for the tests:
{SNIPPET_POM}{link("pom.xml")}
''' OUTPUT_02 = pre("console", """ Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -- in ModularityTests BUILD SUCCESS Same four modules, same ApplicationModules.verify() call, zero violations. The only change from output/01 is that OrderManagement no longer depends on anything in inventory, in either direction. """) SEC_VIOLATION = f'''Here is the shortcut a real developer takes under real time pressure. Before placing
an order, OrderManagement wants to know whether there is enough stock.
The honest way is to ask inventory’s public API. The fast way, if you
already know the schema and you are in a hurry, is to inject
inventory.internal.StockRepository directly and query it yourself:
This compiles. It runs. If you call the endpoint by hand, you will not see anything wrong. The only thing standing between this code and production is the test from the previous section — and here is exactly what it says when it runs against this version of the code:
{OUTPUT_01}Full transcript: {link("output/01-verify-violation-failed.txt")}
One field produced two separate violations in the same run, and they are worth telling apart, because they have different fixes.
The second one — "depends on non-exposed type" — is the
one most people expect: StockRepository lives under
inventory.internal, and nothing outside inventory is allowed
to reference it, public interface or not.
The first one — "Cycle detected: Slice inventory -> Slice order
-> Slice inventory" — is the one that catches people out, and it is the
subject of the rest of this section. inventory already depends on
order: its @ApplicationModuleListener method takes
OrderPlaced as a parameter, and that is a real dependency edge as far as
Spring Modulith is concerned, identical in kind to a constructor argument. Adding a
field that points the other way — order depending on anything in
inventory — closes a two-module cycle, and Spring Modulith treats
the module graph as a strict DAG by default. A cycle fails verification even before the
tool asks whether the specific type you reached for happens to be internal.
The obvious-looking fix is to leave the field, but point it at
InventoryManagement — inventory’s real, intentional public
API — instead of the internal repository:
Run the same test against this version:
{OUTPUT_03}Full transcript: {link("output/03-cycle-via-public-api-still-failed.txt")}
The non-exposed-type complaint is gone, exactly as expected —
InventoryManagement is a perfectly legitimate public type. The cycle is
still there, because the cycle was never about which types are public. It is about
direction, and the direction was already spoken for the moment
inventory chose to listen for OrderPlaced.
The only fix that actually works is to not add the second edge. order
publishes OrderPlaced and stops caring what happens to it:
{link("src/main/java/com/ankurm/modulithdemo/order/OrderManagement.java", "OrderManagement.java")} (final version)
{OUTPUT_02}Full transcript: {link("output/02-verify-passed.txt")}
If inventory genuinely cannot satisfy an order, that has to travel back as a new
event order deliberately chooses to listen for — a second,
intentional relationship, not a shortcut around the first one. Keeping that
back-channel from becoming a cycle of its own is a big enough topic that it gets its
own post later in this series, on the Saga pattern.
Sometimes a module genuinely needs to expose more than flat types in its base package — an SPI sub-package meant for one or two trusted callers, say. Spring Modulith has two escape hatches, both narrower than they look:
@NamedInterface("spi") on a package-info.java inside
inventory.spi promotes that one sub-package to additional public API,
referenced from other modules’ @ApplicationModule(allowedDependencies =
"inventory :: spi") declarations. It is scoped and explicit — exactly one
extra package, named in the dependency declaration of whoever is allowed to use it.
@ApplicationModule(type = Type.OPEN) on the module’s
package-info.java is the blunt version: every internal type in that module
becomes visible to everyone. The reference documentation is direct about this not being
recommended for a well-modularized application, and after watching
verify() catch the StockRepository shortcut above, it should
be obvious why — OPEN does not fix the design problem, it just turns
off the thing that was telling you about it.
Neither of these would have saved the order → inventory
shortcut in this post. They widen who can see a module’s internals; they do
nothing about a cycle, which is a statement about direction, not visibility.
Once order publishes OrderPlaced and gets out of the way,
three independent listeners pick it up. Here is inventory’s:
{link("src/main/java/com/ankurm/modulithdemo/inventory/InventoryManagement.java", "InventoryManagement.java")}
@ApplicationModuleListener looks like a plain marker annotation. It is
not. Reading the actual compiled class file — not the reference docs, the
bytecode — shows exactly what it expands to:
So @ApplicationModuleListener is @Async +
@Transactional(propagation = REQUIRES_NEW) +
@TransactionalEventListener, stacked as meta-annotations on one
declaration. That combination is the whole mechanism:
AFTER_COMMIT:
the listener only runs once the transaction that published the event has actually
committed. Publish inside a transaction that rolls back, and the listener never fires
— which is correct, and also means publishing an event from code with no active
transaction at all silently does nothing. (Scenario.publish(), from the
test library, wraps the publish in its own transaction for exactly this reason.)OrderManagement.placeOrder()
finishes and gives the caller an Order back long before
inventory has reserved anything.Full transcript: {link("output/05-redundant-transactional-failure.txt")}
This is a fail-fast mistake, at least — the context simply will not come up, so it cannot ship silently. It is still worth knowing before it costs you a confused ten minutes staring at a stack trace three frames removed from the line you actually wrote.
Put the three listeners together and one publishEvent() call fans out
into four separate invocations, each on its own thread, in causal order but with no
ordering guarantee between independent branches:
Running the whole chain for real, from a test that boots all four modules together, produces exactly that:
{OUTPUT_06}Full transcript: {link("output/06-event-flow-passed.txt")}
Getting that test to run at all — and the very specific way it fails the first time — is its own lesson about a different Spring Modulith default, and it is worth a section of its own.
''' SEC_TESTING = f'''@ApplicationModuleTest is Spring Modulith’s replacement for
@SpringBootTest in a single module’s tests: instead of booting the
entire application, it boots just the module under test, plus whichever other modules
mode tells it to include. BootstrapMode.ALL_DEPENDENCIES
sounds like exactly what you want for an integration test that follows an event across
three modules. Here is the first version of that test, written the way the name
suggests it should work:
(annotation: @ApplicationModuleTest(mode =
BootstrapMode.ALL_DEPENDENCIES) on a test in the order package,
publishing OrderPlaced and waiting for ShipmentScheduled)
Full transcript: {link("output/04-event-flow-missing-dependency.txt")}
Ten seconds of nothing, then a timeout. The log line that explains it is easy to
miss on a first read: Direct module dependencies: none.
ALL_DEPENDENCIES bootstraps the modules the module under test depends
on — the modules it imports from. It does not infer the reverse: modules that
depend on it, by listening for its events. order imports nothing
from inventory, shipping, or notification —
correctly, as the whole first half of this post just finished establishing — so
from order’s point of view, in this test, those three modules do not
exist. InventoryManagement is never instantiated. The event is published
into a context with no listener to receive it, and the test waits for something that
was never going to arrive.
The fix is extraIncludes, which names modules to bootstrap regardless of
whether the module under test has a code dependency on them:
{link("src/test/java/com/ankurm/modulithdemo/order/OrderFulfillmentIntegrationTests.java", "OrderFulfillmentIntegrationTests.java")}
With inventory, shipping, and notification
named explicitly, their listener beans exist, the cascade actually runs, and this is
the test that produced the passing transcript in the previous section. The
Scenario API itself — publish(event).andWaitForEventOfType(X.class)
.matching(...).toArriveAndVerify(...) — is Spring Modulith’s
Awaitility-backed way of asserting on an async, eventually-consistent chain without a
hand-rolled Thread.sleep().
Everything so far has been about getting the happy path to compile, pass, and run. Two defaults are worth knowing about before this goes anywhere near production, because neither one fails loudly.
Every @ApplicationModuleListener gets one row in the event publication
registry — a table Spring Modulith creates for you (via
spring-modulith-starter-jpa or -jdbc) the moment an event is
published, before the listener even runs:
That row is what makes the registry useful at all — it is how a listener that threw an exception can be found and resubmitted later, and how a process that died between "published" and "handled" does not just lose the event. But two defaults blunt that guarantee more than the reference documentation’s tone suggests:
UPDATE: completed rows are marked
complete and left in the table, forever, growing without bound unless something purges
them. DELETE removes them (and loses the ability to query completed
publications); ARCHIVE moves them to a separate table first, which is
usually the one you actually want.PUBLISHED or PROCESSING after a crash and mark it
FAILED so it becomes eligible for resubmission — is disabled by
default. All three spring.modulith.events.staleness.* durations default to
zero, which this library treats as "off", not "immediately stale".None of this is a defect in Spring Modulith — it is a reasonable default for a library that has to work the same way whether you are prototyping on an in-memory H2 database or running a Kafka-backed outbox in production. It is, however, exactly the kind of default that an architecture diagram does not show you, which is the theme of this whole post applied one layer down: the tool that verifies your module boundaries has its own quiet defaults, and they reward the same treatment — read the actual behavior, not the one-paragraph summary.
''' SEC_DOCS = f'''The module diagram earlier in this post, and the arrows in it, came from running this:
{SNIPPET_DOCUMENTER}{link("src/test/java/com/ankurm/modulithdemo/ModularityTests.java", "ModularityTests.java")}
(the writesDocumentation() test)
Documenter reads the same ApplicationModules model
verify() checks and writes a PlantUML component diagram, one PlantUML
diagram per module showing just that module’s direct dependencies, a tabular
"canvas" per module (Spring beans, grouped by stereotype), and an Asciidoc file linking
all of it together — to target/spring-modulith-docs by default.
Full transcript, including every generated .puml and .adoc
file: {link("output/07-generated-docs.txt")}. Note that the diagram the generator
produces is a C4-style PlantUML file meant for a build pipeline to render —
this post hand-draws the equivalent SVG instead, to match the rest of the
site, but the relationships in it are copied directly from this generated
output, not invented.
The practical value of this is less "pretty diagrams" and more "diagrams that cannot quietly go stale", because they are regenerated from the actual compiled module structure on every build, the same build that is already failing if that structure violates its own rules.
''' SEC_ASIDE = f'''Before any of the module-boundary content above, the very first time this repository’s tests ran against a real database, they failed on something that has nothing to do with Spring Modulith at all:
{OUTPUT_00}Hibernate defaults a JPA entity’s table name to the class’s simple name.
Order the Java class becomes order the table, and
ORDER is a reserved SQL keyword — the ORDER BY clause
— in H2, Postgres, MySQL, and the SQL standard generally. The fix is one
annotation:
{link("src/main/java/com/ankurm/modulithdemo/order/internal/Order.java", "Order.java")}
{callout( "If you are naming an entity after a core domain concept in an order-processing system, check it against your database's reserved-word list before the schema generator does it for you.", "ORDER, GROUP, USER, and DATE have all caught people this way at least once." )} ''' CLOSING = f'''The next post in this series uses this same repository to work through the question that follows naturally from everything above: once your modules are genuinely decoupled and verified, when — if ever — does it actually pay to split them into separate services? And two posts after that, the Transactional Outbox post comes back to the event publication registry diagram above and does something with the completion states this one only described: externalizing events to Kafka, and replaying the ones that got stuck.