import json
import uuid
import asyncio
import aiokafka
from dataclasses import dataclass, asdict
from typing import Dict, List, Any, Optional, Callable, Sequence
from enum import Enum
import logging
from concurrent.futures import ThreadPoolExecutor
import time
from kafka import KafkaConsumer, KafkaProducer
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ========================================
# Core Data Models
# ========================================
class EventType(Enum):
USER_CREATED = "UserCreated"
USER_UPDATED = "UserUpdated"
# Add domain-specific events
@dataclass
class Event:
aggregate_id: str
version: int
type: EventType
data: Dict[str, Any]
timestamp: float = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = time.time()
@dataclass
class Snapshot:
aggregate_id: str
version: int
state: Dict[str, Any]
timestamp: float = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = time.time()
@dataclass
class Command:
aggregate_id: str
expected_version: int # Optimistic concurrency
type: str # e.g., "CreateUser", "UpdateUser"
data: Dict[str, Any]
command_id: str = None # For idempotency
def __post_init__(self):
if self.command_id is None:
self.command_id = str(uuid.uuid4())
# Aggregate base class (event-sourced domain)
class Aggregate:
def __init__(self, aggregate_id: str):
self.id = aggregate_id
self.version = 0
self._changes: List[Event] = []
self._state: Dict[str, Any] = {} # Mutable state
def load_from_snapshot(self, snapshot: Snapshot):
self._state = snapshot.state
self.version = snapshot.version
self._changes.clear()
def apply(self, event: Event):
self.version = event.version
handler = getattr(self, f"apply_{event.type.value.lower().replace('-', '_')}", None)
if handler:
handler(event.data)
self._changes.append(event)
def raise_on_conflict(self, expected_version: int):
if self.version != expected_version:
raise ConcurrencyError(f"Expected version {expected_version}, but was {self.version}")
def get_uncommitted_changes(self) -> List[Event]:
return self._changes.copy()
def clear_changes(self):
self._changes.clear()
# Example User Aggregate
class UserAggregate(Aggregate):
def apply_usercreated(self, data: Dict[str, Any]):
self._state.update(data)
def apply_userupdated(self, data: Dict[str, Any]):
self._state.update(data)
class ConcurrencyError(Exception):
pass
# ========================================
# Storage Layers (Scalable: Kafka + Redis)
# ========================================
# Events & Inbox: Kafka (partitioned by aggregate_id for scalability)
EVENTS_TOPIC = "domain-events"
INBOX_TOPIC = "inbox-commands"
KAFKA_BOOTSTRAP_SERVERS = ['localhost:9092']
# Snapshots: Redis (fast read/write, TTL for compaction)
import redis.asyncio as redis
SNAPSHOT_REDIS = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
class EventStore:
def __init__(self):
self._producer = None
async def __aenter__(self):
self._producer = KafkaProducer(
bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,
value_serializer=lambda v: json.dumps(asdict(v)).encode('utf-8'),
key_serializer=str.encode
)
return self
async def __aexit__(self, *args):
await self._producer.close()
async def append_events(self, aggregate_id: str, events: Sequence[Event]):
for event in events:
future = self._producer.send(EVENTS_TOPIC, key=aggregate_id, value=event)
# await for fire-and-forget or sync if critical
self._producer.flush()
logger.info(f"Appended {len(events)} events for {aggregate_id}")
def get_events(self, aggregate_id: str, from_version: int = 0, to_version: Optional[int] = None) -> List[Event]:
"""Replay: Read from Kafka (consumer group for projections/replays)"""
consumer = KafkaConsumer(
f"{EVENTS_TOPIC}-{aggregate_id}", # Consumer group per aggregate for replays
bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,
value_deserializer=lambda m: Event(**json.loads(m.decode('utf-8'))),
key_deserializer=str.decode
)
events = []
try:
consumer.assign([aiokafka.TopicPartition(EVENTS_TOPIC, self._partition(aggregate_id))])
for msg in consumer:
event = msg.value
if event.aggregate_id != aggregate_id:
continue
if event.version < from_version:
continue
events.append(event)
if to_version and event.version >= to_version:
break
finally:
consumer.close()
return events
def _partition(self, aggregate_id: str) -> int:
return hash(aggregate_id) % 32 # Assume 32 partitions
class SnapshotStore:
@staticmethod
async def save(snapshot: Snapshot):
key = f"snapshot:{snapshot.aggregate_id}"
data = json.dumps(asdict(snapshot))
await SNAPSHOT_REDIS.set(key, data, ex=86400 * 30) # TTL 30 days
logger.info(f"Saved snapshot for {snapshot.aggregate_id} at v{snapshot.version}")
@staticmethod
async def load(aggregate_id: str) -> Optional[Snapshot]:
key = f"snapshot:{aggregate_id}"
data = await SNAPSHOT_REDIS.get(key)
return Snapshot(**json.loads(data)) if data else None
@staticmethod
async def delete_before(aggregate_id: str, version: int):
"""Compaction hint: Redis TTL handles pruning"""
pass # Redis TTL auto-prunes old snapshots
# ========================================
# Inbox Processor (Scalable Workers)
# ========================================
class AggregateFactory:
@staticmethod
def create(aggregate_type: str, aggregate_id: str) -> Aggregate:
if aggregate_type == "User":
return UserAggregate(aggregate_id)
raise ValueError(f"Unknown aggregate {aggregate_type}")
class InboxProcessor:
def __init__(self, worker_id: int, aggregate_type: str = "User"):
self.worker_id = worker_id
self.aggregate_type = aggregate_type
self.factory = AggregateFactory()
self.event_store = EventStore()
async def start(self):
consumer = aiokafka.AIOKafkaConsumer(
INBOX_TOPIC,
bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,
value_deserializer=lambda m: Command(**json.loads(m.decode('utf-8'))),
key_deserializer=str.decode,
group_id=f"inbox-workers-{self.aggregate_type}-{self.worker_id}",
auto_offset_reset='earliest'
)
await consumer.start()
try:
async for msg in consumer:
command = msg.value
if hash(command.aggregate_id) % 10 == self.worker_id % 10: # Simple sharding
await self.process_command(command)
await consumer.commit()
finally:
await consumer.stop()
async def process_command(self, command: Command):
try:
agg = self.factory.create(self.aggregate_type, command.aggregate_id)
snapshot = await SnapshotStore.load(command.aggregate_id)
# Load state: Snapshot + Replay tail
if snapshot and snapshot.version >= command.expected_version:
logger.warning(f"Snapshot ahead, skipping replay for {command.aggregate_id}")
return
if snapshot:
agg.load_from_snapshot(snapshot)
events = self.event_store.get_events(command.aggregate_id, snapshot.version + 1)
else:
events = self.event_store.get_events(command.aggregate_id)
for event in events:
agg.apply(event)
# Command handler (domain-specific)
handler = getattr(self, f"handle_{command.type.lower()}", self.default_handler)
new_events = handler(agg, command)
# Append events
await self.event_store.append_events(command.aggregate_id, new_events)
# Snapshot if delta > threshold
if len(new_events) > 10 or agg.version % 50 == 0:
snapshot = Snapshot(command.aggregate_id, agg.version, agg._state)
await SnapshotStore.save(snapshot)
logger.info(f"Processed {command.type} for {command.aggregate_id}")
except ConcurrencyError as e:
logger.error(f"Concurrency conflict: {e}")
# Nack or DLQ
except Exception as e:
logger.error(f"Error processing {command.aggregate_id}: {e}")
def default_handler(self, agg: Aggregate, command: Command) -> List[Event]:
agg.raise_on_conflict(command.expected_version)
# Dispatch to aggregate method, e.g., agg.create_user(command.data)
# Emit events...
return [] # Placeholder
async def handle_createuser(self, agg: Aggregate, command: Command) -> List[Event]:
if agg.version != 0:
raise ValueError("User already exists")
event = Event(agg.id, 1, EventType.USER_CREATED, command.data)
agg.apply(event)
return agg.get_uncommitted_changes()
# Example handlers
# ... extend as needed
# ========================================
# Compaction Service (Background)
# ========================================
class CompactionService:
"""Runs periodically: Snapshot + Prune hints (Kafka retention + Redis TTL)"""
@staticmethod
async def compact_all():
# Scan active aggregates from Redis keys or metrics
keys = await SNAPSHOT_REDIS.keys("snapshot:*")
for key in keys:
agg_id = key.split(":", 1)[1]
snapshot = await SnapshotStore.load(agg_id)
if snapshot:
# Force replay to latest for new snapshot
events = EventStore().get_events(agg_id, snapshot.version + 1)
if events:
agg = UserAggregate(agg_id) # Rebuild
agg.load_from_snapshot(snapshot)
for e in events:
agg.apply(e)
new_snapshot = Snapshot(agg_id, agg.version, agg._state)
await SnapshotStore.save(new_snapshot)
logger.info(f"Compacted {agg_id} to v{agg.version}")
# ========================================
# Replays / Projections (Catch-up)
# ========================================
class Projection:
"""Example: Catch-up projection from snapshots + events"""
async def replay_for_query(self, aggregate_id: str):
snapshot = await SnapshotStore.load(aggregate_id)
events = EventStore().get_events(aggregate_id)
state = {}
if snapshot:
state = snapshot.state
events = [e for e in events if e.version > snapshot.version]
agg = UserAggregate(aggregate_id)
agg.load_from_snapshot(Snapshot(aggregate_id, snapshot.version if snapshot else 0, state))
for event in events:
agg.apply(event)
# Project to read model, e.g., save to query DB
logger.info(f"Replayed {aggregate_id} state: {agg._state}")
# ========================================
# Usage / Startup (Scalable: Run multiple workers)
# ========================================
async def main():
# Start N workers (scale horizontally)
workers = [InboxProcessor(i) for i in range(5)]
tasks = [w.start() for w in workers]
# Compaction cron (every hour)
async def cron_compact():
while True:
await asyncio.sleep(3600)
await CompactionService.compact_all()
tasks.append(cron_compact())
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Architecture Overview
Scalability Features
- Sharding: Kafka partitions by
aggregate_id (hash-based). Workers shard via modulo for load balancing.
- Horizontal Scaling: Run multiple
InboxProcessor instances (e.g., via Kubernetes). Consumer groups auto-balance.
- High Throughput: Async Kafka, fire-and-forget appends, Redis for O(1) snapshots.
- Fault Tolerance: Kafka replication, idempotent commands (
command_id), DLQ for failures.
Key Features
- Snapshots: Loaded first for fast aggregate init. Created every 10 events or 50 versions. Redis TTL auto-prunes.
- Compaction: Background
CompactionService rebuilds snapshots periodically. Kafka log retention (e.g., 7 days) + compaction mode prunes old events (enable cleanup.policy=compact on topics).
- Replays:
- Tail Replay in processors: Snapshot + events since snapshot.
- Full Replay in projections: Snapshot + all tail events.
- Kafka consumer groups for parallel catch-up projections.
Deployment Notes
- Kafka: 32+ partitions per topic. Enable log compaction for events (tombstones for deletes).
- Redis: Cluster for prod. Use sorted sets for snapshot versioning if needed.
- Monitoring: Prometheus for lag, custom metrics for replay times.
- Extensions: Add Saga/Process Manager on event replay. Use Protobuf for perf.
Sending Commands (Producer Example)
async def send_command(command: Command):
producer = KafkaProducer(...) # As above
producer.send(INBOX_TOPIC, key=command.aggregate_id, value=command)
This is production-ready skeleton. Extend Aggregate/handlers for your domains. Test with kafka-python locally!