Event Sourcing , CQRS And Domain Driven Design
Aggregate is Domain Driven Design concept. Aggregate is cluster of object which is treated as one unit for purpose of state change. Invariants applied with Aggregate will be enforced with completion of each transaction.
Event Sourcing is an Architectural Pattern in which state of application is being determined by sequence of Events.
Events are Immutable, Facts, Named in past tense. Events have happened and can not deleted or modified.
Few examples of Event Sourced Aggregates are — Bank Account, General Ledgers, Append only Logs of Kafka
Lets look at Cart Aggregate in diagrams below. When InitializeCartCommand is sent to CartAggregate, Aggregate will ensure that all invariants are met, it will generate an Event called CartInitializedEvent. Event will be stored in EvenStore and it will be published on message bus for external world to consume it.
Events will be saved in EventStore as shown below
CQRS — Command Query Responsibility Separation
Separate Write side from Read side. Many systems have different requirements for read vs write. Many system are read heavy than write heavy.
Use commands to change Aggregate on write side.
Use read side to query current state of Aggregate. Build Read side by consuming Events published by Aggregate (write side).
Using Event sourcing and replaying events new read store can be built at any time in future.
Read side can use eventual consistency or weaker forms of it (CAP) using non-sql database. e.g Riak, cassandra, mongodb, neo4j
Write side has to be Strong consistency (ACID) — Relational DB Postgres, mysql, CocrochDB, Spanner
Using Event Sourcing and CQRS , you are already in land of Distributed System and microservices.
Code — Work in progress on my github repo (all repos starting with eshop)
This code uses cut-down version of online shop and is implementing it using DDD, Event Sourcing and CQRS