Overview
Domain Events are immutable objects that represent something significant that happened in the domain. They are used to communicate state changes between different parts of the system in a decoupled way, following event-driven architecture principles.Key Characteristics
- Immutable: Once created, events cannot be modified
- Past Tense: Named with past-tense verbs (e.g.,
UserRegisteredEvent) - Rich Information: Contain all relevant data about what happened
- Timestamp: Always include when the event occurred
- Domain Focused: Represent business-significant occurrences
- Decoupling: Allow loose coupling between components
Event Structure
Domain events in Soft-Bee API follow this pattern:Real Example: Auth Events
The auth feature demonstrates various domain events:src/features/auth/domain/events/auth_events.py.
Event Design Principles
1. Past Tense Naming
Events represent things that already happened:2. Include Timestamp
Always track when the event occurred:3. Event Type
Use a consistent event type format:4. Rich Event Data
Include all relevant information:5. Immutability
Use dataclasses (frozen by default for events):Raising Events from Entities
Entities raise events when significant state changes occur:src/features/auth/domain/entities/user.py:39 for the implementation.
Creating New Domain Events
Step 1: Create Base Event Class
Step 2: Define Specific Events
Step 3: Raise Events from Entities
Event Publishing Pattern
Events are collected from entities and published after successful operations:Event Handlers
Create event handlers to react to domain events:Common Event Patterns
State Change Events
Track entity state transitions:Lifecycle Events
Track entity creation and deletion:Action Events
Track user or system actions:Aggregate Events
Events that affect multiple entities:Best Practices
Name Events Descriptively
Include All Relevant Context
Don’t Include Behavior in Events
Pull Events After Operations
Event Versioning
Plan for event schema evolution:Related Documentation
- Domain Entities - Where events are raised
- Value Objects - Used in event data
- Domain Exceptions - Error handling