Monolith and modular monolith
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Twelve developers now change ShopLite, and last week a notifications fix broke checkout. Nobody can say which packages depend on which. How do you stop changes from breaking each other without rewriting everything?
Your turn: how do you stop changes from breaking each other?
ShopLite is one app: one JAR, one database, and every class can use every other. Think before you read on:
- Last week a notifications change stopped checkout. What would you need to know to predict that this could happen?
- Would you split ShopLite into separate servers now, or first draw lines inside the code? Name one cost of each choice.
- If orders needs a product's price, what is the safest way for it to ask the catalogue?
The monolith: one deployable, one database
A monolith is one application, built and deployed as one unit, usually with one database. Every feature lives in the same codebase and runs in the same process.
ShopLite from Sections 15 to 17 is a monolith: catalogue, orders, payments and notifications in one codebase. Run the small version below.
Example 1 · A tiny monolith: one program, one data store, one deploy
import java.util.HashMap;import java.util.Map;
// One program, one database (here: maps), one deploy.// Prices are whole rupees to keep the simulation short; ShopLite uses BigDecimal.public class MonolithDemo { static Map<Integer, Integer> stock = new HashMap<>(); static Map<Integer, Integer> price = new HashMap<>(); static Map<Integer, String> orders = new HashMap<>(); static int nextOrderId = 501;
static int placeOrder(int productId, int qty, String upiId) { if (stock.get(productId) < qty) { throw new IllegalStateException("out of stock"); } int total = price.get(productId) * qty; System.out.println(" charged Rs " + total + " to " + upiId); stock.put(productId, stock.get(productId) - qty); int id = nextOrderId++; orders.put(id, "PLACED"); return id; }
public static void main(String[] args) { stock.put(1, 40); price.put(1, 17999);
System.out.println("Order " + placeOrder(1, 2, "meena@okaxis") + " placed"); System.out.println("Stock of product 1 now " + stock.get(1)); System.out.println("Deploy: 1 jar, 1 database, 1 command"); }}charged Rs 35998 to meena@okaxis Order 501 placed Stock of product 1 now 38 Deploy: 1 jar, 1 database, 1 command
What this code does
- Catalogue, payment and order work sit in one method and share the same maps, which stand in for one database. Prices are whole rupees here; ShopLite uses
BigDecimal. - This is simple and fast to build. The trouble is only that nothing stops any code from touching any data, which shows up as the app grows.
It is a good default. A call between features is a plain method call, a change across features is one commit and one deploy, and one database transaction can update stock and create an order together. Most products should start here.
Pain points as the team grows
A tangle is a set of packages that depend on each other in both directions or in cycles, so nobody can tell what a change will break.
After two years, the packages of an old monolith use each other in every direction. Run the code to measure that tangle.
Example 2 · Measuring the tangle in an old monolith
import java.util.List;import java.util.Map;import java.util.TreeMap;
public class TangleCheck { public static void main(String[] args) { // "package -> packages it imports from", read from a 2-year-old monolith Map<String, List<String>> uses = new TreeMap<>(); uses.put("catalogue", List.of("orders", "common")); uses.put("orders", List.of("catalogue", "payments", "notifications", "common")); uses.put("payments", List.of("orders", "common")); uses.put("notifications", List.of("orders", "catalogue", "payments")); uses.put("common", List.of());
int edges = 0; for (Map.Entry<String, List<String>> e : uses.entrySet()) { edges += e.getValue().size(); for (String other : e.getValue()) { if (uses.getOrDefault(other, List.of()).contains(e.getKey()) && e.getKey().compareTo(other) < 0) { System.out.println("Two-way dependency: " + e.getKey() + " <-> " + other); } } } System.out.println(edges + " dependencies between 5 packages"); System.out.println("A change in orders can break: " + whoUses("orders", uses)); }
static List<String> whoUses(String pkg, Map<String, List<String>> uses) { return uses.entrySet().stream() .filter(e -> e.getValue().contains(pkg)) .map(Map.Entry::getKey) .toList(); }}Two-way dependency: catalogue <-> orders Two-way dependency: notifications <-> orders Two-way dependency: orders <-> payments 11 dependencies between 5 packages A change in orders can break: [catalogue, notifications, payments]
What this code does
- The map lists which packages each package imports. Three pairs depend on each other in both directions, such as catalogue and orders.
whoUsesshows that a change in orders can break three other packages. This is the "nobody knows what will break" pain, measured.
Problems appear when many developers work on one growing monolith for years. Tangled packages: any class can use any other, so nobody knows what a change will break. Slow builds and tests: every change rebuilds and retests everything. Risky deploys: a small change to notifications ships the whole app, so one bug can stop checkout.
These are problems of missing boundaries, not of having one deployable. That is why the first fix is usually boundaries inside the monolith, not splitting it.
Predict the output
Who can a change break?
Read who imports whom, then pick the answer.
If you change the orders package, which packages can break?
Modular monolith: modules by business area
A modular monolith is one deployable whose code is split into business-area modules (catalogue, orders, payments). Each module has a small public API and hides everything else.
The code is split by business area, and each module shows a small public API. Other modules may call only that API.
[ShopLite JAR] catalogue API: CatalogueApi owns: categories, products orders API: OrderApi owns: orders, order_items payments API: PaymentApi owns: payments notifications listens to OrderPlaced owns: notification_log common Money, errors, config (usable by everyone)The orders module asks CatalogueApi.reserveStock(...); it never reads the catalogue's ProductRepository or its products table. It is still one JAR and one database, so you keep simple deploys and local method calls.
Order of execution
Add boundaries step by step
Tap the steps in the order a team would take them.
ShopLite package layout and the interfaces-only rule
A module API is the small set of interfaces and records that other modules may use. Everything else in the module, including its tables, is internal.
In Java, a module is a top-level package with an api sub-package that others may use and an internal one only it may use. The rule: no import of another module's internal package.
com.shoplite.catalogue.api.CatalogueApi <- others may usecom.shoplite.catalogue.internal.ProductRepository <- catalogue onlycom.shoplite.orders.api.OrderApicom.shoplite.orders.internal.OrderServicecom.shoplite.payments.api.PaymentApicom.shoplite.common.Money <- everyoneExample 3 · Checking the interfaces-only rule automatically
import java.util.List;
record Usage(String fromClass, String usesClass) {}
public class BoundaryChecker { // com.shoplite.<module>.<rest>: the module is the third part of the name static String moduleOf(String className) { return className.split("\\.")[2]; }
// Rule: another module may only use classes in its "api" package static boolean allowed(Usage u) { String from = moduleOf(u.fromClass()); String to = moduleOf(u.usesClass()); return from.equals(to) || to.equals("common") || u.usesClass().contains("." + to + ".api."); }
public static void main(String[] args) { List<Usage> usages = List.of( new Usage("com.shoplite.orders.internal.OrderService", "com.shoplite.catalogue.api.CatalogueApi"), new Usage("com.shoplite.orders.internal.OrderService", "com.shoplite.orders.internal.OrderRepository"), new Usage("com.shoplite.orders.internal.OrderService", "com.shoplite.catalogue.internal.ProductRepository"), new Usage("com.shoplite.payments.internal.RefundJob", "com.shoplite.orders.internal.OrderEntity"), new Usage("com.shoplite.payments.internal.RefundJob", "com.shoplite.common.Money"));
int violations = 0; for (Usage u : usages) { if (!allowed(u)) { violations++; System.out.println("VIOLATION: " + simple(u.fromClass()) + " uses " + u.usesClass()); } } System.out.println(violations + " boundary violation(s) in " + usages.size() + " usages"); }
static String simple(String className) { return className.substring(className.lastIndexOf('.') + 1); }}VIOLATION: OrderService uses com.shoplite.catalogue.internal.ProductRepository VIOLATION: RefundJob uses com.shoplite.orders.internal.OrderEntity 2 boundary violation(s) in 5 usages
What this code does
allowedaccepts a usage inside the same module, ofcommon, or of another module'sapipackage, and rejects everything else.- Two violations are found: orders reaching into the catalogue's repository and payments using an order entity. In a real project the same check runs as a test and fails the build.
A rule nobody checks is soon broken, so teams check it automatically. Tools such as ArchUnit or Spring Modulith can fail the build on a forbidden import; the Java example below does the same check on a list of usages.
Find the bug
Find the broken boundary
Each snippet breaks a module rule. Tap the wrong line, then check the fix.
Imports at the top of an orders class.
Round 1 of 3Demo: orders calling the catalogue through its interface
Orders receives a CatalogueApi in its constructor and calls only findProduct and reserveStock. Run it with an active and an inactive product.
Example 4 · OrderModule calling CatalogueApi, never its internals
import java.util.HashMap;import java.util.Map;import java.util.Optional;
// ---- catalogue module: public API ----record ProductInfo(int id, String name, int price) {}
interface CatalogueApi { Optional<ProductInfo> findProduct(int id);
boolean reserveStock(int productId, int qty);}
// ---- catalogue module: internals (other modules never see these) ----record ProductRow(int id, String name, int price, int stock, boolean active) {}
class CatalogueModule implements CatalogueApi { private final Map<Integer, ProductRow> products = new HashMap<>();
CatalogueModule() { products.put(1, new ProductRow(1, "Redmi Note 13 5G", 17999, 40, true)); products.put(3, new ProductRow(3, "Old Nokia 3310", 2499, 5, false)); }
public Optional<ProductInfo> findProduct(int id) { ProductRow r = products.get(id); if (r == null || !r.active()) { return Optional.empty(); } return Optional.of(new ProductInfo(r.id(), r.name(), r.price())); }
public boolean reserveStock(int productId, int qty) { ProductRow r = products.get(productId); if (r == null || !r.active() || r.stock() < qty) { return false; } products.put(productId, new ProductRow(r.id(), r.name(), r.price(), r.stock() - qty, r.active())); return true; }}
// ---- orders module: knows only CatalogueApi ----class OrderModule { private final CatalogueApi catalogue; private int nextId = 501;
OrderModule(CatalogueApi catalogue) { this.catalogue = catalogue; }
String place(int productId, int qty) { Optional<ProductInfo> product = catalogue.findProduct(productId); if (product.isEmpty()) { return "rejected: product " + productId + " not available"; } if (!catalogue.reserveStock(productId, qty)) { return "rejected: not enough stock"; } int total = product.get().price() * qty; return "order " + nextId++ + ": " + qty + " x " + product.get().name() + " = Rs " + total; }}
public class ModuleApiDemo { public static void main(String[] args) { OrderModule orders = new OrderModule(new CatalogueModule()); System.out.println(orders.place(1, 2)); System.out.println(orders.place(3, 1)); System.out.println(orders.place(1, 50)); }}order 501: 2 x Redmi Note 13 5G = Rs 35998 rejected: product 3 not available rejected: not enough stock
What this code does
OrderModuleonly seesCatalogueApiandProductInfo.ProductRow, the stock numbers and theactiveflag stay insideCatalogueModule.- The inactive Nokia is rejected and the 50-unit order fails because the catalogue applies its own rules. Orders never has to know those rules.
Example 5 · The same OrderModule with a local or remote catalogue
import java.util.Map;import java.util.Optional;
record ProductInfo(int id, String name, int price) {}
interface CatalogueApi { Optional<ProductInfo> findProduct(int id);}
class LocalCatalogue implements CatalogueApi { // inside the same JVM private final Map<Integer, ProductInfo> products = Map.of(1, new ProductInfo(1, "Redmi Note 13 5G", 17999));
public Optional<ProductInfo> findProduct(int id) { System.out.println(" (method call inside the monolith)"); return Optional.ofNullable(products.get(id)); }}
class RemoteCatalogueStub implements CatalogueApi { // pretend it calls another service public Optional<ProductInfo> findProduct(int id) { System.out.println(" (HTTP GET http://catalogue/api/v1/products/" + id + ")"); return Optional.of(new ProductInfo(id, "Redmi Note 13 5G", 17999)); }}
class OrderModule { private final CatalogueApi catalogue;
OrderModule(CatalogueApi catalogue) { this.catalogue = catalogue; }
String quote(int productId, int qty) { return catalogue.findProduct(productId) .map(p -> qty + " x " + p.name() + " = Rs " + p.price() * qty) .orElse("not available"); }}
public class SwapImplementationDemo { public static void main(String[] args) { System.out.println("Modular monolith:"); System.out.println(" " + new OrderModule(new LocalCatalogue()).quote(1, 2)); System.out.println("Same OrderModule, catalogue moved out later:"); System.out.println(" " + new OrderModule(new RemoteCatalogueStub()).quote(1, 2)); }}Modular monolith: (method call inside the monolith) 2 x Redmi Note 13 5G = Rs 35998 Same OrderModule, catalogue moved out later: (HTTP GET http://catalogue/api/v1/products/1) 2 x Redmi Note 13 5G = Rs 35998
What this code does
- Both classes implement
CatalogueApi, soOrderModuleruns unchanged with either. The stub only prints the HTTP call it would make. - A clean module boundary is a ready-made service boundary. If splitting is ever justified, the work is mostly writing a new implementation of the interface.
Rules such as "inactive products cannot be sold" stay inside the catalogue module, in one place.
A bonus of the boundary: because orders depends on an interface, the catalogue could later move into its own service and orders would get a different implementation of the same interface, with no change to its own code.
Predict the output
Predict the order result
The catalogue hides inactive products. What does orders print?
Product 3 is an inactive Old Nokia 3310. What is printed?
Next step
Check your understanding
10 quick questions