Event sourcing lưu trữ mọi thay đổi state của domain object dưới dạng immutable event (append-only log) thay vì chỉ lưu state hiện tại.
Kafka là storage backend lý tưởng: durable, ordered, replayable.
Pattern hoạt động:
- Mọi action (OrderPlaced, PaymentProcessed, OrderShipped) được publish như event vào Kafka topic;
- Current state được derive bằng cách replay tất cả event từ đầu hoặc từ snapshot gần nhất;
- CQRS thường đi kèm: Command side (write) publish event → Kafka → Event handler rebuild read model cho Query side. Lợi ích: audit trail đầy đủ, time-travel debugging, eventual consistency tự nhiên, dễ scale read side. Nhược điểm: eventual consistency phức tạp hơn strong consistency; query current state cần rebuild từ events (giải quyết bằng snapshot và read model); schema evolution khó (events immutable nên không thể sửa); storage lớn theo thời gian
Dùng log compaction để snapshot state, giảm replay time.
Event sourcing stores every change to a domain object's state as an immutable event in an append-only log, rather than storing only the current state.
Kafka is an ideal storage backend: durable, ordered, and replayable.
How the pattern works:
- every action (OrderPlaced, PaymentProcessed, OrderShipped) is published as an event to a Kafka topic;
- current state is derived by replaying all events from the beginning or from the nearest snapshot;
- CQRS often accompanies it: the Command side (write) publishes events → Kafka → Event handlers rebuild read models for the Query side. Benefits: complete audit trail, time-travel debugging, natural eventual consistency, easy read-side scaling. Drawbacks: eventual consistency is harder to reason about than strong consistency; querying current state requires event replay (mitigated with snapshots and read models); schema evolution is difficult (events are immutable so they cannot be changed retroactively); storage grows over time
Use log compaction to snapshot state and reduce replay time.