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
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
That removes the duplicated rules. The database dependency needs one more step: reversing the direction of the layers.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
That answers the first team. For the second, a bare number hides its meaning in code only its authors know.
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.
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
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Transaction script | Simple logic needs no class design | Turns into long, fragile procedures as rules grow |
| Domain model | Business rules scattered through long procedures | More design up front; objects still need boundaries |
| Aggregate | Concurrent edits to parts of an object break a rule for the whole | Boundaries 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 lines | Multi-aggregate changes need sagas and are eventually consistent |
| Thin service, rich aggregate | Rules duplicated across service methods; anemic domain objects | Discipline to keep logic out of the service layer |
| Clean (hexagonal) architecture | Database and framework details shape and slow down the business logic | More interfaces and adapters |
| Domain events | A service must know and call every party interested in a change | Reliable publishing; consumers depend on the event's shape |
| Event enrichment | Consumers of thin events must call back for details | Event classes change more often |
| Ubiquitous language | Constant translation between business words and code | Works only inside one context |
| Bounded context | One shared model tries to mean everything to everyone | Translation and anti-corruption layers at the boundaries |
| Coarse services first | Too many tiny services too early | Later splits, which must keep each aggregate in one service |
| Explicit references | Bare ids whose target and owner are unclear | Following a reference is a network call |
Recap
- A transaction script is fine for simple logic, but complex logic such as FTGO's orders belongs in a domain model organized with DDD's building blocks.
- An aggregate is a cluster of objects changed as one unit through its root, which enforces the rules that span the whole cluster and may refuse a change.
- Aggregates refer to each other by id, and one transaction changes one aggregate; changes that span aggregates use a saga, and smaller aggregates give more throughput.
- The service class stays thin and the aggregate holds the logic and its life cycle, while clean architecture keeps the database and broker outside the domain.
- Aggregates emit past-tense domain events and the service publishes them, so other services can react without Order Service knowing who listens.
- Ubiquitous language and bounded contexts give each part of the business its own precise model; services start one per context, each aggregate has one owning service, and cross-service links are explicit references.
Quick check
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.
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.
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.
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.