- CQRS often goes hand in hand with event sourcing.
- This is a pattern where you don’t store the current state of your model in the database, but rather the events that happened to the model.
- When the name of a customer changes, you won’t store the value in a “Name” column.
- You will store a “NameChanged” event with the new value (and possibly the old one too).
- When you need to retrieve a model, you retrieve all its stored events and reapply them on a new object.
- This is caleed "rehydrating an object".
- A real-life analogy of event sourcing is accounting.
- When you add an expense, you don’t change the value of the total.
- A new line is added with the operation to be performed.
- If an error was made, you simply add a new line.
- To make your life easier, you could calculate the total every time you add a line.
- This total can be regarded as the read model.
- The event sourcing works in a wayt that you never remove events, because they have undeniably happened in the past.
- To correct situations, we add new events.
- Event sourcing is often combined with CQRS because rehydrating an object can have a performance impact.
- A fast read model can significantly improve the response time of the application.
- A microservice architecture based on events and commands helps with resilience, scalability, traceability, and loose coupling in the system.
- Events represent facts of information about something that has happened in the past (for example, OrderCreated, ProductShipped).
- Events can be disregarded but they cannot be retracted or deleted.
- New events/facts arrive in the system that can invalidate the existing facts.
- Commands, on the other hand, are the object form of a method/action.
- They are imperative.
- Examples of commands are CreateOrder and ShipProduct.
Advantages
- This software architecture pattern can provide an audit log out of the box.
- Each event represents a manipulation of the data at a certain point in time.
Disadvantages
- It requires some discipline because you can’t just fix wrong data with a simple edit in the database.
- It’s not a trivial task to change the structure of an event.
- If you add a property, the database still contains events without that data.
- Your code will need to handle this missing data graciously.
Scenarios
- Need to publish events to external systems.
- Will be built with CQRS.
- Have complex domains.