The user wants a "modular monolith blueprint" with three specific architectural pillars:
Bounded Contexts: Dividing the application into logical business domains (DDD concept).
Dependency Inversion: Ensuring high-level modules don't depend on low-level modules; both depend on abstractions.
Compile-time Enforcement: Using the type system or build tools to prevent illegal dependencies (e.g., one module accessing another's internals directly).
I need to design a conceptual blueprint (likely using a Java/Kotlin/C# perspective as these languages support this well, but I'll keep it generally applicable with code-like examples, probably leaning towards Java/Spring or .NET as they are common for this). Let's stick to a pseudo-code/Java-style for clarity.
1. High-Level Structure:
A modular monolith is a single deployable unit (one process) but with internal modularization.
Structure:
Core / Kernel / Common (Shared Kernel).
Modules (The Bounded Contexts).
App / Bootstrapper (The composition root).
2. The Bounded Contexts (Modules):
Let's pick a standard e-commerce example: Billing, Inventory, Shipping.
Each module needs:
Api (Interfaces/DTOs exposed to other modules).
Domain (Entities, pure logic).
Application (Use Cases/Services).
Infrastructure (Database implementation, external API clients).
Module B's Infrastructure or Application implements the interface.
The App layer wires them up (Dependency Injection).
4. Compile-Time Enforcement:
This is the tricky part. How do we physically prevent Billing from accessing Inventory's internal classes?
Approach A (Packages): Java packages with module-info (JPMS). This is the strictest standard way.
Approach B (Separate Maven/Gradle modules): Build separate JARs. The build fails if a non-whitelisted dependency is added.
Approach C (ArchUnit): A testing library that checks architecture rules.
I will recommend Separate Build Modules (Maven/Gradle subprojects) + ArchUnit as the most robust practical approach, but acknowledge JPMS as the "native" way. I'll structure the blueprint using a multi-module build system structure because it forces the dependency rules at compilation time (if you don't declare the dependency, you can't compile against it).
Drafting the Blueprint:
Directory Structure:
/app (Main application)
/modules
/billing
/billing-api (Interfaces)
/billing-core (Logic, depends on billing-api)
/inventory
/inventory-api
/inventory-core
/common (Shared Kernel)
Interaction Flow:
Billing needs to check stock.
Billing calls InventoryCheckService (interface in inventory-api).
Inventory implements InventoryCheckServiceImpl (in inventory-core).
Dependency rule: billing-core can depend on inventory-api, but notinventory-core.
Refining the "Compile-time Enforcement":
The user specifically asked for "compile-time enforcement."
If I just use packages, a developer can import a class from another context if they really want to.
If I use separate JARs (Maven modules), the build simply fails if billing-core tries to import inventory-core without the dependency defined in pom.gradle. This is the strongest enforcement.
Key Components of the Design:
The Module Structure (Physical): Multi-module Gradle/Maven project.
The "API" Submodule: Each bounded context is split into api (public contracts) and core/infrastructure (internal implementation).
The Dependency Rule:Core depends on Api. App depends on everything to wire it.
Communication: Synchronous (Interface calls) vs Asynchronous (Events). I should mention both.
Step-by-Step Guide:
Define the Architecture Diagram (Mental):
Top: Monolith Shell (App).
Middle: Bounded Contexts (Billing, Catalog).
Internal: API vs. Implementation.
Detailed Module Design (The "Blueprint"):
Context A: Order
Context B: Inventory
Shared: Kernel (Value objects like Money, ID types).
Enforcement Mechanism:
Use a build tool (Gradle/Maven).
order-core -> depends on -> inventory-api
order-core -> CANNOT depend on -> inventory-core
Code Example:
InventoryApi: Interface CheckStock.
InventoryCore: Class InventoryService implements CheckStock.
OrderCore: Uses CheckStock.
Event-Driven Communication (Loose Coupling):
Define DomainEvent.
Mediator pattern or internal event bus.
Testing Strategy:
ArchUnit (Architecture Tests) to ensure rules aren't broken if the build system allows internal packages. (Actually, with multi-module jars, ArchUnit isn't strictly needed for inter-module checks, but it's good for internal package checks).
Self-Correction during drafting:
I initially thought about using Java's module-info.java. While correct, it's often complex to set up with frameworks like Spring Boot. The "Multi-Project Build" (separate JARs for API vs Core) is more idiomatic in the enterprise Java/.NET world for this specific pattern because it solves the dependency issue strictly without the headaches of the Java Module System. I will focus on the Multi-Project Build strategy.
Final Outline:
Philosophy: Why this structure? (Strict boundaries).
Physical Structure: Directory tree.
The API/Implementation Split: How to isolate contracts.
Dependency Graph: The direction of arrows.
Implementation Details (Pseudo-code/Java): Showing interfaces vs implementations.
Wiring (The Monolith Kernel): How to put it together at runtime.
Enforcement: How the build tool prevents coupling.
Let's generate the response.
Designing a Modular Monolith requires moving beyond "folder organization" to strict physical isolation of code. To achieve compile-time enforcement, we must treat logical modules as physically separate code units (e.g., separate Maven/Gradle modules or C# projects) that are assembled into a single deployable artifact.
Here is a blueprint for a Modular Monolith using Bounded Contexts, Dependency Inversion (DIP), and Java Package/Module enforcement.
1. The High-Level Architecture
The core philosophy is that no module depends on another module's implementation. Modules communicate exclusively via abstract interfaces defined in a shared "Public API" layer or via a central "Kernel".
The Layered View
The Shell (Bootstrap): The executable entry point (e.g., Main). It knows about all modules and wires them together.
The Modules (Bounded Contexts): logically and physically separated code containing domain logic.
The Contracts (SPI - Service Provider Interface): Abstract interfaces defining the capabilities of a module.
2. Project Structure (Physical Separation)
To enforce compilation rules, we split the application into distinct build artifacts. In a Java/Maven setup, this looks like:
This module contains zero business logic. It only contains technical interfaces that allow modules to talk to the infrastructure (like emitting events) and generic value objects.
We split this into API (Contract) and Core (Implementation).
1. billing-api (The Contract)
This module is compiled separately. It contains the interfaces other modules are allowed to call. It must depend only on the Kernel.
java
// billing-api/src/main/java/com/example/billing/BillingService.java
public interface BillingService {
void chargeAccount(UUID orderId, BigDecimal amount);
}
// billing-api/src/main/java/com/example/billing/events/PaymentCompletedEvent.java
public class PaymentCompletedEvent implements DomainEvent {
private final UUID orderId;
// constructor, getters...
}
2. billing-core (The Implementation)
This module implements the logic.
Crucial Rule: Other modules (like Inventory) must depend on billing-api, neverbilling-core.
java
// billing-core/src/main/java/com/example/billing/internal/BillingServiceImpl.java
public class BillingServiceImpl implements BillingService {
private final PaymentGateway gateway;
public BillingServiceImpl(PaymentGateway gateway) {
this.gateway = gateway;
}
@Override
public void chargeAccount(UUID orderId, BigDecimal amount) {
// Business logic here...
gateway.process(amount);
// Publish event
EventPublisher.publish(new PaymentCompletedEvent(orderId));
}
}
C. Dependency Inversion & Integration
The Inventory Module needs to know when a payment happens, but it shouldn't know who did the payment (Billing).
1. The Inventory Listener (in inventory-core)
Inventory listens for events defined in billing-api (or generic domain events).
java
// inventory-core/src/main/java/com/example/inventory/internal/PaymentListener.java
public class PaymentListener {
private final InventoryManager inventoryManager;
public void onPaymentCompleted(PaymentCompletedEvent event) {
// Logic to pack items
inventoryManager.reserveStock(event.getOrderId());
}
}
2. Compile-Time Enforcement (The Build File)
This is where the architecture is enforced.
inventory-core is allowed to depend on billing-api (to see the event class).
inventory-core is FORBIDDEN from depending on billing-core.
Maven Example (pom.xml):
xml
<!-- In inventory-core/pom.xml -->
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>billing-api</artifactId>
<version>1.0</version>
</dependency>
<!-- This dependency is NOT allowed:
<dependency>
<groupId>com.example</groupId>
<artifactId>billing-core</artifactId>
</dependency>
-->
</dependencies>
If a developer in inventory-core tries to import BillingServiceImpl, the compiler will fail because it doesn't have that class on its classpath.
4. The Composition Root (App Shell)
Since billing-core and inventory-core do not know about each other, how do they run in the same app?
The app-shell module is the only module that depends on everything (all -api and -core modules). It uses Dependency Injection (e.g., Spring Boot, Guice) to wire the interfaces to the implementations.
java
// app-shell/src/main/java/com/example/Application.java
public class Application {
public static void main(String[] args) {
// 1. Instantiate Core Implementations
BillingService billing = new BillingServiceImpl(...);
InventoryManager inventory = new InventoryManagerImpl(...);
// 2. Wire Dependencies (Manual DI or Framework)
// When billing emits an event, inventory handles it.
EventBus.subscribe(PaymentCompletedEvent.class, inventory::onPaymentReserved);
// 3. Start App
billing.chargeAccount(...);
}
}
5. Summary of Enforcement Rules
To guarantee this blueprint works:
Strict API/Implementation Split: Every module is two projects: module-api and module-core.
Upstream/Downstream Contracts:module-A-core implements module-B-api interfaces, or listens to module-B-api events. module-A-core never imports module-B-core.
Package Sealing: Ensure module-core classes are package-private or internal (in C#) where possible, exposing only the classes in module-api.
Architecture Tests (Optional but Recommended): Use a tool like ArchUnit to programmatically assert that no class in inventory depends on billing implementation packages.
java
// ArchUnit Test example
@ArchTest
static final ArchRule no_billing_in_inventory =
noClasses()
.that().resideInAPackage("..inventory..")
.should().dependOnClassesThat()
.resideInAPackage("..billing.internal..");
Why this works
Decoupling: You can delete the billing folder entirely and the inventory code will still compile (it just won't receive events at runtime until you wire a new module in).
Microservices Readiness: If you need to split, you move billing-api and billing-core to their own repo. You replace the local method calls in app-shell with HTTP client calls. No logic in inventory-core needs to change because it only relied on the API interface.