Serverless Event-Sourcing Platform Design
This design outlines a fully serverless event-sourcing (ES) platform using AWS services (adaptable to GCP/Azure equivalents). It implements CQRS (Command Query Responsibility Segregation), where commands mutate state via events, and queries read from projections. Key principles:
- Immutability: Events are append-only; no deletes/updates.
- Serverless: Lambda, DynamoDB, API Gateway, EventBridge, S3, Step Functions—no servers.
- Scalability: Auto-scales to millions of events/sec (DynamoDB/Kinesis limits apply).
- Fault Tolerance: Idempotency, dead-letter queues (DLQs), retries.
- Cost: Pay-per-use; ~0.01/GBstored,<1/M requests.
High-Level Architecture
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ API Gateway │ │ Command Lambda │ │ DynamoDB Event │
│ (Commands/ │───▶│ (Handler) │───▶│ Store (Streams) │
│ Queries) │ │ - Validate │ │ - PK: aggId │
└─────────────────┘ │ - Load snapshot │ │ - SK: seq#ts#type│
│ + events │ │ - JSON payload │
│ - Emit events │ └──────────┬──────┘
│ - Store snapshot │ │
└──────────────────┘ │ Streams
│
┌──────────────────┐ ▼
│ Snapshots │ ┌──────────────────┐
│ Lambda (Cron) │◄───┤EventBridge Fan- │
└──────────────────┘ │out (Projections) │
└──────────┬──────┘
│
┌─────────────────┐ ▼
│ Read API Gateway│ ┌──────────────────┐ ┌──────────────────┐
│ (Queries Only) │◄───┤Projection Lambdas│◄───┤Read Model DBs │
│ │ │ - Per projection │ │(DynamoDB Tables) │
└─────────────────┘ │ - Idempotent │ │- UserProfiles │
│ - Upcast events │ │- Orders │
└──────────────────┘ └──────────────────┘
│
┌──────────────────┐
│ S3 (Backups, │
│ Snapshots) │
└──────────────────┘
- Traffic Split: Separate API Gateways for commands (write-heavy) vs. queries (read-heavy).
- Async Flow: Commands → Events → Projections (eventual consistency).
- Orchestration: Step Functions for complex sagas (e.g., multi-aggregate commands).
1. Command Handlers
Purpose: Receive commands, validate business rules, load aggregate state, emit events.
Implementation:
- Trigger: API Gateway (HTTP API) → Lambda (Node.js/Python/Go for perf).
- Flow (in single Lambda for simplicity; use Step Functions for sagas):
- Deserialize command (JSON with
aggregateId, expectedVersion, data).
- Optimistic Concurrency: Query Event Store for events up to
expectedVersion + snapshot.
- Rehydrate aggregate by replaying events (in-memory).
- Validate command against current state → Emit 0+ events (immutable JSON:
{type: 'UserCreated|v1', aggregateId, sequence, timestamp, data, metadata}).
- Idempotency: Check
commandId in DynamoDB (TTL 24h).
- TransactWrite to Event Store (atomic: append events + update snapshot).
- Publish to SNS/EventBridge for notifications (optional).
Code Snippet (Pseudo-Python):
def handler(event, context):
cmd = json.loads(event['body'])
events = load_events(cmd['aggregateId'], cmd['expectedVersion']) # Dynamo query
aggregate = Aggregate(cmd['type']).replay(events)
new_events = aggregate.handle(cmd)
if new_events:
transact = [{'Put': event_item(e) for e in new_events}] + snapshot_item(aggregate)
dynamodb.transact_write_items(transact)
return {'statusCode': 201}
- Error Handling: 409 Conflict on version mismatch; DLQ for failures.
- Snapshots: Store every 100 events (or cron Lambda queries streams → S3/DynamoDB).
2. Immutable Storage (Event Store)
DynamoDB Single-Table Design (GSIs for queries):
PK (Partition Key) | SK (Sort Key) | Data (JSON)
----------------------|--------------------------------|-----------------------
aggId | 000001#2024-01-01T00:00:00Z#UserCreated.v1 | {data: {...}, meta: {corrId}}
aggId | SNAPSHOT#100 | {state: {...}, version: 100}
- GSIs:
- GSI1:
GSI1PK=type#timestamp (event sourcing queries).
- GSI2:
GSI2PK=commandId (idempotency).
- Immutability: Use TransactWrite (no updates); enable PITR (Point-in-Time Recovery).
- Streams: DynamoDB Streams (NEW_IMAGE) → Lambda/EventBridge.
- Backup: Streams → Kinesis → S3 (immutable Glacier for compliance).
- Throughput: Auto-scale provisioned; on-demand for bursts.
- Retention: TTL on old snapshots (7 days); events indefinite.
Loading Events:
def load_events(agg_id, from_version):
return dynamodb.query(
KeyConditionExpression='PK = :pk AND SK > :sk',
ExpressionAttributeValues={':pk': agg_id, ':sk': f"{from_version:06d}#"}
)['Items']
3. Projection Pipelines
Purpose: Build denormalized read models from events (e.g., User Profile table).
Implementation:
- Trigger: DynamoDB Streams → EventBridge (fan-out to multiple projections).
- Lambda per Projection (stateless, idempotent):
- Receive event batch.
- Idempotency: Check projection position table (
PK=projectionName, SK=aggId → lastProcessedSeq).
- Upcast event if needed.
- Apply to read model (DynamoDB UpdateItem with condition
sequence > lastSeq).
- Update position atomically.
- Scaling: Provisioned Concurrency for hot projections; batch size 10k.
- Multiple Projections: EventBridge rules route by
event.type (e.g., User* → UserProjection).
- Rebuild: Manual trigger (S3 event replay) or Step Functions.
Code Snippet:
def project(event):
for record in event['Records']:
ev = json.loads(record['dynamodb']['NewImage']['Data'])
if ev.sequence <= get_last_seq(ev.aggregateId): continue
update_read_model(ev) # e.g., $addToSet, $inc
put_position(ev.aggregateId, ev.sequence)
- Read Queries: API Gateway → Lambda → Query GSI on read model tables.
4. Schema Evolution
Strategy: Versioned, backward-compatible events (no breaking changes).
5. Observability
Comprehensive Monitoring (Zero-config where possible):
| Aspect | Tools/Services | Key Metrics/Logs |
|---|
| Tracing | AWS X-Ray (auto-instrument Lambdas) | End-to-end latency (command → projection) |
| Metrics | CloudWatch + Custom (PutMetricData) | Events/sec, Replay time, Projection lag, Error rate |
| Logs | CloudWatch Logs (structured JSON) | {level, corrId, aggId, eventType} |
| Alerts | CloudWatch Alarms + SNS | Lag > 5min, Error >1%, Throughput >90% |
| Dashboards | CloudWatch + Grafana OSS (on ECS Fargate if needed) | Custom: Event volume, Projection health |
| Debug | Lambda Insights, Stream position tables | Replay from seq X via Lambda tester |
- Custom Metrics (in Lambdas):
cloudwatch.put_metric_data(Namespace='ESPlatform', MetricData=[{
'MetricName': 'EventsEmitted', 'Value': len(new_events), 'Dimensions': [{'Name': 'Aggregate', 'Value': agg_type}]
}])
- Health Checks: Lambda cron pings projections (compare event count vs. position).
- Auditing: All events to S3 → Athena for SQL queries (e.g., "find all failed sagas").
Deployment & Ops
- IaC: AWS CDK/Terraform (modular stacks: core, projections).
- CI/CD: CodePipeline → Lambda versions (blue-green).
- Security: IAM least-privilege, API keys, WAF, encrypt everything (KMS).
- Testing:
- Unit: Replay fixtures.
- Integration: LocalStack + Step Functions Local.
- Load: Artillery on API Gateway.
- Cost Optimization: Lambda Power Tuning, Dynamo on-demand, S3 Intelligent-Tiering.
- Limits & Scaling:
| Component | Limit | Mitigation |
|---|
| Lambda | 15min | Async + Step Functions |
| Dynamo | 40k RCU | Sharding by aggId prefix |
| Streams | 2MB/s/shard | Kinesis for >10k events/sec |
This platform supports 1M+ events/day out-of-box; scales horizontally. Prototype in <1 week with CDK. Questions? Let's iterate!