Intermediate LevelSoftware Engineering Principles
What is Event Sourcing and how does it reconstruct state from immutable event logs?
❓ Interview Prompt: Explain Event Sourcing, append-only event streams, state reconstruction, audit logs, and combining Event Sourcing with CQRS.
Event Sourcing stores the state of a business entity as a sequence of immutable, append-only domain events rather than overwriting current state database rows:
How It Works:
To determine current state, the system replays all historical events ('OrderCreated', 'ItemAdded', 'PaymentProcessed').
•
Benefits: Perfect audit log out of the box, ability to view system state at any historical point in time, and seamless temporal querying.
Code Implementation Example
typescript
interface Event { type: string; payload: any; timestamp: Date; }
class BankAccountAggregate {
private balance = 0;
// Rebuild state by replaying event log
applyEvents(events: Event[]) {
for (const e of events) {
if (e.type === 'DEPOSITED') this.balance += e.payload.amount;
if (e.type === 'WITHDRAWN') this.balance -= e.payload.amount;
}
}
}💡Reconstructing aggregate state by replaying immutable domain events.
🎯 Interview Key Takeaway
Use Event Sourcing to store state changes as an immutable stream of events for complete auditability and temporal state reconstruction.
#Event Sourcing#CQRS#Architecture#Intermediate
Back to all Software Engineering Principles Questions→