Subjects
Understanding subjects in event sourcing and how to identify the entities that events describe.
In event sourcing, a subject (also called an aggregate or entity) is the thing that events are about. It's the core entity whose state changes are being tracked through events.
Every event is associated with a specific subject, identified by a unique identifier. The subject's current state is derived by replaying all events associated with that subject's ID.
Example: An Order subject with IDorder-12345 might have events likeOrderPlaced,OrderPaid, andOrderShipped.
Represents a customer in your system.
customer-789Represents an order placed by a customer.
order-12345Represents a product in your catalog.
product-456Represents a financial account.
account-101Defining clear boundaries for your subjects is crucial. A subject should represent a single, cohesive concept that can be independently versioned and managed.
Good Boundaries
- ✓Each subject has a clear, single responsibility
- ✓Events for a subject can be replayed independently
- ✓Subject lifecycle is well-defined
- ✓Minimal coupling with other subjects
Poor Boundaries
- ✗Subject represents multiple unrelated concepts
- ✗Heavy dependencies on other subjects for state
- ✗Unclear ownership and lifecycle
- ✗Events that affect multiple subjects simultaneously
Each subject instance must have a unique identifier. This ID is used to:
- •Group events: All events for a subject share the same ID
- •Reconstruct state: Load all events for a specific subject ID
- •Ensure consistency: Changes to a subject are serialized through its ID
- •Enable partitioning: Distribute subjects across storage or processing nodes
Common ID Formats:
550e8400-e29b-41d4-a716-446655440000order-12345customer:789:order:12345In Domain-Driven Design (DDD), subjects are often called aggregates. An aggregate is a cluster of domain objects that can be treated as a single unit.
The aggregate root (main subject) is responsible for maintaining consistency within the aggregate boundary. All changes to objects within the aggregate must go through the aggregate root.
Example: An Order aggregate might contain Order Line Items. The Order is the aggregate root, and line items cannot be modified independently—all changes go through the Order.
- •One subject, one stream of events
- •Subject IDs must be globally unique
- •Keep subject boundaries aligned with business concepts
- •Subjects should be independently versionable
- •Consider transactional boundaries when defining subjects