Bird
Raised Fist0
Microservicessystem_design~7 mins

Aggregates and entities in Microservices - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When multiple related data objects are updated independently in a distributed system, inconsistencies and race conditions occur, leading to corrupted or invalid states. Without clear boundaries, services may update parts of data that should be treated as a single unit, causing data integrity failures and complex coordination issues.
Solution
Aggregates group related entities into a single unit with a root entity that controls all changes. This root enforces consistency rules and transactional boundaries, ensuring updates happen atomically within the aggregate. Services interact only with the aggregate root, preventing partial updates and maintaining data integrity across distributed components.
Architecture
Client
Aggregate Root
Entity A

This diagram shows a client interacting only with the aggregate root, which manages multiple related entities internally to maintain consistency.

Trade-offs
✓ Pros
Ensures data consistency by enforcing transactional boundaries within aggregates.
Simplifies service interactions by exposing only aggregate roots, reducing coupling.
Improves maintainability by clearly defining ownership and boundaries of data.
Reduces race conditions and partial updates in distributed systems.
✗ Cons
Can lead to large aggregates that are hard to manage if boundaries are not well defined.
May increase complexity in designing aggregates and enforcing invariants.
Overly strict boundaries can reduce flexibility and increase latency if aggregates are too coarse.
Use when your system has complex domain models with related data that must remain consistent, especially in microservices handling distributed transactions or eventual consistency scenarios. Typically beneficial when aggregates fit within a single transactional boundary.
Avoid when your data relationships are simple and do not require transactional consistency, or when aggregates would become too large and impact performance or scalability negatively.
Real World Examples
Amazon
Amazon uses aggregates to manage order processing where the order aggregate root controls order items, payment status, and shipment details to ensure consistency during order lifecycle.
Uber
Uber models a trip as an aggregate where the trip root entity manages related entities like driver assignment, route, and payment to maintain consistent trip state.
Netflix
Netflix uses aggregates in their microservices to manage user profiles where the profile root controls related entities like preferences and viewing history to avoid inconsistent user data.
Code Example
The before code allows direct modification of order items, risking inconsistent states. The after code encapsulates item management inside the Order aggregate root, enforcing rules and preventing invalid updates.
Microservices
### Before: No aggregate root, direct entity updates
class OrderItem:
    def __init__(self, product_id, quantity):
        self.product_id = product_id
        self.quantity = quantity

class Order:
    def __init__(self):
        self.items = []

    def add_item(self, item):
        self.items.append(item)

order = Order()
order.items.append(OrderItem('p1', 2))  # Direct access allows inconsistent state


### After: Aggregate root controls entity updates
class OrderItem:
    def __init__(self, product_id, quantity):
        self.product_id = product_id
        self.quantity = quantity

class Order:
    def __init__(self):
        self._items = []

    def add_item(self, product_id, quantity):
        if quantity <= 0:
            raise ValueError('Quantity must be positive')
        item = OrderItem(product_id, quantity)
        self._items.append(item)

    @property
    def items(self):
        return list(self._items)  # Read-only access

order = Order()
order.add_item('p1', 2)  # Controlled update through aggregate root
OutputSuccess
Alternatives
Event Sourcing
Stores all changes as a sequence of events rather than current state, reconstructing aggregates from events.
Use when: Choose when you need full audit trails, temporal queries, or complex state reconstruction beyond simple aggregates.
Shared Database with Foreign Keys
Uses relational database constraints to maintain consistency instead of aggregate boundaries.
Use when: Choose when microservices share a database and strong consistency is required without complex domain logic.
Domain Services
Encapsulates business logic outside entities and aggregates, focusing on operations rather than data ownership.
Use when: Choose when operations span multiple aggregates or entities and cannot be cleanly modeled inside a single aggregate.
Summary
Aggregates group related entities under a root to enforce consistency and transactional boundaries.
They prevent partial updates and race conditions by controlling all changes through the aggregate root.
Properly designed aggregates improve data integrity and simplify microservice interactions.

Practice

(1/5)
1. In microservices, what is the main role of an aggregate root entity?
easy
A. It acts as a database for all microservices.
B. It stores unrelated data from different services.
C. It handles user interface rendering.
D. It controls all changes within the aggregate to keep data consistent.

Solution

  1. Step 1: Understand aggregate root responsibility

    The aggregate root is the main entity that manages all changes inside its aggregate to ensure consistency.
  2. Step 2: Eliminate unrelated options

    Options A, B, and D describe roles unrelated to aggregate roots in microservices.
  3. Final Answer:

    It controls all changes within the aggregate to keep data consistent. -> Option D
  4. Quick Check:

    Aggregate root controls changes = C [OK]
Hint: Aggregate root manages changes inside its group [OK]
Common Mistakes:
  • Confusing aggregate root with database or UI component
  • Thinking aggregate root stores unrelated data
  • Assuming aggregate root handles external service data
2. Which of the following correctly represents an aggregate in a microservice domain model?
easy
A. Order (root) -> OrderItems (entities) -> PaymentDetails (entity)
B. OrderItems (root) -> Order -> PaymentDetails
C. PaymentDetails (root) -> Order -> OrderItems
D. Order -> PaymentDetails -> OrderItems (all roots)

Solution

  1. Step 1: Identify the aggregate root

    In an order system, the Order is the root entity controlling related entities like OrderItems and PaymentDetails.
  2. Step 2: Check the hierarchy correctness

    Order (root) -> OrderItems (entities) -> PaymentDetails (entity) shows Order as root with related entities under it, which is correct. Other options misplace roots or treat all as roots.
  3. Final Answer:

    Order (root) -> OrderItems (entities) -> PaymentDetails (entity) -> Option A
  4. Quick Check:

    Root entity is Order controlling others = A [OK]
Hint: Root entity leads related entities in aggregate [OK]
Common Mistakes:
  • Assigning wrong entity as root
  • Treating all entities as roots
  • Ignoring aggregate boundaries
3. Given the aggregate root Customer with entities Address and Order, which operation should only be performed through Customer?
medium
A. Deleting Order independently from Customer
B. Directly updating an Order without Customer involvement
C. Adding a new Address via the Customer aggregate root
D. Querying Order data directly from the database

Solution

  1. Step 1: Understand aggregate root control

    The aggregate root Customer controls all changes to its entities like Address and Order to maintain consistency.
  2. Step 2: Identify allowed operations

    Adding a new Address should go through Customer. Direct updates or deletes bypassing root break consistency.
  3. Final Answer:

    Adding a new Address via the Customer aggregate root -> Option C
  4. Quick Check:

    Changes go through root entity = A [OK]
Hint: All changes pass through aggregate root only [OK]
Common Mistakes:
  • Updating entities directly without root
  • Deleting entities independently
  • Confusing querying with updating
4. You have a microservice with an aggregate root Invoice and entities LineItem. The code allows direct modification of LineItem without Invoice. What is the main problem?
medium
A. Performance will improve due to direct access.
B. Data consistency may break because changes bypass the aggregate root.
C. It will reduce network calls between services.
D. It simplifies the codebase without side effects.

Solution

  1. Step 1: Identify aggregate root role in consistency

    The aggregate root Invoice ensures all changes to LineItem are consistent and valid.
  2. Step 2: Analyze direct modification impact

    Directly modifying LineItem bypasses Invoice, risking inconsistent or invalid data.
  3. Final Answer:

    Data consistency may break because changes bypass the aggregate root. -> Option B
  4. Quick Check:

    Bypassing root risks consistency = B [OK]
Hint: Bypass root risks data consistency [OK]
Common Mistakes:
  • Assuming direct access improves design
  • Ignoring consistency importance
  • Confusing performance with correctness
5. You design a microservice for a shopping cart system. The cart is an aggregate root with entities like CartItem and Discount. Which design choice best ensures data consistency and scalability?
hard
A. Make Cart the aggregate root controlling all CartItem and Discount changes.
B. Use a single database table for Cart, CartItem, and Discount without aggregates.
C. Store CartItem and Discount in separate microservices with no coordination.
D. Allow CartItem and Discount to be updated independently without Cart involvement.

Solution

  1. Step 1: Apply aggregate root principle for consistency

    Cart as aggregate root should control all changes to CartItem and Discount to keep data consistent.
  2. Step 2: Consider scalability and design best practices

    Centralizing changes through Cart allows easier management and scaling of the microservice without data conflicts.
  3. Step 3: Evaluate other options

    Options A and C risk inconsistency; B ignores aggregate design and can cause complexity.
  4. Final Answer:

    Make Cart the aggregate root controlling all CartItem and Discount changes. -> Option A
  5. Quick Check:

    Aggregate root controls changes for consistency and scale = D [OK]
Hint: Aggregate root controls related entities for consistency and scale [OK]
Common Mistakes:
  • Allowing independent updates breaking consistency
  • Splitting tightly coupled entities into separate services
  • Ignoring aggregate design principles