InterviewHubPRO
Section Overview
Q29

Question 29 of 50

Part 3: Distributed Transactions, Consensus & Reliability (26 - 36)

58%
System Design (50 Qs)•Part 3: Distributed Transactions, Consensus & Reliability (26 - 36)

CQRS (Command Query Responsibility Segregation) & Event Sourcing.

In Simple Words:

  • CQRS: Separates the data model for write modifications (Commands) from read queries (Queries). The Write DB is normalized for high-throughput ACID writes; the Read DB is denormalized for lightning-fast reads.
  • Event Sourcing: Instead of storing only the current state of an entity, every state change is stored as an immutable append-only event log. Current state is reconstructed by replaying events.
typescript
// Event Sourcing: Reconstructing Account Balance from Immutable Events
export interface BankEvent {
  type: 'DEPOSITED' | 'WITHDRAWN';
  amount: number;
  timestamp: number;
}

export function reconstructBalance(events: BankEvent[]): number {
  return events.reduce((balance, ev) => {
    switch (ev.type) {
      case 'DEPOSITED': return balance + ev.amount;
      case 'WITHDRAWN': return balance - ev.amount;
      default: return balance;
    }
  }, 0);
}