The user wants a modernization plan for an existing system (likely a "Big Ball of Mud" monolith) to transition it into a "Modular Monolith."
Key elements requested:
- Package Boundaries: How to separate code physically/namespace-wise.
- Shared Kernel Rules: What goes in the core shared logic and how to prevent abuse.
- Dependency Linting: Tooling to enforce these architectural rules automatically.
Target Audience: Architects, Tech Leads, Senior Developers.
Goal: A step-by-step, actionable strategy, not just high-level theory.
Structure of the Plan:
- Phase 0: Assessment & Culture: Acknowledge that this is as much a people/process change as a code change.
- Phase 1: The Structural Skeleton (The "Container"): Setting up the Shared Kernel and the Module Interface.
- Phase 2: Defining Modules (The "Bounded Contexts"): Identifying where to cut.
- Phase 3: Hardening Boundaries (The "Enforcement"): Using tooling (ArchUnit, Checkstyle, etc.).
- Phase 4: Decoupling Logic (The Refactoring): Moving code.
- Phase 5: Infrastructure & Deployment: How this changes the build/runtime.
Detailed Breakdown & Brainstorming:
Drafting the Content - Specific Technologies:
I should keep it somewhat language-agnostic but provide specific tool examples because "dependency linting" is very tool-dependent. I'll assume a Java/Spring context is the most likely candidate for "Modular Monolith" terminology, but I will mention others (Node/TS, .NET) where appropriate. I will focus heavily on ArchUnit principles as they are universally applicable conceptually.
Refining the "Shared Kernel" Rules:
- DDD (Domain-Driven Design) alignment.
- Must not depend on modules.
- Must be stable.
Refining the "Dependency Linting":
- Directionality (Inward/Outward).
- Visibility (Public vs Package-private).
- Coupling analysis (Incoming vs Outgoing complexity).
Self-Correction/Review during drafting:
- Initial thought: Just list folders. Correction: No, architecture is about constraints. I need to explain why specific folder structures matter (encapsulation).
- Initial thought: Suggest microservices. Correction: The prompt specifically asks for a "Modular Monolith." I need to emphasize keeping it one deployment initially.
Final Outline:
- Executive Summary: The goal (Modularity within a Monolith).
- Phase 1: Architecture Setup (Package Structure & Shared Kernel).
- Phase 2: The Enforcement Layer (Dependency Linting).
- Phase 3: Migration Strategy (The Strangler Fig pattern applied to modules).
- Phase 4: Operational Excellence (Testing & CI/CD).
- Tech Stack Examples (Java, JS, .NET).
Let's write it out with a professional, architectural tone. Use diagrams (ASCII) to visualize package structures. Emphasize the "Why" (Circular dependency elimination).
Key Concept to highlight: Unidirectional Dependency Rule.
Key Concept to highlight: API/Public vs Internal/Private.
(Self-Correction on Shared Kernel): Be careful not to make the Shared Kernel the new "Util" package. Define strict rules: "Value Objects," "Event Bus Interface," "Auth Context."
(Dependency Linting details): Mention that linting should fail the build.
Let's assemble.
- Step 1: Layout.
modules/{module_name}.
- Step 2: Shared Kernel.
kernel/.
- Step 3: Linting. ArchUnit/NDepend.
- Step 4: The Process. Pick a domain -> Move -> Refactor -> Lock.
Okay, ready to generate the response.
This modernization plan outlines the transition from a "Big Ball of Mud" (or a tightly coupled layered architecture) to a Modular Monolith.
The goal is to achieve clear separation of concerns at the code level, enforce architectural boundaries via build pipelines, and prepare the system for potential future microservices extraction—all while maintaining the operational simplicity of a single deployment unit.
1. The Strategic Goal: Modularity First
We are not breaking the application into separate repositories or deployable artifacts yet. Instead, we enforce logical boundaries within a single physical codebase.
Core Principles:
- Strict Directionality: Dependencies flow downwards (UI → Application → Domain). Horizontal dependencies between modules are forbidden.
- Explicit Interfaces: Modules communicate via public APIs (Application Services) and DTOs, not by accessing internal domain entities.
- Shared Kernel Minimalism: Only cross-cutting concerns and generic domain primitives live in the shared kernel.
2. Phase 1: Directory Structure & Package Boundaries
We will move away from "technical layering" (e.g., com.company.controllers, com.company.services) and adopt Feature-based Modularization.
The Target Layout
The root level of the source code should represent the Business Domains, not technical roles.
src/main/java/com/company/
├── shared/ # THE SHARED KERNEL
│ ├── domain/ # (Value Objects: Money, Email, Ids)
│ ├── events/ # (Integration Event Interfaces)
│ └── exceptions/ # (Generic Framework Exceptions)
│
├── modules/ # LOGICAL MODULES
│ ├── billing/
│ │ ├── api/ # Public Interface (DTOs, Service Interfaces)
│ │ ├── application/ # Use Cases / Orchestration
│ │ ├── domain/ # Entities, Aggregates, Domain Logic
│ │ └── infrastructure/ # DB Repositories, External API Clients
│ │
│ ├── inventory/
│ │ ├── api/
│ │ ├── domain/
│ │ └── ...
│ │
│ └── user-management/
│ └── ...
│
└── bootstrap/ # Application Entry Point
├── config/
└── Application.java
The Rules
- Encapsulation: Classes in
domain must be package-private (default access modifier) where possible. Only classes in api should be public.
- The Gatekeeper: The
application layer implements the interfaces defined in api and orchestrates the domain.
3. Phase 2: Defining the Shared Kernel Rules
The Shared Kernel is the most dangerous part of the architecture. If it becomes a dumping ground, you recreate the monolith.
Allowed in Shared Kernel:
- Generic Value Objects:
Money, DateRange, EmailAddress, UUIDGenerator.
- Technical Cross-Cutting: Logging interfaces, Metrics abstractions.
- Integration Events: Simple POJOs used for event-driven communication between modules (must contain only IDs, no entities).
Forbidden in Shared Kernel:
- Business Logic: No services calculating taxes or inventory.
- Module Specifics: No "User" entity in the shared kernel (unless it is a bare-minimum
AuthenticatedUser DTO).
4. Phase 3: Dependency Linting (Enforcement)
Architecture is useless without enforcement. We cannot rely solely on code reviews. We will introduce automated tools to fail the build if boundaries are violated.
Tool A: ArchUnit (Java/JVM Example)
ArchUnit allows us to write tests for architecture rules.
// ArchitectureTest.java
@AnalyzeClasses(packages = "com.company")
public class ArchitectureTest {
// 1. Define the layers
static final ArchRule LAYERED_ARCHITECTURE = layeredArchitecture()
.consideringAllPackages()
.layer("API").definedBy("..api..")
.layer("Application").definedBy("..application..")
.layer("Domain").definedBy("..domain..")
.layer("Infrastructure").definedBy("..infrastructure..")
// 2. Define constraints
.whereLayer("API").mayNotBeAccessedByAnyLayer()
.whereLayer("Domain").mayOnlyBeAccessedByLayers("Application", "Infrastructure")
.whereLayer("Infrastructure").mayOnlyAccessLayers("Application", "Domain");
// 3. Enforce Module Isolation
@ArchTest
static final ArchRule NO_CROSS_MODULE_TALK =
noClasses()
.that().resideInAPackage("..modules.billing..")
.should().accessClassesThat()
.resideInAPackage("..modules.inventory..")
.because("Modules must communicate only via Public API or Events");
}
Tool B: Dependency Analyzer (CI/CD)
Use a tool like JDepend, SonarQube, or language-specific lock-files to detect cycles.
- Python: Use
import-linter.
- C#: Use
NsDepCop or NDepend.
- Node/TS: Use
eslint-plugin-import with import/no-internal-modules.
The "Ban Rule":
Configure your linter to throw an error if module.billing.domain imports module.inventory.*.
5. Phase 4: The Migration Roadmap
Do not try to refactor everything at once. Use the "Strangler Fig" pattern.
Step 1: Identify a Bounded Context
Pick a distinct domain (e.g., Notifications or Reporting).
Step 2: Carve out the Module
- Create the directory structure
modules/notification/{api,domain,infrastructure}.
- Move classes related to this domain into the new package.
- Refactor Imports: As you move files, the compiler will scream about broken imports. Fix these by:
- Moving shared logic to
shared/.
- Creating an Interface in the
api/ package if other modules need this functionality.
Step 3: Decouple Dependencies
If the new module (e.g., Billing) depends on an older part of the codebase (e.g., User Management):
- Define a
UserDto interface in Billing's api/ package.
- Create an Adapter in
User Management that implements UserDto and fetches the data.
- Use Dependency Injection to pass the implementation to Billing.
Step 4: The "Event" Switch
If Module A needs to trigger logic in Module B, do not call Module B directly.
- Module A publishes
BillingCompletedEvent.
- Module B listens for this event.
- This breaks the direct compile-time dependency.
6. Governance Checklist
To ensure the plan is followed, implement these checks:
| Area | Check | Enforcement |
|---|
| Package | Does every module follow the api/domain/infra structure? | CI Build Failure (Script check) |
| Shared | Is the Shared Kernel free of business logic? | Manual Code Review + ArchUnit |
| Coupling | Are there circular dependencies between modules? | ArchUnit / SonarQube |
| Visibility | Are domain entities public? | Linting Rule (Mandate package-private) |
Summary
This plan transforms the system into a Modular Monolith.
- Structure: Group by Feature, not Layer.
- Shared Kernel: Keep it tiny and generic.
- Communication: Use DTOs and Events, never direct Entity access.
- Enforcement: ArchUnit/Linting in the CI pipeline prevents architectural decay.