Chapter 02 of 27 · Part 2: Decomposition

Decomposition strategies: where to cut

Splitting a monolith only helps if the service boundaries are in the right place. Draw them wrong and every change still needs several teams. This chapter shows how FTGO finds boundaries that hide details, keep related changes together and survive the god classes that every part of the monolith uses.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 1 FTGO decided to leave its monolith, for a measured reason and one domain at a time. We saw that the property to protect is independent deployability, and that a bad split gives a distributed monolith. That left one problem open: where exactly do the service boundaries go?

This chapter

How do we find service boundaries that let each FTGO team change and deploy its service alone? By the end you can judge a boundary by cohesion and coupling, derive services from business capabilities or DDD subdomains, run an event storming workshop, spot the obstacles a split creates, and break up a god class such as Order.

What a good boundary hides

Problem

FTGO's first new Delivery service reads the customer's address straight from the monolith's ORDERS table. A month later the order team splits the address into street and city columns. Nobody tells the delivery team, because nobody knows they depend on it. That evening couriers get empty addresses.

A microservice is a module with a network between it and the other modules, so the old rules of good modular design still apply. David Parnas showed that modules pay off only when their boundaries hide details. The connections between modules are the assumptions they make about each other; fewer assumptions mean freer modules.

Solution · Hide everything behind an API

A service exposes a public API of commands (change data), queries (read data) and events (announce that something changed). Its database is private: no other service reads or writes its tables.

Anatomy of a service A client calls the public API. Inside are business logic and a private database. The service publishes events. Client Order service Public API commands and queries Business logic Private DB Events order created Everything goes through the API. Nobody touches another service's database.

Size matters less than people think. A good service is one a small team can build and change without waiting for others. Share code between services only for things that rarely change, such as a Money class.

Two words describe how good a boundary is. Cohesion is about the things inside it: code that changes together should live together. Coupling is about things across it: a change on one side should not force a change on the other. Constantine's law puts it in one line: a structure is stable when cohesion is strong and coupling is low. Only a stable boundary allows independent deployment.

Information hiding, cohesion and coupling Information hiding gives three benefits. Cohesion is about inside a boundary and coupling about across it. Information hiding fewer assumptions between modules Faster parallel work Easier to understand Easier to change Judging a boundary Cohesion (inside) code that changes together stays together Coupling (across) a change here should not force a change there Constantine's law: a structure is stable when cohesion is strong and coupling is low.
Cost

Services that work together are always coupled somehow: Order must ask Accounting to charge the card. "No coupling" is not an option. We need a way to tell harmless coupling from the kind that will hurt.

Not all coupling is equal

With every call now going through APIs, FTGO can still build boundaries that leak.

Problem

To place an order, Order Service builds a delivery manifest and sends it to Kitchen Service, only so that Kitchen can forward it to Delivery Service. When the delivery team adds a field to the manifest, the order team must change and redeploy too, even though Order never uses the manifest.

Solution · Rank the coupling, and push it toward the loose end

Name the kind of coupling between two services. Domain coupling is normal; pass-through, common and content coupling each have a known fix.

Four kinds of coupling, from loose to tight Domain, pass-through, common and content coupling with a fix for each. Looser Tighter Domain needs its function Keep it small send the least data Pass-through data only passed on Hide it caller need not know Common shared read/write data One owner others send requests Content touches internal data Use the API never its tables Top row: the kind of coupling. Bottom row: the usual fix. Temporal coupling is separate: both services must be up at once. Async messaging relieves it.
KindFTGO exampleWhat to do
DomainOrder Service calls Kitchen to create a ticket and Accounting to authorize the cardUnavoidable. Send as little data as possible. Many downstream calls hint that one service does too much.
Pass-throughOrder sends a delivery manifest to Kitchen only so Kitchen can forward it to DeliveryLet the service that needs the manifest build it, so changes to it stay hidden from Order.
CommonOrder and Kitchen both update the status column of one shared orders tableGive the table one owner. Others send it requests, which it can reject if the status change is invalid.
ContentKitchen reads and writes Order Service's internal tables directlySend requests to Order Service's API instead.

A fifth kind sits beside the ranking: temporal coupling, where both services must be up at the same moment for a call to work. Asynchronous messaging (chapter 5) relieves it.

Watch for CRUD wrappers. A service that is only a thin layer of create, read, update and delete calls over its tables is a warning sign. The business rules have leaked out to its callers, so cohesion is weak and coupling is tight.
Cost

Cohesion and coupling tell FTGO whether a boundary is good once it exists. They do not say where to draw the first one. For that the team needs a method that starts from the business.

Start from what the business does: capabilities

Problem

The FTGO architects stand at an empty whiteboard with a long backlog of user stories. Grouping the existing code by package gives the old modules back, tangles included. They need a starting point that does not come from today's code.

Solution · Three-step process, cut by business capability

Start from the requirements. First find the system operations, then group them into services, then define each service's API and how services collaborate. For the grouping, use business capabilities: the things the company does to make money.

Three steps to define services Requirements user stories 1. Operations what must it do 2. Services group by business 3. APIs who calls whom

Step 1 reads the user stories: verbs become operations (createOrder, acceptTicket), nouns become domain objects (Order, Ticket, Courier). Step 2 groups them by capability. A capability stays stable even when the way the business performs it changes, so a service built around it stays stable too.

Business capabilities mapped to services What the business does Service Courier management Courier service Restaurant information Restaurant service Consumer management Consumer service Order management Order service Restaurant order preparation Kitchen service Courier availability + delivery Delivery service Accounting (all three kinds) Accounting service Your first guess. You can merge or split services later.

Step 3 assigns each operation to a service and works out who must call whom. Placing an order, for example, belongs to Order Service but needs four others:

createOrder collaborates with four services Order service: createOrder() Consumer verify consumer Restaurant verify order Kitchen create ticket Accounting authorize card Verbs in user stories become operations. Nouns become domain objects.
Cost

A capability map names the services but says little about what goes inside them. Worse, the same word means different things to different parts of the business: to the kitchen an "order" is a list of dishes to cook, to accounting it is an amount to charge.

Give each part its own model: DDD subdomains

Domain-driven design (DDD) attacks exactly that problem: one word, several meanings.

Problem

The FTGO monolith has one enterprise-wide data model. The kitchen team wants to add a prepare-by time to orders, accounting wants a refund state, delivery wants a pickup window. Every change lands in the same Order definition, and every team argues over it.

Solution · Decompose by subdomain

Split the business domain into subdomains, such as order taking, kitchen, delivery and accounting, and give each one its own model with an explicit boundary, called a bounded context. Each bounded context becomes a service, or a small group of services.

In practice FTGO ends up with nearly the same services as the capability map. What DDD adds is a vocabulary for what lives inside each boundary. Three ideas matter most for drawing service boundaries:

IdeaMeaningWhy it helps
Ubiquitous languageUse the same words in code as the business usesGives APIs and events a shared vocabulary. A generic data model that calls every product an "arrangement" hides the real domain.
AggregateA cluster of objects managed as one unit, such as an Order, with state, identity and a life cycleKeep one aggregate inside one service. Other services ask for changes, and the aggregate may refuse.
Bounded contextAn explicit boundary around one model that exposes some things and hides the restIt is information hiding by design, so it makes a stable service boundary.

The same real-world thing can have a different name and different fields in each context. A short side example from MusicCorp, an online music shop: Finance keeps payments for a customer, while Warehouse ships goods to a recipient. They are the same person. A shared model can also expose less than the internal one, such as a stock count instead of shelf locations.

Two bounded contexts with a shared idea Finance and Warehouse each keep private models. They share a customer and a stock count under different names. Finance context Warehouse context General ledger (private) Customer Stock count Pickers and shelves (private) Recipient Stock item same person count only Aggregate: has state, identity and a life cycle, and can say no to a bad change. Across services, store an explicit reference such as a URI, not a bare ID.
MusicCorp side example.

A context can even be split into several services inside, as long as the outside world still sees one boundary. Two design guidelines, borrowed from object-oriented design, help decide what belongs together:

Two decomposition guidelines Single Responsibility A service has one reason to change Order, kitchen and delivery are separate Common Closure Things that change together live together Cure for the distributed monolith
Cost

Subdomains are only as good as the team's understanding of the business. Developers who model from the existing database tables will rebuild the monolith's structure with new names.

Find the model with the experts: event storming

Problem

FTGO's developers draft the subdomains alone, from the database schema. They miss that a restaurant can reject a ticket after accepting it, a case the kitchen staff deal with every day. The model looks tidy and is wrong.

Solution · Event storming

Run a workshop with the people who know the business. Put everyone in one room with a long wall and plenty of sticky notes. First write down what happens, as events in the past tense; then work toward the structure: commands, aggregates and bounded contexts.

Event storming in four steps Events first, then commands, then aggregates, then bounded contexts. 1 Events facts: Order Placed 2 Commands user actions 3 Aggregates the nouns: Order 4 Contexts candidate services Get all stakeholders in one room with lots of wall space and sticky notes. Do not let today's code bend the model. That comes later. Events cluster around the aggregate they belong to.
  1. Events. Orange notes, one per business event: Order Placed, Ticket Accepted, Ticket Rejected, Payment Authorized. Pain points and open questions get notes of their own.
  2. Commands. Blue notes for the actions that cause each event, such as Place Order or Accept Ticket, and the actors who issue them.
  3. Aggregates. Yellow notes for the nouns the events cluster around: Order, Ticket, Delivery.
  4. Bounded contexts. Group the aggregates into contexts. These often follow the company's structure, and they are the candidate services.

The wall also shows where events cross a boundary, which is where event schemas will have to be shared. The result can feed an event-driven design or a plain request and response one. Treat it as a draft of the domain model, not a finished design.

Cost

A workshop takes the time of busy domain experts, and it finds the boundaries the domain suggests. But the domain is not the only force on a boundary: law, technology and teams push too.

When the domain is not the only force

The domain is the best default because domain boundaries change least. Do not turn it into dogma: the goal you are chasing decides which driver matters most.

Problem

Card numbers enter FTGO with every order. If Order Service passes them on to Accounting, both services, and everything that can reach them, fall under the strict PCI audit for card data. The domain map does not say anything about that.

Solution · Combine the domain with other drivers

Start from domain boundaries, then refine them by volatility, data sensitivity, technology and team ownership. Keep each extra cut only when it serves a goal you can name.

Other drivers for a service boundary Volatility, data, technology and organization, with a PCI zone example. Volatility split what changes often: fast time to market Data limit the scope of personal or card data Technology a different runtime forces a boundary Organization one owning team per service Example: PaymentCo splits by data Gateway routes by data Green zone services never see card numbers: no PCI audit Red zone services handle card data: fully audited
PaymentCo side example: card data stays in one audited zone.

Mixing drivers is fine. A domain-shaped Restaurant service might still be split further because one part, say a menu-recommendation engine, needs a different language.

Cost

Every extra boundary is one more network hop. With the boundaries drawn, FTGO now has to face what the split breaks in operations that used to be simple method calls.

What splitting breaks

Problem

In the monolith, createOrder was a few method calls inside one database transaction. Now it calls four services over the network. Each hop adds latency. If Accounting is down, nobody can order. If Kitchen creates a ticket and the card is then declined, there is no single transaction to roll both back.

These obstacles are why the rest of the course exists. Each has a fix, and each fix gets its own chapter:

Obstacles to decomposition and their fixes Obstacle Fix Network latency Batch APIs, or merge services Sync calls hurt availability Async messaging (ch 5) Data consistency across services Sagas (ch 9) No single consistent view Keep that data in one service God classes DDD: one model per service
ObstacleWhat to do for now
Network latencyIf two services chat constantly, give them a batch API that fetches many things in one call, or merge them.
Synchronous calls reduce availabilityIf Order needs Accounting, Kitchen and Consumer all up at once, its availability is lower than any of theirs. Asynchronous messaging (chapter 5) removes that dependency.
Consistency across servicesNo ACID transaction spans services. Sagas (chapter 9) use local transactions and compensations instead.
No single consistent viewEach service's data is consistent on its own, but a snapshot across services is not. If some data must always be read consistently, keep it in one service.
Cost

Those four have later chapters. The last obstacle in the figure blocks the split itself, today: some classes are used by every part of the monolith, so no boundary can be drawn around them.

The god class: Order is needed everywhere

Problem

FTGO's Order class does order taking, restaurant preparation, delivery and billing. It has dozens of fields and every module uses it. Put it in Order Service, and Kitchen, Delivery and Accounting call Order Service for every step. Copy it into every service, and four teams share one model: back to common coupling.

Solution · One model per service

Apply DDD: each service keeps its own small model of the order, with only the fields and behavior it needs, under its own name. Order Service keeps an Order (status, total, items), Kitchen Service a Ticket (items, prepare-by time), Delivery Service a Delivery (pickup, address, courier).

Splitting the Order god class One bloated Order class with four responsibilities becomes three small models. Order (god class) Order taking Restaurant preparation Delivery Billing Order service: Order status, total, items Kitchen service: Ticket items, prepare-by time Delivery service: Delivery pickup, address, courier Same real-world order, three small views.

Each model can now change without the others. When the kitchen adds a prepare-by time, only the Ticket changes. Billing data moves to Accounting in the same way. The models refer to one another by order id, not by sharing an object.

Cost

One real order now lives as three models in three services, and they must stay in step: when an order is cancelled, the ticket and the delivery must follow. That means deciding how big each model should be, and how a change in one reaches the others.

Aggregates, and when to add a service

The unit that answers both questions is the aggregate.

Problem

FTGO wants to add scheduled orders, placed today for delivery on Friday. Should this extend the Order aggregate in Order Service, or become a new service? And how much should one aggregate hold: one order, or a restaurant's whole day of orders?

DDD gives the vocabulary. A bounded context is the scope of one model with its own ubiquitous language. It holds one or more aggregates, each modelling one domain concept; an entity is one instance of it. A command changes one aggregate and may be rejected. The change that happened is announced as an event. An anti-corruption layer translates at the edge so one context's concepts do not leak into another.

From bounded context to entity A bounded context holds aggregates; an aggregate has entities; commands go in and events come out. Bounded context Order management Aggregate Order Entity order 231 Commands go in to the aggregate and may be rejected. Events come out as facts. One aggregate is changed by one thread at a time; different aggregates change in parallel.

Aggregate size is a performance decision. One aggregate is changed by one thread at a time, so small aggregates allow more parallel work, while a large aggregate keeps a bulk change consistent. A side example from an online beauty shop makes the trade-off visible: its products have variants (sizes or colors) and belong to categories.

Aggregate granularity trade-off A small aggregate gives parallelism and many events; a large one gives consistent bulk changes and slower sequential processing. Variant parallel updates many small events Product balanced middle if consumers agree Category bulk change atomic slow, large events small: high concurrency, more broker load large: consistent, sequential Ask: is it a real domain concept? How many events? Does it scale to millions of aggregates?

Match the aggregates of your consumers where you can. If the stock service emits one event per variant but the discount service works per category, the discount service must do a lot of work to relate them. For FTGO, one aggregate per order is the natural size: a restaurant's whole day in one aggregate would force every order through one thread.

Solution · Extend a service or add one, by explicit rules

Add the feature to an existing service when it belongs to the same concept and changes with it. Create a new service when the existing one is overloaded, unclearly owned, or needs a different stack or scaling.

Add to the existing service whenCreate a new service when
The concept is closely related and changes together, like an order and its order lines.The service already depends on many others and carries too much responsibility.
A new service would otherwise have to share the existing one's database. That is a red flag; consume its event stream instead.Several teams own the existing service and nobody owns it clearly.
The existing service is anemic: a thin shell around a database with no domain logic.It needs a different technology stack, needs to scale on its own, or has a different usage pattern.

Scheduled orders change together with orders, so they extend the Order aggregate. A courier-payout feature with its own team and its own batch load would be a new service. Not every service needs to be event-driven either. A small, low-traffic admin service can be a plain synchronous service with strong consistency, while data that many services share travels as events.

Request-driven and event-driven services in one system Use synchronous services for strong consistency at low scale; use events for sharing large data. UI a few hundred calls/day Request-driven sync API, strong consistency Event-driven stream shares the data Do not build a mesh of sync services: that is a distributed monolith with cascading failures.
Cost

The boundaries are drawn and each service has its own models. But we have said little about how the code inside a service should be organized, how an aggregate enforces its rules, or how it announces its changes so the other services can follow.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Information hiding behind an APIServices break when another team changes its tablesEvery access needs an API call; the API must be designed and kept stable
Coupling ranking (domain, pass-through, common, content)Boundaries that look clean but still force joint changesJudges an existing boundary; does not say where to draw the first one
Decompose by business capabilityNo starting point that is independent of today's codeCoarse; says little about the model inside each service
Decompose by subdomain (bounded contexts)One enterprise-wide model that every team fights overNeeds real domain knowledge; one concept now has several models
Event stormingDevelopers modelling the domain alone, from database tablesWorkshop time from domain experts; the output is only a draft
Boundaries by volatility, data, technology or teamSensitive data, fast-changing parts or ownership disputes spread across servicesExtra boundaries and network hops; must serve a named goal
One model per service (split the god class)A class like Order that every part needs blocks any splitSeveral models of one real thing must be kept in step
Aggregate sized for its consumersUnclear unit of consistency and changeSmall means more events and broker load; large means sequential processing

Recap

Quick check

Why does Kitchen Service call its order a Ticket instead of an Order?
Show answer

Each service has its own model in its own bounded context. The kitchen only cares about items, the prepare-by time and the ticket status, so a small Ticket fits better than the huge shared Order, and it can change without touching Order Service.

FTGO's Kitchen Service updates the status column of the Order Service's orders table directly when a ticket is ready. What kind of coupling is this, what breaks, and what fixes it?
Show answer

It is content coupling, the tightest kind: Kitchen reaches into Order's internal data. When the order team renames the column or adds a status rule, Kitchen breaks or writes invalid states that Order Service never checked. Kitchen should send a request through Order Service's API, or publish a "ticket ready" event that Order Service reacts to, so Order stays the only owner of its data.

FTGO wants card numbers to touch as few services as possible. Which decomposition driver is this, and where should the card data live?
Show answer

It is a data-driven boundary. Keep full card numbers inside Accounting only, the "red zone", and let Order and the other services work with a token or payment id. Then only Accounting falls under the strict card-data audit.

Still open

FTGO now has services with clear boundaries and their own models. Next we look inside one service: how to organize its business logic, how aggregates enforce their rules, and how they publish domain events.

Next: 03 Designing business logic inside a service →