The user wants a "scalable inbox for event-sourced domains" with specific features: snapshots, compaction, and replays. This is a complex architectural request. I need to design a system (likely an inbox service or pattern) that fits into an Event Sourcing (ES) and potentially CQRS architecture.
1. Deconstructing the Request:
-
"Inbox for event-sourced domains": This sounds like an "Inbox Pattern" (or "Inbox Table") often used in distributed systems to ensure idempotency and exactly-once processing, or it could simply mean a user's inbox (like an email inbox) implemented using event sourcing. Given the context of "domains," "snapshots," "compaction," and "replays," it implies a domain model that receives commands/events and needs to manage state efficiently. Let's assume the latter (a domain entity representing an Inbox, e.g., a User Notification Inbox) but implemented via ES, while keeping the former (Inbox Pattern for idempotency) in mind as a necessary infrastructural detail if this involves external messages.
- Decision: I will treat this as building an "Inbox Aggregate" within an Event Sourced system. This inbox might hold messages, notifications, or tasks.
-
"Scalable": The volume of events will grow indefinitely. Reading the entire event stream to build state (hydration) will become too slow. Hence, the requirement for:
- Snapshots: Persisting the current state at specific intervals to avoid replaying the whole history.
- Compaction (or Event Garbage Collection/Archiving): Removing irrelevant old events or merging them to save space/cost. In log-compaction terms (like Kafka), it means keeping only the latest value for a key. In ES, it usually means creating "snapshots" and truncating the event stream, or aggregating old granular events into a single "Summary" event.
- Replays: The ability to re-process events to rebuild state (projections) or to fix bugs/deploy new features.
2. Architecture Design:
- Core Concept: The "Inbox" is an Aggregate Root.
- Event Store: The database holding the sequence of events.
- Snapshot Store: Key-Value store (Blob) holding serialized aggregate state.
- Flow:
- Command arrives (e.g.,
AddMessageToInbox).
- Load Aggregate.
- Check for Snapshot.
- Load events after Snapshot version.
- Hydrate state.
- Handle Command -> Generate Event (
MessageAdded).
- Save Event.
- Trigger Snapshot check (every N events).
- Trigger Compaction check (every M events or scheduled job).
3. Addressing Specific Features:
-
Snapshots:
- Need a strategy (e.g., every 100 events).
- Format: JSON/Protobuf of the current state.
- Storage: separate table/bucket.
-
Compaction:
- This is the tricky part for an "Inbox". Inboxes often contain "deleted" items or "read" items.
- Strategy: If a message is deleted, we can compact
MessageAdded, MessageRead, MessageUnread into... nothing (if deleted). Or, if we want to keep history, we don't delete.
- However, the prompt asks for compaction. A scalable inbox eventually accumulates too many events.
- Approach: "State Re-hydration + Truncation".
- If the user deletes 10,000 emails, we don't want to replay 10,000
MessageAdded then MessageDeleted.
- We want to snapshot the current state (which has 0 messages) and truncate the old event stream.
- Alternative: "Tombstone" compaction. If the stream is infinite, maybe we only keep "active" events.
-
Replays:
- Used to rebuild read models (Projections) or to fix the write model (if we are doing "compaction" via replay-rewrite).
- Need a mechanism to subscribe to the stream from the beginning.
4. Drafting the Solution (Code & Concept):
I will use TypeScript as it's neutral and clear for architectural patterns. I'll define interfaces and a concrete implementation for an EventSourcedInbox.
- Entity:
Inbox
- Events:
MessageReceived, MessageRead, MessageDeleted.
- State: List of messages (or optimized structure).
5. Structuring the Response:
- Conceptual Overview: Explain the challenges of a growing inbox in ES.
- The Architecture: Diagram/Flow description.
- Implementation Details (The "How-To"):
- Domain Events.
- Aggregate Root (The Inbox).
- Snapshotting Logic.
- Compaction Logic (The "Rewriter").
- Replaying Logic.
- Code Example: A robust implementation skeleton.
Refining the Compaction Strategy (Crucial Step):
In a standard ES system, you never delete events usually. But for "Scalable", we must.
Scenario: User has 1M emails.
Problem: Loading 1M events is impossible.
Solution 1 (Snapshotting): Snapshot at event 100. We load snapshot + 50 events. Fast. But the database still holds 1M events. Storage cost high.
Solution 2 (Compaction): This implies moving old events to "Cold Storage" or "Summarizing" them.
Or (The Kafka approach): Keep the latest state. But ES relies on history.
Best approach for this prompt: Snapshot-Only Storage / Stream Truncation.
When the stream gets too long, we take a snapshot. We save the snapshot. We archive the old events (move to S3/Glacier) or delete them if the business allows, starting the stream fresh from the Snapshot version.
Even better: Upscaling. Keep the "Active" inbox in memory/fast store via ES, but move "Archived" items out of the domain stream.
Let's stick to the specific prompt requests: Implement a system that handles snapshots (performance) and compaction (storage management).
Revised Plan for Code:
- Repository: Handles loading (Snapshot + Stream) and saving (Events).
- Compactor: A background worker. It looks for long streams, calculates the "Current State", saves a Snapshot, and optionally truncates the event stream (marking old events as archived/deleted).
Let's write the code.
- Events:
InboxItemAdded, InboxItemRead, InboxItemArchived.
- State:
Map<Id, Item>.
- Snapshot: Serialized
Map.
Self-Correction during drafting:
If I just write generic ES code, it misses the "Inbox" nuance. An inbox has specific behavior (Mark read, Delete).
The "Compaction" part needs to be distinct. I will implement a compact() method that generates a "Rollup" event or truncates based on a snapshot.
Final Structure:
- The Pattern: CQRS + Event Sourcing.
- Key Components:
EventStore: Storage.
SnapshotStore: Cache of state.
InboxAggregate: The domain logic.
InboxProjector: For read models (replay target).
- The Compaction Strategy: "Snapshot and Truncate".
- Code: TypeScript implementation showing the
Repository handling the snapshot loading logic and the Compaction service.
Let's start writing.
- Language: TypeScript (clear typing for events).
- Focus: The infrastructure around the aggregate.
Drafting the Compaction Logic:
If we want to compact, we might say: "Any event older than X days that is 'Deleted' or 'Archived' can be removed." Or, "Condense these 100 'Moved' events into 1 'IsAtLocation' state."
I will focus on Stream Truncation: If the stream is huge and we have a snapshot, we can effectively "start over" from that snapshot, discarding the history before it if audit requirements permit, or moving them to a "History" stream.
Let's refine the "Replay". Replay usually applies to Read Models (Projections). In ES, the Write Model is strict history. I will assume Replay refers to rebuilding the Read Side or repairing state.
Let's produce the output.
- Title: Scalable Event-Sourced Inbox Architecture.
- Core:
InboxAggregate.
- Mechanisms:
- Snapshot: optimize Read.
- Compaction: optimize Storage.
- Replay: Consistency/Repair.
(Self-Correction): Make sure to handle concurrency (Optimistic Locking) via version numbers.
Plan:
- Define Interfaces (Event, Aggregate, Store).
- Implement Aggregate (Inbox).
- Implement Repository (Snapshot logic).
- Implement Compactor (Background process).
- Explain Replay.
Let's go.
Compaction Detail: "Log Compaction" in Kafka keeps the latest message for a key. In ES, we can implement "Semantic Compaction".
Example:
Events: AddMsg(A), AddMsg(B), DeleteMsg(A), ReadMsg(B).
State: { B (read) }.
Compact: We can delete AddMsg(A) and DeleteMsg(A) (cancels out). We can merge AddMsg(B) and ReadMsg(B) into AddedAndReadMsg(B).
I will implement a generic "Snapshot + Truncate" strategy as it's the most robust for generic ES.
Let's write the response.
Designing a scalable inbox using Event Sourcing (ES) requires handling three specific problems that eventually plague every ES system: Read latency (loading history), Storage costs (keeping dead data), and Debugging/Recovery (rebuilding state).
Here is a comprehensive architectural guide and implementation pattern for a Scalable Event-Sourced Inbox.
1. Architectural Overview
In a standard ES system, the "Write Model" is the stream of events. The "Read Model" is a projection. However, to support complex business logic on the inbox (e.g., "Is this user allowed to archive this message?" which depends on the message state), we often need to hydrate the domain object from the stream.
As the inbox grows to millions of entries, replaying events for every command becomes impossible. We introduce three mechanisms to solve this:
- Snapshots: Point-in-time state dumps to skip history.
- Compaction: Structural cleanup of the event stream (removing "dead" messages).
- Replays: The ability to rebuild the state or projections idempotently.
2. Domain Model: The Inbox
Let's define the events that make up the inbox.
// Types
type Event = {
type: string;
payload: any;
timestamp: number;
version: number; // For optimistic concurrency
};
// The Events
const Events = {
RECEIVED: 'MessageReceived', // A new message arrives
OPENED: 'MessageOpened', // User read it
ARCHIVED: 'MessageArchived', // User archived it
DELETED: 'MessageDeleted', // Soft delete
PURGED: 'MessagePurged' // Hard delete (Compaction target)
};
3. Implementation: The Infrastructure
We will create a Repository pattern that handles the complexity of snapshots and streaming.
A. The Snapshot Strategy
We don't store the state in the database; we derive it. But deriving it from 50,000 events is slow.
Rule: Every N events (e.g., 100), save a "Snapshot" (a JSON blob of the current state) under a specific key.
B. The Compaction Strategy
In an Inbox, DELETED messages usually don't need to preserve the history of "Opened" or "Archived". Once a message is PURGED or fully DELETED, we can remove those events from the stream to save space.
Logic: A background worker merges streams, keeping only valid "Tombstones" or active messages.
C. The Code (TypeScript)
import { v4 as uuidv4 } from 'uuid';
// 1. Define the Aggregate State
interface InboxState {
messages: Map<string, Message>;
version: number;
}
interface Message {
id: string;
subject: string;
status: 'UNREAD' | 'READ' | 'ARCHIVED' | 'DELETED';
}
// 2. The Repository
class EventSourcedInboxRepository {
private eventStore: any; // DB Client (e.g., DynamoDB, EventStoreDB, Postgres)
private snapshotStore: any; // Cache/Key-Value Store (Redis, S3, Postgres JSONB)
private SNAPSHOT_FREQUENCY = 50;
constructor(eventStore: any, snapshotStore: any) {
this.eventStore = eventStore;
this.snapshotStore = snapshotStore;
}
/**
* LOAD: Get Inbox State using Snapshots for performance
*/
async load(inboxId: string): Promise<InboxState> {
// Step 1: Try to get a Snapshot
const snapshot = await this.snapshotStore.get(`snapshot_${inboxId}`);
let state: InboxState;
let startVersion: number;
if (snapshot) {
// Snapshot Hit: Start from saved state
state = snapshot.state;
startVersion = snapshot.version + 1;
} else {
// Snapshot Miss: Start from beginning
state = { messages: new Map(), version: 0 };
startVersion = 1;
}
// Step 2: Fetch remaining events after snapshot version
const events = await this.eventStore.getEvents(inboxId, startVersion);
// Step 3: Fold events over state (Hydration)
state = events.reduce((currentState, event) => {
return this.applyEvent(currentState, event);
}, state);
state.version = events.length > 0 ? events[events.length - 1].version : (snapshot?.version || 0);
return state;
}
/**
* SAVE: Persist events and manage Snapshot creation
*/
async save(inboxId: string, currentState: InboxState, newEvents: Event[]) {
if (newEvents.length === 0) return;
// 1. Persist events atomically
await this.eventStore.appendEvents(inboxId, newEvents, currentState.version);
// 2. Check if we need a new Snapshot
const lastEventVersion = newEvents[newEvents.length - 1].version;
if (lastEventVersion % this.SNAPSHOT_FREQUENCY === 0) {
await this.snapshotStore.save(`snapshot_${inboxId}`, {
state: currentState,
version: lastEventVersion
});
}
}
/**
* STATE FOLDER: Pure function logic
*/
private applyEvent(state: InboxState, event: Event): InboxState {
switch (event.type) {
case 'MessageReceived':
state.messages.set(event.payload.id, {
id: event.payload.id,
subject: event.payload.subject,
status: 'UNREAD'
});
break;
case 'MessageOpened':
const msg = state.messages.get(event.payload.id);
if (msg) msg.status = 'READ';
break;
case 'MessageDeleted':
if (state.messages.has(event.payload.id)) {
state.messages.delete(event.payload.id); // Or mark as deleted
}
break;
}
state.version = event.version;
return state;
}
}
4. Handling Scale: Compaction
In an Inbox, "Compaction" means removing the history of messages that no longer exist. Storing the MessageReceived event for an email deleted 5 years ago is a waste of space and read-time.
We implement a Stream Compactor service. This runs as a background job (Lambda/K8s CronJob).
Compaction Logic:
- Trigger: Stream length > 10,000 events OR Last Modified > 1 year ago.
- Process:
- Load the current state (via snapshot).
- Filter: If the state contains the message, keep it. If the message is gone (deleted), discard its history.
- Rewrite: Create a new stream containing only "active" events or a single "Synthesized" event representing the current state.
class InboxCompactor {
constructor(private repo: EventSourcedInboxRepository) {}
async compact(inboxId: string) {
// 1. Hydrate full state (use latest snapshot)
const state = await this.repo.load(inboxId);
// 2. Generate "Ghost" events only for active messages
// We replace the entire history with a single "InboxRestored" event
// representing the current state for storage efficiency.
const compactedEvent: Event = {
type: 'InboxSnapshotSynthesized', // Internal system event
payload: Array.from(state.messages.values()),
version: state.version + 1,
timestamp: Date.now()
};
// 3. Archive old stream to Cold Storage (S3/Glacier) for audit
await this.archiveOldStream(inboxId);
// 4. Replace stream with the single synthesized event
await this.repo.eventStore.replaceStream(inboxId, [compactedEvent]);
console.log(`Compacted Inbox ${inboxId}. Reduced to state snapshot.`);
}
}
5. Replays
Replays are necessary when:
- You added a new field to the
InboxState and need to update existing data.
- You are fixing a bug in the
applyEvent logic.
- You are migrating to a new database technology.
The Replay Strategy (The "Backfill")
We treat the Replay as a specific "Projection Mode" of the repository.
class ReplayService {
/**
* Replays all events for a specific inbox to rebuild state/fix bugs
*/
async replayInbox(inboxId: string) {
// 1. Fetch ALL events from the beginning (Ignore Snapshots)
const allEvents = await this.repo.eventStore.getEvents(inboxId, 0);
// 2. Initialize Empty State
let state: InboxState = { messages: new Map(), version: 0 };
// 3. Re-apply logic (with potential bug fixes)
for (const event of allEvents) {
state = this.repo.applyEvent(state, event);
}
// 4. Force a new Snapshot to "seal" the replay
await this.repo.snapshotStore.save(`snapshot_${inboxId}`, {
state: state,
version: state.version
});
// 5. Update Read Models (Projections)
await this.updateSearchIndex(state);
}
/**
* Scalable Global Replay (Fan-out)
*/
async replayAllInboxes() {
// Fetch list of all Inbox IDs (from a metadata table or stream catalog)
const inboxIds = await this.repo.eventStore.getAllStreamIds();
// Process in parallel batches
await Promise.map(inboxIds, (id) => this.replayInbox(id), { concurrency: 10 });
}
}
6. Summary of Scalability Rules
- Don't load from scratch: Always use Snapshots. If the stream is > 100 events, a snapshot must exist.
- Compaction is not Deletion: Deletion is a business event (
MessageDeleted). Compaction is an infrastructure maintenance task (merging history).
- Idempotent Replays: Ensure your
applyEvent logic is pure (no side effects) so replays produce the exact same state every time.
- Separate Read/Write: Do not query the Event Store for the UI list view. Use the Replay service to populate a standard SQL/NoSQL "Read Model" table optimized for querying. The Event Store is only for the "Source of Truth" and complex state hydration.