Event sourcing is a way to update state and publish event. The traditional way to persist an entity is to save its current state. A business object with event sourcing is persisted by storing a sequence of state changing events. And CQRS (Command Query Responsibility Segregation) always comes with event sourcing, but that is not include in this article.
- accurate audit logging
- release the responsibility from write operation
- easy for the analysis the data
- database would not be the bottleneck
- support multiple read model
- increase the complexity on read operation
- hard to build the data model
In this section, we are going to practice the event souring by implementing a bowling game.
Source code: cs-lexliu/practice-event-sourcing
In bowling_game.go, the BowlingGame
model has been implemented as a event sourcing model.
Create
andRoll
are the command methods response to generate the event.When
method is the event handler contains most of the business logic of bowling game.newBowlingGameFromEvent
is a constructor to create theBowlingGame
model from events.
In use case package, CreateBowlingGame
and RollOneBall
is the use case command service, they operate the domain model and store the state into the database. Repository is the interface of the database, this is the dependency inversion to decouple the database dependency from service.
If you are interested in the usage of this example, check main.go file. This is a console program for playing the bowling game.
Last, most of the magic in under ddd package. This package contains the reusable behavior by using theses package me can add new domain model easier.
- Why Event Sourcing?
- What is Event Sourcing? - Event Store Blog
- Event Sourcing Example & Explained in plain English
- CQRS, Event Sourcing Patterns and Database Architecture | Upsolver
- When not to use Event Sourcing? - Event-Driven.io
- https://levelup.gitconnected.com/basics-of-event-sourcing-12ebe0b86788
- Event sourcing vs CRUD - RisingStack Engineering