🏗️ Architecture

Event Sourcing

Event Sourcing

Event Sourcing is an architectural pattern that stores state changes as a stream of events. Instead of the current state, it records every event that occurred in order and restores state by replaying them. Enables a complete audit trail and time-travel debugging.

📖 Detailed Explanation

Event Sourcing, unlike the traditional CRUD approach, stores a sequence of state-change events rather than the current state of the data. It works on the same principle as a bank ledger, which records every deposit and withdrawal rather than only the balance.

Traditional Approach vs Event Sourcing

Traditional CRUD Event Sourcing
Stores only the current state (balance: 10000) Stores all events (deposit 5000, withdrawal 3000, ...)
Past states cannot be restored Can restore the state at a specific point in time (Time Travel)
Change history is hard to trace Complete audit trail (Audit Trail)
Data may be lost Events are immutable, with no deletion

Key concepts

Advantages of Event Sourcing

💻 Code Example

Domain Event Definition

// domain/events/AccountEvents.ts
interface DomainEvent {
  readonly eventId: string;
  readonly aggregateId: string;
  readonly version: number;
  readonly occurredAt: Date;
  readonly eventType: string;
}

export class AccountOpened implements DomainEvent {
  readonly eventType = 'AccountOpened';

  constructor(
    public readonly eventId: string,
    public readonly aggregateId: string,
    public readonly version: number,
    public readonly occurredAt: Date,
    public readonly ownerId: string,
    public readonly initialBalance: number
  ) {}
}

export class MoneyDeposited implements DomainEvent {
  readonly eventType = 'MoneyDeposited';

  constructor(
    public readonly eventId: string,
    public readonly aggregateId: string,
    public readonly version: number,
    public readonly occurredAt: Date,
    public readonly amount: number,
    public readonly description: string
  ) {}
}

export class MoneyWithdrawn implements DomainEvent {
  readonly eventType = 'MoneyWithdrawn';

  constructor(
    public readonly eventId: string,
    public readonly aggregateId: string,
    public readonly version: number,
    public readonly occurredAt: Date,
    public readonly amount: number,
    public readonly description: string
  ) {}
}

type AccountEvent = AccountOpened | MoneyDeposited | MoneyWithdrawn;

Event Sourced Aggregate

// domain/aggregates/Account.ts
import { AccountOpened, MoneyDeposited, MoneyWithdrawn } from '../events/AccountEvents';

export class Account {
  private _id: string = '';
  private _ownerId: string = '';
  private _balance: number = 0;
  private _version: number = 0;
  private _uncommittedEvents: DomainEvent[] = [];

  private constructor() {}

  // Factory: 새 계좌 생성
  static open(ownerId: string, initialDeposit: number = 0): Account {
    const account = new Account();

    // 이벤트 발생 (상태 변경 아님)
    account.apply(new AccountOpened(
      crypto.randomUUID(),
      crypto.randomUUID(),
      1,
      new Date(),
      ownerId,
      initialDeposit
    ));

    return account;
  }

  // 이벤트 스트림에서 Aggregate 재구성
  static fromHistory(events: DomainEvent[]): Account {
    const account = new Account();
    for (const event of events) {
      account.applyFromHistory(event);
    }
    return account;
  }

  get id(): string { return this._id; }
  get balance(): number { return this._balance; }
  get version(): number { return this._version; }

  // 명령: 입금
  deposit(amount: number, description: string): void {
    if (amount <= 0) {
      throw new Error('Deposit amount must be positive');
    }

    this.apply(new MoneyDeposited(
      crypto.randomUUID(),
      this._id,
      this._version + 1,
      new Date(),
      amount,
      description
    ));
  }

  // 명령: 출금
  withdraw(amount: number, description: string): void {
    if (amount <= 0) {
      throw new Error('Withdrawal amount must be positive');
    }
    if (this._balance < amount) {
      throw new Error('Insufficient balance');
    }

    this.apply(new MoneyWithdrawn(
      crypto.randomUUID(),
      this._id,
      this._version + 1,
      new Date(),
      amount,
      description
    ));
  }

  // 이벤트 적용 (새 이벤트)
  private apply(event: DomainEvent): void {
    this.mutate(event);
    this._uncommittedEvents.push(event);
  }

  // 이벤트 적용 (히스토리 재생)
  private applyFromHistory(event: DomainEvent): void {
    this.mutate(event);
  }

  // 상태 변경 (이벤트 타입별 처리)
  private mutate(event: DomainEvent): void {
    if (event instanceof AccountOpened) {
      this._id = event.aggregateId;
      this._ownerId = event.ownerId;
      this._balance = event.initialBalance;
      this._version = event.version;
    } else if (event instanceof MoneyDeposited) {
      this._balance += event.amount;
      this._version = event.version;
    } else if (event instanceof MoneyWithdrawn) {
      this._balance -= event.amount;
      this._version = event.version;
    }
  }

  // 커밋되지 않은 이벤트 가져오기
  getUncommittedEvents(): DomainEvent[] {
    return [...this._uncommittedEvents];
  }

  clearUncommittedEvents(): void {
    this._uncommittedEvents = [];
  }
}

Event Store Interface and Implementation

// infrastructure/eventstore/EventStore.ts
interface IEventStore {
  append(streamId: string, events: DomainEvent[], expectedVersion: number): Promise<void>;
  getStream(streamId: string): Promise<DomainEvent[]>;
  getStreamFromVersion(streamId: string, fromVersion: number): Promise<DomainEvent[]>;
}

// PostgreSQL 기반 Event Store 구현
export class PostgresEventStore implements IEventStore {
  constructor(private db: Pool) {}

  async append(
    streamId: string,
    events: DomainEvent[],
    expectedVersion: number
  ): Promise<void> {
    const client = await this.db.connect();

    try {
      await client.query('BEGIN');

      // 낙관적 동시성 제어
      const currentVersion = await this.getCurrentVersion(client, streamId);
      if (currentVersion !== expectedVersion) {
        throw new Error(`Concurrency conflict: expected ${expectedVersion}, got ${currentVersion}`);
      }

      // 이벤트 append (INSERT only, never UPDATE)
      for (const event of events) {
        await client.query(
          `INSERT INTO event_store
           (event_id, stream_id, version, event_type, payload, occurred_at)
           VALUES ($1, $2, $3, $4, $5, $6)`,
          [
            event.eventId,
            streamId,
            event.version,
            event.eventType,
            JSON.stringify(event),
            event.occurredAt
          ]
        );
      }

      await client.query('COMMIT');
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  async getStream(streamId: string): Promise<DomainEvent[]> {
    const result = await this.db.query(
      `SELECT payload FROM event_store
       WHERE stream_id = $1
       ORDER BY version ASC`,
      [streamId]
    );
    return result.rows.map(row => this.deserialize(row.payload));
  }

  private deserialize(payload: any): DomainEvent {
    // Event Type에 따라 적절한 클래스로 역직렬화
    const eventType = payload.eventType;
    switch (eventType) {
      case 'AccountOpened':
        return new AccountOpened(
          payload.eventId, payload.aggregateId, payload.version,
          new Date(payload.occurredAt), payload.ownerId, payload.initialBalance
        );
      case 'MoneyDeposited':
        return new MoneyDeposited(
          payload.eventId, payload.aggregateId, payload.version,
          new Date(payload.occurredAt), payload.amount, payload.description
        );
      // ... 다른 이벤트 타입들
      default:
        throw new Error(`Unknown event type: ${eventType}`);
    }
  }
}

Optimization Using Snapshots

// infrastructure/snapshot/SnapshotStore.ts
interface Snapshot<T> {
  aggregateId: string;
  version: number;
  state: T;
  createdAt: Date;
}

export class AccountRepository {
  private readonly SNAPSHOT_INTERVAL = 100; // 100개 이벤트마다 스냅샷

  constructor(
    private eventStore: IEventStore,
    private snapshotStore: ISnapshotStore
  ) {}

  async getById(accountId: string): Promise<Account> {
    // 1. 스냅샷 조회
    const snapshot = await this.snapshotStore.get<AccountState>(accountId);

    let account: Account;
    let fromVersion = 0;

    if (snapshot) {
      // 2. 스냅샷에서 시작
      account = Account.fromSnapshot(snapshot.state);
      fromVersion = snapshot.version;
    } else {
      account = new Account();
    }

    // 3. 스냅샷 이후 이벤트만 재생
    const events = await this.eventStore.getStreamFromVersion(accountId, fromVersion);
    for (const event of events) {
      account.applyFromHistory(event);
    }

    return account;
  }

  async save(account: Account): Promise<void> {
    const events = account.getUncommittedEvents();
    if (events.length === 0) return;

    const expectedVersion = account.version - events.length;

    // 이벤트 저장
    await this.eventStore.append(account.id, events, expectedVersion);
    account.clearUncommittedEvents();

    // 스냅샷 생성 여부 확인
    if (account.version % this.SNAPSHOT_INTERVAL === 0) {
      await this.snapshotStore.save({
        aggregateId: account.id,
        version: account.version,
        state: account.toSnapshot(),
        createdAt: new Date()
      });
    }
  }
}

Projection (Read Model)

// infrastructure/projections/AccountBalanceProjection.ts
// 이벤트를 구독하여 Read Model 업데이트

export class AccountBalanceProjection {
  constructor(private db: Pool) {}

  // 이벤트 핸들러
  async handle(event: DomainEvent): Promise<void> {
    if (event instanceof AccountOpened) {
      await this.db.query(
        `INSERT INTO account_balances (account_id, owner_id, balance, updated_at)
         VALUES ($1, $2, $3, $4)`,
        [event.aggregateId, event.ownerId, event.initialBalance, event.occurredAt]
      );
    } else if (event instanceof MoneyDeposited) {
      await this.db.query(
        `UPDATE account_balances
         SET balance = balance + $1, updated_at = $2
         WHERE account_id = $3`,
        [event.amount, event.occurredAt, event.aggregateId]
      );
    } else if (event instanceof MoneyWithdrawn) {
      await this.db.query(
        `UPDATE account_balances
         SET balance = balance - $1, updated_at = $2
         WHERE account_id = $3`,
        [event.amount, event.occurredAt, event.aggregateId]
      );
    }
  }

  // Projection 리빌드 (모든 이벤트 재처리)
  async rebuild(): Promise<void> {
    await this.db.query('TRUNCATE account_balances');

    const allEvents = await this.eventStore.getAllEvents();
    for (const event of allEvents) {
      await this.handle(event);
    }
  }
}

💬 Real-world conversation examples

👨‍💼 PM

"A customer is asking us to check why a withdrawal failed on the 15th of last month. Can we tell what the balance was at that time?"

👩‍💻 Backend developer

"That's possible because of Event Sourcing. If we replay the events up to the 15th, we can get the exact balance at that point. The 'MoneyWithdrawn failure' event is also recorded, so we can trace why it failed as well."

👨‍💻 Junior developer

"If events keep piling up, won't replay take too long? If we have to read thousands of events every time we look up an account..."

👩‍💻 Senior developer

"We use Snapshots. We save the current state every 100 events, and then only need to replay the events after that. And the Read Model for reads is managed separately as a Projection, so query performance isn't a problem."

👨‍💼 Architect

"You need 'daily transaction volume' statistics on the new dashboard? Thanks to Event Sourcing, that's easy. If we replay the existing events into a new Projection, we can fill in all the past data as well."

⚠️ Cautions

Event schema changes: It is hard to change the structure of events that have already been stored. Adding a new field is easy, but changing an existing field makes migration complex. Event version management is essential.

Storage space: Because all events are stored permanently, data keeps growing. You must consider storage costs and an archiving strategy.

Complexity: For a simple CRUD system, Event Sourcing is excessive complexity. It suits domains where audit trails and time travel are essential (finance, healthcare).

Tip: Event Sourcing works effectively when used together with CQRS. Separate writes into event streams and reads into optimized Projections.

🔗 Related Terms

📚 Learn More