CQRS

This week I came across my first real-world honest-to-goodness example of a CQRS application. It works really well, and it’s very interesting to see a proper example of CQRS.

Even if you’re a full-time professional progammer, the chances are you won’t know what CQRS is. Martin Fowler explains it well in a blog post, though even after reading that you still might not be entirely sure what it really means.

So far as I understand, CQRS means updating your data-model using well-defined commands, which in turn cause events to fire, which in turn can be used to build a read-only view.

It sounds strange, and the name CQRS doesn’t help. I’ll be honest here and tell you that I can’t even remember what the acronym means, and even if I could it doesn’t really describe the mechanism that well [I just looked it up, and it means Command Query Responsibility Segregation].

Now, the idea of updating a model through commands actaully makes a lot of sense in many ways. It kind of ties in with the way you should do Domain-Driven-Development — you don’t want a bunch of properties and a Save() method, you really want operations that describe well-defined business goals.

As you execute commands against your model, events are fired. These events are used by the application to build a view of the data that meets a particular need. For example, let’s say you’re building an app for tracking used car sales. If you had a page that listed Prestige Used Cars, you might have a ‘NewCarListing’ event handler that only pays attention to events that involve cars over $30,000, and stores that data in a way that is custom-built just for that screen. It seems redundant, and it is, but the goal is to keep your domain logic pure.

As you read the last paragraph, you might have wondered how you could possibly build new reports based on commands and events that have already happened? Well, you keep a history of the commands, so you can replay them. [edit: I got a correction from @ToJans on Twitter that you actually replay events, not commands]. This strikes me as the place where any CQRS app is going to start getting overly complicated (compared to an equivelant solution, using an ORM for example), but in the example I saw yesterday (a definitely non-trivial application) it absolutely worked.

There aren’t many CQRS drop-in frameworks that you can easily use in your own projects, but there is a SimpleCQRS example project over on Gregory Young’s git hub page, and it might be worth looking at the Ncqrs Framework. Even if you don’t do CQRS in your own solution, just being aware of it is going to give you some good ideas that you definitely will be able to use.