CQRS System Design
I recently had the opportunity to design and build a system for a major automotive parts sales company using the CQRS design pattern. Below you can see the slides from a presentation I gave on the system architecture and how all the parts work together.
Here is the core architecture diagram showing all the major components in the software.
Next, I annotate each component to show the technology used for each item.
Here is an example of one of the REST APIs. For this, I used the NancyFX framework to create REST/JSON endpoints for commands and queries. Note how the API endpoint is only responsible for DTO deserialization and the work is delegated to the Command Bus.
The command bus invokes the appropriate command handler for this particular action.
Handlers will then find and call methods on the affected Aggregate Root domain objects. All domain objects are Event Sourced, so the use the Emit/Apply pattern internally to track all state changes.
All the events are stored in SQL Server as binary serialized objects. This makes it quick to save changes and simple to restore domain entities by “playing back” the events for that entity in order.
After the event is applied to the entity, it is routed to the Event Bus. The Event Bus uses a concept of a View Locator to find and relay the event to all of the event handlers that are affected by this event.
The event handler creates an event-sourced view. Each view represents one ViewModel used by the client application.
The views are managed by View Manager classes. In this case, we used the Microsoft SQL Server view manager to persist the view model content directly into SQL Server tables.
And here is an example of one of the SQL Server tables.
The REST API supports both commands and queries, of course. The Queries use a simple Micro ORM called PetaPoco to perform queries against the SQL Server tables created by the views. Since these tables are essentially read-only from this API, the methods in the Read API are very simple and fast.
That should give you a good overview of how the system was constructed.