Articles Architecture

Modular monolith vs microservices: start with modules

Modular monolith vs microservices, the short answer: start with a modular monolith. Build one deployable application, split it into modules with boundaries that a test enforces, and extract a module into its own service only when a concrete reason appears, such as a different scaling profile, a different release cadence or a workload that must be isolated. Microservices solve real problems, but they are problems of scale and organisation, and they charge their price from the first day.

The code and the failure messages below come from one small project: Spring Boot 4.2.0, Spring Modulith 2.2.0 (the current GA release, which brings ArchUnit 1.5.1) and JDK 25. Spring Modulith 2.x is the line for Spring Boot 4. For Spring Boot 3.5 the compatibility table lists Spring Modulith 1.4.

What is a modular monolith?

A modular monolith is a single deployable unit whose code is divided into modules, where each module owns one business capability, exposes a small public API and hides everything else. Calls between modules are ordinary method calls inside one process, and by default they share one database transaction.

What it is not: an application with controller, service and repository packages where any class may call any other. That is a monolith with folders. The difference is not the package names, it is whether a forbidden dependency fails the build. Without enforcement, boundaries erode one convenient import at a time.

What do microservices cost on day one?

Each of these costs arrives with the second service, whether or not the system needs it yet:

  • Method calls become network calls. A call that could not fail now needs a timeout, a retry policy, idempotency and a versioned contract.
  • One transaction becomes several. A business operation that spans two services cannot be rolled back as a unit. You design for eventual consistency, with compensating actions, an outbox or a saga.
  • Every service needs its own pipeline and observability. Build, deployment, configuration, logs, metrics and tracing are multiplied, and a single request has to be followed across processes.
  • Local development gets heavier. Running one feature may require several services, a broker and their databases on a laptop.
  • A wrong boundary is expensive to move. Shifting a responsibility between services means changing APIs, data ownership and deployments. Inside a monolith it is a refactoring.

The last point matters most early on, because boundaries are least understood when the system is new.

What makes a module in a Spring Boot application?

Three rules: a package per business capability, a small public API, and no access to another module’s internals or tables. Spring Modulith treats every direct sub-package of the application’s main package as a module:

shop
  ShopApplication.java
  order
    OrderService.java         public
    OrderPlaced.java          public event
  inventory
    InventoryService.java     public
    ReservationPolicy.java    package-private
    internal
      StockRepository.java    public, but internal to the module
  notification
    OrderMailer.java          package-private

Public types in a module’s base package are its API. Everything in a sub-package such as inventory.internal is internal, as described in the fundamentals chapter.

How do you enforce module boundaries in Java?

The first tool is the compiler. A class without the public modifier is invisible outside its package, so ReservationPolicy cannot be imported by the order module at all:

package shop.inventory;

class ReservationPolicy { // package-private: other modules cannot reference it
    void check(int quantity) { ... }
}

Package-private stops working once a module needs sub-packages. StockRepository has to be public so that InventoryService can use it, and from that moment any class in the application can import it. This is the gap a build-time test closes. Add spring-modulith-starter-test and write one test:

class ModularityTests {

    @Test
    void modulesRespectTheirBoundaries() {
        ApplicationModules.of(ShopApplication.class).verify();
    }
}

According to the verification chapter, verify() rejects cycles between modules and references to another module’s internal packages. Now break the rule on purpose and inject the repository into OrderService:

OrderService(InventoryService inventory, StockRepository stock, ApplicationEventPublisher events) {

The test fails with four entries, one per reference. The first two:

org.springframework.modulith.core.Violations:
- Module 'order' depends on non-exposed type shop.inventory.internal.StockRepository within module 'inventory'!
OrderService declares constructor OrderService(InventoryService, StockRepository, ApplicationEventPublisher) in (OrderService.java:0)
- Module 'order' depends on non-exposed type shop.inventory.internal.StockRepository within module 'inventory'!
Method <shop.order.OrderService.place(java.lang.String, int)> calls method <shop.inventory.internal.StockRepository.available(java.lang.String)> in (OrderService.java:28)

Cycles are caught the same way. order already calls InventoryService. Add a listener for OrderPlaced inside inventory and the modules depend on each other:

- Cycle detected: Slice inventory ->
                Slice order ->
                Slice inventory

Projects without Spring Modulith can write the same rule directly in ArchUnit:

JavaClasses classes = new ClassFileImporter().importPackages("shop");

noClasses().that().resideOutsideOfPackage("shop.inventory..")
        .should().dependOnClassesThat().resideInAPackage("shop.inventory.internal..")
        .check(classes);

Against the broken OrderService it reports:

Rule 'no classes that reside outside of package 'shop.inventory..' should depend on classes that reside in a package 'shop.inventory.internal..'' was violated (3 times)

With plain ArchUnit you write one such rule per module, or a generic one. Spring Modulith derives them from the package layout.

How should modules talk to each other?

There are two options, and most systems use both.

A direct call through the public API fits when the caller needs the result, or when the operation must succeed or fail as a whole. OrderService calls inventory.reserve(sku, quantity) inside its transaction. If the reservation throws, the order is rolled back.

An application event fits when the other module only reacts. The publisher does not know who listens, so the dependency points from the listener to the publisher:

events.publishEvent(new OrderPlaced(id, sku, quantity));
@Component
class OrderMailer {

    @ApplicationModuleListener
    void on(OrderPlaced event) { ... }
}

A plain @EventListener runs synchronously inside the publisher’s transaction. With @TransactionalEventListener the listener runs after the transaction has committed (AFTER_COMMIT is the default phase), so an email is never sent for an order that was rolled back. The events chapter describes @ApplicationModuleListener as a shortcut for @Async, @Transactional with REQUIRES_NEW and @TransactionalEventListener. In the test project the caller ran on main and the listener on task-1. These annotations work through proxies, with the usual limits of @Transactional.

A listener that runs after commit can fail with the order already saved, and then the event is gone. Spring Modulith’s event publication registry covers that case: with a starter such as spring-modulith-starter-jdbc, an entry for every transactional listener is written to an event_publication table as part of the original transaction, and marked completed when the listener succeeds. After the test run the row had STATUS=COMPLETED and COMPLETION_ATTEMPTS=1. Entries of failed listeners stay incomplete and can be resubmitted. This is an outbox inside the monolith, and it is the same consistency model you would need between services.

Should modules share one database?

One database server is fine. Shared tables are not. A workable guideline for new code:

  • each module owns its tables, in its own schema or behind a table-name prefix,
  • no SQL joins across modules,
  • no foreign keys across modules, only plain identifiers,
  • data of another module is read through that module’s API.

The trade-off is real. You give up some referential integrity and the convenience of one query that joins everything, and a screen that combines two modules needs two calls or a dedicated read model. In return a module’s schema can change without breaking others, and the data already has an owner on the day the module moves out.

When should you extract a microservice?

Extract a module when a specific pressure appears, not in advance:

  • Independent scaling. One module needs far more instances, memory or a different hardware profile than the rest.
  • A different runtime or release cadence. A part that is better written on another stack, or that must ship many times a day while the rest ships weekly.
  • Team ownership. Several teams block each other in one codebase and one release train. Service boundaries that follow team boundaries remove that coordination.
  • Isolation of risky workloads. Code that runs untrusted input, heavy batch jobs or anything that can exhaust memory should not share a process with the rest of the system.

Where these pressures exist from the start, for example many teams working on a large product with very uneven load, microservices are the right choice and a monolith would be the bottleneck.

Clean boundaries make the extraction cheap. A module that is reached only through a small API, communicates through events and owns its tables is already shaped like a service: the API becomes an HTTP or messaging contract, the events move to a broker, the tables move to another database. A module tangled into its neighbours has to be untangled first, and that work is the same in either architecture.

Summary

A modular monolith keeps the deployment simple and the boundaries strict. Before splitting a system, check:

  • Is there a module whose scaling, runtime, release cadence or risk profile differs from the rest? If not, stay in one deployable.
  • Does every module have a small public API, with internals package-private or in an internal package?
  • Does a test (ApplicationModules.verify() or an ArchUnit rule) fail the build on a forbidden dependency or a cycle?
  • Do modules that only react use events, with listeners that run after commit?
  • Does every table have exactly one owning module, with no cross-module joins or foreign keys?
  • Can the team operate several pipelines, distributed tracing and eventual consistency today? If not, extraction can wait.