← Back to microservices patterns map
Lesson 2 · Decomposition Patterns

Decompose by Subdomain (DDD)

Use Domain-Driven Design bounded contexts to create services with their own language and model.

Intermediate40 min

What you will be able to do

  • Explain domain, subdomain, model, bounded context and ubiquitous language in plain words
  • Show, with a real example, why one shared model for the whole company causes wrong results
  • Find bounded contexts with a five-step method: listen for where a word changes meaning
  • Model the same real-world thing differently in each context, and translate at the boundary
  • Sort subdomains into core, supporting and generic - and decide where to build and where to buy
  • Explain how bounded contexts become services, and how they relate to business capabilities

The idea, in plain English

Lesson 1 split a system by what the business DOES. Domain-Driven Design (DDD) adds a second, sharper test: where does a WORD keep one meaning? Ask billing what an "active customer" is and they say "pays a subscription". Ask marketing and they say "logged in this month". Both are right - in their own part of the business.

Trouble starts when the whole company shares one model with one "active" field. It has to pick one meaning, and every team using the other meaning gets wrong answers - without any error. DDD’s answer is the bounded context: an area where one model and its words have exactly one meaning. Across the line, the same word can mean something else, and each side keeps its own model.

A bounded context is one of the best service boundaries there is: one model, one language, one team. DDD also tells you where to spend effort - build the core parts that make you different, keep supporting parts simple, and buy the generic parts every business has.

Worked example: One word - "active", "order" - meaning different things to different teams, and the services that keep each meaning separate.

An everyday example: what is an "order"?

At a restaurant, ask three people what an order is:

  • The cook: "Two masala dosas and a filter coffee, ready by 7:30." Dishes and a time.
  • The cashier: "Rs 160 plus Rs 8 GST, not paid yet." An amount and a status.
  • The rider: "A parcel for 12 MG Road." An address and who carries it.
  • All three are right. Each needs different facts, in different words.
  • One shared order form with dishes, prices, GST, address, rider and payment status helps nobody - and any change to it affects all three.
  • So each keeps its own form, in its own language, linked by the order number. Each of those is a bounded context.
The story -> DDD
The whole restaurant businessThe domain.
Cooking, billing, deliverySubdomains - parts of the business.
Each person’s own order formA bounded context: one model, one meaning per word.
The words each person usesThe ubiquitous language of that context.
Linked by the order numberContexts share ids, not models.
One giant shared formThe shared company-wide model DDD avoids.

The words you need

  • DDD has a lot of vocabulary. These six words are enough for this lesson.
Six words
DomainThe whole area the business works in.
SubdomainOne part of the business.
ModelHow the software represents things: which fields, which rules.
Bounded contextThe area where one model and its words have exactly one meaning. Often a service.
Ubiquitous languageThe words used inside one context - the same in code and in conversation.
Context mapA picture of the contexts and how they talk to each other.

Why one shared model goes wrong

A real example of the same word meaning two things:

  • Billing: an active customer has a paid subscription right now.
  • Marketing: an active customer logged in during the last 30 days.
  • On the same five customers, both count 3 active - but they are DIFFERENT people. The numbers even agree, which hides the problem.
  • Now share one Customer model with one is_active field, filled in by billing.
  • Marketing sends "we miss you" emails to inactive users. The email goes to John, who logged in 5 days ago - and skips Kiran, who has not logged in for 95 days but pays.
  • No error, no crash. Just wrong results, in a team that did nothing wrong.
  • Separate contexts fix it: billing has its own is_subscribed, marketing has its own last_login rule. Each word means one thing where it is used.
One word, two meanings, one shared field
customers = [ {"name": "Ravi", "paid": True, "days_since_login": 2}, {"name": "Kiran", "paid": True, "days_since_login": 95}, # pays, never logs in {"name": "John", "paid": False, "days_since_login": 5}, # free user, very active {"name": "Anil", "paid": False, "days_since_login": 200}, {"name": "Meena", "paid": True, "days_since_login": 12}, ] billing_active = [c["name"] for c in customers if c["paid"]] marketing_active = [c["name"] for c in customers if c["days_since_login"] <= 30] print("billing 'active': ", len(billing_active), billing_active) print("marketing 'active':", len(marketing_active), marketing_active) # One shared model with ONE is_active field has to pick a meaning. # Say billing wrote it. Marketing's "send a re-engagement email to inactive users": for c in customers: c["is_active"] = c["paid"] inactive = [c["name"] for c in customers if not c["is_active"]] print("re-engagement email goes to:", inactive, "<- John logged in 5 days ago") # billing 'active': 3 ['Ravi', 'Kiran', 'Meena'] # marketing 'active': 3 ['Ravi', 'John', 'Meena'] # re-engagement email goes to: ['John', 'Anil'] <- John logged in 5 days ago

Watch out: A shared model fails quietly. The code runs, the numbers look plausible, and the bug only shows when someone notices the wrong customers got an email - or a wrong report reaches a meeting.

Finding bounded contexts: a five-step method

Listen for where words change meaning:

  • 1. COLLECT the important nouns of the business: customer, order, course, product, payment.
  • 2. ASK each team what each noun means to them, and what they need to know about it.
  • 3. MARK where the meaning or the needed facts change. "Course" to the catalogue is a listing with a price; to the video player it is lessons and progress.
  • 4. DRAW a line at each change, and name each area: Catalogue, Billing, Learning.
  • 5. CHECK inside each area: does every word now have exactly one meaning? If not, split again.
  • The lines usually fall where teams and business departments already are - which is why contexts and capabilities (Lesson 1) mostly agree.
The method applied to an online course platform
The noun: "course" Catalogue a listing people browse and buy -> title, description, tags, rating, price shown Billing a product that is sold -> sku, price, currency, tax class, refund window Learning something a learner works through -> lessons, order, videos, quizzes, progress Three meanings -> three bounded contexts, linked by course_id. Each can change its model without asking the other two.

The same thing, three models

  • Each context keeps ONLY the fields it needs, named in its own words: a ticket, an invoice, a parcel.
  • They are linked by an id (812), not by sharing one object.
  • Billing can add a discount field without touching the kitchen. Delivery can add live tracking without touching billing.
  • Inside each context the words match the business’s own - in the code, in documents and in meetings. That is the ubiquitous language.
One restaurant order, three bounded contexts
from dataclasses import dataclass @dataclass class KitchenTicket: # Kitchen context: what to cook ticket_no: int dishes: list ready_by: str @dataclass class Invoice: # Billing context: what to charge invoice_no: str amount: float gst: float paid: bool @dataclass class Delivery: # Delivery context: what to carry where parcel_id: str address: str rider: str | None placed = {"id": 812, "items": [("Masala Dosa", 120), ("Filter Coffee", 40)], "address": "12 MG Road, Pune", "time": "19:30"} kitchen = KitchenTicket(placed["id"], [name for name, _ in placed["items"]], placed["time"]) subtotal = sum(price for _, price in placed["items"]) billing = Invoice(f"INV-{placed['id']}", subtotal, round(subtotal * 0.05, 2), False) delivery = Delivery(f"P{placed['id']}", placed["address"], None) print(kitchen) print(billing) print(delivery) # KitchenTicket(ticket_no=812, dishes=['Masala Dosa', 'Filter Coffee'], ready_by='19:30') # Invoice(invoice_no='INV-812', amount=160, gst=8.0, paid=False) # Delivery(parcel_id='P812', address='12 MG Road, Pune', rider=None)

Translating at the boundary

  • Contexts still need each other’s information: billing needs to know what was ordered.
  • So data crosses the line - through an API call or an event (Lesson 7) - and is TRANSLATED into the receiving context’s own model.
  • In the example, Ordering speaks of order lines and unit prices. Billing receives that and builds its own Invoice, with taxable amount and GST.
  • The translation lives in one place, at the edge of Billing. Billing’s inner code never sees Ordering’s model.
  • When the other side’s model is messy - often an old system - this translation layer has a name: the Anti-Corruption Layer (Lesson 15).
Ordering’s words in, Billing’s words out
from dataclasses import dataclass @dataclass class PlacedOrder: # Ordering context: what the customer asked for order_id: int lines: list # (sku, qty, unit_price) customer_id: int @dataclass class Invoice: # Billing context: what to charge invoice_no: str customer_ref: str taxable_amount: float gst: float @property def total(self): return round(self.taxable_amount + self.gst, 2) GST_RATE = 0.18 def to_invoice(order: PlacedOrder) -> Invoice: """Translate at the boundary: Ordering's words in, Billing's words out.""" amount = sum(qty * price for _, qty, price in order.lines) return Invoice( invoice_no=f"INV-{order.order_id}", customer_ref=f"C{order.customer_id:05d}", taxable_amount=amount, gst=round(amount * GST_RATE, 2), ) order = PlacedOrder(812, [("P1", 3, 20), ("P3", 2, 60)], 7) invoice = to_invoice(order) print(order) print(invoice) print("total to charge:", invoice.total) # PlacedOrder(order_id=812, lines=[('P1', 3, 20), ('P3', 2, 60)], customer_id=7) # Invoice(invoice_no='INV-812', customer_ref='C00007', taxable_amount=180, gst=32.4) # total to charge: 212.4

Core, supporting and generic: where to spend effort

Not every part of the business deserves the same effort:

  • CORE: what makes you different - why customers choose you. Build it yourself, with your best people, and model it carefully.
  • SUPPORTING: needed and specific to you, but not what you compete on. Build it, and keep it simple.
  • GENERIC: every business has one - login, payments processing, sending SMS. Buy it, or use an existing product.
  • The same subdomain can be core for one company and generic for another: route planning is core for a delivery company, generic for a bookshop.
  • A quick test: "If we did this twice as well as competitors, would customers notice and care?" Yes means core.
Three kinds of subdomain - a food delivery app
CoreMatching orders to riders, delivery-time prediction. Build in-house, invest most.
SupportingRestaurant onboarding, menu management. Build, keep it simple.
GenericLogin, payments, SMS. Buy or use a managed product.

From bounded contexts to services

  • A bounded context is a natural service boundary: one model, one language, one owning team.
  • One context can be one service, or a few services that share the model and the team.
  • A service should NEVER span two contexts - it would have to serve two meanings of the same word, and become the shared model again.
  • Capabilities (Lesson 1) say WHAT the business does; contexts say where a MODEL is valid. Use both. Where they disagree, look closer - the disagreement usually points at a missing boundary.
  • Avoid sharing model code between contexts (a "shared kernel" library). It quietly couples the teams again. Share ids and published events instead.
How two contexts can relate
Customer / supplierDownstream needs data from upstream; they agree an API or events together.
ConformistDownstream simply adopts upstream’s model - fine when it is clean and stable.
Anti-corruption layerDownstream translates upstream’s model into its own - for messy or legacy systems.
Shared kernelBoth share part of a model in code - use sparingly; it couples the teams.

DDD for service boundaries

Bounded context

Where one model and its words have one meaning. A strong service boundary.

billing context
Ubiquitous language

The context’s words, the same in code and in conversation.

invoice, GST
Five-step method

Collect nouns, ask each team, mark the changes, draw, check.

"course" x 3
Translate at the edge

Turn the other context’s model into yours, in one place.

to_invoice(order)
Core

Where you compete. Build and invest.

dispatch
Supporting

Needed, specific, not a differentiator. Build simply.

menus
Generic

Same for every business. Buy.

login, payments

What usually goes wrong

One shared model for everything

A single Customer or Order used by every team grows every field anyone needs, and one field ends up with two meanings - like is_active.

✗ class Customer: is_active, ... (used by billing AND marketing)
✓ Billing: is_subscribed    Marketing: last_login_days
Sharing model classes across services

A common library of Order and Customer classes couples every service to every change. Share ids and events, not model code.

A service that spans two contexts

It must serve two meanings of the same word, so its model becomes the giant shared model again - inside one service.

Building generic subdomains in-house

Writing your own login or payment processing spends your best effort where you cannot stand out - and adds risk.

Treating everything as core

If every part gets the full DDD treatment, the parts that really matter get no more care than the rest.

Finding contexts without the business

The meanings live in the teams that do the work. Developers alone tend to draw the current code, not the language.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

In a hospital system, what does "patient" mean to the front desk, to the doctors and to billing? Write the fields each context keeps.

Show hint

Ask what each part of the hospital needs to know to do its job.

Show solution
Front desk Visitor(name, phone, appointment_time, department) Clinical Patient(history, allergies, diagnoses, prescriptions) Billing Account(insurer, policy_no, charges, amount_due) Linked by patient_id. Clinical data never needs to live in billing.
2.

Sort these parts of a ride-hailing app into core, supporting and generic: surge pricing, driver document checks, SMS sending, matching riders to drivers, login.

Show solution
Core matching riders to drivers, surge pricing Supporting driver document checks Generic SMS sending, login
3.

Sales and Support both use a field "priority" on a customer: Sales means "likely to buy soon", Support means "has a paid support plan". What goes wrong with one shared field, and how do you fix it?

Show solution
One field can only hold one meaning. Whichever team writes it, the other team's work goes to the wrong customers - with no error. Fix: separate contexts, separate fields in their own words - Sales: lead_score (or buying_intent) Support: support_tier linked by customer_id.

Key points

  • A bounded context is where one model and its words have exactly one meaning.
  • The same word can mean different things in different contexts - that is normal; each keeps its own model.
  • One shared model forces one meaning, and gives other teams wrong results with no error.
  • Find contexts by listening for where a word changes meaning: collect, ask, mark, draw, check.
  • Contexts share ids and events, and translate at the boundary - not shared model code.
  • Core: build and invest. Supporting: build simply. Generic: buy.
  • A bounded context is a strong service boundary; a service should never span two.
  • Capabilities and contexts usually agree; where they disagree, look closer.

Quick check before you move on

What is a bounded context?
The area inside which one model and its words have one consistent meaning.
Billing and marketing both count 3 active customers. Can there still be a problem?
Yes - they can be different customers. In this lesson the two lists shared only Ravi and Meena.
How do two contexts exchange data without sharing a model?
Through an API or events, translating into their own model at the boundary - linked by ids.
Should you build your own login system?
Usually not. Login is generic - buy or reuse it, and spend effort on the core.

Interview questions

How does Domain-Driven Design help with microservices?

It gives a principled way to find boundaries: bounded contexts, where one model and language are consistent, map well to services with their own data and team. Subdomain classification shows where to invest, and context mapping describes how services integrate and translate.

What is a ubiquitous language?

The vocabulary shared by developers and domain experts inside one bounded context, used the same way in conversation, documentation and code - so the code reads in the business’s own terms.

What happens at the boundary between two bounded contexts?

Data crosses through an API or events and is translated into the receiving context’s model, in one place at the edge. When the upstream model is legacy or messy, an anti-corruption layer keeps its concepts from leaking in.

What is the risk of a shared kernel?

Shared model code couples the teams that use it: any change needs agreement and coordinated releases. It can work for a small, stable piece, but sharing ids and published contracts is usually safer.

Quiz

  1. 1.

    Why does a single shared model across the company break down?

  2. 2.

    What is the difference between a core and a generic subdomain?

  3. 3.

    How do business capabilities and bounded contexts relate?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...