The user wants a program that implements Event Sourcing and CQRS (Command Query Responsibility Segregation) patterns.
This is a broad request, usually implying a backend service or a core domain logic implementation.
Key Concepts to Implement:
-
CQRS: Separate the "Write" model (Commands) from the "Read" model (Queries).
- Command Side: Handles intents (e.g., "CreateOrder", "ShipOrder"). It validates business rules, updates state by generating events.
- Query Side: Handles data retrieval (e.g., "GetOrderDetails"). It reads from a optimized read model (projection), not the source of truth (event store).
-
Event Sourcing: The state is not stored as a current snapshot (like in a standard SQL DB row) but as a sequence of immutable events.
- Event Store: Append-only log of facts.
- Rehydration: Rebuilding the current state by replaying past events.
- Projections: Listening to events to update the read models.
Domain Selection:
To make it understandable, I need a simple domain. A "Bank Account" or "Todo List" are classics. Let's go with a Bank Account (or simple "Account") because it involves state changes that are critical (money in/money out) and easy to visualize as events.
Architecture Components:
- Domain Objects:
Account (Aggregate Root).
- Commands:
CreateAccount, DepositMoney, WithdrawMoney.
- Events:
AccountCreated, MoneyDeposited, MoneyWithdrawn.
- Command Handler: Receives commands, loads aggregate, executes logic, saves events.
- Event Store: A repository for events (in-memory for simplicity, interface defined).
- Event Bus/Publisher: To notify the read side.
- Projectors/Read Model: Updates a queryable database (in-memory dict) based on events.
- Query Handlers: Serve data from the read model.
Language:
Python is good for readability and expressing patterns without too much boilerplate. C# is also popular for this, but Python is often more accessible for a general algorithm demonstration. I'll use Python with type hinting.
Step-by-Step Implementation Plan:
- Definitions & Base Classes: Define what an Event and Command look like.
- Domain (The Aggregate):
Account class.
- Methods to handle commands (e.g.,
deposit).
- Methods to apply events (e.g.,
apply_money_deposited).
- State fields (balance, ID).
- Event Store: A simple class to append and retrieve events for an ID.
- CQRS - Command Side:
CommandBus: Dispatches commands to handlers.
AccountCommandHandler: Loads aggregate, calls method, persists new events.
- CQRS - Query Side:
ReadModel: A simple database (dictionary) denormalized for queries.
Projector: Subscribes to events and updates the ReadModel.
QueryBus: Dispatches queries.
- Main/Demo: Wire it all together. Create account, deposit, withdraw, query balance.
Refining the Code Structure:
- Events: Immutability is key. Use dataclasses.
- Aggregate Root: Needs to track uncommitted changes.
- Concurrency: I won't implement complex locking, but I'll mention it's needed in real systems.
Drafting the Code (Mental or Scratchpad):
-
Event Store:
events = {} # dict of stream_id -> list of events
def save(stream_id, expected_version, new_events): ...
def load(stream_id): ...
-
Aggregate:
class Account:
def __init__(self):
self.version = 0
self.changes = []
self.balance = 0
def create(self, id):
# Validation logic (e.g., does it exist?) usually happens in handler or here if we have state
self._apply(AccountCreated(id))
def deposit(self, amount):
if amount <= 0: raise Error
self._apply(MoneyDeposited(amount))
def _apply(self, event):
# Update state logic
# Add to changes
pass
-
Projector:
def handle_event(event):
if isinstance(event, AccountCreated):
db[event.id] = {"balance": 0}
elif isinstance(event, MoneyDeposited):
db[event.id].balance += event.amount
Self-Correction during thought process:
- Snapshotting: Should I include snapshotting? No, it adds complexity that might confuse the user. Keep it to simple event replay.
- Frameworks: Should I use a library? No, "raw" Python is better for understanding the pattern.
- Async: Real systems are usually async. For a demonstration, synchronous code is easier to follow. I will stick to synchronous but mention where async fits.
Final Structure for the Output:
- Explanation: Briefly define CQRS and Event Sourcing.
- Python Implementation: Complete, runnable code.
- Imports.
- Domain Events & Commands.
- The Aggregate (Write Model).
- The Repository (Event Store).
- The Projector (Read Model builder).
- The Service/Buses.
- Usage Example: A script showing the flow.
- Summary: Key takeaways.
Let's write the code.
- Events:
AccountOpened, FundsDeposited, FundsWithdrawn.
- Commands:
OpenAccount, DepositFunds, WithdrawFunds.
- Read Model: Just stores the current balance and maybe the last operation for display.
One critical detail in Event Sourcing: The apply method.
The Aggregate needs two ways to interact with events:
handle_command: Creates an event based on logic.
apply_event: Updates internal state based on an event.
Why separate? Because when we load from history, we don't run command logic (like checking "is balance > 0"), we just rebuild state ("set balance to X").
Let's proceed with the generation.
This is a complete implementation of Event Sourcing (ES) and Command Query Responsibility Segregation (CQRS) in Python.
To keep the code runnable and easy to understand, I have implemented the "Infrastructure" layer (Event Store, Bus) using in-memory structures. In a production environment, these would be replaced by databases (e.g., PostgreSQL, EventStoreDB) and message brokers (e.g., Kafka, RabbitMQ).
Architecture Overview
- Domain: The core business logic (e.g.,
BankAccount). It knows nothing about databases.
- Events: Facts that happened in the past (e.g.,
MoneyDeposited).
- Commands: Intents to change state (e.g.,
DepositMoney).
- Command Handler: Validates commands and generates Events.
- Event Store: The "Write" database. It only stores streams of events.
- Projectors (Read Models): Listen to events and update a simplified "Read" database (a flat dictionary in this case).
The Implementation
import uuid
from dataclasses import dataclass, field
from typing import List, Dict, Callable, Any, Optional
from abc import ABC, abstractmethod
from copy import deepcopy
# ==========================================
# 1. Domain Events & Commands Definitions
# ==========================================
@dataclass
class Event(ABC):
"""Base class for all events."""
pass
@dataclass
class AccountOpened(Event):
account_id: str
owner: str
@dataclass
class MoneyDeposited(Event):
account_id: str
amount: float
@dataclass
class MoneyWithdrawn(Event):
account_id: str
amount: float
# Commands (Intents)
@dataclass
class Command(ABC):
pass
@dataclass
class OpenAccount(Command):
account_id: str
owner: str
@dataclass
class DepositMoney(Command):
account_id: str
amount: float
@dataclass
class WithdrawMoney(Command):
account_id: str
amount: float
# ==========================================
# 2. Domain Entity (The Aggregate Root)
# ==========================================
class BankAccount:
"""
The Aggregate Root.
It protects business invariants and emits events.
Note: It does NOT have public setters. State changes only via events.
"""
def __init__(self, events: List[Event] = None):
# Re-hydrate state from history (Event Sourcing)
self.version = -1
self._balance = 0.0
self._id = None
self._owner = None
self._uncommitted_changes = []
if events:
for event in events:
self._apply(event)
self.version += 1
@property
def id(self):
return self._id
@property
def balance(self):
return self._balance
# --- Command Handlers ---
def open_account(self, account_id: str, owner: str):
if self._id is not None:
raise ValueError("Account already opened")
# Business Logic passed -> Emit Event
self._record_event(AccountOpened(account_id, owner))
def deposit(self, amount: float):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._record_event(MoneyDeposited(self._id, amount))
def withdraw(self, amount: float):
if amount <= 0:
raise ValueError("Withdrawal must be positive")
if self._balance < amount:
raise ValueError("Insufficient funds")
self._record_event(MoneyWithdrawn(self._id, amount))
# --- Event Sourcing Mechanics ---
def _record_event(self, event: Event):
# 1. Apply the change to memory
self._apply(event)
# 2. Add to list of changes to be saved to DB
self._uncommitted_changes.append(event)
self.version += 1
def _apply(self, event: Event):
"""Updates internal state based on the event type."""
if isinstance(event, AccountOpened):
self._id = event.account_id
self._owner = event.owner
self._balance = 0.0
elif isinstance(event, MoneyDeposited):
self._balance += event.amount
elif isinstance(event, MoneyWithdrawn):
self._balance -= event.amount
def get_uncommitted_changes(self):
return self._uncommitted_changes
def mark_changes_as_committed(self):
self._uncommitted_changes = []
# ==========================================
# 3. Infrastructure: Event Store (Write Side)
# ==========================================
class EventStore:
"""Simulates a database that stores events in streams."""
def __init__(self):
# Dictionary: {stream_id: [list_of_events]}
self._streams: Dict[str, List[Event]] = {}
# Subscribers for the Event Bus (CQRS projection side)
self._subscribers: List[Callable[[Event], None]] = []
def save(self, aggregate_id: str, changes: List[Event], expected_version: int):
"""
Persists events.
In a real DB, this would use Optimistic Concurrency Control
checking 'expected_version' against the DB version.
"""
if aggregate_id not in self._streams:
self._streams[aggregate_id] = []
# Append events
for event in changes:
self._streams[aggregate_id].append(event)
# Publish to Read Side immediately (CQRS Sync)
self._publish(event)
def load_events(self, aggregate_id: str) -> List[Event]:
return self._streams.get(aggregate_id, [])
def subscribe(self, subscriber: Callable[[Event], None]):
self._subscribers.append(subscriber)
def _publish(self, event: Event):
for sub in self._subscribers:
sub(event)
# ==========================================
# 4. Infrastructure: Read Model (Query Side)
# ==========================================
@dataclass
class AccountSummaryDTO:
"""A Data Transfer Object for the Read Model. Flat and optimized for queries."""
id: str
owner: str
balance: float
class ReadDatabase:
"""
In CQRS, we maintain a separate Read Model optimized for lookups.
This simulates a SQL Table or a Redis Cache.
"""
def __init__(self):
self._data: Dict[str, AccountSummaryDTO] = {}
def get(self, account_id: str) -> Optional[AccountSummaryDTO]:
return self._data.get(account_id)
def update(self, dto: AccountSummaryDTO):
self._data[dto.id] = dto
def delete(self, account_id: str):
if account_id in self._data:
del self._data[account_id]
# ==========================================
# 5. Projectors (Updating the Read Model)
# ==========================================
class AccountProjector:
"""
Listens to events and updates the Read Database.
This is the 'Synchronization' part of Event Sourcing.
"""
def __init__(self, read_db: ReadDatabase):
self.read_db = read_db
def project(self, event: Event):
if isinstance(event, AccountOpened):
dto = AccountSummaryDTO(event.account_id, event.owner, 0.0)
self.read_db.update(dto)
elif isinstance(event, MoneyDeposited):
dto = self.read_db.get(event.account_id)
if dto:
dto.balance += event.amount
self.read_db.update(dto)
elif isinstance(event, MoneyWithdrawn):
dto = self.read_db.get(event.account_id)
if dto:
dto.balance -= event.amount
self.read_db.update(dto)
# ==========================================
# 6. Application Service (The Facade)
# ==========================================
class BankAppService:
"""
The API layer.
1. Receives Commands.
2. Loads Aggregate from Event Store.
3. Calls Aggregate methods.
4. Saves changes.
"""
def __init__(self, event_store: EventStore):
self.event_store = event_store
def handle(self, command: Command):
if isinstance(command, OpenAccount):
# For a new account, we pass empty history
account = BankAccount()
account.open_account(command.account_id, command.owner)
self._save(account)
elif isinstance(command, DepositMoney):
account = self._load(command.account_id)
account.deposit(command.amount)
self._save(account)
elif isinstance(command, WithdrawMoney):
account = self._load(command.account_id)
account.withdraw(command.amount)
self._save(account)
def _load(self, account_id: str) -> BankAccount:
history = self.event_store.load_events(account_id)
if not history:
raise ValueError(f"Account {account_id} not found")
return BankAccount(history)
def _save(self, account: BankAccount):
changes = account.get_uncommitted_changes()
if changes:
self.event_store.save(account.id, changes, account.version - len(changes))
account.mark_changes_as_committed()
# ==========================================
# 7. Running the Program
# ==========================================
if __name__ == "__main__":
# 1. Setup Infrastructure
event_store = EventStore()
read_db = ReadDatabase()
projector = AccountProjector(read_db)
# Link the Projector to the Event Store
event_store.subscribe(projector.project)
# Setup Application Services
service = BankAppService(event_store)
# Generate an ID
acc_id = str(uuid.uuid4())
print(f"--- Executing Commands for Account {acc_id} ---")
# 1. Open Account
cmd_open = OpenAccount(acc_id, "Alice Smith")
service.handle(cmd_open)
# 2. Deposit Money
cmd_deposit = DepositMoney(acc_id, 100.00)
service.handle(cmd_deposit)
# 3. Withdraw Money
cmd_withdraw = WithdrawMoney(acc_id, 40.00)
service.handle(cmd_withdraw)
# --- Verification ---
print("\n--- Verifying Read Model (Query Side) ---")
summary = read_db.get(acc_id)
print(f"Owner: {summary.owner}")
print(f"Balance: ${summary.balance}")
print("\n--- Verifying Write Model (Event History) ---")
history = event_store.load_events(acc_id)
for i, event in enumerate(history):
print(f"{i+1}. {event.__class__.__name__}: {event}")
Key Concepts Explained
1. The Aggregate (BankAccount)
Notice that BankAccount does not have setters like set_balance. Its state is private. The public methods (deposit, withdraw) validate business rules (e.g., "Insufficient funds") and then create an Event.
The _apply method is the only thing that actually changes the variable self._balance. This ensures that the state is always consistent with the history of events.
2. Event Sourcing (Persistence)
We do not save the balance to the database. We save the stream of events: AccountOpened, MoneyDeposited, MoneyWithdrawn.
When we need the BankAccount later, we create an empty object BankAccount() and replay the history through the constructor.
3. CQRS (Separation)
We have two databases effectively:
- Event Store: The append-only list of facts (Write Model).
- Read Database (
ReadDatabase): A dictionary containing the current state (AccountSummaryDTO).
The Projector (AccountProjector) acts as a bridge. It listens to events and updates the Read Database. This allows the Read Database to be highly optimized (e.g., SQL views, ElasticSearch indices) without complicating the business logic.