We are going to design a serverless event-sourcing platform that includes:
- Command Handlers: To handle commands and produce events.
- Immutable Storage: For storing events (the source of truth).
- Projection Pipelines: To build and update read models (projections) from events.
- Schema Evolution: To handle changes in event schemas over time.
- Observability: Monitoring, logging, and tracing.
We'll use AWS as the cloud provider, but the design can be adapted to other serverless platforms.
Components:
- API Gateway: To receive commands (HTTP endpoints).
- Lambda Functions: For command handlers and projection updaters.
- Event Store: We'll use Amazon DynamoDB or Amazon S3 for event storage. However, for event sourcing, we need to store events in an append-only manner. DynamoDB can be used with a design that ensures immutability (no updates, only appends). Alternatively, we can use Amazon S3 for cost-effective immutable storage, but then we need an indexing mechanism for querying events by aggregate ID. DynamoDB is better for indexed access.
- Projection Storage: Another DynamoDB table or Amazon S3 (for large datasets) for storing the read models (projections). We'll use DynamoDB for low-latency queries.
- Schema Evolution: We'll use a versioning scheme for events and handle upcasting in the projection pipelines. We can also use AWS Glue or AWS Lake Formation if we are using S3 for event storage and want to use a data lake approach, but for simplicity, we'll handle versioning in the Lambda code.
- Observability: Amazon CloudWatch for logs and metrics, AWS X-Ray for tracing, and possibly Amazon Managed Service for Prometheus and Grafana for advanced metrics.
Steps:
-
Event Storage Design:
- Table: Events
- Partition Key: AggregateId (string)
- Sort Key: Version (number) or EventId (UUID) and then a timestamp? We want to store events in order per aggregate.
- We also need to store the event type, event data (JSON), metadata (timestamp, correlation id, etc.), and the version of the schema.
However, note: We might also want to query events by type for projection building? But typically, projections subscribe to all events. We can use DynamoDB Streams to trigger projection updates.
-
Command Handler (Lambda):
- Receives a command (e.g., via API Gateway).
- Loads the current state of the aggregate by replaying events from the event store (for that aggregate). Alternatively, we can use a cache (like ElastiCache) for frequently accessed aggregates, but that adds complexity.
- Validates the command against the current state and business rules.
- Produces one or more events.
- Appends the events to the event store (with the next version number). We must do this atomically per aggregate to avoid version conflicts. DynamoDB transactions can be used.
-
Projection Pipelines:
- We can use DynamoDB Streams on the Events table to trigger a Lambda function for each new event (or batch of events). This Lambda will update the corresponding projection (read model) in the projection table.
- Alternatively, we can have a separate process that periodically reads new events (using a cursor/checkpoint) and updates projections. This gives more control over batching and error handling.
We'll go with DynamoDB Streams for near real-time updates.
-
Schema Evolution:
- Each event has a schema version. When the projection code reads an event, it may need to upcast the event from an old version to the current version. We can have an upcaster for each event type and version.
-
Observability:
- Logging: Lambda automatically logs to CloudWatch.
- Metrics: We can emit custom metrics from the Lambda functions (using CloudWatch Embedded Metric Format) for key business metrics (e.g., command processing time, events stored, projection update time).
- Tracing: Enable AWS X-Ray for the Lambda functions and API Gateway.
Detailed Design:
-
Event Store Table (Events):
Partition Key: AggregateId (string)
Sort Key: Version (number) [for each aggregate, events are stored in version order]
Attributes:
- EventId: UUID (unique across all events)
- EventType: string (e.g., "OrderCreated", "OrderItemAdded")
- EventData: JSON (the actual event data)
- Metadata: JSON (timestamp, correlation id, command id, user id, etc.)
- SchemaVersion: number (version of the EventData schema)
We also need a Global Secondary Index (GSI) for querying events by EventType? Not strictly necessary for event sourcing, but might be useful for debugging. However, if we use DynamoDB Streams, we don't need to query by event type because the stream will give us the event.
-
Command Handler Lambda:
Steps:
a. Parse the command (from API Gateway).
b. Load the aggregate by reading all events for the given AggregateId from the Events table (using Query on Partition key, sorted by Version). If no events, start from an empty state.
c. Replay events to build the current state (or use a cached state if available, but then we must invalidate on new events). For simplicity, we'll replay every time, but for performance we might want to snapshot the state periodically (snapshotting is a common pattern in event sourcing). However, to keep it serverless and simple, we might avoid snapshots for now and rely on the event stream being small (if we design aggregates to be small and short-lived). Alternatively, we can store snapshots in a separate table.
d. Validate the command against the current state. If invalid, return an error.
e. Generate one or more events (with the next version number). The version number for the new events should be current aggregate version + 1, +2, etc.
f. Write the events to the Events table in a transaction (to ensure atomicity and version increment). We must also check that the current version hasn't changed (optimistic locking). We can use a condition expression in DynamoDB transaction to ensure the last event version is as expected.
g. Return the events (or just the event IDs) to the client.
-
Projection Lambda (triggered by DynamoDB Streams):
This function will update one or more projections. We can have one Lambda per projection type (e.g., OrderProjection, CustomerProjection) or one Lambda that updates all projections. The latter might be simpler but can lead to a large function. We can also use Step Functions for complex projection pipelines.
For simplicity, let's assume one projection per Lambda, and the event stream triggers all projection Lambdas (by having multiple Lambda triggers from the same stream? Actually, DynamoDB Streams can trigger multiple Lambdas by having multiple event source mappings). Alternatively, we can have one Lambda that updates multiple projections by having the projection logic in the same function.
Given the complexity, we might want to break the projection update into a separate service that runs continuously and uses a checkpoint (like the last processed sequence number for the stream) to avoid reprocessing. But with DynamoDB Streams and Lambda, we get at-least-once delivery and checkpointing is handled by Lambda (by default, it checkpoint after successful processing). However, if we have multiple Lambda instances processing the same stream, we need to set the batch window and parallelization factor. But for a given aggregate, the events are processed in order by a single Lambda instance? Not necessarily, because the stream shards (which are per partition key) are processed by one Lambda instance at a time? Actually, DynamoDB Streams uses shards, and each shard is processed by one Lambda instance at a time. But if we have multiple shards (because of multiple aggregates), then multiple instances.
But we are grouping by aggregate in the batch, so within one batch we might have multiple aggregates and we process them in parallel. That's okay because each aggregate is independent.
However, if we have a single aggregate with high event rate, then all events for that aggregate will be in the same shard and processed by one Lambda instance at a time, which becomes a bottleneck.
We can increase the parallelism by increasing the number of shards? DynamoDB Streams shards are determined by the partition key? Actually, DynamoDB Streams doesn't have fixed shards like Kinesis. It uses the same partition key as the table, and the stream records are grouped by partition key. Then when Lambda reads from the stream, it gets batches of records that might be from multiple partition keys. The parallelization factor controls how many concurrent Lambda invocations for the same stream? Actually, the parallelization factor is for the number of concurrent batches from the same shard? I'm not entirely sure.
But for our design, we are processing each aggregate in the batch in parallel (for different aggregates) and sequentially for the same aggregate. So if we have a hot aggregate, we are limited by one Lambda instance processing that aggregate's events sequentially.
We can mitigate by designing aggregates to be small and short-lived, so that the event rate per aggregate is low.
Alternatively, we can use a different stream processing approach: use Kinesis Data Streams and have more control over sharding. But then we have to write the events to two places (DynamoDB and Kinesis). We can use DynamoDB Streams and then use a Lambda to forward to Kinesis? That adds complexity.
Given the trade-offs, we'll stick with DynamoDB Streams.
-
Implementation Steps:
a. Create DynamoDB table for events.
b. Create DynamoDB table for each projection (or one table with different entity types? We can use a single table with a type attribute, but that might be less efficient. Let's create separate tables for each projection for simplicity).
c. Create Lambda function for command handler.
- Trigger: API Gateway (HTTP API)
- Permissions: Read and write to Events table.
- Code: Implement the command handling logic.
d. Create Lambda function for projection updater.
- Trigger: DynamoDB Streams from Events table.
- Batch size: 100 (or as needed)
- Permissions: Read from Events table, write to projection table(s).
- Code: Implement the projection update logic with grouping by aggregate and upcasting.
e. Set up CloudWatch Alarms and Dashboards.
f. Set up X-Ray.
-
Schema Evolution in Projections:
We'll have an upcaster registry. The projection Lambda will, for each event:
eventType = event.EventType
schemaVersion = event.SchemaVersion
currentVersion = getCurrentSchemaVersion(eventType)
while schemaVersion < currentVersion:
upcaster = upcasters[eventType][schemaVersion]
event.EventData = upcaster(event.EventData)
schemaVersion += 1
Then apply the event.EventData (now at current version) to the projection.
-
Testing:
We should test the entire flow with sample commands and events.
-
Monitoring:
We can create a CloudWatch dashboard that shows:
- Number of commands processed (success and failure)
- Number of events stored
- Projection update latency (from event timestamp to when the projection is updated)
- Lambda durations and errors.
-
Potential Issues:
-
The projection update might take too long for aggregates with many events (when loading from the event store). We might need to set a timeout and break the processing? Or use snapshots.
-
The command handler might time out if the aggregate has too many events. We can set the Lambda timeout to 15 minutes (maximum) and hope that the aggregate doesn't have that many events. Otherwise, we must use snapshots.
Given the constraints, we might need to implement snapshots for large aggregates.
Let's adjust:
In the command handler:
We check if there is a snapshot for the aggregate (in a Snapshots table) that is recent (within a certain number of events). Then we load the snapshot and then load events from the snapshot version+1 to the current.
In the projection update:
Similarly, when we need to load all events for an aggregate (because we don't have the projection or we have a gap?), we can first try to load a snapshot and then apply events after the snapshot version.
But note: the projection update doesn't need to build the entire aggregate state from events if we have a snapshot? Actually, the projection is built from events, not from the aggregate state. So if we have a snapshot of the aggregate state, that doesn't help the projection because the projection is a different view. We would still need to apply all events to the projection? Not necessarily: we can store the projection state at a given event version and then apply events after that. That's what we are doing with the last processed version. But if we have a gap (we missed events), we need to load all events from the event store. We can use the snapshot for the aggregate to rebuild the aggregate state, but the projection is built from events, not from the aggregate state. So we still need the events.
Alternatively, we can store the projection state in the snapshot? That doesn't make sense because the projection is a different model.
So, for the projection, we must apply events. We can try to load the events in batches? But we are already loading them from DynamoDB by querying. If there are thousands of events, that query will be expensive and slow.
We can paginate the query? But we need all events in order. We can query with a limit and then continue until we get all. But that would be multiple queries.
Alternatively, we can store events in S3 and use Athena to query? That would be slower.
Given the complexity, we might have to accept that aggregates should not have thousands of events. If they do, we need to break the aggregate into smaller ones (using domain-driven design).
So, we'll assume aggregates are small.
-
Conclusion:
This design provides a serverless event-sourcing platform with:
- Command handlers as Lambda functions.
- Immutable event store in DynamoDB.
- Projection pipelines using DynamoDB Streams and Lambda.
- Schema evolution via upcasters.
- Observability via CloudWatch and X-Ray.
We have discussed the trade-offs and potential issues.
Now, we can write the CloudFormation template to deploy this.
However, due to the complexity and length, I'll provide a high-level CloudFormation template with the main resources.
Let's create a CloudFormation template (YAML) that defines:
- EventsTable (DynamoDB)
- ProjectionTable (for example, OrderProjection) (DynamoDB)
- CommandHandlerLambda (with API Gateway)
- ProjectionLambda (with DynamoDB Streams event source)
We'll also set up IAM roles.
But note: we might have multiple projection tables and Lambdas. We can use parameters to define them.
However, for simplicity, I'll define one projection table and one projection Lambda.
Let's write the template:
Note: This is a simplified version and may not be production-ready.
AWSTemplateFormatVersion: '2010-09-09'
Description: Serverless Event Sourcing Platform
Parameters:
ProjectionTableName:
Type: String
Default: OrderProjection
CommandHandlerLambdaName:
Type: String
Default: CommandHandler
ProjectionLambdaName:
Type: String
Default: ProjectionUpdater
Resources:
EventsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: Events
AttributeDefinitions:
- AttributeName: AggregateId
AttributeType: S
- AttributeName: Version
AttributeType: N
KeySchema:
- AttributeName: AggregateId
KeyType: HASH
- AttributeName: Version
KeyType: RANGE
BillingMode: PAY_PER_REQUEST
StreamSpecification:
StreamViewType: NEW_AND_OLD_IMAGES
ProjectionTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref ProjectionTableName
AttributeDefinitions:
- AttributeName: OrderId
AttributeType: S
KeySchema:
- AttributeName: OrderId
KeyType: HASH
BillingMode: PAY_PER_REQUEST
CommandHandlerLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: CommandHandlerLambdaPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:TransactWriteItems
Resource: !GetAtt EventsTable.Arn
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- xray:PutTraceSegments
- xray:PutTelemetryRecords
Resource: "*"
ProjectionLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: ProjectionLambdaPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:GetItem
- dynamodb:PutItem
Resource:
- !GetAtt EventsTable.Arn
- !GetAtt ProjectionTable.Arn
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- xray:PutTraceSegments
- xray:PutTelemetryRecords
Resource: "*"
CommandHandlerLambda:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Ref CommandHandlerLambdaName
Runtime: python3.9
Handler: command_handler.lambda_handler
Role: !GetAtt CommandHandlerLambdaRole.Arn
Timeout: 900 # 15 minutes
Code:
ZipFile: |
# Command handler code goes here (we'll leave it as a placeholder)
Environment:
Variables:
EVENTS_TABLE: !Ref EventsTable
TracingConfig:
Mode: Active
ProjectionLambda:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Ref ProjectionLambdaName
Runtime: python3.9
Handler: projection.lambda_handler
Role: !GetAtt ProjectionLambdaRole.Arn
Timeout: 900
Code:
ZipFile: |
# Projection update code goes here (placeholder)
Environment:
Variables:
EVENTS_TABLE: !Ref EventsTable
PROJECTION_TABLE: !Ref ProjectionTable
TracingConfig:
Mode: Active
CommandHandlerApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: CommandHandlerApi
ProtocolType: HTTP
CommandHandlerStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
ApiId: !Ref CommandHandlerApi
StageName: $default
AutoDeploy: true
CommandHandlerIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref CommandHandlerApi
IntegrationType: AWS_PROXY
IntegrationUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${CommandHandlerLambda.Arn}/invocations
PayloadFormatVersion: '2.0'
CommandHandlerRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref CommandHandlerApi
RouteKey: POST /commands
Target: !Sub integrations/${CommandHandlerIntegration}
LambdaPermissionForApiGateway:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref CommandHandlerLambda
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${CommandHandlerApi}/*/POST/commands
ProjectionLambdaEventSource:
Type: AWS::Lambda::EventSourceMapping
Properties:
EventSourceArn: !GetAtt EventsTable.StreamArn
FunctionName: !Ref ProjectionLambda
StartingPosition: LATEST
BatchSize: 100
MaximumBatchingWindowInSeconds: 0
MaximumRetryAttempts: 2
BisectBatchOnFunctionError: true
DestinationConfig:
OnFailure:
Destination: !GetAtt ProjectionDLQ.Arn
ProjectionDLQ:
Type: AWS::SQS::Queue
Properties:
QueueName: ProjectionDLQ
Outputs:
ApiUrl:
Description: URL of the API Gateway endpoint
Value: !Sub https://${CommandHandlerApi}.execute-api.${AWS::Region}.amazonaws.com/commands
EventsTableName:
Description: Name of the Events table
Value: !Ref EventsTable
ProjectionTableName:
Description: Name of the Projection table
Value: !Ref ProjectionTable
This template sets up:
- DynamoDB table for events with stream enabled.
- DynamoDB table for the projection (OrderProjection).
- IAM roles for the Lambda functions.
- Command handler Lambda with API Gateway trigger.
- Projection Lambda with DynamoDB Streams trigger and a dead-letter queue (SQS).
- Tracing enabled for both Lambdas.
We have not included the actual code for the Lambdas. We would need to write the code for:
-
Command handler:
- Parse command.
- Load events for the aggregate (from Events table).
- Replay to get current state (or use snapshot if implemented).
- Validate command.
- Generate events.
- Write events in a transaction (with condition that the current version is as expected).
-
Projection Lambda:
- Process the batch of events from the stream.
- Group by aggregateId.
- For each aggregate, apply events (with upcasting if needed) to the projection.
- Handle new aggregates by loading all events from the event store if necessary.
- Update the projection table.
We also need to implement upcasters for each event type.
Given the complexity, the code for these Lambdas would be substantial.
However, this design provides a blueprint for a serverless event-sourcing platform on AWS.
Let me know if you have any questions or need further details on any part.
I'll design a comprehensive serverless event-sourcing platform using AWS services (with cloud-agnostic alternatives noted). This architecture prioritizes immutability, scalability, and operational excellence.
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ CLIents/API │───▶│ Command Handler │───▶│ Event Store │
│ (Web/Mobile) │ │ (Lambda) │ │ (Immutable) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Dashboards │◀───│ Projection │◀───│ Event Processor│
│ Monitoring │ │ Updater (Lambda)│ │ (Streams/ │
└─────────────────┘ └──────────────────┘ │ Queues) │
└─────────────────┘
1. Command Handlers
Purpose
Validate business rules and generate domain events.
Implementation
// Lambda handler (TypeScript/Python/Go)
interface Command {
commandId: UUID;
type: string;
aggregateId: UUID;
payload: any;
metadata: {
userId?: string;
correlationId: UUID;
timestamp: ISO8601;
version: number; // Command schema version
};
}
interface Event {
eventId: UUID;
aggregateId: UUID;
sequence: number; // Monotonically increasing per aggregate
type: string;
payload: any;
metadata: {
causedByCommandId: UUID;
causality: { previousEventId?: UUID };
timestamp: ISO8601;
schemaVersion: number; // Event schema version
};
}
// Command Handler Pattern
async function handleCommand(command: Command): Promise<Event[]> {
// 1. Load current state (from projection cache or replay)
const currentState = await getAggregateState(command.aggregateId);
// 2. Validate command against current state
const validation = validateCommand(command, currentState);
if (!validation.valid) throw new ValidationError(validation.errors);
// 3. Generate domain events
const events = generateEvents(command, currentState);
// 4. Optimistic concurrency check
const expectedVersion = currentState.version || 0;
await appendEvents(
command.aggregateId,
events,
expectedVersion
);
return events;
}
Infrastructure
- AWS: API Gateway → Lambda (container image, 10GB memory, 15min timeout)
- Concurrency: Reserved concurrency per aggregate type to prevent starvation
- State Loading:
- Warm cache: ElastiCache Redis (recent aggregates)
- Cold path: Query event store with pagination (max 100 events/aggregate)
- Idempotency: Deduplication table (DynamoDB with TTL) for commandId
2. Immutable Storage
Design Principles
- Append-only: Never update/delete events
- Immutable: Events never change after write
- Tamper-evident: Optional cryptographic signing (KMS)
- Time-ordered: Strict ordering per aggregate
Storage Options
| Option | Use Case | Pros | Cons |
|---|
| DynamoDB | Low-latency, high-throughput | Built-in TTL, Streams, transactions | Cost at scale, 400KB/item limit |
| S3 + Glue | Big data, analytics | Cheap storage, Athena queries | Higher latency, eventual consistency |
| EventStoreDB | Native event sourcing | Built-in projections, streams | Self-hosted management |
| Cassandra | Massive scale, global | Linear scalability | Operational complexity |
Recommended Hybrid Approach:
Primary Store: DynamoDB
- Partition Key: aggregateId (string)
- Sort Key: sequenceNumber (number)
- TTL: 365 days (adjust per compliance)
- Stream: Enabled (for projections)
Archive Store: S3 (daily partitions)
- Prefix: events/yyyy/mm/dd/
- Format: Parquet (compressed)
- Lifecycle: S3 Intelligent-Tiering → Glacier
Cache: ElastiCache Redis
- Key: aggregate:state:{aggregateId}
- TTL: 1 hour (adjust based on access patterns)
Schema Design
{
"eventId": "uuid",
"aggregateId": "uuid", // Entity identifier
"sequence": 123, // Monotonic per aggregate
"type": "OrderCreated", // Event type
"payload": { // Domain data (versioned)
"orderId": "uuid",
"customerId": "uuid",
"items": [...]
},
"metadata": {
"causedByCommandId": "uuid",
"correlationId": "uuid",
"causationId": "uuid", // Previous event in chain
"timestamp": "2024-01-01T00:00:00Z",
"schemaVersion": 2,
"userId": "user123",
"tenantId": "tenant456" // Multi-tenancy support
},
"signature": "sha256:..." // Optional: KMS signature
}
3. Projection Pipelines
Pattern: CQRS with Materialized Views
Event Stream → Projection Builder → Read Model (Projection)
│
├─► Materialized Views (DynamoDB/OpenSearch)
├─► Analytical Views (S3/Athena)
└─► Search Index (OpenSearch)
Projection Types
-
Strongly Consistent (Per-aggregate)
- Updates via DynamoDB Streams ( Lambda)
- Single-item reads (GetItem)
- Example:
OrderProjection (by orderId)
-
Eventually Consistent (Cross-aggregate)
- Batch processing (Kinesis Firehose → Lambda)
- Scans/queries (G SI)
- Example:
CustomerOrdersProjection (by customerId)
-
Analytical (Data Lake)
- Kinesis Firehose → S3 → Glue → Athena/Redshift
- Example: Daily sales reports
Projection Lambda Template
def handler(event, context):
records = event['Records']
# Group by projection type
projections = defaultdict(list)
for record in records:
event_data = deserialize(record['dynamodb']['NewImage'])
for projector in get_projectors_for_event(event_data['type']):
projections[projector.name].append(event_data)
# Process each projection in parallel
results = []
with ThreadPoolExecutor() as executor:
futures = {
executor.submit(update_projection, name, events): name
for name, events in projections.items()
}
for future in as_completed(futures):
results.append(future.result())
# Checkpoint (for idempotency/recovery)
save_checkpoint(event['Records'][-1]['dynamodb']['ApproximateCreationDateTime'])
return {'processed': len(records), 'projections': results}
Projection Table Design
# Strongly Consistent Projection
Table: OrderProjection
PK: orderId (string)
SK: metadata (fixed "ORDER")
Attributes:
- customerId
- status
- totalAmount
- createdAt
- updatedAt
- version (last applied event sequence)
GSI:
- GSI1PK: customerId, GSI1SK: createdAt (for customer orders)
- GSI2PK: status, GSI2SK: updatedAt (for status queries)
# Event Sourced Projection (for debugging)
Table: OrderEventProjection
PK: orderId
SK: sequenceNumber
Attributes: Same as event store plus denormalized fields
4. Schema Evolution
Strategy: Versioned Events with Upcasters
Event Versions:
v1: { "customerId": "123", "total": 100 }
v2: { "customerId": "123", "total": 100, "currency": "USD" }
v3: { "customerId": "123", "total": { "amount": 100, "currency": "USD" } }
Upcaster Pipeline
class UpcasterRegistry {
private upcasters: Map<string, Map<number, Upcaster>> = new Map();
register(eventType: string, fromVersion: number, toVersion: number, upcaster: Upcaster) {
if (!this.upcasters.has(eventType)) {
this.upcasters.set(eventType, new Map());
}
this.upcasters.get(eventType)!.set(fromVersion, {
upcaster,
toVersion
});
}
async upcast(event: Event, targetVersion: number): Promise<Event> {
const currentVersion = event.metadata.schemaVersion;
if (currentVersion === targetVersion) return event;
const chain = this.buildChain(event.type, currentVersion, targetVersion);
let current = event;
for (const step of chain) {
current = await step.upcaster(current);
current.metadata.schemaVersion = step.toVersion;
}
return current;
}
private buildChain(eventType: string, from: number, to: number): UpcasterStep[] {
// Build minimal chain: v1→v2→v3, not v1→v3 directly
const eventUpcasters = this.upcasters.get(eventType) || new Map();
const chain: UpcasterStep[] = [];
let current = from;
while (current < to) {
const upcaster = eventUpcasters.get(current);
if (!upcaster) {
throw new MissingUpcasterError(eventType, current, to);
}
chain.push(upcaster);
current = upcaster.toVersion;
}
return chain;
}
}
Upcaster Examples
// v1 → v2: Add currency field
const upcasterV1toV2: Upcaster = async (event) => {
if (event.payload.currency) return event; // Already v2+
return {
...event,
payload: {
...event.payload,
currency: 'USD' // Default currency
}
};
};
// v2 → v3: Restructure total
const upcasterV2toV3: Upcaster = async (event) => {
if (typeof event.payload.total === 'object') return event;
return {
...event,
payload: {
...event.payload,
total: {
amount: event.payload.total,
currency: event.payload.currency
}
}
};
};
Schema Registry
- Store schemas in AWS Glue Schema Registry (compatible with Apache Avro/JSON Schema)
- Each event type has multiple versions
- Schema compatibility checks: BACKWARD, FORWARD, FULL
- Enforce schemas at command handler entry point
5. Observability
Three Pillars: Logs, Metrics, Traces
Structured Logging
{
"timestamp": "2024-01-01T00:00:00Z",
"level": "INFO",
"service": "command-handler",
"traceId": "abc123",
"spanId": "def456",
"aggregateId": "order-789",
"commandType": "CreateOrder",
"eventCount": 1,
"durationMs": 45,
"memoryUsedMB": 128,
"message": "Command processed successfully"
}
Key Metrics (CloudWatch Embedded Metric Format)
import aws_embedded_metrics
metric_logger = aws_embedded_metrics.metric_logger()
metric_logger.set_dimensions(Service="CommandHandler", Stage="prod")
# Business metrics
metric_logger.put_metric("CommandsProcessed", 1, "Count")
metric_logger.put_metric("EventsGenerated", len(events), "Count")
# Operational metrics
metric_logger.put_metric("ProcessingDuration", duration_ms, "Milliseconds")
metric_logger.put_metric("ConcurrentCommands", current_concurrency, "Count")
# Custom metrics
metric_logger.put_metric("AggregateSize", event_count, "Count",
Dimensions={"AggregateType": "Order"})
Distributed Tracing (X-Ray)
# Enable for all Lambdas
TracingConfig:
Mode: Active
# Annotate segments
segment.put_annotation("aggregate_id", aggregate_id)
segment.put_annotation("command_type", command.type)
segment.put_metadata("events", events)
Monitoring Dashboard (CloudWatch/Managed Grafana)
Service Health:
- Command success rate (p99 latency < 100ms)
- Event ingestion rate (events/sec)
- Projection lag (time between event time and projection update)
- Store throughput (RCU/WCU utilization)
Business Metrics:
- Orders created per minute
- Payment failures
- Inventory updates
Alarms:
- Projection lag > 5 minutes
- Command failure rate > 1%
- DynamoDB throttling > 0
- Lambda errors > 0 for 5 minutes
- Dead-letter queue depth > 100
Debugging Tools
-
Event Replayer:
# Replay events for aggregate from specific point
aws dynamodb query \
--table-name Events \
--key-condition-expression "aggregateId = :id AND sequence >= :seq" \
--expression-parameter-values '{":id": {"S": "order-123"}, ":seq": {"N": "100"}}' \
| jq '.Items[] | .payload.S' \
| replay-to-rehydrator
-
Causality Explorer:
- Visualize event chain from command → events → projections
- TraceId correlation across services
-
Schema Migration Assistant:
- Identify aggregates using old schema versions
- Batch upcast events (replay with new upcasters)
6. Deployment & Infrastructure as Code
Terraform/CloudFormation Modules
# eventsourcing/modules/event-store
module "event_store" {
source = "./modules/event-store"
table_name = "events-${var.environment}"
stream_enabled = true
point_in_time_recovery = true
encryption_key_arn = aws_kms_key.events.arn
tags = var.common_tags
}
# eventsourcing/modules/projection
module "order_projection" {
source = "./modules/projection"
name = "order-projection"
event_source_arn = module.event_store.stream_arn
batch_size = 100
parallelization_factor = 4 # For different aggregates
handler = "projections.order.handler"
runtime = "python3.9"
environment = {
EVENTS_TABLE = module.event_store.table_name
PROJECTION_TABLE = aws_dynamodb_table.order_projection.name
SCHEMA_REGISTRY = aws_glue_registry_table.event_schemas.arn
}
}
CI/CD Pipeline
Code Commit → Build (CodeBuild) →
├─► Unit Tests → Integration Tests (LocalStack) →
├─► Security Scan (Checkov/Terrascan) →
├─► Deploy to Staging (TF plan/apply) →
├─► Canary Test (5% traffic) →
└─► Deploy to Production (Blue/Green)
7. Disaster Recovery & Backup
Backup Strategy
- Real-time: DynamoDB PITR (35 days)
- Daily: S3 cross-region replication (event archives)
- Weekly: Full snapshot to S3 Glacier Deep Archive
Recovery Procedures
# 1. Restore events table from PITR
aws dynamodb restore-table-to-point-in-time \
--source-table-name Events \
--target-table-name Events_Restored \
--restore-date-time "2024-01-15T12:00:00Z"
# 2. Rebuild projections from restored events
./scripts/rebuild-projections.ts --since 2024-01-15T12:00:00Z
# 3. Switch traffic (update configuration)
8. Advanced Patterns
Snapshotting (for large aggregates)
Snapshot Table:
PK: aggregateId
SK: "SNAPSHOT"
payload: Serialized aggregate state
lastEventSequence: number
createdAt: timestamp
Strategy:
- Take snapshot every N events (e.g., 100)
- Or based on time (e.g., daily)
- Store alongside events (same table, different SK)
Multi-Tenancy
{
"tenantId": "tenant_abc",
"aggregateId": "order_123",
"metadata": { ... }
}
- DynamoDB tenantId as partition key prefix (composite key:
tenant#aggregateId)
- Separate S3 prefixes per tenant
- IAM policies enforce tenant isolation
Event Deduplication
-- Deduplication table (DynamoDB)
PK: eventId (UUID) // Unique event identifier
SK: tenantId#aggregateId#sequence
TTL: 24 hours
-- In command handler:
if (await dedupTable.get(eventId)) {
throw new DuplicateEventError();
}
await dedupTable.put({ eventId, ttl: 86400 });
9. Cost Optimization
| Component | Optimization | Estimated Cost (per month) |
|---|
| DynamoDB | Auto-scaling, on-demand, TTL | 0.25/GB+1.25/M writes |
| Lambda | 1GB memory, 100ms avg duration | $0.20/M invocations |
| S3 | Intelligent tiering, lifecycle | $0.023/GB (standard) |
| Kinesis | On-demand, retention 24h | $0.015/GB ingested |
| Glue | Serverless, job bookmarking | Pay per DPU-hour |
Example: 1M commands/month, 10 events/command:
- Events: 10M × 1KB = 10GB storage = $2.5
- Writes: 10M × 1.25/M=12.5
- Lambda: 1M × 0.20=200
- Total: ~$215/month (excluding analytics)
10. Migration & Versioning
Zero-Downtime Schema Migration
// Phase 1: Write to both schemas (dual write)
const eventsV2 = convertToV2(eventsV1);
await writeEvents(eventsV1); // Legacy
await writeEvents(eventsV2); // New
// Phase 2: Read from v2 with fallback to v1
const event = await readEvent(eventId);
const v2Event = upcast(event, 2);
// Phase 3: Stop writing v1
// Phase 4: Archive v1 events to S3
Gradle/Maven-style Versioning
Event Type: OrderCreated
v1.0: Initial (2023-01-01)
v1.1: Added discount field (2023-06-01)
v2.0: Restructured payload (2024-01-01)
Breaking change - upcaster required
11. Security
Encryption
- At rest: KMS CMK (per environment)
- In transit: TLS 1.3 everywhere
- Client-side: Optional envelope encryption
Access Control
IAM Policies:
CommandHandler:
- dynamodb:PutItem (Events table)
- dynamodb:Query (Events table)
- dynamodb:GetItem (Projections)
ProjectionUpdater:
- dynamodb:GetRecords (Streams)
- dynamodb:GetItem (Events table)
- dynamodb:PutItem (Projections)
ReadOnly:
- dynamodb:Query (Projections)
- s3:GetObject (Event archives)
Audit Trail
- CloudTrail for all management events
- DynamoDB Streams → Audit table (immutable)
- Event metadata includes
userId, sourceIp
12. Testing Strategy
Unit Tests:
- Command validation logic
- Upcaster functions
- Projection logic (pure functions)
Integration Tests:
// Using LocalStack or Testcontainers
describe("Event Sourcing Flow", () => {
it("should handle command and update projection", async () => {
// 1. Send command
const command = buildCreateOrderCommand();
const events = await commandHandler(command);
// 2. Verify events stored
const stored = await queryEvents(command.aggregateId);
expect(stored).toEqual(events);
// 3. Process projections (simulate stream)
await processStream([events[0]]);
// 4. Verify projection
const projection = await getOrderProjection(command.aggregateId);
expect(projection.status).toBe("CREATED");
});
});
Chaos Testing:
- Random Lambda failures (temporary)
- DynamoDB throttling simulation
- Network latency injection
- Schema evolution during writes
13. Vendor Alternatives
| AWS Service | Azure | GCP | Self-hosted |
|---|
| API Gateway | APIM | API Gateway | Kong/NGINX |
| Lambda | Functions | Cloud Functions | OpenFaaS/Knative |
| DynamoDB | Cosmos DB | Firestore | Cassandra/ScyllaDB |
| S3 | Blob Storage | Cloud Storage | MinIO |
| Kinesis | Event Hubs | Pub/Sub | Kafka/Pulsar |
| Glue | Data Factory | Dataflow | Airflow |
| ElastiCache | Cache | Memorystore | Redis Cluster |
Key Design Decisions Summary
- Event Store: DynamoDB (primary) + S3 (archive) - balances performance & cost
- Command Handlers: Stateless Lambdas with idempotency - scales infinitely
- Projections: DynamoDB Streams → Lambda - near real-time, serverless
- Schema Evolution: Upcaster chain + registry - backward/forward compatible
- Observability: X-Ray + CloudWatch EMF + custom dashboards - full visibility
- Cost: On-demand pricing + TTL + archival - pay for what you use
Getting Started Quickstart
# 1. Clone template
git clone https://github.com/aws-samples/event-sourcing-serverless
cd event-sourcing-serverless
# 2. Deploy stack
sam build
sam deploy --guided
# 3. Test command
aws apigatewayv2 test-invoke-method \
--api-id <api-id> \
--resource-id <resource-id> \
--method POST \
--path /commands \
--body '{"type":"CreateOrder","aggregateId":"order-1","payload":{...}}'
# 4. View projection
aws dynamodb get-item \
--table-name OrderProjection \
--key '{"orderId": {"S": "order-1"}}'
This design provides a production-ready, scalable event-sourcing platform that handles schema evolution, provides full observability, and remains cost-effective at scale. The serverless approach eliminates operational overhead while maintaining enterprise-grade reliability.