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

Domain-Driven Design (DDD)

Model the software around the business: shared language, bounded contexts, aggregates and events.

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

01Quick Summary

Domain-Driven Design (DDD) is a way of building software where the code is shaped around the business it serves. You work with the people who know the business (the domain experts) and put their words and rules straight into the code.

  • The team and the experts share one vocabulary, the ubiquitous language, and use it in talks, documents and code.
  • A big system is cut into bounded contexts. Inside one, every word has exactly one meaning.
  • Inside a context, rules are kept together in aggregates, small groups of objects that always stay consistent.
  • It pays off when the business rules are complex. For a simple form-and-table app it is more work than it is worth.

02Concept: What is it?

Most projects fail to deliver value not because the code is slow, but because developers and the business do not understand each other. The business says "a policy lapses". The code says status = 3. Every question needs a translator, and mistakes hide in the translation.

DDD attacks this problem. You sit with experts, learn their words, and then model the domain in code with the same words. Two groups of ideas make this work. The strategic ideas decide how to cut a big system into parts. The tactical ideas decide how to build the inside of one part.

Strategic design: the big picture

  • Ubiquitous language: one shared set of terms, used by everyone, in conversation and in the code.
  • Bounded context: a boundary inside which a model and its words are consistent. The word "Customer" in Sales is not the same thing as "Customer" in Support, and that is fine.
  • Subdomains: the business area split by value. The core subdomain is what makes you special, so invest the most here. Supporting parts are needed but not special. Generic parts (like login or payments) you can buy or reuse.
  • Context map: how contexts relate and talk to each other, for example through an anti-corruption layer or a shared kernel.

Tactical design: building blocks inside a context

  • Entity: has an identity that lasts over time (this particular order, number 1042), even when its data changes.
  • Value object: has no identity and is compared by its value. A money amount of 5 dollars or an address is the same as any other with the same values, and it is never changed in place.
  • Aggregate: a cluster of entities and value objects treated as one unit, with one entry point called the aggregate root. The root guards the rules (invariants) of the whole cluster.
  • Repository: a collection-like object used to load and save aggregates.
  • Domain event: a fact that happened in the business, such as OrderPlaced.
  • Domain service: a rule that does not naturally belong to a single entity.
Three bounded contexts and how they talk
Sales context
🧑Customercredit limit
🧾Orderaggregate root
→↓OrderPlaced event
Shipping context
📍Recipientdelivery notes
📦Shipmentaggregate root
→↓ShipmentSent event
Support context
🎧Customerpast tickets
🎫Ticketaggregate root
Sales Shipping Support Events between contexts
Each context has its own model. Contexts exchange small, agreed messages instead of sharing one big model.
🧠DDD is about people first, patterns second
Most of the value comes from the conversation with the experts and the shared language. The building blocks only help you write that understanding down in code.

03Real-Life Example

🍵One Hospital, Many Meanings of "Patient"
In a hospital, the reception desk sees a patient as a name, an insurance card and an appointment. The pharmacy sees a patient as a list of allergies and current medicines. The billing office sees a patient as an account with unpaid invoices. All three use the word "patient", and all three are right. Forcing one giant patient form on every department would please nobody. So each department keeps its own view, and they pass short, clear messages: "prescription issued", "visit finished".
Hospital
Domain-Driven Design
A department with its own meaning of “patient”
A bounded context
The words doctors and nurses really use
The ubiquitous language
A patient file with one owner who keeps it valid
An aggregate with its root
Patient number 5521, the same person for life
An entity (it has an identity)
A blood pressure reading of 120/80
A value object (no identity, just a value)
The notice “visit finished” sent to billing
A domain event
A clerk who translates old paper forms for a new system
An anti-corruption layer
How a team applies DDD
🗣️Talkwith experts
→↓
📖Nameshared language
→↓
🗺️Drawbounded contexts
→↓
💻Codeaggregates, events
It is a loop of talking, naming, drawing boundaries and coding. The language is refined each time.

04Why Do We Need It?

🗣️Less lost in translation
Developers and the business use the same words, so requirements arrive with fewer misunderstandings.
🧱Smaller, clearer models
Each context holds only what it needs. Nobody has to understand one giant model of everything.
🛡️Rules kept in one place
An aggregate guards its own rules, so no caller can break them by accident.
👥Teams that fit the business
Each team owns a context and can change it without a meeting with everyone else.
🚪Natural service boundaries
Bounded contexts are good first guesses for where to cut a monolith into microservices.
🎯Effort where it counts
Splitting core from generic parts lets you spend your best people on what makes the business different.
Build the software in the language of the business, cut it where the language changes, and guard each rule in one place.

05Where Do We Use It?

🏦Banking and insurance
Policies, claims and accounts have long lists of rules that experts know well.
🚚Logistics
Orders, shipments, routes and warehouses each mean different things to different teams.
🏥Healthcare
Patient, visit, prescription and billing views differ a lot, and rules matter for safety.
🛒E-commerce
Catalogue, cart, pricing, orders and support are natural separate contexts.
🧩Breaking up a monolith
Use contexts to find seams before you extract services (see the Strangler Fig pattern).
🔌Joining old systems
A context map and an anti-corruption layer keep old models from leaking into new ones.
📝Note
DDD helps most where the domain is hard. A simple admin screen that just creates, reads, updates and deletes rows does not need aggregates and a ubiquitous language.

06Types / Parts / How It Works

The building blocks and what each one is for

BlockIdentity?What it isExample
EntityYes, lasts over timeAn object defined by who it is, not by its dataCustomer 77, Order 1042
Value objectNo, compared by valueA small, unchangeable group of valuesMoney(5, USD), Address, DateRange
AggregateRoot has an identityA cluster that is always consistent as a wholeOrder with its order lines
Repositoryn/aLoads and saves whole aggregatesOrderRepository.find(id)
Domain eventn/aA fact from the past, named in the language of the businessOrderPlaced, PaymentReceived
Domain servicen/aA rule that spans several objectsTransferMoney(from, to)

Rules of thumb for aggregates

  1. Make them small. Include only what must be consistent together right now.
  2. Change one aggregate per transaction. Updates across aggregates happen later, through events.
  3. Reach other aggregates by id, not by holding a direct object reference.
  4. Go through the root. Outside code never edits an order line directly. It asks the order.

How two contexts can relate

RelationshipMeaningWhen to use it
Customer-supplierOne team supplies, the other consumes, and they agree on needsTwo teams who can plan together
Shared kernelTwo contexts share a small piece of model and codeVery close teams, kept deliberately tiny
ConformistThe downstream team simply accepts the upstream modelYou have no power to change the other side
Anti-corruption layerA translator protects your model from a foreign oneDealing with a legacy or third-party system
Separate waysNo integration at allThe link is not worth the cost
VisualizerSame word, different meaning, and an aggregate that guards a ruleSwitch contexts to see the words change. Then try placing capabilities in contexts, and add items to an order with the rule inside or scattered.
What do you want to explore?
Bounded context
Modelling style
The word "Customer"
Customer
namecredit limitdiscount tier
The word "Product"
Product
pricestockpromotion
The word "Order"
Order
itemstotalstatus
The word "Address"
Billing address
streetcitytax id
Fields in this view
12
across the 4 words
If one model for all
28
every field in one place
Contexts
3
each with its own meaning
In Sales, the customer and only 12 fields matter. Each team keeps a small model it fully understands, and a word means one thing here.

A teaching example with made-up fields and numbers. Real models are discussed with domain experts and are never this small.

07How to Use It / Steps / Implementation

Starting with DDD

  1. 1
    Talk to the experts
    Run short sessions where they explain how the work really happens. Write down the words they use.
  2. 2
    Build the language
    Keep a small glossary. If two people mean different things by one word, you have found a boundary.
  3. 3
    Find the subdomains
    Mark which parts are core, supporting and generic. Spend design effort on the core.
  4. 4
    Draw bounded contexts
    Group things that change for the same reasons and use the same words. Name each context.
  5. 5
    Map the relationships
    Decide how contexts talk: events, an API, a translator. Write it on a context map.
  6. 6
    Model inside one context
    Pick the main aggregates, their rules and the events they raise. Keep aggregates small.
  7. 7
    Mirror it in code
    Use the same names for classes, methods and modules. If the experts cannot read the names, rename them.
💡Try it on one context first
You do not need to redesign everything. Pick the part of the system with the trickiest rules, model it carefully, and leave simple parts as plain CRUD.
⚠️Careful with the word "model"
A DDD model is not a database diagram. It describes behaviour (what the business does and which rules apply), and tables are only one way to store it.

08Key Terms to Know

TermMeaning in easy words
DomainThe business area your software is about
Domain expertA person who knows the business deeply (for example a claims manager)
Ubiquitous languageOne shared vocabulary used in talks, documents and code
Bounded contextA boundary inside which a model and its words keep one clear meaning
SubdomainA part of the business: core, supporting or generic
EntityAn object with an identity that lasts while its data changes
Value objectAn object with no identity, compared by its values and not changed in place
AggregateA cluster of objects that must always be consistent together
Aggregate rootThe single entry point of an aggregate, which enforces its rules
Domain eventA fact that happened in the business, named in the past tense
Context mapA picture of how bounded contexts relate and exchange data

09Pros, Cons and Trade-offs

✅ Pros
  • Code that the business can read and check
  • Smaller models that are easier to change
  • Rules protected inside aggregates
  • Clear boundaries that suit team ownership
  • A good guide for cutting a monolith into services
⚠️ Cons
  • Needs time with domain experts
  • Heavy for simple data-entry apps
  • Takes practice to find good boundaries
  • Easy to over-engineer with too many layers and patterns
  • Boundaries drawn wrongly are costly to fix later

Trade-offs

ChoiceWe gainWe lose
Many small contextsIndependent teams and modelsMore integration work and duplicated data
One big contextSimple, one model to learnWords become vague and the model turns into a ball of mud
Small aggregatesFewer lock conflicts, easy to scaleRules across aggregates are eventually consistent
Large aggregatesStrong consistency in one transactionContention and slow saves under load
Full DDD toolkitRich, protected modelMore code and concepts for a simple problem
Plain CRUDFast to buildRules scatter across the app as it grows

10Common Problems and Mistakes

Common mistakes

  1. Skipping the experts. Developers invent the language alone, and it never matches the business.
  2. One model for everything. A single "Customer" class with 80 fields that every team edits.
  3. Huge aggregates. Loading the whole customer history to change one address.
  4. Anemic model. Objects that only hold data, with all the rules in service classes elsewhere.
  5. Technical names. Classes called Manager, Helper or Processor instead of business words.
  6. Using the tactical patterns without the strategic ones. Lots of repositories and factories, but no clear contexts.
  7. Reaching across aggregates. Direct object links between aggregates make boundaries blur.

Things to watch

🌫️Language drift
Over time the code and the business words part ways. Review the glossary regularly.
🔗Leaky contexts
A foreign model slips in through a shared database or table. Use a translator at the border.
⏳Eventual consistency
Changes across aggregates take a moment to spread. Users and tests must expect it.
🧰Pattern overload
Adding every block because the book lists it. Use only what the problem needs.

11Real-World Examples

🛍️Online shops
Catalogue, pricing, cart, checkout and delivery are often split into contexts, each with its own team.
🏦Insurers and banks
Policy, claim and billing models differ, so each is kept as its own context.
🚕Ride and delivery apps
Matching, pricing, payments and driver onboarding use different words and change at different speeds.
🏥Health systems
Scheduling, clinical records and billing are separated, with careful messages between them.
🎬Streaming services
Catalogue, playback, recommendations and subscriptions are separate areas with their own models.
🧳Booking platforms
Search, availability, reservation and payment each protect their own rules.
📝Note
These are typical ways companies in these fields are organised. The details of any one company differ, and many teams use DDD ideas without using the name.
Mini case: a monolith cut along contexts
🏗️One big appone shared model
→↓find contexts
🧾Sales
📦Shipping
🎧Support
→↓events
🧩Services or modulesone per context
Contexts are found first. Only then are they moved out into their own services, one at a time.

12Related Topics to Read Next

Microservices→

Bounded contexts are the usual starting point for service boundaries.

Hexagonal Architecture→

A good way to build the inside of one context so the domain stays clean.

Event-Driven Architecture→

Contexts often talk through domain events.

Event Sourcing→

Stores an aggregate as its list of domain events.

CQRS→

A context can use separate models for writes and reads.

Anti-Corruption Layer→

Protects your model from an old or foreign one.

Clean Architecture and Modular Monolith→

Ways to keep contexts as clean modules before splitting into services.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: design the code around the business, with its words and rules.
  • ✔Language: one shared vocabulary for experts and developers (ubiquitous language).
  • ✔Strategic: split into bounded contexts, and find core, supporting and generic subdomains.
  • ✔Tactical: entities, value objects, aggregates, repositories, domain events.
  • ✔Aggregate: small, one per transaction, reached through its root, linked to others by id.
  • ✔Between contexts: events or APIs, with an anti-corruption layer if the other model is foreign.
  • ✔Use when: the domain is complex. Skip it for simple CRUD.
  • ✔One line: “Speak the language of the business, and draw a line wherever the words change.”
← Previous
Event Sourcing
Next →
Layered (N-Tier) Architecture