The user wants a program that implements Event Sourcing and CQRS (Command Query Responsibility Segregation) patterns.
-
Understand the Concepts:
- CQRS: Separates the model for updating information (Commands/Write Model) from the model for reading information (Queries/Read Model).
- Event Sourcing: Persists the state of a business entity as a sequence of state-changing events. The current state is derived by replaying these events.
-
Determine the Scope & Language:
- A complete production-grade system is too complex for a single code snippet (requires message brokers, separate databases, etc.).
- I need a conceptual implementation that demonstrates the mechanics clearly.
- Language: Python is good for readability. TypeScript/Node.js is also popular. Let's stick to Python as it's pseudocode-friendly but executable.
-
Design the Domain (The "Example"):
- A "Bank Account" is the classic example. It has clear state changes (Opened, Money Deposited, Money Withdrawn) and clear queries (Get Balance).
-
Architecture Components:
- Events: Immutable facts (e.g.,
AccountOpened, FundsDeposited).
- Aggregate (Write Model): Handles commands, validates business rules, emits events. Holds the current state in memory for validation (e.g., check for overdraft).
- Event Store: Repository to save and retrieve events.
- Projector/Projection (Read Model): Listens to events and updates a read-optimized database (in this case, a simple in-memory dict).
- Command Bus/Service: The entry point for actions.
- Query Service: The entry point for reads.
-
Step-by-Step Implementation Plan:
-
Step 1: Define the Events.
- Base
Event class.
- Specific events:
AccountOpened, MoneyDeposited, MoneyWithdrawn.
-
Step 2: The Event Store.
- Needs
append (save events) and get_events (load history).
-
Step 3: The Aggregate (Write Model).
BankAccount class.
- State fields:
id, balance, is_open.
- Command handlers:
open_account, deposit, withdraw.
- Apply methods: Logic to update internal state based on an event.
_load_from_history: Mechanism to rebuild state.
-
Step 4: The Repository.
- Bridges the Aggregate and the Event Store. Handles the "get" and "save" lifecycle.
-
Step 5: The Read Model (Projections).
- A separate class/list/dict that just stores the final view (e.g.,
{account_id: balance}).
- Needs a method
handle_event to process updates.
-
Step 6: Putting it together (Main).
- Initialize store, repository, read model.
- Execute commands.
- Execute query.
-
Refining the Code (Self-Correction during drafting):
- Initial thought: Should I use a framework?
- Correction: No, frameworks obscure the pattern. Use raw Python classes to show how it works.
- Detail: Make sure to distinguish between "handling a command" (generating an event) and "applying an event" (changing state).
- Concurrency: Ignore for this simple example (optimistic locking is too much boilerplate).
-
Drafting the Code Structure (Mental or scratchpad):
class Event: ...
class AccountOpened(Event): ...
class EventStore:
def save(events): ...
def load(id): ...
class BankAccount:
def __init__(self): self.changes = []
def deposit(amount):
# validate
event = MoneyDeposited(...)
self.apply(event)
self.changes.append(event)
class ReadModel:
balance = {}
def project(event): ...
-
Writing the Explanation:
- Start with a high-level explanation of CQRS + Event Sourcing.
- Explain the specific code components.
- Provide the code.
- Show the output.
-
Review against User Request:
- "Event Sourcing": Yes, storing events.
- "CQRS": Yes, separate read/write paths.
- "Program": Yes, executable code.
-
Final Polish:
- Add comments.
- Ensure variable names are descriptive.
- Add a simulation of "reloading from history" to prove the Event Sourcing part works (e.g., create account -> crash -> reload -> state is restored).
(Self-Correction during coding): I need to ensure the Read Model updates automatically. In a real app, this happens via a message queue. Here, I'll just pass the events directly to the Read Model after saving to the Store.
Let's write the Python solution. It's the most accessible for this pattern.
This is a complete implementation of Event Sourcing and CQRS (Command Query Responsibility Segregation) in Python.
To keep the logic clear without external dependencies (like Kafka or PostgreSQL), this example uses in-memory storage.
The Architecture
- Domain (Write Side): The
BankAccount aggregate. It accepts Commands, validates business rules, and generates Events. It never saves "state," only the stream of events.
- Event Store: The database that appends events to a list.
- Projector (Read Side): Listens to events and updates a flattened "Read Model" (optimized for queries).
- Facade/Service: The entry point that coordinates the write and read sides.
The Implementation
import json
from dataclasses import dataclass, field
from typing import List, Dict, Any, Callable, Union
from datetime import datetime
from copy import deepcopy
# ==========================================
# 1. Events (The facts)
# ==========================================
@dataclass
class Event:
timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
@dataclass
class AccountOpened(Event):
account_id: str = ""
owner: str = ""
@dataclass
class FundsDeposited(Event):
account_id: str = ""
amount: float = 0.0
@dataclass
class FundsWithdrawn(Event):
account_id: str = ""
amount: float = 0.0
# ==========================================
# 2. Commands (The intent)
# ==========================================
@dataclass
class Command:
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
# ==========================================
# 3. Domain Aggregate (Write Model)
# ==========================================
class BankAccount:
def __init__(self):
# Internal state (not persisted directly)
self.account_id = None
self.balance = 0.0
self.is_open = False
self.uncommitted_changes = [] # List of new events
# --- Command Handlers ---
def handle(self, command: Command):
if isinstance(command, OpenAccount):
self._open_account(command)
elif isinstance(command, DepositMoney):
self._deposit(command)
elif isinstance(command, WithdrawMoney):
self._withdraw(command)
def _open_account(self, command: OpenAccount):
if self.is_open:
raise Exception("Account is already open")
# Business logic passed -> Create Event
event = AccountOpened(account_id=command.account_id, owner=command.owner)
self._apply_change(event)
def _deposit(self, command: DepositMoney):
if not self.is_open:
raise Exception("Account is closed")
if command.amount <= 0:
raise Exception("Must deposit positive amount")
event = FundsDeposited(account_id=self.account_id, amount=command.amount)
self._apply_change(event)
def _withdraw(self, command: WithdrawMoney):
if not self.is_open:
raise Exception("Account is closed")
if self.balance < command.amount:
raise Exception("Insufficient funds")
event = FundsWithdrawn(account_id=self.account_id, amount=command.amount)
self._apply_change(event)
# --- Event Sourcing Logic (Apply & Load) ---
def _apply_change(self, event: Event):
"""
1. Updates the in-memory state based on the event.
2. Adds the event to the list of uncommitted changes.
"""
self._mutate(event)
self.uncommitted_changes.append(event)
def _mutate(self, event: Event):
"""Logic to update state based on event type"""
if isinstance(event, AccountOpened):
self.account_id = event.account_id
self.is_open = True
elif isinstance(event, FundsDeposited):
self.balance += event.amount
elif isinstance(event, FundsWithdrawn):
self.balance -= event.amount
def load_from_history(self, history: List[Event]):
"""
Rebuilds the aggregate state by replaying past events.
This is the core of Event Sourcing.
"""
for event in history:
self._mutate(event)
# ==========================================
# 4. Infrastructure (Store & Bus)
# ==========================================
class EventStore:
def __init__(self):
self.events: Dict[str, List[Event]] = {}
def save(self, aggregate_id: str, events: List[Event]):
if aggregate_id not in self.events:
self.events[aggregate_id] = []
self.events[aggregate_id].extend(events)
def get_events(self, aggregate_id: str) -> List[Event]:
return self.events.get(aggregate_id, [])
# ==========================================
# 5. Read Model (Projections) - CQRS
# ==========================================
@dataclass
class AccountSummary:
account_id: str
owner: str
balance: float
transaction_count: int
class InMemoryReadDatabase:
def __init__(self):
self.views: Dict[str, AccountSummary] = {}
def save_view(self, view: AccountSummary):
self.views[view.account_id] = view
def get_view(self, account_id: str) -> AccountSummary:
return self.views.get(account_id)
class Projector:
"""
Listens to events and updates the Read Database.
In a real system, this would be an async subscriber to a message queue.
"""
def __init__(self, read_db: InMemoryReadDatabase):
self.read_db = read_db
def project(self, events: List[Event]):
for event in events:
self._handle(event)
def _handle(self, event: Event):
# Retrieve current view (or create new)
view = self.read_db.get_view(event.account_id)
if isinstance(event, AccountOpened):
view = AccountSummary(
account_id=event.account_id,
owner=event.owner,
balance=0.0,
transaction_count=0
)
elif isinstance(event, FundsDeposited):
view.balance += event.amount
view.transaction_count += 1
elif isinstance(event, FundsWithdrawn):
view.balance -= event.amount
view.transaction_count += 1
self.read_db.save_view(view)
# ==========================================
# 6. Application Service (The Controller)
# ==========================================
class BankService:
def __init__(self, store: EventStore, read_db: InMemoryReadDatabase):
self.store = store
self.projector = Projector(read_db)
def execute(self, command: Command):
# 1. Load Aggregate History
account = BankAccount()
history = self.store.get_events(command.account_id)
account.load_from_history(history)
# 2. Handle Command (Generate Events)
account.handle(command)
# 3. Persist Events (Write Side)
new_events = account.uncommitted_changes
if new_events:
self.store.save(command.account_id, new_events)
# 4. Update Read Model (CQRS Sync)
self.projector.project(new_events)
def get_account_summary(self, account_id: str) -> AccountSummary:
return self.read_db.get_view(account_id)
# ==========================================
# 7. Execution Example
# ==========================================
if __name__ == "__main__":
# Setup Infrastructure
event_store = EventStore()
read_database = InMemoryReadDatabase()
service = BankService(event_store, read_database)
acc_id = "acc-123"
print("--- Executing Commands ---")
# Command 1: Open Account
service.execute(OpenAccount(account_id=acc_id, owner="Alice"))
print(f"Opened account for Alice")
# Command 2: Deposit
service.execute(DepositMoney(account_id=acc_id, amount=100.00))
print(f"Deposited $100")
# Command 3: Withdraw
service.execute(WithdrawMoney(account_id=acc_id, amount=30.00))
print(f"Withdrew $30")
print("\n--- Read Side (CQRS Query) ---")
summary = service.get_account_summary(acc_id)
print(f"Owner: {summary.owner}")
print(f"Balance: ${summary.balance}")
print(f"Transactions: {summary.transaction_count}")
print("\n--- Event Sourcing Verification (Write Side) ---")
raw_events = event_store.get_events(acc_id)
print(f"Total events stored: {len(raw_events)}")
for e in raw_events:
print(f" - {e.__class__.__name__}: {vars(e)}")
Key Concepts to Identify in the Code
-
Event Sourcing (The load_from_history method):
Notice inside the BankService.execute method. We don't fetch a "Bank Account" object from the database. We fetch a history (list of events) and pass it to a new, empty BankAccount instance to rebuild its current state. If you needed to enforce a rule like "Cannot withdraw more than $10,000 in a single day," you could replay the day's events and calculate the sum within the aggregate.
-
CQRS (The Projector):
The BankAccount (Aggregate) cares about consistency and validation. It is complex.
The AccountSummary (Read Model) cares about speed. It is a simple data structure (dataclass).
The Projector decouples the two. If the database fails to save the Read Model, the Event Store has still safely recorded the transaction. You can always rebuild the Read Model later by replaying the events.
-
Immutability:
Events (AccountOpened, FundsDeposited) are never modified. They are only appended to the list.