CQRS and MVC

What is CQRS? Well if we ask google it will say “did you mean CARS?” (although it seems for developers who search a lot it now actually comes up.

According to http://www.all-acronyms.com/CQRS CQRS is Commercial Quality Rimmed Steel

 

CQRS is none of these things. CQRS is not new. One of my favorite questions I get from people is “How many real systems are there running with this kind of CQRS stuff”. The answer is ten if not hundreds of thousands. It even funnier when asked about Event Sourcing as I actually worked on a system 10 years ago using Event Sourcing (it used to be really popular).

 

CQRS is pretty much MVC!

 

I have had very few people notice this when teaching but occasionally a bright one will pick up on it. Of course CQRS is not precisely MVC but it is definitely a variant. Let’s go way back to 1979 and look at what Trygve had to say about MVC. http://heim.ifi.uio.no/~trygver/1979/mvc-2/1979-12-MVC.pdf

 

 

MODELS

Models represent knowledge. A model could be a single object (rather uninteresting), or it

could be some structure of objects. The proposed implementation supports knowledge

represented in something resembling semantic nets (If I understand Laura correctly)

There should be a one-to-one correspondence between the model and its parts on the one

hand, and the represented world as perceived by the owner of the model on the other hand.

The nodes of a model should therefore represent an identifiable part of the problem.

The nodes of a model should all be on the same problem level, it is confusing and considered

bad form to mix problem-oriented nodes (e.g. calendar appointments) with implementation

details (e.g. paragraphs).

 

VIEWS

A view is a (visual) representation of its model. It would ordinarily highlight certain attributes

of the model and suppress others. It is thus acting as a presentation filter.

A view is attached to its model (or model part) and gets the data necessary for the presentation

from the model by asking questions. It may also update the model by sending appropriate

messages. All these questions and messages have to be in the terminology of the model, the

view will therefore have to know the semantics of the attributes of the model it represents. (It

may, for example, ask for the model’s identifier and expect an instance of Text, it may not

assume that the model is of class Text.)

The main difference when we talk about a system that has had CQRS applied is that there are TWO models. There is a model representing the mental model of the user and there is another model representing how transactions flow through the system. These two models are often eventually consistent with each other.
The model on the read side, supporting the views is read only. The model supporting the controllers is write-only. Synchronization is achieved either through a shared data model or through events from the write model to the read model.

 

CQRS is pretty much MVC. I am not sure I would assert that it is MVC given the definition but it is very similar. I also doubt that it is Udi or I who first thought of doing it. My guess is you can find many systems doing it.

 

CQRS is also very similar to P-7: INPUT/OUTPUT SEPARATION in http://heim.ifi.uio.no/~trygver/2003/javazone-jaoo/MVC_pattern.pdf 

The input and output aspects of the Editor are technically very different with few interdependencies. Their

combination in a single object tends to make this object unnecessarily complex.

 

The major difference being the separation is only being applied at the first level then returning to a single model as drawn (CQRS is about driving this separation further and further back with benefits at each step). I am rather certain that Trygve has also come across the point that very often the model representing the user’s mental model is often very different than the model for expressing how invariants are maintained and that it can be advantageous to push the separation even further back to the models. The benefit is also seen technically when pushing even further back to data storage mechanisms. 

 

Understanding this will take you a long way towards understanding what people are talking about with CQRS it is certainly a variant of if not actually MVC.

 

 

If you are from Australia they are trying to get me to come down. Could you fill out this? 

This entry was posted in CQRS. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

17 Responses to CQRS and MVC

  1. Raisul Kabir says:

    Nice article Greg. In one of our project we are using CQRS with Microsoft MVC 3. It’s not like, either or, both can be used at the same time IMHO.

  2. william simons says:

    Greg,
    I am excited to see you write a new book about this subject! I have always liked the idea of commanding in a controller. Java spring mvc seems to closely follow this pattern
    I do have a question Can you use this technology in asp.net mvc 4 web api? What are some good educational sources ?
    sources rence

  3. Thanks for writing this. I really feel as though I know so much more about this than I did before. Your blog really brought some things to light that I never would have thought about before reading it. You should continue this, Im sure most people would agree youve got a gift.

  4. scooletz says:

    Can you post a similar survey for Poland as you did for Australia? 😉

  5. Nuno Lopes says:

    Hi Scott,

    Just one more quick note.

    “I just don’t get how CQRS is any different from using a cache.”

    Probably in your solutions isn’t. But cache is a result of using CQRS wether you characterize it that way or not. Indeed I don’t see how we can cache data without using CQRS.

    You may think of that is the case then thousands of developers use CQRS. Most CMS apps do etc etc. Well that is what makes a pattern a pattern IMHO, not because someone says so.

    On another note, CQRS does not imply the use of cache IMHO. A common scenario is when you use an ORM to map the domain model to a relational model in an RDBMS. Instead of going through the ORM Query language I seldom go diecretly to the database for that matter. The reason is that developers know more about SQL then say OQL and UI widgets are already built dealing with the data structure as exposed by a Relational Model then a Domain Model.

    The good thing of formalizing this usages into a pattern is such that we can then think about why we are using it and fit it to particular usages.

    In Clarified CQRS from Udi, I think he describes CQRS in ways too complicated. Although all the content is valuable. IMHO in the end of the day is just one implementation of CQRS. I goes to the extent that CQRS is composed by a set of principles rather then a set of solutions in some posts. Well we can’t argue against a set of principles can we?

    As far as I know CQRS is born to deal with a client side concerns then internal concerns of a domain model in a distributed environment. I don’t mean it is a implemented on the client, but from a domain model point of view is above it to facilitate client interactions. Commands, queries, events, views, controllers are all artifacts to facilitate this. It also provides the guide lines to create an integration language (SubmittPurchaseOrder – > PurchaseOrderSubmitted) to facilitate the integration of client usages. Otherwise, why bother. Building a view without intent the only option is crack the database model (as we did with W4), but as you know that is not an easy task most of th time, sometimes the costs are so high that becomes impossible considering budget constraints. With events things can be easier I guess.

    Hence I argue that that CQRS core is to bridge he gap between the clients processing model and the suppliers processing model . Much like MVC is a bridge between the user mental model and the computer processing model.

    Now what I see Udi and Greg describing is particular applications of this pattern taking into consideration other forces.

    Perfection is achieved not when there is no more things to add but when there are no more things to take away. I think this should be kept in mind when looking at a pattern, because it needs to be perfect.

    Cheers,

    Nuno
    PS: I should warn that I may be a bit of a DDD rogue. I’m just exposing my thoughts. In no way I’m stating what CQRS should be or not. But if I make sense, then maybe I’m not that far away.

  6. Nuno Lopes says:

    Hi Scott, according to Trygve the essential purpose of MVC is to bridge the gap between the human user’s mental model and the digital model that exists in the computer.

    Now the case that is made in my article that the essential purpose of CQRS is to bridge the gap between the clients processing model and the internal model that exists within a Bounded Context.

    Lately I’ve been working with team responsible for implementing Workflows supporting several processes within the company. To this they use a product named W4. Users use a Workbench where processes and tasks are defined visually, fields per tasks, connector, rules, routing, notifications etc etc. You can imagine the generic model used by W4 since has no specific domain attached to it besides the one of building workflows. The tool generates screens dynamically, transitions and so on.

    Has it happens the model of W4 is so dynamic, that as the data grown in quantity searches became extremely slow! A search could take form 2 to 10 seconds or more.

    What we did? We developed a script that is ran every 5 seconds extracting the new or changed data and denormalizes into to a view only model.

    Searches are now snappy and is an incredible boost in user productivity yet we haven’t lost the flexibility offerend by W4.

    Changes still go through the W4 APIs while, user searches use the view model.

    Granted, this is not CQRS applied to the all application, but I argue that it CQRS applied to a slice.

    If W4 was designed to publish events, then we could use those events to update the view in our script could be much simpler and lighter. The view could be updated in a split of a second.

    There are loads of exemples, as for instance searching through hierachical data. We know that RDBMS is not really good for that. Then we have full text search. We also know that most database are not very good with that either.

    On top of this we have that clients that require data to be serviced in a particular intricate format. There is no reason why we can’t just pre compute changes in structure and store them in some view only data store and let clients query that store instead.

    The most pure case is when you imagine not having a database supporting queries retuning flat results as well as an RDBMS and the only thing you have to store objects is a database that simple stores blobs. What do you do then?

    There is a huge advantage in terms of performance in using a scheme such as CQRS. It allow developers to explore the best structure data needs to have for a particular task.

    On top of this you also get the benefit of not charging the domain model data store with systematic query requests that add no business value but presentation.

    The core difference between MVC and CQRS is that MVC can virtually deal with thousands of views over the same model, most of them durable as the lifecycle of a screen.

    Unlike MVC, CQRS Views have a more permanent lifecycle. So in that respect different challenges and solutions are necessary. But it also opens other opportunities.

    On another note you can imagine a P2P chat program when each chat program publish messages to each pear and receive messages subscribed form some pears. Using this architecture you could eventually have thousands of pears in a ring or diamond, talking to each other.

    Hope this helps understanding how powerful this pattern is.

    Markus, controllers get data either sent with commands or from Repositories in the domain model. That is the way I use it.

    Cheers,

    Nuno

  7. Markus Zywitza says:

    You are writing that the controllers use a write-only model. Do they also get the state they need from the read-side-model?

    I thought that the command-side uses the command-side-model entirely for both reading and writing, constituting a headless application. The application GUI uses the read-side-model for displaying values to the user, just as reporting or services that access the application’s data.

  8. Scott Rudy says:

    Nuno, I see the point is that users don’t update the view, but they update the model through the controller, which could publish updates to the view in a rich client scenario. I get that. I just see the view as something that deals with more than data as it contains UI elements like buttons and images. For that reason it just seems fundamentally different. That’s why the comparison doesn’t make sense to me.

    I see that there are two models, that can be structurally differently, in CQRS which present themselves as two different logical data stores, one for read and one for write. These stores would probably be physically separated as well. The read store would also be synchronized with the write store in some manner, whether pushed by events or pulled using some polling mechanism. That read-only store could be placed in various places in the architecture where it makes sense. I just don’t get how CQRS is any different from using a cache.

  9. Agafonov says:

    Command-Query Responsibility Segregation – CQRS
    is a way of designing and developing scalable and robust enterprise solutions with rich business value.

  10. Nuno Lopes says:

    When I mentioned “we then argue” meant “we, the programmers”.

  11. Nuno Lopes says:

    Hi Scott, if you read my article, several MVC – CQRS compositions are discussed.

    From the MVC point of view, the set of Commands and Queries built using CQRS compose a façade over a domain model.

    Facade: http://en.wikipedia.org/wiki/Facade_pattern

    Trygve admits that the MVC model can be implemented has a facade :http://heim.ifi.uio.no/~trygver/2003/javazone-jaoo/MVC_pattern.pdf

    So in the end of the day, from the UI point of view we have only one model, not two.

    CQRS is at a layer “bellow”.

    We then argue that such separation of concerns is driven by downstream and up stream forces within the context of scalability and business process orchestration.

    Does this help?

  12. Scott Rudy says:

    Greg, thanks for the response. I actually do have two distinct models, but I felt the query model could just abstract the command model allowing the controller to only have to deal with a single model.

  13. Scott Rudy says:

    I can’t say I agree with you on this one Greg, but I am wondering if maybe I am missing something. I posted a response on my blog illustrating how I see the two relate to each other and how I might go about implementing the model in MVC.

    http://h30507.www3.hp.com/t5/The-Watering-Can-of-Enterprise/Implementing-CQRS-Using-MVC/ba-p/82300

  14. George Mauer says:

    @Tony
    Yes, that’s what Greg is talking about, though he tends to rely more on Event Sourcing than Udi does.

  15. Tony says:

    I have never heard of CQRS before. Just so we are on the same page, would this overview match http://www.udidahan.com/2009/12/09/clarified-cqrs/ what you are referring to? More or less?

  16. Roco says:

    “Synchronization is achieved either through a shared data model or through events from the write model to the read model.”

    I am interested in hearing more specifics around how you keep the two models in sync. If possible, please elaborate on the shared data model approach with specifics. Are we talking transaction replication, ETL, triggers, etc???

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>