Thursday, November 29, 2012

Hybrid CQRS implementation using MongoDb

Introduction to CQRS

Command and Query Responsibility Segregation(CQRS) is a pattern that suggests you to use different models to read and to write information.

In standard relational systems you have dilemma: use normalized database or denormalized database? In first case you get fine-designed database that is good for writing data, but has poor reading performance. In second case you get headache with your updates, but(if properly denormalized) you can get good reading performance.

So, CQRS suggests to use 2 different databases: one optimized for reading(denormalized) and another for writing(normalized). It is a very tempting way to designing systems. The only big problem with this solution is that you need somehow to sync you databases. You can create some sort of Denormalizer that would perform synchronization between your normalized and denormalized databases, after writings to your normalized database.

Is there a simpler solution?
I think there is one using NoSQL database(for example, MongoDb).

What is MongoDb?

MongoDb is a non-relational data store for JSON documents. More about MongoDb.
Big benefit of MongoDb is that it you can easily store\restore objects that you have inside your program to\from database. This help us much in our Hybrid CQRS implementation.

Hybrid CQRS implementation using MongoDb
All commands(write operations) go through Service layer where validators and other protective measures are applied. Querying(read operations) are allowed directly from Database to speed up process.

Since we use NoSQL database(MongoDb) it is not strictly necessary for us to use different databases for reading and writing. If we make proper design of our MongoDb database, it will be good for reading(due to structure of data storage) and no bad for writings(if we do not go too far with denormalization).

This CQRS implementation is applicable in cases when you want to use Domain-Driven design approach for your system Core, at the same time retaining the ability for fast data reading for your Web application.

No comments:

Post a Comment