Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
A closed ticket must accept no new comment, yet the AI assistant's new code path adds one anyway. Move the rule into the Ticket aggregate root, save one aggregate per transaction with a version number, and keep aggregates small: 5 messages loaded instead of 2,000.
What you will learn
- Tell an entity from a value object with one question
- Put business rules inside an aggregate root so every channel obeys them
- Use a version number so one transaction saves one aggregate safely
- Keep aggregates small and link them by ID and events
Before you start
- Python classes
- Layered, Hexagonal and Clean Architecture
This lesson looks inside the code that holds an app's business rules, the domain model. Our example is TicketHub, a support-ticket app with an AI assistant. Three building blocks carry it: entities, value objects and aggregates. One idea to keep: the aggregate is the boundary. It guards the rules, and one transaction saves one aggregate.
One rule, three doors
TicketHub has a simple rule: a closed ticket accepts no new comment. Ticket 4821 is closed. The ticket itself is just data, and a service around it checks the rule.
- A reply comes in through the web page. The service checks: closed, blocked.
- A reply comes in by email. Checked again, blocked.
- Then the team adds the AI assistant. Its drafts take a new code path, nobody copies the check, and a comment lands on a closed ticket.
This shape has a name: an anemic entity with a fat service. The rule lives outside the data, so every new door has to remember it.
Entity: the same thing, changing over time
Ticket 4821 goes from open to waiting to closed. Its priority changes, even its subject gets edited, but it's still the same ticket because the ID stays. A second ticket arrives with the very same subject, "charged twice", but ID 5107. Two different tickets.
An entity has an identity and a lifecycle. You compare entities by who they are, not by what they hold. The customer and the agent are entities too.
Value object: defined by its values
A value object has no identity; it's defined only by its values. An email address typed with spaces and capitals goes in and comes out trimmed and in lower case, so two forms of the same address end up equal. A broken one with nothing after the @ is refused. It's checked once, when it's created, so a bad email can't exist anywhere in the app.
The SLA deadline is a value object too. The ticket opened at 09:00; high priority gives 4 hours, so it's due at 13:00. Then the priority becomes urgent, 1 hour. You don't edit the old deadline. It's thrown away and a new one is made: 09:00 + 1 = due at 10:00. Value objects never change. You replace them.
Which is which?
| Entity | Value object |
|---|---|
| Ticket, customer, agent | Email address, SLA deadline, priority, money amount |
A comment is the tricky one. Two comments can say the same words and still be two comments, so it's an entity. But it only lives inside a ticket. Keep that in mind.
The test: do you care which one it is, or only what it holds? "Which one" means entity. "What it holds" means value object.
The aggregate: one root, one boundary
An aggregate is a small group of entities and value objects that change together: the ticket, its comments, its attachments, the AI draft and the SLA deadline. One of them is the root, here the ticket.
The AI assistant wants to add a comment. It can't reach inside and grab the comment list. It stops at the boundary, goes to the root, and the root adds the comment. Outsiders talk to the root, never to a part inside. Other parts of the app usually keep just the ID, 4821, and ask for the ticket when they need it.
Rules sit inside the root
Now all three doors lead to the root. A web reply arrives; the ticket checks itself and rejects it. An email reply: same rule, same place, rejected. The AI draft has no other path to take, so it's rejected too. A new door can't forget the rule, because the rule isn't in the door.
The root can hold more rules, such as: only one AI draft can wait for review at a time. A second draft arrives, and the ticket says no.
The lecture is a concept lesson with no project code, so here's a small sketch of the idea in Python. It isn't from the lecture project; the output below comes from running it.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class EmailAddress:
value: str
def __post_init__(self):
clean = self.value.strip().lower()
if "@" not in clean or clean.endswith("@"):
raise ValueError(f"bad email: {self.value!r}")
object.__setattr__(self, "value", clean)
@dataclass
class Ticket:
id: int
status: str = "open"
comments: list[str] = field(default_factory=list)
def add_comment(self, text: str) -> None:
if self.status == "closed":
raise ValueError("closed ticket accepts no comment")
self.comments.append(text)
def close(self, note: str) -> None:
self.comments.append(note)
self.status = "closed"
print(EmailAddress(" [email protected] ") == EmailAddress("[email protected]"))
try:
EmailAddress("olivia@")
except ValueError as err:
print(err)
t = Ticket(4821)
t.close("refunded")
for channel in ("web", "email", "ai draft"):
try:
t.add_comment(f"reply from {channel}")
except ValueError as err:
print(channel, "->", err)
True
bad email: 'olivia@'
web -> closed ticket accepts no comment
email -> closed ticket accepts no comment
ai draft -> closed ticket accepts no comment
frozen=True makes EmailAddress a value: equal by its values, impossible to edit. Ticket is the root, and its method is the only way to add a comment.
The transaction boundary
This is the heart of the lesson. The aggregate is also the transaction boundary.
- Ticket 4821 is in the store at version 7. Emma loads it, closes it with the note "refunded", and saves. The whole aggregate travels as one package, ticket and comments together, and the version rolls from 7 to 8.
- Meanwhile Noah loaded the same ticket a minute ago, at version 7. He adds a comment and saves, still expecting 7. The store says it's at 8 now. His save is rejected, and nothing is half written.
- Noah reloads version 8, sees the ticket is closed, and the root refuses his comment by the same rule as before.
One transaction saves one aggregate, all of it or none of it. That version number is called optimistic locking: nobody waits, and a late save simply fails and tries again.
Between aggregates: IDs and events
Olivia, the customer, is her own aggregate. The ticket doesn't hold the whole customer, just her ID, 3301. When the ticket closes, it doesn't reach over and change the customer in the same transaction. It sends an event, ticket closed. A moment later the customer side counts her open tickets: 3 becomes 2.
Inside one aggregate, everything is consistent at once. Between aggregates, it's consistent soon after. That's the trade for small, safe transactions.
Keep aggregates small
| Design | To add one comment, load |
|---|---|
| Wrong: customer is the aggregate, holding all 400 tickets of a busy business customer, 5 messages each | 400 × 5 = 2,000 messages |
| Right: the ticket is the aggregate | 5 messages |
That's 400 times less, and two agents working on two different tickets no longer clash, because each ticket has its own version number.
One repository per aggregate
A repository loads and saves data. With aggregates you get one per aggregate: the ticket repository gets ticket 4821 and saves the ticket with everything inside. What you don't build is a comment repository. That would be a back door to the parts, skipping every rule in the root. The Python version of a repository is in Repository and Unit of Work with SQLAlchemy.
Fat service or aggregate root
| Anemic entity, fat service | Aggregate root | |
|---|---|---|
| Where the rule lives | In each service method | In the root |
| A new channel like the AI assistant | Has to remember the rule | Gets it for free |
| One save touches | A ticket here, a comment there | One ticket, all of it, protected by its version |
| Testing the rule | Through the service | Test the ticket alone, no database |
The honest cost: a little more design up front, and changes across aggregates are consistent soon after, not at once.
Say it in an interview
"What is an aggregate, and why does it matter?" Answer in four parts. Definition: a cluster of entities and value objects with one root. Boundary: the root guards the rules, and one transaction saves one aggregate. Trade-off: keep aggregates small, and link them by ID and events. Example: in a ticket app the ticket is the root; a closed ticket rejects comments from every channel, and one save covers the ticket with its comments.
Recap
- An entity is known by its identity. A value object is known by its values, and you replace it instead of changing it.
- An aggregate is a boundary with one root. Outsiders hold the root or its ID, never a part.
- One transaction saves one aggregate; a version number stops two people overwriting each other.
- Keep aggregates small and connect them with IDs and events.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
