Event Sourcing
info
Event Sourcing stores all changes as a sequence of events, providing a complete audit trail and the ability to replay history.
What is Event Sourcing?
Event Sourcing is a pattern where:
- State changes are stored as events: Every change is an immutable event
- Current state is derived: State is computed by replaying events
- Complete history: All changes are preserved forever
- Time travel: Replay events to any point in time
Events in Fluvius
Events are automatically generated from aggregate actions:
from fluvius.domain import Aggregate, action
class UserAggregate(Aggregate):
@action(evt_key='user-created', resources=['user'])
async def create_user(self, name: str, email: str):
# Event 'user-created' is automatically generated
self._state = UserState(name=name, email=email)
return self._state
Event Storage
Events are stored in the domain log store:
# Events are automatically stored when commands are processed
response = await domain.process_command(command)
# Access event log
events = await domain.logstore.get_events('user', user_id)
Replaying Events
Reconstruct state by replaying events:
# Get all events for an aggregate
events = await domain.logstore.get_events('user', user_id)
# Replay events to reconstruct state
state = None
for event in events:
state = apply_event(state, event)
Benefits
- Audit Trail: Complete history of all changes
- Debugging: See exactly what happened and when
- Time Travel: Reconstruct state at any point
- Event Replay: Rebuild state from events
- Integration: Events can trigger other systems
Event Structure
Events contain:
- Event Key: Identifier for the event type
- Source Command: The command that generated the event
- Arguments: Arguments passed to the action
- Data: Result data from the action
- Timestamp: When the event occurred
Best Practices
- Immutable Events: Events should never change
- Meaningful Names: Use clear, descriptive event names
- Include Context: Store relevant data in events
- Version Events: Handle event schema evolution
- Idempotent Replay: Ensure events can be replayed safely
Next Steps
- Learn about Domain Module
- Read about State Management
- Check out Examples