Event SourcingCameron Fletcher
Agenda
What is an Event? Events as a Storage Mechanism Versioning Testing with Events Performance and Scalability Demonstration
What is an Event?
An EventAn event is something that has happened in the past as a result of a change in state of our domain
Fill glassRequest to change state
Glass has been filledEvent
Glass is already full!
Glass is broken!Exception
Events as aStorage Mechanism
Carts
CartId HasCheckedOut1 False
CartItems
CartId ItemId Name1 1 Domain Driven Design1 2 Enterprise Integration
Patterns1 3 Event Centric
Item Added
Item Added
Item Added
Checkout Completed
Shopping Cart Created
True
Item Added
Item Added
Item Added
Checkout Completed
Shopping Cart Created
Domain Object
Item Added
Item Added
Item Added
Item Removed
Shopping Cart Created
Checkout Completed
Versioning
7
6
5
4
3
2
1
snapshot
Cart Domain Object Example// request to mutate statepublic void Add(Item item){
if (this.itemCount > 5)throw new CartFullException(this.id);
ApplyChange(new ItemAdded(this.id, item.Name));
}
// mutate stateprivate void Apply(ItemAdded @event){
this.itemCount++;}
Domain Object Base
protected void ApplyChange(Event @event){
this.ApplyChange(@event, true);}
private void ApplyChange(Event @event, bool isNew){
this.AsDynamic().Apply(@event);
if (isNew)this.uncommittedChanges.Add(@event);
}
Domain Object Reconstitutionpublic void LoadFromHistory(IEnumerable<Event> history){
foreach (var @event in history)this.ApplyChange(@event, false);
}
Domain Object Persistencepublic IEnumerable<Event> GetUncommittedChanges() {
return this.uncommittedChanges;}
public void MarkChangesAsCommitted(){
this.uncommittedChanges.Clear();}
Testing with Events
Overdraw Attempts are RejectedGiven
An account with a balance of 100
WhenA debit is requested for 101
ThenAn InsufficientBalanceException is thrown
Overdraw Attempts are RejectedGiven
An account is createdA deposit was made for 100
WhenA debit is requested for 101
ThenAn InsufficientBalanceException is thrown
Overdraw Attempts are RejectedGiven
A series of events
WhenA command
ThenZero or more events, or an exception is
thrown
Overdraw Attempts are RejectedGiven
An account is createdA deposit was made for 100A debit is requested for 101
WhenA debit is requested for 20
ThenAn InsufficientBalanceException is thrown
Performance and Scalability
Performance and Scalability Benefits Append-only model Partitioning (Sharding) Persisting Objects Reconstituting Objects
Demonstration
Summary
Questions?