Skip to main content

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

  1. Audit Trail: Complete history of all changes
  2. Debugging: See exactly what happened and when
  3. Time Travel: Reconstruct state at any point
  4. Event Replay: Rebuild state from events
  5. 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

  1. Immutable Events: Events should never change
  2. Meaningful Names: Use clear, descriptive event names
  3. Include Context: Store relevant data in events
  4. Version Events: Handle event schema evolution
  5. Idempotent Replay: Ensure events can be replayed safely

Next Steps