11.2.3 Event Sourcing
event sourcing -- DDD (domain-driven design) technique, store all changes to the app state as a log of change events
aspect |
CDC |
event sourcing |
app usage |
can use the DB in a mutable way, no need to be aware of CDC |
logic built on the basis of immutable events |
CRUD |
read, insert, delete at will |
append-only, updates & deletes are discouraged / prohibited |
log extraction |
low level (e.g. replication log) -- ensures data order |
event log -- reflect things at app level |
features
- powerful technique for data modeling -- record the user's actions as immutable events, rather the effect of those actions on a mutable DB
- make app easier to evolve
- help with debugging
example
event |
side effects |
student cancelled their course enrollment |
- delete 1 record from the enrollments table - add 1 cancel reason to the feed back table |
the place is offered to the next person |
|
- event clearly expresses the intent of an action
- side effects embed many assumptions about the way of using data
- new event could be chained off the existing event with event sourcing
- similar to the chronicle data model
- specialized DB -- Event Store
11.2.3.1 deriving current state from the event log
- users expect to see the current state, not the history of modifications
==> an event log by itself is not useful
- so apps need to transform the event logs into app state -- should be repeatable
- like CDC, replaying the event logs allows you to reconstruct the current state
- unlike CDC, log compaction is not possible
- the intention is to store all raw events forever and reprocess the full event log whenever required
==> could use snapshot approach for performance optimization
11.2.3.2 commands and events
command -- a request from a user before validation
=> e.g. a user tries to reserve a seat on an airplane
event -- validated command, durable & immutable ==> fact
=> e.g. the app checked that the seat is not taken, if ok, then generate an event that the seat has been reserved for a particular customer
A consumer of the event stream is not allowed to reject an event: by the time the consumer sees the event, it is already an immutable part of the log, and it may have already been seen by other consumers.
- sync approach
e.g. make (command validation + event publication) a transaction
- async approach
e.g. split into 2 events
=> event 1 : tentative reservation
=> event 2 : confirmation
Reference
Designing Data-Intensive Applications by Martin Kleppman