English

Artykuł · Event Sourcing · CQRS

Event sourcing: zapisuj fakty, a nie tylko ostatni stan

Stan jako ciąg niezmiennych zdarzeń: strumienie, odtwarzanie przez fold, optymistyczna współbieżność, projekcje, migawki i wersjonowanie zdarzeń. Agregat i magazyn zdarzeń w C# (Marten), TypeScript, Javie, Go i Pythonie.

Autor · · 13 min czytania

„Gdzie się podziały moje punkty?” – pyta pan Zdzisio, stały klient pierogarni Haliny. W bazie widać tylko balance = 40. Nie wiadomo, czy punkty wygasły, czy ktoś je wymienił, czy był błąd przy zwrocie. Event sourcing odpowiada na takie pytania z definicji: zamiast nadpisywać stan, system zapisuje każdą zmianę jako niezmienne zdarzenie, a stan bieżący oblicza, odtwarzając historię.

2005
opis wzorca „Event Sourcing” – Martin Fowler, kontynuacja katalogu PoEAA
6 mln
zamówień na sekundę w LMAX – jeden wątek, logika odtwarzana ze zdarzeń (Fowler, 2011)
0
operacji UPDATE i DELETE na zdarzeniach – magazyn zdarzeń jest tylko do dopisywania

Kontekst i siły

  • Audyt i spory – program lojalnościowy dotyczy pieniędzy klienta; trzeba umieć pokazać, skąd wziął się każdy punkt.
  • Pytania o przeszłość – „ile punktów miał Zdzisio w Wigilię?” albo „co by było, gdyby promocja trwała dłużej?”.
  • Nowe widoki z istniejących danych – dział marketingu chce raportu, o którym nikt nie myślał przy projektowaniu tabel.
  • Integracja przez zdarzenia – inne moduły i usługi i tak potrzebują informacji o tym, co się wydarzyło.

Bankowość i księgowość robią to od wieków: saldo konta to wynik księgowań, a błędu nie wymazuje się gumką, tylko księguje korektę. Martin Fowler opisał wzorzec w 2005 roku, a Greg Young spopularyzował go razem z CQRS i bazą EventStoreDB (dziś KurrentDB).

Struktura

Diagram: Komenda, strumień zdarzeń i projekcje
PojęcieZnaczenie
ZdarzenieFakt z przeszłości w czasie przeszłym, niezmienny: PointsRedeemed(reward, 300)
StrumieńUporządkowane zdarzenia jednego agregatu, np. loyalty-<id>; pozycja w nim to wersja
RehydratacjaOdtworzenie stanu przez zastosowanie (fold) wszystkich zdarzeń strumienia
Oczekiwana wersjaWarunek przy dopisywaniu: „dopisz, jeśli strumień ma nadal wersję 12” – optymistyczna współbieżność
ProjekcjaProces, który czyta zdarzenia i buduje z nich model odczytu; można go odtworzyć od zera
Migawka (snapshot)Zapisany stan po N zdarzeniach, żeby nie odtwarzać tysięcy zdarzeń przy każdym odczycie

Dobrym sposobem, żeby zobaczyć ideę, jest strumień jednego konta – tak wygląda historia, której brakowało przy pytaniu pana Zdzisia:

  1. 1 marca AccountOpened – Zdzisio zakłada konto w aplikacji, saldo 0.
  2. 3 marca PointsEarned +85 – Zamówienie 20 ruskich i 10 jagodowych.
  3. 17 marca PointsEarned +120 – Catering na urodziny wnuczki.
  4. 2 kwietnia Próba wymiany 300 pkt – Odrzucona przez regułę (saldo 205) – żadne zdarzenie nie powstaje.
  5. 20 kwietnia PointsEarned +140 – Kolejne zamówienia, saldo 345.
  6. 21 kwietnia PointsRedeemed −300 – Darmowe 10 ruskich, saldo 45.
  7. 1 lipca PointsExpired −5 – Wygaśnięcie punktów sprzed roku według regulaminu – saldo 40.

Jak to wygląda w kodzie

Agregat ma dwie funkcje: apply/evolve (jak zdarzenie zmienia stan) i decide (jakie zdarzenia wynikają z komendy w danym stanie). Obie są czyste i testuje się je bez bazy: „mając te zdarzenia, po tej komendzie oczekuję tych zdarzeń”.

Agregat odtwarzany ze zdarzeń

LoyaltyAccount.cs
// Events are facts in the past tense. They are the source of truth.
public abstract record LoyaltyEvent;
public sealed record AccountOpened(Guid CustomerId, DateTimeOffset At) : LoyaltyEvent;
public sealed record PointsEarned(Guid OrderId, int Points, DateTimeOffset At) : LoyaltyEvent;
public sealed record PointsRedeemed(string Reward, int Points, DateTimeOffset At) : LoyaltyEvent;
public sealed record PointsExpired(int Points, DateTimeOffset At) : LoyaltyEvent;

public sealed class LoyaltyAccount
{
    public Guid Id { get; private set; }
    public int Balance { get; private set; }
    public int Version { get; private set; }               // number of events applied so far

    // State = left fold of all events. No setters, no ORM mapping.
    public static LoyaltyAccount Rehydrate(Guid id, IEnumerable<LoyaltyEvent> history)
    {
        var account = new LoyaltyAccount { Id = id };
        foreach (var e in history) account.Apply(e);
        return account;
    }

    // Decide: check the rules against the current state and return NEW events (nothing is mutated yet).
    public IReadOnlyList<LoyaltyEvent> Redeem(string reward, int cost, DateTimeOffset now) =>
        Balance >= cost
            ? [new PointsRedeemed(reward, cost, now)]
            : throw new InvalidOperationException($"Balance {Balance} is lower than {cost}.");

    public void Apply(LoyaltyEvent e)
    {
        Balance = e switch
        {
            AccountOpened => 0,
            PointsEarned x => Balance + x.Points,
            PointsRedeemed x => Balance - x.Points,
            PointsExpired x => Balance - x.Points,
            _ => Balance
        };
        Version++;
    }
}
loyalty-account.ts
// Events are facts in the past tense. They are the source of truth.
export type LoyaltyEvent =
  | { type: "AccountOpened"; customerId: string; at: string }
  | { type: "PointsEarned"; orderId: string; points: number; at: string }
  | { type: "PointsRedeemed"; reward: string; points: number; at: string }
  | { type: "PointsExpired"; points: number; at: string };

export interface LoyaltyState {
  balance: number;
  version: number;
}

// evolve: (state, event) -> state. State is a left fold of the whole stream.
export const evolve = (s: LoyaltyState, e: LoyaltyEvent): LoyaltyState => {
  switch (e.type) {
    case "AccountOpened": return { balance: 0, version: s.version + 1 };
    case "PointsEarned": return { balance: s.balance + e.points, version: s.version + 1 };
    case "PointsRedeemed":
    case "PointsExpired": return { balance: s.balance - e.points, version: s.version + 1 };
  }
};

export const rehydrate = (events: LoyaltyEvent[]): LoyaltyState =>
  events.reduce(evolve, { balance: 0, version: 0 });

// decide: (command, state) -> new events. Pure function, trivially testable.
export function redeem(state: LoyaltyState, reward: string, cost: number, now: Date): LoyaltyEvent[] {
  if (state.balance < cost) throw new Error(`Balance ${state.balance} is lower than ${cost}`);
  return [{ type: "PointsRedeemed", reward, points: cost, at: now.toISOString() }];
}
LoyaltyAccount.java
public sealed interface LoyaltyEvent permits AccountOpened, PointsEarned, PointsRedeemed, PointsExpired {}
public record AccountOpened(UUID customerId, Instant at) implements LoyaltyEvent {}
public record PointsEarned(UUID orderId, int points, Instant at) implements LoyaltyEvent {}
public record PointsRedeemed(String reward, int points, Instant at) implements LoyaltyEvent {}
public record PointsExpired(int points, Instant at) implements LoyaltyEvent {}

public final class LoyaltyAccount {
    private int balance;
    private int version;

    public static LoyaltyAccount rehydrate(List<LoyaltyEvent> history) {
        var account = new LoyaltyAccount();
        history.forEach(account::apply);                    // state = fold of events
        return account;
    }

    public List<LoyaltyEvent> redeem(String reward, int cost, Instant now) {
        if (balance < cost) throw new IllegalStateException("Balance " + balance + " is lower than " + cost);
        return List.of(new PointsRedeemed(reward, cost, now)); // decide, don't mutate
    }

    public void apply(LoyaltyEvent e) {
        balance = switch (e) {                             // exhaustive thanks to the sealed interface
            case AccountOpened o -> 0;
            case PointsEarned p -> balance + p.points();
            case PointsRedeemed r -> balance - r.points();
            case PointsExpired x -> balance - x.points();
        };
        version++;
    }

    public int balance() { return balance; }
    public int version() { return version; }
}
loyalty/account.go
package loyalty

import (
	"fmt"
	"time"
)

// Event is a fact in the past tense; concrete types below.
type Event interface{ isEvent() }

type AccountOpened struct {
	CustomerID string
	At         time.Time
}
type PointsEarned struct {
	OrderID string
	Points  int
	At      time.Time
}
type PointsRedeemed struct {
	Reward string
	Points int
	At     time.Time
}

func (AccountOpened) isEvent()  {}
func (PointsEarned) isEvent()   {}
func (PointsRedeemed) isEvent() {}

type Account struct {
	Balance int
	Version int
}

// Rehydrate folds the stream into the current state.
func Rehydrate(history []Event) Account {
	var a Account
	for _, e := range history {
		a.Apply(e)
	}
	return a
}

func (a *Account) Apply(e Event) {
	switch ev := e.(type) {
	case AccountOpened:
		a.Balance = 0
	case PointsEarned:
		a.Balance += ev.Points
	case PointsRedeemed:
		a.Balance -= ev.Points
	}
	a.Version++
}

// Redeem decides which events should happen; it does not mutate the account.
func (a Account) Redeem(reward string, cost int, now time.Time) ([]Event, error) {
	if a.Balance < cost {
		return nil, fmt.Errorf("balance %d is lower than %d", a.Balance, cost)
	}
	return []Event{PointsRedeemed{Reward: reward, Points: cost, At: now}}, nil
}
loyalty/account.py
from dataclasses import dataclass, replace
from datetime import datetime
from functools import reduce


# Events are facts in the past tense. They are the source of truth.
@dataclass(frozen=True)
class AccountOpened:
    customer_id: str
    at: datetime


@dataclass(frozen=True)
class PointsEarned:
    order_id: str
    points: int
    at: datetime


@dataclass(frozen=True)
class PointsRedeemed:
    reward: str
    points: int
    at: datetime


@dataclass(frozen=True)
class Account:
    balance: int = 0
    version: int = 0


def evolve(state: Account, event) -> Account:
    match event:
        case AccountOpened():
            return Account(balance=0, version=state.version + 1)
        case PointsEarned(points=p):
            return replace(state, balance=state.balance + p, version=state.version + 1)
        case PointsRedeemed(points=p):
            return replace(state, balance=state.balance - p, version=state.version + 1)
    return state


def rehydrate(history: list) -> Account:
    return reduce(evolve, history, Account())


def redeem(state: Account, reward: str, cost: int, now: datetime) -> list:
    if state.balance < cost:
        raise ValueError(f"Balance {state.balance} is lower than {cost}")
    return [PointsRedeemed(reward=reward, points=cost, at=now)]

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Ewolucja zdarzeń i dane osobowe
  • Kompromisy
  • Ścieżka wdrożenia
  • W praktyce
  • Antywzorce
  • Powiązane tematy
  • Sprawdź się

Załóż darmowe konto · Zaloguj się