Monday, January 6, 2014

Introduction to NCQRS

At Cognitive X Solutions, we use a piece of technology called NCQRS, which is a .NET implementation of the CQRS, Command Query Responsibility Segregation, pattern. At its heart, CQRS, is a simple notion that you can use a different model to update information than the model you use to read information. This simple notion leads to some profound consequences for the design of information systems. Normally, when we build information systems, we think in turns of CRUD (Create, Read, Update, Delete).  With CRUD, the expectation is that when you perform a database altering operation (Create, Update, Delete) that the next Read will reflect that change.  Not necessarily so with a CQRS system, as the Read and Write model are actually separate and the read model may take a bit of time to be updated from the write model because with CQRS it is possible that the machine that handled the update is not the same machine responsible for the read model.

So why would anyone want to use a CQRS data model?  It easily allows scalability. Before I can explain how, you first need to understand how CQRS works.  First off, CQRS is a pattern that enables Domain Driven Development, and is by nature object orientated.  So all modifying operations occur against an object, but not directly, you send a command to the CQRS system and it in turn performs the modification (create, update, delete).  Example:  You have an object that represents a Client, and to change their shipping address, you issue the command ChangeShippingAddress to the CQRS system.  The Client object then generates events that get answered (ie.  ShippingAddressChanged), and it is the answering of these events that perform the actual update.

So how does this command -> object -> event -> update process make for scalability?  Simple, the computer that issued the command isn't necessarily the computer that generates the events, nor does it have to be the computer that handles the events.  In fact you can go as far as having each domain object (ie.  Client, Inventory, Bill) handled by a separate computer, and each event generated by the domain objects handled by different computers.  This allows you to create a massively scalable system that can start as a single computer and very easily span multiple systems as demand dictates (especially if you introduce an Enterprise Service Bus (ESB) or some other type of mesasging middleware).

So over the next series of posts, I will lead you through developing a complex CQRS system with NCQRS.