CQRS+event sourcing posts
In the next post series I will show a CQRS architecture. A CQRS architecture is an architecture that splits the system in two parts: the one for managing commands and another one that is a read model (Query). How the data is stored and how to synchronize the command and read model can vary veeeeery much between different architectures, from Relational DDBBs to NOSQLs. Here I will cover a radical one, using event sourcing and a special database for it. If you use this you just store business events, what has happened, and you have to create the read model from it.
When to use it? For me I would only use it if:
- Scalability is a must, tons of business events a day.
- You don’t need real time UI but you have to show complex information.
- Your business entities are very isolated: metering, bank accounts. You just work with one or two entities in each business step. It is difficult to create queries that searchs over the entities in the command model, and the query model could be not in synch.
It is a complex architecture for very complex systems, not the default way to go.
In this example I will use the following mix of technologies:
– NServiceBus: a messaging bus for implementing the “command” part of the CQRS system. It processes commands from the UI or other systems and emits events if necessary.
– Event Store: Greg Young’s database for the event sourcing. This is a blowminder database. In short it stores JSON events in sequences. For instance:
In the sequence Bank-Client-22 the following events are stored: ClientCreated, MoneyDeposited (+50), MoneyWithdrawn (-30).
It also has something for the query part of the system: the projections. These are “temporal queries” that runs over the events “queue”. At the end they take event by event and apply logic, they can also create more streams or events. It is very powerful and can easily (or better than SQL) answer questions like: “detect the clients where their cards have been used in an ATM several times in X minutes”, or it can just add or substract all the movements and keep a variable with the total money in the bank.
– ElasticSearch: this is a search and analytics engine. The core of the read model.
– AngularJS: The UI is a SPA in an asynch fashion. It can receive events from the bus.
Here is the code:
To run it you need to:
– Download event store and run it. For example: “
.\EventStore.ClusterNode.exe -db .\ESData --run-projections=ALL”
– Load the projections in the .NET solution (EventStore/Projections) on event store. Create them as continuous. Make sure that every projection in the system is running.
– Download ElasticSearch
– Run the services, UI and the synchronicers.
Next post… The C