Introduction to Event Sourcing and Command-Query Responsibility Segregation
CQRS helps create task-based UIs, naturally maps to business contexts and use cases, and it makes reporting a lot easier.
Join the DZone community and get the full member experience.Join For Free
the concepts of event sourcing (es) and command-query responsibility segregation (cqrs) have been around for quite a while. they are getting more and more attention in the java community, though they seem to have been much more popular over on the .net side.
i have spent the last few months implementing a system with such an architecture at oasis digital . while working on it, we aimed for flexibility and the ability to make the right trade-offs and choose our own tools. some interesting solutions came up in the process, things that would probably be impossible with existing frameworks like axon .
i am going to write more about some of these pieces in the future. before we get there, let’s start with a brief introduction to event sourcing and command-query responsibility segregation.
the main idea of command-query separation (cqs) is that all operations are either:
- commands, changing state of the system,
- queries, getting some information from the system.
either one or the other, never both. for example, if a command changes anything in the system, it should not be used to read its state. mutation-free read access should always be possible. asking a system to change something to read a value seems plain wrong, and queries inadvertently changing state are very confusing, surprising and leading to bugs at best.
these principles can be applied on all levels. uncle bob in “clean code” calls it one of the main principles of good function design. the pattern is also applicable to system design.
cqrs in system architecture
command-query responsibility segregation (cqrs) is a pattern in system architecture inspired by cqs. it divides the system in two distinct parts, separating the components used for writing (executing commands) from those for querying. in such a system we can find two kinds of requests corresponding to these two models.
ac stands for autonomous component
firstly, there are commands – ordering the system do something or change its state. a piece of business logic updates the domain model (or rejects the command) and lets the client know that the change has been accepted (or not).
the business logic is often implemented using domain-driven design , but it may just as well be transaction script or any other applicable technique. actually, we ended up using a mix of these two in one area of the system.
whenever anything changes, the domain model somehow notifies everyone – for example by publishing domain events. these events are received by view models , which update their own representation of the state, separate from the domain model.
this leads us to the second kind of requests: queries , getting information from the system without changing its state. these only use the view models, not the domain.
what is especially powerful about this pattern is the separation of concerns.
the domain (write) side is all about the business. it does not care about queries, all the different ways to show this information to the users, performance, optimal storage for these purposes and all that.
on the other hand, the query (read) side is all about the read access. its main purpose is making queries fast and convenient.
while the domain is only implemented once, there can be multiple view models over the same data. they often use different databases. they can even be using different technologies – all kinds of nosql, normalized and denormalized sql, in-memory representations, lucene indexes, olap cubes etc.
the read models are also free to use different languages, if they make anything easier. there are no obstacles to implementing the domain model in scala, but doing view models in clojure or even sql stored procedures.
overall, the view models are very good (and safe) candidates for innovation.
unlike the domain model, code quality in view models does not have to be perfect. they’re all about reshaping data and moving it around to make reads convenient. some shortcuts and dirty tricks may be acceptable, as long as they don’t make the whole thing unmaintainable.
read models are often denormalized, prepared to answer concrete questions in optimal way. it can even be as extreme as having a precomputed set answers to every query that the system will handle, stored in some trivial key-value way.
we often call the view models “projections” – because they “project” the domain events to a particular model, keeping only as much information as is necessary and in optimal shape for queries they serve.
note that all the domain logic is only implemented in the domain (write) model. it’s done once and in the right place. even if a value is directly derived (calculated), as soon as it has a business meaning or is calculated with some business logic, it belongs in the domain model.
another pattern commonly used with cqrs is event sourcing .
in short, it means that all data in the system is stored in the form of events, in an event log. an event is a piece of information stating that something has occurred (user created, name changed, shipping address added, order submitted, order delivered). they’re always in past tense, saying that something has happened.
the events never change. you can never delete or update them. if something has happened, it’s happened. if it was a mistake, it can be corrected with a complementary action generating a new “inverse” event, but there’s no going back and saying it has not happened.
combining es and cqrs
event sourcing and command-query responsibility segregation perfectly fit each other. it’s a powerful synergy effect: each of them becomes more powerful thanks to the combination.
when a command comes in, the domain model calculates the new state of the system and possibly emits some new events (which are the only way the changes are persisted). when another command comes in for the same logical area, the domain model is restored from the past events, and responds to the new command by generating some new events. the events represent concrete changes that have business meanings. technically in a sense they are “deltas” (or “diffs”) of the system state.
the view models simply handle these events, picking up only these they are interested in, and updating their state to support future queries.
there are many benefits to using this approach, let me just point out a few of them.
cqrs naturally leads to task-based uis . every action represents some very concrete business event. there can be a huge difference between changing someone’s name, changing their shipping address, or making them a gold customer. if end user wants to change name, they get a small form that has exactly what is needed for that operation. if they make a customer gold – that’s another action in another form.
contrast this with the traditional crud, spreadsheet-like systems. they have no such operations as “change name” or “change customer status to gold”. all the users can do is “change user”. implementing logic that changes something when a particular field changes all of a sudden becomes harder. validation is a nightmare. auditing and simply seeing when something happened and what the users did, is impossible without adding more layers of complexity on top.
it is harder for the users, too – the use cases have to be implemented in their minds, knowing what to change when to achieve a desired effect.
related to the above, and a reason why cqrs is often used with domain-driven design, is that the shape of the system naturally maps to business contexts and use cases . commands correspond to concrete user intents, and queries are designed to answer concrete questions. once again, it’s the exact opposite of a glorified spreadsheet-like db frontend.
it’s applicable on higher level, too: different areas of the business (bounded contexts in the ddd lingo) can be implemented as separate models. for example, a warehousing context can represent a book in a completely different way than a sales context. one may be interested in its size, weight and number on stock. the other – in author, genre, cover image, publisher description etc.
event sourcing also makes reporting a lot easier . by definition it never loses information. maybe yesterday you did not need to know how often users add and remove items from the shopping cart, and only cared about the orders they eventually submitted. but today business wants to trace this information, so maybe they can discover items that clients wanted but changed their mind. it may be worthwhile to tempt them with these items in future ads.
answering such a change in a “traditional” system would be a nontrivial effort. with es+cqrs chances are that all it will take is just another straightforward projection of data that is already there, and immediately answer questions about the past!
finally, another obvious benefit is performance . since the view models are separate, they can have very different schema. avoid joins, keep data denormalized, answer many questions in linear or even constant time. read-only access is much easier to scale, as is the write side which doesn’t care about queries anymore.
es+cqrs is not without cost, and is not the best approach to all systems. more about this in a future post.
like i said in the beginning, these ideas have been around for quite a few years. there is a huge number of resources available online, in books and at conferences. this post has merely scratched the surface and is only meant as (yet another) humble introduction to the topic.
here’s a few links to the masters:
- martin fowler on event sourcing , cqs and cqrs .
- udi dahan on cqrs .
- greg young:
- sandro mancuso on crafted design (video) – pragmatic approach to architecture inspired by cqrs.
this post also appeared on the oasis digital blog .
Published at DZone with permission of Konrad Garus, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.