#📝 Note: Event Sourcing
#Overview
Event Sourcing is a pattern where all changes to application state are stored as a sequence of immutable events. Instead of storing the current state, you store the history of state transitions and derive the current state by replaying events.
#Core Idea
- Events are facts: "OrderPlaced", "PaymentReceived", "ItemShipped" — things that happened, never deleted or modified.
- Append-only log: New events are always appended; the log is the source of truth.
- State reconstruction: Current state is derived by replaying events from the beginning (or from a snapshot).
#Event Sourcing vs Traditional CRUD
| Aspect | CRUD | Event Sourcing |
|---|---|---|
| Storage | Current state only | Full history of changes |
| Updates | Overwrite existing record | Append new event |
| Audit Trail | Requires explicit logging | Built-in by design |
| Debugging | "Why is the state wrong?" | Replay events to see exactly what happened |
| Storage Cost | Lower | Higher (all events retained) |
#Key Components
- Event Store: Append-only log (Kafka, EventStoreDB, or custom on PostgreSQL).
- Projections: Read-optimized views built by consuming events (e.g., materialized views in Elasticsearch, Redis).
- Snapshots: Periodic checkpoints of current state to avoid replaying millions of events from scratch.
#When to Use
- Audit Requirements: Financial systems, compliance — need to know exactly what happened and when.
- Complex Domain Logic: When understanding the sequence of events matters (e.g., order lifecycle).
- CQRS Companion: Often paired with CQRS — events on the write side, projections on the read side.
- Replayability: Ability to rebuild read models, fix bugs by replaying corrected logic, or build new projections from historical data.
#When NOT to Use
- Simple CRUD applications with no audit requirements.
- When storage cost of event history is prohibitive.
- When eventual consistency between write and read models is unacceptable.
#Trade-offs
- Pros: Complete audit trail, temporal queries ("what was the state at time T?"), easy to add new projections, enables replay for debugging/reprocessing.
- Cons: Increased complexity, eventual consistency for projections, event schema evolution challenges, higher storage costs.
#Used In This Repo
- E-Commerce (#11) — Product updates via Kafka for CQRS index building
- Recommendation Engine (#23) — Interaction events as immutable log for model retraining replay
- Fraud Detection (#24) — Transaction + decision audit trail for compliance and model feedback