Decomposition and bounded contexts
Mid-level Frequently asked 6 min
On this page
The question
How do you decide where to split a system into services?
30-second answer
Split by business capability, along bounded contexts from Domain-Driven Design (DDD): areas where words and rules have one meaning, such as Ordering, Payments and Shipping. Each service owns its data and is owned by one team. A good split keeps changes local: most features touch one service. Avoid splitting by technical layer, and avoid services so small that every feature needs several to change together.
Understand it
Give each meaning its bounded context
BuildSix teams all say "Product" or "Customer", and mean different things. Put each meaning in the bounded context that owns it.
Drag a piece, or select it and then select a place.
- Empty
- Empty
- Empty
- Empty
- Empty
- Empty
View as text
Six rows, one per bounded context, each with an empty slot for the model it owns. Six teams all say "Product" or "Customer", and mean different things. Put each meaning in the bounded context that owns it.
Catalog owns Product: name, photos, text. Ordering owns Product: price paid, quantity. Inventory owns Product: units per warehouse. Shipping owns Product: weight and box size. Payments owns Customer: card token, refunds. Identity owns Customer: login, password.
One word, six models. Each context keeps only the data it needs, owns it, and shares just an ID with the others.
Six rows, one per bounded context, each with an empty slot for the model it owns. Six teams all say "Product" or "Customer", and mean different things. Put each meaning in the bounded context that owns it.
Catalog owns Product: name, photos, text. Ordering owns Product: price paid, quantity. Inventory owns Product: units per warehouse. Shipping owns Product: weight and box size. Payments owns Customer: card token, refunds. Identity owns Customer: login, password.
One word, six models. Each context keeps only the data it needs, owns it, and shares just an ID with the others.
Takeaway: A bounded context is where a word has one exact meaning. Split services along those contexts, and the shared "Product" table with forty columns becomes six small models, each with one owner.
A context map of an online shop
Tap the partsSelect a part to see what it does.
Tap a bounded context. Arrows point from upstream to downstream; the dashed arrow is an event, and the striped box translates an external model.
View as text
A map of seven boxes in two columns. On the left, Catalog above Ordering above Shipping, with an arrow from Catalog down to Ordering and a dashed event arrow from Ordering down to Shipping. On the right, Identity, then Payments, an anticorruption layer and the external card provider. Ordering has an arrow to Payments.
Catalog, upstream supplier. Catalog is upstream of Ordering:
Identity, generic: buy it. Login, passwords and tokens are a generic subdomain:
Payments, our payment model. Payments is ours:
Ordering, core domain. Ordering is the core domain, where the business differs from its competitors.
Anticorruption, translates models. An anticorruption layer translates the provider's model into ours, so its field names and status codes never leak into Payments.
Shipping, listens to events. Shipping is downstream of Ordering through events:
Card provider, external: not ours. The card provider is an external system whose model we cannot change.
A map of seven boxes in two columns. On the left, Catalog above Ordering above Shipping, with an arrow from Catalog down to Ordering and a dashed event arrow from Ordering down to Shipping. On the right, Identity, then Payments, an anticorruption layer and the external card provider. Ordering has an arrow to Payments.
Catalog, upstream supplier. Catalog is upstream of Ordering:
Identity, generic: buy it. Login, passwords and tokens are a generic subdomain:
Payments, our payment model. Payments is ours:
Ordering, core domain. Ordering is the core domain, where the business differs from its competitors.
Anticorruption, translates models. An anticorruption layer translates the provider's model into ours, so its field names and status codes never leak into Payments.
Shipping, listens to events. Shipping is downstream of Ordering through events:
Card provider, external: not ours. The card provider is an external system whose model we cannot change.
Takeaway: A context map shows how bounded contexts depend on each other: who is upstream, who translates, who only listens to events. Put the best design work into the core, and buy what is generic.
In code
// Catalog context: what a shopper reads
package com.shop.catalog;
public record Product(ProductId id, String name, String description, List<URI> photos) {}
// Ordering context: what an order needs, with the price frozen at checkout
package com.shop.ordering;
public record OrderLine(ProductId productId, int quantity, Money unitPrice) {
public Money total() { return unitPrice.times(quantity); }
}@Component
class CardProviderTranslator { // the only class that knows the provider's types
private final ProviderClient provider;
CardProviderTranslator(ProviderClient provider) { this.provider = provider; }
Charge charge(OrderId order, Money amount) {
ProviderChargeResponse r = provider.createCharge(amount.cents(), amount.currency(), order.value());
return new Charge(order, amount, switch (r.status()) { // their codes, our states
case "succeeded" -> ChargeState.CAPTURED;
case "requires_action" -> ChargeState.NEEDS_CUSTOMER;
default -> ChargeState.FAILED;
});
}
}@Service
class PriceLookup {
// Ordering queries Catalog's database: one schema change in Catalog breaks Ordering
Wrong Money wrong(ProductId id) { return jdbc.queryForObject("select price from catalog.products where id = ?", Money.class, id.value()); }
// Ordering keeps the prices it needs, updated from Catalog's events
@KafkaListener(topics = "catalog.price-changed")
void on(PriceChanged e) { prices.save(new LocalPrice(e.productId(), e.newPrice())); }
Right Money right(ProductId id) { return prices.findById(id).orElseThrow().price(); }
private final JdbcTemplate jdbc;
private final LocalPriceRepository prices;
PriceLookup(JdbcTemplate jdbc, LocalPriceRepository prices) { this.jdbc = jdbc; this.prices = prices; }
}Solve it
Split an online shop’s shared Product table between services
An online shop is moving to services. Its database has one products table with 40 columns: name, photos, price, cost,
stock per warehouse, weight, box size, tax class and more. Five teams read and write it. Propose how the data is
split, and how services that need someone else’s fields get them.
- Group the columns by who changes them. Merchandisers edit name and photos, finance edits cost and tax class, warehouses change stock, and logistics owns weight and size. Each group is a candidate bounded context.
- Give each context its own model. Catalog, Pricing, Inventory and Shipping each keep only their columns, keyed by the same product ID. Only the ID is shared.
- Pick the owner of each fact. Exactly one context writes each field. Others hold read-only copies, or ask.
- Choose how data travels. Copies follow events such as
PriceChanged, which tolerate the owner being down. Use a synchronous call only when the answer must be current, such as stock at checkout. - Check. No service reads another’s tables, each can deploy alone, and a renamed column in one context touches no other team’s code.
// Catalog owns what shoppers read
record CatalogItem(ProductId id, String name, List<URI> photos) {}
// Pricing owns money
record PriceItem(ProductId id, Money price, Money cost, TaxClass taxClass) {}
// Inventory owns stock
record StockItem(ProductId id, WarehouseId warehouse, int onHand) {}
// Shipping owns the parcel
record ShippableItem(ProductId id, Grams weight, BoxSize box) {}
// The published event others subscribe to, instead of reading Pricing's tables
record PriceChanged(ProductId productId, Money newPrice, Instant at) {}How to answer
- Find the contexts by listening to the business, for example with event storming.
- High cohesion inside a service, loose coupling between them, measured by how often they change together.
- Start coarse; splitting a service later is cheaper than merging two.
- Match services to teams, as Conway's law predicts you will anyway.
Common mistakes
- Splitting into a controller service, a business logic service and a database service. Every feature then changes all three.
- Making one service per entity, such as a Customer service and an Address service, which turns every use case into chatty calls.
Follow-up questions
What is a bounded context?
A boundary inside which one model, and one meaning of each word, applies. "Product" in Catalog has a name and photos; in Shipping it has a weight and a box size; in Ordering it is a line with the price paid. Each context keeps its own model instead of one shared model with every field. Bounded contexts are the natural candidates for service boundaries.
- The ubiquitous language is the vocabulary the team and the business share inside one context.
- Contexts share IDs, not models.
- A subdomain is a problem area; a bounded context is the solution's boundary, often one per subdomain.
See it in the infographic: Give each meaning its bounded context See it in the infographic: A context map of an online shop
Why should each service have its own database, and how do services then share data?
A shared database couples services through its schema: one team's migration can break another, and nobody knows who owns a column. With a database per service, only the owner reads and writes its data, and others get it through its API or from events. Services that need someone else's data often keep a local, read-only copy, updated by events, and accept that it is slightly stale.
- It can be a separate schema on the same server, as long as no service reads another's.
- A query across services becomes an API composition or a read model built from events.
- A transaction across services becomes a saga.
See it in the infographic: Give each meaning its bounded context
What is a context map, and what does an anticorruption layer do?
A context map draws the bounded contexts and how they relate: who is upstream and who is downstream, and how a downstream context copes with an upstream model. An anticorruption layer is a translator in the downstream context that turns the upstream model, often a legacy or external system, into its own, so foreign names and rules never spread through its code.
- Common relationships: customer-supplier, conformist, shared kernel, open host service with a published language.
- The anticorruption layer is where you put the adapter pattern at the boundary.
- Use one when integrating a legacy system during a strangler fig migration.
How small should a microservice be?
Small enough that one team owns it and can rewrite it in weeks, and large enough that most features change only one service. Size in lines of code is the wrong measure. If two services must always be changed and released together, they are one service split in the wrong place.
Check yourself
Show answers
- Each context keeps its own Product model, sharing only the ID: Correct. One meaning per context; the ID links them.
- One shared Product class with every field, in a common library: Incorrect. A shared model couples every team to every change.
- A base Product class that each context extends: Incorrect. Still a shared model, and the base class changes for everyone.
Show answers
- In an anticorruption layer inside Payments: Correct. One translator keeps the provider's model at the edge of the context.
- Wherever Payments code reads a provider response: Incorrect. The provider's vocabulary then spreads through the whole service.
- Ask the provider to use our model: Incorrect. An external provider will not change its API for one customer.