SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Clean Architecture and Modular Monolith

Keep rules independent of frameworks, and split one deployable app into clear modules before you split it into services.

⏱ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

These are two ideas that share one goal: keep the parts of your code separate, so a change in one place does not break ten others.

  • Clean architecture puts your business rules in the centre. Everything else (database, web framework, screens) is outside, and depends on the rules, never the other way round.
  • A modular monolith is one app that you deploy as one unit, but inside it is split into modules with clear borders. Each module owns its own data.
  • Together they give you most of the order of microservices, without the cost of a network between every part.

02Concept: What is it?

Clean architecture

Picture rings, like an onion. In the middle are your entities (the core business objects, such as an Order) and the use cases (what the app does: place an order, cancel an order). Around them are adapters that translate to the outside world: web controllers, database code, message handlers. On the outside are the tools themselves: the framework, the database product, the UI.

The one rule that holds it together is the dependency rule: source code can only point inward. The business rules never import the database or the web framework. When the rules need to save something, they call a small interface that they own (a "port"), and the database code on the outside implements it. This trick is called dependency inversion.

The rings, and which way dependencies point
4Frameworks and driversweb framework, database, UI, message broker
3Interface adapterscontrollers, repositories, presenters
2Use casesplace order, cancel order
1EntitiesOrder, Customer, Money: the core rules
Arrows point inward. The centre knows nothing about the outside.

Modular monolith

A monolith does not have to be a mess. In a modular monolith you divide the one app into modules by business area (Orders, Billing, Shipping). Each module has a small public interface and keeps its internals and its tables private. Other modules may only use the interface. Calls between modules are plain in-process calls, so they are fast and can share one transaction when really needed.

🧠Same goal as microservices, lower price
Microservices put the border between parts on the network. A modular monolith puts the same border in the code. You keep the clean borders, and skip the network failures, the deployment pipelines and the distributed data problems.

03Real-Life Example

🍵A Hospital and Its Departments
A hospital is one building (one deployable unit), but it has departments: Emergency, Pharmacy, Billing. Each department keeps its own records in its own locked cabinet. If Billing wants to know a patient's medicines, it does not break into the Pharmacy cabinet. It sends a request to the Pharmacy desk, which gives back only what is allowed. Because of this, Pharmacy can reorganise its cabinet any time, and Billing never notices. Meanwhile the whole hospital sits on one site, so a nurse can walk between departments in a minute.
Hospital
Modular monolith
The building
One deployable application
A department
A module (Orders, Billing, Shipping)
The locked cabinet of records
The module's private tables
The request desk
The module's public interface
Breaking into another cabinet
Reading another module's tables (the mistake)
Walking between departments
A cheap in-process call
Moving a department to its own building
Splitting a module into a microservice later
Modules with private data, one deployment
One application
🧾Order
🗃️orders tablesprivate
💳Billing
🗃️billing tablesprivate
🚚Shipping
🗃️shipping tablesprivate
↔only through public interfaces

04Why Do We Need It?

🧪Easy to test
The business rules run without a database or a web server, so tests are fast and simple.
🔄Swappable tools
Change the database or the framework by changing one adapter, not the whole app.
🧩Contained changes
A change inside one module does not ripple through the others.
👥Team ownership
Different teams can own different modules and work in parallel.
🪜A path to microservices
A well-bounded module can later be moved into its own service with little rewriting.
💸Low operating cost
One deployment, one database, no network between parts. Much simpler to run than many services.
Draw the borders in your code first. You can move a border onto the network later, if you ever need to.

05Where Do We Use It?

🏢Business software
Systems with rich rules (banking, insurance, logistics) benefit most from rules kept apart from tools.
🚀Growing start-ups
A modular monolith lets a young team move fast, and keeps a clean exit towards services.
🧓Long-lived apps
Frameworks and databases change over the years. Keeping rules independent keeps the app alive.
↩️Moving back from microservices
Some teams merge too many tiny services into a modular monolith to cut cost and complexity.
🧱Domain-driven designs
Modules often match bounded contexts from Domain-Driven Design.
🚫Tiny CRUD apps
A simple form-over-database app does not need rings of abstraction. Keep it plain.

06Types / Parts / How It Works

Clean architecture, side by side with its cousins

StyleMain pictureCore idea
Layered (N-tier)A stack: UI, business, dataEach layer talks to the one below. The business layer often ends up depending on the data layer.
Hexagonal (ports and adapters)A hexagon with plugsThe core defines ports. Adapters plug in from outside.
OnionConcentric ringsDomain at the centre, dependencies point inward.
Clean architectureFour ringsThe same dependency rule, with named rings (entities, use cases, adapters, frameworks).

These styles are close relatives. They all invert the dependency on the database, so the business rules sit in the middle.

What makes a module a real module

RuleMeaningWhy it matters
Public interfaceOther modules call a small, stable set of functions.Everything else can change without notice.
Private dataOnly the module's own code touches its tables.Prevents hidden coupling through the database.
No cyclic dependenciesOrder calls Billing, but Billing does not call Order back.Cycles make modules impossible to split later.
Events for side effectsA module announces 'order placed' and others react in-process.Keeps modules from knowing each other.
Enforced by tests or toolsA build check fails on a forbidden import.Rules written only in a document get broken.
The same rules, three ways of drawing the border
🧱Tangled monolithno borders
→↓add borders
🧩Modular monolithborders in code
→↓only if needed
🌐Microservicesborders on the network
Hard to change Good default More cost and power
You can move the border outward as the need grows.
VisualizerWhere do the borders hold?Switch Order and Shipping between reading Billing's tables and using its public interface, then press the schema change. Then try the database swap view to see how many boxes change.
What do you want to explore?
How do Order and Shipping use Billing?
One deployable app. Arrows show who depends on whom. Red = reaches into another module's tables. Green = uses a public interface.
Order
owns its own tables
Billing
owns billing tables
Shipping
owns its own tables
  • Order → Billing (reads its tables directly)
  • Shipping → Order (through the public interface)
  • Shipping → Billing (reads its tables directly)
🗄️ One shared database. Billing's tables are open to everyone.
Dependencies
3
between modules
Hidden couplings
2
reads of another module's tables
Break on schema change
?
press the change button
Order and Shipping read Billing's tables directly. It works today, but Billing's table design is now a public contract that nobody agreed to. Press 'Billing changes its schema' to see the cost.

A teaching sketch with a fixed example app. The counts (3 dependencies, 7 boxes against 1) are illustrative, not measurements. Real systems have many more modules, and boundaries are checked by tests or tools.

07How to Use It / Steps / Implementation

Building it step by step

  1. 1
    Split by business area
    Find the natural areas (Orders, Billing, Shipping). Domain-Driven Design's bounded contexts are a good guide.
  2. 2
    Give each module a small public interface
    A few functions or a facade. Keep everything else private by default.
  3. 3
    Give each module its own tables
    No joins across module tables. If you need data from another module, ask its interface.
  4. 4
    Put business rules in the middle
    Rules do not import the database or the framework. They use interfaces that they own.
  5. 5
    Write adapters for the outside
    A repository class that implements the port, a controller that calls a use case.
  6. 6
    Use in-process events for side effects
    When an order is placed, publish an event. Billing and Shipping subscribe, and Order does not know them.
  7. 7
    Enforce the borders
    Add an architecture test or a build rule that fails when a module imports another module's internals.
💡Do not over-build
Add rings and interfaces where change is likely or where the rules are rich. A simple screen that reads and writes one table does not need a use case class, a port and three mappers.
⚠️The shared database trap
A single database makes it very easy to "just join across modules". Do it once and the border is gone. Consider a separate schema per module, and review the SQL.

08Key Terms to Know

TermMeaning in easy words
Dependency ruleSource code dependencies may only point inward, towards the business rules
EntityA core business object with its rules, such as Order or Money
Use caseOne thing the app does, such as 'place an order'
PortAn interface owned by the business rules that the outside must implement
AdapterCode that connects a port to a real tool, such as a database
Dependency inversionHigh-level rules depend on an interface, not on low-level details
ModuleA part of the app with a public interface and private internals
Public interfaceThe small set of calls other modules are allowed to use
Bounded contextA business area with its own words and rules (from Domain-Driven Design)
CouplingHow much one part needs to know about another
Architecture testAn automatic check that fails the build if a forbidden dependency appears

09Pros, Cons and Trade-offs

✅ Pros
  • Business rules are easy to test
  • Tools can be swapped with little change
  • Clear ownership and smaller blast radius for changes
  • Modular monolith needs only one deployment
  • A realistic path to splitting out services later
⚠️ Cons
  • More files, interfaces and mapping code
  • Takes discipline: borders must be enforced
  • Overkill for small, simple apps
  • A single database can quietly break module borders
  • Wrong module borders are costly to move

Trade-offs

ChoiceWe gainWe lose
Clean architecture ringsTestable rules, swappable toolsExtra indirection and boilerplate
Direct database calls in rulesLess code at the startPainful to test and to change tools
Modular monolithClean borders with simple operationsWhole app deploys together and scales together
MicroservicesIndependent deploys and scalingNetwork failures, data splitting, more operations
Shared tables across modulesEasy joins and reportsHidden coupling, so modules cannot change alone
Strict module rulesFewer surprises laterSlower feature work at first

10Common Problems and Mistakes

Common mistakes

  1. Modules in name only. Folders exist, but every module reads every other module's tables. It is still a tangled monolith.
  2. Abstracting everything. A port for every tiny thing adds files and no value.
  3. Leaking framework types inward. Using the web framework's request object or database entity inside business rules breaks the dependency rule.
  4. A shared "utils" module. It becomes a dumping ground that every module depends on, creating hidden coupling.
  5. Circular dependencies. Order needs Billing, and Billing needs Order. These cannot be split later.
  6. Wrong borders. Splitting by technical layer (all controllers together) instead of business area.
  7. Splitting into services too early. Moving to microservices before the borders are right makes every mistake a network problem.

Things to watch

🕸️Dependency drift
Imports creep in over time. Check them automatically on every build.
🗃️Shared database
One schema invites cross-module joins. Review queries, or use a schema per module.
🔁Duplicated models
Each module may need its own small view of a Customer. That is fine and often better than one giant shared class.
⚖️Transactions across modules
In one process it is easy. Moving a module out later turns it into a distributed transaction.

11Real-World Examples

🏦Banking cores
Long-lived systems with complex rules often protect those rules with ports and adapters.
🛒E-commerce platforms
Orders, payments and inventory as modules in one app, split into services only where load demands.
🧰Framework support
Several ecosystems offer module tools and architecture tests that check allowed dependencies (for example ArchUnit for Java).
↩️Teams moving back
Some teams have publicly described merging too many small services back into a modular monolith.
🪜Strangler migrations
A well-bounded module is the easiest thing to carve out with the Strangler Fig approach.
🧪Test-driven teams
Teams who value fast tests like rules that run with no database.
📝Note
The right amount of structure depends on the size of the team and the app. Treat these as options, not rules.
Mini case: swapping the database
🧠Business rulesunchanged
→↓uses port
🔌Repository portan interface
→↓implemented by
🗄️New adapterthe only change
With a port, the change stays in one place.

12Related Topics to Read Next

Hexagonal Architecture→

Ports and adapters: the closest cousin of clean architecture.

Domain-Driven Design (DDD)→

Bounded contexts are a good guide for module borders.

Monolithic Architecture→

The starting point that a modular monolith improves.

Microservices→

Where a module can go if it needs its own deployment.

Layered (N-Tier) Architecture→

The older layered style that clean architecture refines.

Strangler Fig→

A safe way to carve a module out of a monolith.

Database per Service→

The data rule that a module's private tables prepare you for.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Clean architecture: business rules in the centre, tools outside.
  • ✔Dependency rule: dependencies point inward only.
  • ✔Trick: rules own a port (interface). The adapter on the outside implements it.
  • ✔Modular monolith: one deployable app, split into modules with private data.
  • ✔Module: small public interface, private internals, private tables.
  • ✔Trap: cross-module joins in a shared database.
  • ✔Enforce: architecture tests on every build.
  • ✔One line: “Draw the borders in code first, and move them onto the network only if you must.”
← Previous
Kubernetes Basics
Next →
Multi-Tenancy