Chapter 03 of 27 · Part 2: Decomposition

Designing business logic inside a service

Splitting FTGO into services does not make its business rules simpler: each service still has to keep them correct as they grow. This chapter shows how to organize the logic inside one service with aggregates and domain events, so the rules stay in one place and the service is ready to live among others.

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

Where we are

In chapter 02 we drew FTGO's service boundaries by business capability and subdomain, and broke up the Order god class so that each service keeps its own small view of an order. That left one problem open: we know which services exist, but not how the logic inside each one should be organized, or how DDD's aggregates and events fit into it.

This chapter

How should Order Service hold its rules so that they stay correct as FTGO adds features? By the end you can choose between a transaction script and a domain model, draw aggregate boundaries, keep the logic out of the service layer and the database, publish domain events, and map aggregates and bounded contexts onto services.

Procedures that grow out of control: transaction script or domain model

Problem

Order Service started with one createOrder() procedure. It loads the data, checks that the restaurant is open, checks the order minimum, computes the total and saves the rows. Then came revisions, cancellations, promotions and delivery fees. Each rule became another if in the same long method. Now a change to cancellation can break order creation, and nobody wants to touch the code.

There are two ways to organize business logic. A transaction script writes one procedure per request, working on data classes that have no behavior. A domain model writes small classes, such as Order and OrderLineItem, that each hold both state and behavior and mirror concepts the business talks about.

Two ways to organize business logic Transaction script One procedure per request Data classes with no behavior Fine for simple logic Gets messy when logic grows Domain model Small classes with state + behavior Mirrors real-world concepts Easy to test and extend Use DDD to organize it

A transaction script is a fine choice when the logic is simple. FTGO's Notification Service, which formats a message and sends it, does not need more. Order Service does.

Solution · Domain model

Put each rule in a class named after the business concept it belongs to, so the rule lives in one place and can be tested on its own. Use the tactical patterns of domain-driven design (DDD) to organize those classes.

DDD tactical patterns DDD building blocks Entity has an identity Value object just values Factory builds objects Repository loads and saves Aggregate unit of change Aggregates are the building block that matters most for microservices.

An entity has a lasting identity (order 4711), a value object is just values (a delivery address), a factory builds complex objects, and a repository loads and saves them. The fifth block, the aggregate, needs its own section.

Cost

A domain model takes more design up front than a script. And a plain graph of objects has no edges: any code can reach any object and change it, so nothing says which objects must change together. That gap shows up as soon as two people edit the same order.

Edits that break a rule nobody owns: aggregates

The domain model ends the giant procedure, but without boundaries it cannot protect a rule that spans several objects.

Problem

FTGO has an order minimum: an order must total at least, say, $20. Sam and Mary share a group order. Sam lowers the number of samosas; Mary lowers the number of naan. Each change is checked against the total they loaded, and each one alone keeps the order above the minimum. Both commit. The restaurant now receives an order below the minimum, and no line of code broke a rule on its own.

The fuzzy boundary problem Sam lowers samosas total still OK Mary lowers naan total still OK Both commit each saw old total Order is invalid below the minimum Updating parts of an order directly can break a rule that spans the whole order.

Sam and Mary each updated a line item directly. The minimum belongs to the whole order, but nobody was in charge of the whole order.

Solution · Aggregate

Group the objects that must stay consistent into an aggregate with one root entity. Outside code may touch only the root, and every load, update or delete acts on the whole aggregate. The root checks the invariants, the rules that must always hold for the cluster as a whole.

An aggregate and its boundary The Order aggregate holds line items, delivery and payment. It refers to Consumer and Restaurant only by id. Order aggregate Order aggregate root Line items value objects Delivery value object Payment value object Only the root is touched from outside. Consumer aggregate Consumer referenced by consumerId Restaurant aggregate Restaurant referenced by restaurantId
A load, update or delete acts on the whole aggregate.

Now Sam and Mary both call a method on the Order root, such as revise(). The root checks the minimum against the full order, and because the aggregate is saved as one unit (usually with a version number), the second save sees that the order changed underneath it and fails. Mary retries against the real total and is told her change goes below the minimum.

This also means an aggregate guards itself. When outside code asks for a state change, the aggregate can say no, so illegal transitions cannot happen.

Cost

Someone now has to decide where each aggregate ends and how big it is. Draw the edge too tight and a rule is left unprotected; draw it too wide and unrelated changes wait in line behind each other.

Where to draw the edge: the aggregate rules

Aggregates only help if their edges are firm. Four rules make them firm, and the same rules make an aggregate a natural fit for one service.

Problem

In the monolith, Order held an object reference to a Consumer and a Restaurant, and placing an order also updated fields on the consumer in the same database transaction. When Consumer moves to Consumer Service, there is no object to point to, and no transaction that spans both services' data.

Solution · Aggregate rules

Reference only an aggregate's root, refer to other aggregates by primary key, and change only one aggregate per transaction. When a request must change several aggregates, use a saga: a series of local transactions, one aggregate each.

Aggregate rules Aggregate rule Why it helps 1. Reference only the root the root enforces the rules 2. Refer to others by primary key loose coupling, easy to split 3. One transaction, one aggregate fits one service / NoSQL 4. Need several? Use a saga one aggregate per local txn

With these rules, Order stores a consumerId and a restaurantId, not objects. Each transaction stays inside one aggregate, so it stays inside one service and also fits NoSQL stores whose transactions cover only one record. Sagas are the subject of chapter 9.

The rules also settle the size question. One aggregate is changed by one request at a time, while different aggregates are changed in parallel. If Order contained the Consumer, two orders from the same person would have to wait for each other. Smaller aggregates therefore give more throughput.

Aggregate granularity Small aggregates (preferred) More parallel updates Fewer conflicts Easier to split into services Large aggregates Atomic updates across more data Updates serialize Hard to decompose
Cost

Anything that spans two aggregates is no longer one atomic step. It becomes a saga, and the data is only eventually consistent between steps. Small aggregates also mean more of these multi-step flows to design.

Keep the rules in the aggregate, not the service or the database

With the aggregates drawn, the rest of the service must not pull the logic back out of them.

Problem

The OrderService class still decides everything. It reads order.getState(), checks it, sets fields and calls the database code, while Order is a bag of getters and setters. The rule "only an approved order can be cancelled" now exists in three service methods, and every unit test needs a database because the domain classes import the data-access layer.

Solution · Thin service, rich aggregate

Keep the service class thin: load the aggregate through a repository, call one method on it, save it. The aggregate holds the business rules and its own life cycle of states.

Business logic of a service Inbound adapter REST API, command handlers Service (OrderService) thin: load, call, save Aggregate (Order) most business logic lives here Repository + DB adapter loads and saves aggregates Sagas and the event publisher sit beside the service.

The life cycle is part of the logic. An FTGO order is created in APPROVAL_PENDING while other services check it, and becomes APPROVED when that check succeeds. Order.cancel() refuses unless the order is approved, then moves it to CANCEL_PENDING while the cancellation runs. The _PENDING states tell everyone that a multi-step change is in progress.

Order aggregate life cycle APPROVAL PENDING created APPROVED saga done CANCEL PENDING cancelling CANCELLED final A failed create saga moves the order to REJECTED. Revising uses REVISION_PENDING the same way.

That removes the duplicated rules. The database dependency needs one more step: reversing the direction of the layers.

N-tier versus clean architecture In N-tier the domain depends on data access. In clean architecture dependencies point inward to the domain. N-tier: dependencies point down Presentation API, event handlers Application and domain Data access Database Clean: dependencies point in Presentation / infrastructure Application Domain knows nothing outside

In an N-tier layout the business logic depends on the data-access layer, so the database shapes the logic and testing it needs a database. In clean architecture (also called hexagonal or onion) the domain sits at the core and knows nothing outside. Frameworks, database drivers and the message broker client live in the outer layer, so upgrading the messaging library touches only the outside.

Solution · Clean (hexagonal) architecture

Make dependencies point inward to the domain. The domain defines interfaces such as OrderRepository; adapters in the outer layer implement them for a real database or broker.

Be pragmatic: the real win is that database and framework quirks stay out of the business rules, not that you can swap databases. Use the same layout in every service so anyone can change any service.

Cost

More interfaces and adapters to write and keep in sync. And the logic is now nicely sealed inside Order, which raises the opposite question: when the order changes state, how do other parts of FTGO find out?

Other parts of FTGO need to know: domain events

An aggregate that keeps its changes to itself is correct but lonely.

Problem

When an order is created, Kitchen Service must prepare a ticket, Notification Service must email the consumer, and the analytics team wants to count orders. If OrderService calls each of them, it must know every party that cares. Adding a loyalty program next month means editing Order Service again.

Solution · Domain events

When an aggregate changes state, it announces the change as an event named in the past tense, such as OrderCreated or OrderCancelled. The service publishes the event, and anyone who cares subscribes. Order Service no longer needs to know who is listening.

Why publish domain events Domain event an aggregate changed Sagas chaining steps CQRS views keep copies fresh Notify email, SMS Webhooks other systems Analytics monitoring

Later chapters build on them: sagas (chapter 9) and CQRS views (chapter 11).

The aggregate creates the events, because it knows what changed. It does not send them, because that would tie the domain to the messaging library. The service saves the aggregate and hands the events to a publisher.

Generating and publishing events Service loads aggregate Aggregate updates state returns events Service saves aggregate Publisher sends events The aggregate creates events. The service, which has the messaging API, publishes them.

How much should an event carry? A thin OrderCreated with only the order id is stable, but Kitchen Service must call back to learn what to cook. An enriched event carries the line items, address and payment details, so consumers need no extra call, but the event class changes more often. Chapter 7 treats this choice in depth.

Event enrichment Thin event OrderCreated with just orderId Stable event class Consumers must call back Enriched event Carries items, address, payment Consumers need no extra call Event class changes more often

To find which events a service needs, reuse the event storming workshop from chapter 2. The orange notes become your domain events, their triggers become commands, and whatever handles each command is an aggregate.

Event storming workshop 1. Brainstorm events orange notes on a timeline 2. Find triggers user, system, time, event 3. Find aggregates who handles each command
Cost

Saving the order and publishing its event are two separate writes that must both happen (chapter 6), and every subscriber now depends on the event's shape. Subscribers also read OrderCreated through their own idea of what an order is, which may not match Order Service's.

One word, many meanings: ubiquitous language and bounded contexts

Events and APIs carry names across the system, so the names have to mean something precise.

Problem

To Kitchen Service, an order is a ticket: items to cook and a ready-by time. To Delivery Service it is a pickup address and a drop-off. To Accounting it is an amount to charge. The monolith's single Order class tried to be all three. Meanwhile the restaurant team talks about "tickets" and "ready times", the code says OrderItemStatus, and every story needs someone to translate.

A side example: a bank team built a corporate-liquidity product on a generic model where everything, from a loan to a credit card, was an "arrangement". The product owner talked about haircuts and end-of-day sweeps, none of which appeared in the code, so analysts spent their days translating.

Generic model versus domain language Generic model Arrangement Arrangement type: loan Arrangement type: share Domain language Corporate liquidity Haircut End-of-day sweep When code uses the product owner's words, a developer can read a story and understand it.
Solution · Ubiquitous language

Use the same words in code that the business uses. If the kitchen says "ticket", the class is Ticket and the event is TicketAccepted. The same words then flow into API names, event names and service boundaries.

One language cannot cover the whole company, because one word means different things in different departments. A bounded context is an explicit boundary around one part of the business, with one model and one language inside. It offers some things to the rest of the system and hides the rest. At the music retailer MusicCorp, a second side example, finance and the warehouse are two contexts.

Two bounded contexts and what they share Warehouse Finance Picker Shelves Stock Item (with shelf location) Ledger Payroll Stock Count (a number only) shared internal details stay hidden needs stock to value the firm Share only what the other side needs, and give the shared view its own name.

The warehouse shares a trimmed, separately named view (a count, not shelf locations). A concept can also live in both contexts with different meanings: finance tracks a customer's payments, while the warehouse tracks parcels sent to a recipient. Both link to one global customer id.

One person, two models Finance Customer Payments, refunds Warehouse Recipient Parcels sent Shared Global customer id Name, email lookup
Solution · Bounded context

Give each part of the business its own model and language, behind an explicit boundary. Back in FTGO, Kitchen Service has a Ticket, Delivery Service has a Delivery, and Accounting has a charge. Each keeps only the fields it needs and links to the others by the order id.

Cost

Models now differ on purpose, so data must be translated at each boundary. Where one context consumes another's model, an anti-corruption layer keeps foreign concepts from leaking in. And we still have to decide how contexts and aggregates turn into deployable services.

From aggregates to services, linked by explicit references

Aggregates and bounded contexts both describe edges in the model. Now they have to become edges between services.

Problem

One FTGO team proposes a separate service for every aggregate before the first release. Another team, in Accounting, stores a bare CUST_ID = 2346 column in its ledger. A new developer cannot tell whether that number is a consumer, a restaurant or a courier, or which service to ask about it.

Both make good service boundaries. Start with one service per bounded context. You can split it later, but each aggregate must stay within one service; a service may own several. Callers need not see a split: at MusicCorp, one Warehouse API hides two services.

Hiding a split behind one API Warehouse boundary (what callers see) Warehouse API one coarse interface Inventory service Shipping service Owns Stock Item and Shipment Each aggregate is owned by one service.
Solution · Coarse services first, one owner per aggregate

Begin with one service per bounded context, holding its domain, API, read model and anti-corruption layer. Split it later along aggregate lines only when there is a reason, such as different scaling needs.

Coarse services first, finer ones later Start with one service per boundary and split it later if needed. Start: one service Order service domain, API read model, ACL Later: same boundary, finer services Domain service Anti-corruption layer Read model API service Many tiny services early on means lockstep releases and compounding distributed-systems problems.

That answers the first team. For the second, a bare number hides its meaning in code only its authors know.

Solution · Explicit references

When an aggregate refers to one owned by another service, store a reference that names its target and can be followed: a REST address such as /consumers/2346, or a scheme like soundcloud:tracks:123.

An explicit cross-service reference Accounting ledger row: consumer ref Reference consumer/2346 Consumer Service owns the aggregate Store a reference you can follow, not a number whose meaning lives only in code.
Cost

A reference you can follow is still only a reference. In the monolith, Order could call a method on Consumer in the same process. Now the consumer lives in another service, so following the reference means a call across the network, with all the latency and failure that brings.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Transaction scriptSimple logic needs no class designTurns into long, fragile procedures as rules grow
Domain modelBusiness rules scattered through long proceduresMore design up front; objects still need boundaries
AggregateConcurrent edits to parts of an object break a rule for the wholeBoundaries and sizes must be chosen with care
Aggregate rules (root only, reference by id, one aggregate per transaction)Object references and transactions that cannot cross service linesMulti-aggregate changes need sagas and are eventually consistent
Thin service, rich aggregateRules duplicated across service methods; anemic domain objectsDiscipline to keep logic out of the service layer
Clean (hexagonal) architectureDatabase and framework details shape and slow down the business logicMore interfaces and adapters
Domain eventsA service must know and call every party interested in a changeReliable publishing; consumers depend on the event's shape
Event enrichmentConsumers of thin events must call back for detailsEvent classes change more often
Ubiquitous languageConstant translation between business words and codeWorks only inside one context
Bounded contextOne shared model tries to mean everything to everyoneTranslation and anti-corruption layers at the boundaries
Coarse services firstToo many tiny services too earlyLater splits, which must keep each aggregate in one service
Explicit referencesBare ids whose target and owner are unclearFollowing a reference is a network call

Recap

Quick check

Why should one transaction update only one aggregate?
Show answer

It keeps each transaction inside a single service, because an aggregate lives in exactly one service, and it matches the limited transactions of many NoSQL stores. Changes across aggregates use a saga of local transactions instead.

FTGO's OrderService.cancelOrder() checks the order's state, sets the status field, and calls kitchenService.cancelTicket() and notificationService.send() directly. Two other service methods repeat the same state check. What is wrong, and which patterns fix it?
Show answer

The rule lives in the service layer and is duplicated, and Order Service is coupled to every party that cares about cancellation. Move the rule into the aggregate (Order.cancel() refuses unless the order is approved and moves it to CANCEL_PENDING), keep the service thin, and have the aggregate emit an OrderCancelled domain event that Kitchen and Notification subscribe to.

Kitchen Service calls its model Ticket, while Order Service calls it Order. Is that a mistake?
Show answer

No. They are different bounded contexts, each with its own model and language. The kitchen cares about items to cook and a ready-by time, not payment or delivery. Both models link through the order id.

Still open

Each FTGO service now holds its own aggregates and publishes events. But aggregates in different services can no longer call each other in memory: every interaction is a message or a request over the network, and we have not yet decided how those calls should work.

Next: 04 Interprocess communication and synchronous APIs →