What is the difference between CQRS (Command Query Responsibility Segregation) and Event Sourcing?
I believe Event Sourcing is a type of CQRS. What distinguishes each, and what makes Event Sourcing different from other types of CQRS?
Thanks,
CQRS was introduced by Greg Young; his explanation in 2010
CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query (the same definition that is used by Meyer in Command and Query Separation, a command is any method that mutates state and a query is any method that returns a value).
Typically, this means that each of the objects will use a different representation of the data, so as to be fit for purpose. Common language here is to refer to a "write model" and a "read model". It is usually the case that changes will be made to the write model first, and propagate asynchronously to the read model.
As it happens, there's nothing magic about the number "2"; you could just as easily have 3 different representations as two.
The key benefit here is that you can tune the data structures for your read use cases and your write use cases independently.
Event sourcing is a pattern for recording the state in a non-destructive way. Each change of state is appended to a log. Because the changes are non-destructive, we preserve the ability to answer queries about the state of the object at any point in its life cycle.
The use of events affords a more efficient use of storage space (relative to storing the complete representation of the state after each change) while retaining the semantic intent of the change (relative to just storing diffs)
Greg described event sourcing this way
storing current state as a series of events and rebuilding state within the system by replaying that series of events
These techniques are frequently paired together, because the log, as a conceptual data structure, is not particularly efficient at supporting queries. You will normally want to condense the log into some other representation that is more suitable for reads (which are likely to be much more frequent than writes).
Thus, in the CQRS pattern, we typically use a log as the persistence model, and then from that log create query suitable representations of the object, and cache those representations such that queries can be supported quickly (accepting the compromise that the representation used in the query will not always reflect the absolute latest information available).