CQRS is so easy.

This is just a quick post as I sit in the hospital bored to death and recovering.

I have been intrigued by CQRS, command and query responsibility segregation, ever since I heard about it in a talk by Greg Young at the first Code on the Beach conference. I decided to surf the blogosphere to see what people are doing these days with CQRS. It seems like there is still quite a bit of confusion about what it is.

I have to admit, at first it was extremely intimidating to me too. Not because CQRS is hard, but like many people, I blurred the lines between CQRS, DDD, and event sourcing. When you look at CQRS in the context of everything it is not, it tends to look more complicating than it really is.

I am going to borrow a trick that Greg uses and show a code example of the simplicity of CQRS. Let’s say we have a service that provides an API to manage a product catalog:

ProductManager

void CreateProduct(Product product)
Product GetProduct(string productId)
bool IsProductInStock(string productId)
void UpdateProductPrice(string productId, decimal price)
void RemoveProduct(string productId)
List<Product> GetProductRecommendations(string productId)

If we apply CQRS to this service, we would simply wind up with two services. One that we can optimize for write operations (commands) and another that is optimized for read operations (queries).

ProductQueries

Product GetProduct(string productId)
bool IsProductInStock(string productId)
List<Product> GetProductRecommendations(string productId)
ProductCommands

void CreateProduct(Product product)
void UpdateProductPrice(string productId, decimal price)
void RemoveProduct(string productId)

Easy, peazy… With the read and write operations segregated into their own APIs you are free to do all sorts of fancy optimizations and are on better footing to explore DDD and event sourcing.

Conclusion

The point is CQRS is just an extension of the simple CQS pattern that moves the concept a step further from the method to the class or API level. Nothing more, nothing less. I believe most applications can benefit from CQRS even if you aren’t going to do DDD or event sourcing. So, read all about CQRS, but if you are studying more than simple separation of read and write operations you have read too far and getting into other concepts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s