Udi Dahan   Udi Dahan  -  The  Software  Simplist
 
Enterprise  Development  Expert  &  SOA  Specialist
 
 
Home Blog Consulting Training Articles Speaking About Contact
  

Command Query Separation and SOA

Monday, August 11th, 2008.

One of the common questions I receive from people starting to use nServiceBus is how one-way messaging fits with showing the user a grid (or list) of data. Thinking about publish/subscribe usually just gets them even more confused. Trying to resolve all this with Service Oriented Architecture leaves them wondering - why bother?

client server

In regular client-server development, the server is responsible for providing the client with all CRUD (create, read, update, and delete) capabilities. However, when users look at data they do not often require it to be up to date to the second (given that they often look at the same screen for several seconds to minutes at a time). As such, retrieving data from the same table as that being used for highly consistent transaction processing creates contention resulting in poor performance for all CRUD actions under higher load.

A Scalable Solution

One of the common answers to this question is for the server/service to publish a message when data changes (say, as the result of processing a message) and for clients to subscribe to these messages. When such a notification arrives at a client, the client would cache the data it needs. Then, when the user wants to see a grid of data, that data is already on the client. Of course, this solution doesn’t work so well for older client machines (like some point of service devices) or if there are millions of rows of data.

The thing is that this solution is one implementation of a more general pattern - command query separation (CQS).

Command Query Separation

Wikipedia describes CQS as a pattern where "… every method should either be a command that performs an action, or a query that returns data to the caller, but not both. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects."

Martin Fowler is less strict about the use of CQS allowing for exceptions: "Popping a stack is a good example of a modifier that modifies state. Meyer correctly says that you can avoid having this method, but it is a useful idiom. So I prefer to follow this principle when I can, but I’m prepared to break it to get my pop."

So, how does separating commands from queries and SOA help at all in getting data to and from a UI? The answer is based on Pat Helland’s thinking as described in his article Data on the Inside vs. Data on the Outside.

Services Cross Boxes

The biggest lie around SOA is that services run.

Let that sink in a second.

Sure services have runnable components, but that’s not why they’re important.

I’ll skip the books of background and cut to the chase:

Services communicate with each other using publish/subscribe and one-way messaging. Services have components inside them. Inside a service, these components can communicate with each using synchronous RPC, or any other mechanism. Also, these components can reside on different machines.

This is broader than just scaling out a service. There can be service components running on the client as well as the server.

SOA & CQS

Combining these two concepts together, here’s what comes out:

In this solution there are two services that span both client and server - one in charge of commands (create, update, delete), the other in charge of queries (read). These services communicate only via messages - one cannot access the database of the other.

The command service publishes messages about changes to data, to which the query service subscribes. When the query service receives such notifications, it saves the data in its own data store which may well have a different schema (optimized for queries like a star schema).

The client component which is in charge of showing grids of data to the user behaves the same as it would in a regular layered/tiered architecture, using synchronous blocking request/response to get its data - SOA doesn’t change that.

Composite Applications

Although the client side components of both the command and query services are hosted in the same process, they are very much independent of each other. That being said, from an interoperability perspective (the one that most people attribute to SOA), all of the client-side components will likely be developed using the same technology - although there are already ways to host Java code in .NET and vice-versa.

Of course, once we talk about web UI’s things are a bit different - but still similar. While web-server-side there may be a level of independence, for browser side inter-component communications we’re still likely to target javascript. There, I’ve managed to say something technical supporting mashups and SOA without lying through my teeth.

On the Microsoft side with the recent release of the Composite Application Guidance & Library (pronounced "prism") I hope that more of these principles will be reaching the "smart client". The command pattern is especially critical in maintaining the separation while enabling communication to still occur so I’m glad that, as one of the Prism advisors, I was able to simplify that part (Glenn still has nightmares about that rooftop conversation).

Publish / Subscribe

In the "scalable solution" section up top I mentioned how publish/subscribe to the smart client is really just one implementation of CQS and SOA. So, how different is it really?

smart client pub/sub

Well, there will probably be a different technology mapping. Instead of a star-schema OLAP product, we might simply store the published data in memory on the client. That is, if you designed your components to be technology agnostic.

In terms of the use of nServiceBus, the same component is going to be subscribing to the same type of message - all that’s different is that now every client will be having data pushed to them rather than this occurring server-side only.

You could have the same code deployed differently in the same system - stronger clients subscribing themselves, weaker ones using a remote server. Web servers would probably be considered stronger clients. This kind of flexible deployment has proven to be extremely valuable for my larger clients. The added benefit of enabling users to work (view data) even while offline (somewhere there’s no WIFI) is just icing on the cake.

A Word of Warning

Once the client starts receiving notifications, and handling those on a background thread (as it should) the code becomes susceptible to deadlocks and data races. Juval does a good job of outlining some of those with respect to the use of WCF. Prism doesn’t provide any assurances in this area either.

Summary

NServiceBus is not designed to be used for any and all types of communication in a given architecture. In the examples above, nServiceBus handles the publish/subscribe but leaves the synchronous RPC to existing solutions like WCF. Not only that, but synchronous RPC does have its place in architecture, just not across service boundaries. In all cases, data is served to users from a store different from that which transaction processing logic uses.

Command Query Separation is not only a good idea at the method/class level but has advantages at the SOA/System level as well - yet another good idea from 20 years ago that services build upon. Making use of CQS requires understanding your data and its uses - SOA builds on that by looking into data volatility and the freshness business requirements around it.

Finally, designing the components of your services in such a way that their dependency on technology is limited buys a lot of flexibility in terms of deployment and, consequently, significant performance and scalability gains.

Simple, it is. Easy, it is not.

  
If you liked this article, you might also like articles in these categories:


Check out my Best Content If you've got a minute, you might enjoy taking a look at some of my best articles.
I've gone through the hundreds of articles I've written over the past 4 years and put together a list of the best ones as ranked by my 2000+ readers.
You won't be disappointed.

Subscribe to my feedIf you'd like to get new articles sent to you when they're published, it's easy and free.
Subscribe right here.



Something on your mind? Got a question? I'd be thrilled to hear it.
Leave a comment below or email me, whatever works for you.

15 Comments

  1. Alex Simkin Says:

    Short question on CQS.

    “Usual” return value of the CREATE command is a surrogate key of the inserted (or sometimes upserted) entity. Even if natural key exists, it may be to clumsy to use. How this (getting identity of the created entity) should be handled in CQS.

    I have ment upsert to underline that it’s not always possible to generate identity on the client side.


  2. commenter Says:

    Its kind of funny that the wikipedia article illustrates CQS with a function that returns a value and changes the state. I think they’re saying that returning a value via an out parameter isn’t ‘returning a value’.

    So, to my understanding, CQS is really ‘only change state in methods with returntype == void’.


  3. udidahan Says:

    Alex,

    Actually, the SQL insert command doesn’t return the value of an identity column - you specifically have to query for it. That being said, all SQL statement do return the number of rows affected, an apparent violation of CQS.

    Personally, I liked GUIDs for IDs.


  4. udidahan Says:

    Commenter,

    Wikipedia is the outer join of the wisdom of crowds and the ignorance of herds, or so someone once told me ;)


  5. Alex Simkin Says:

    Even though you didn’t answer my question your responce gave me an idea to use GUID as a correlation value for subsequent query. As I explained, I cannot generate ID on the client, the record being “created” may already exist (service automatically removes duplicate facts).

    However, in this case, a new question arises: how long should service keep correlation value?


  6. Sergey Shishkin Says:

    Why don’t you use async messages for any potentially remote communication? Why at all do you encourage people to use RPC? (let’s left streaming aside) Is your position more like “RPC is OK for in-service remote communication” or more like “Avoid using Messages for in-service communication”? Could you elaborate more on this?


  7. Sergey Shishkin Says:

    Off topic: the comments feed seems to be broken, I can’t subscribe. See http://feedvalidator.org/check.cgi?url=http%3a%2f%2fwww.udidahan.com%2fcomments%2ffeed%2f


  8. Tyler Burd Says:

    Thanks for the great post, Udi. This applies to my current situation, and it has helped clarify things greatly.

    Alex, we’re toying with the idea of using an ID broker service for things that we can’t have GUIDs for. This way a client can send a RequestNextId message, the server generates the next id (and reserves it so no future entities can use it), and then sends back a message to the original sender. The correlation is done automatically for you in nServiceBus (via the IdForCorrelation property of the TransportMessage class if you’re using the MSMQTransport). The client receives the message and knows which RequestNextId message it correlates to.


  9. udidahan Says:

    Alex,

    I’m not quite sure I understand your question, but does the REST style solution I described in previous post correlate to the way your thinking about using GUIDs?

    If so, then I’d use a long-running process like nServiceBus’ sagas to manage the allocation and cleanup of those GUIDs. You’d probably want to experiment with various cleanup times until you settle on a cleanup policy that works for you.

    Hope that helps.


  10. Alex Simkin Says:

    Oh, now I see from where this idea has come to me :)

    Thank you very much, indeed.


  11. The straw that healed the camels back | The Freak Parade Says:

    […] the system within that paradigm, even when the fit seemed just terrible. Udi Dahan was kind enough to post about that exact topic in his blog last night, setting a critical thought-balloon free and allowing a system design […]


  12. udidahan Says:

    Sergey,

    > Why don’t you use async messages for any potentially remote communication?

    When the architecture itself is synchronous, introducing one-way messaging brings quite a lot of complexity. Also, the robustness and scalability benefits are thwarted by the synchronous architecture.

    You can’t be going both left and right at the same time.

    > Why at all do you encourage people to use RPC?

    I’m trying to encourage people to understand the tradeoffs between the various choices - one way/pub sub/rpc. What makes sense where, and why.

    > Is your position more like “RPC is OK for in-service remote communication” or more like “Avoid using Messages for in-service communication”?

    My position is that, if there’s any place where RPC will cause the minimal amount of damage, it’s within service bounaries.

    I would definitely NOT suggest the latter. Messaging is such a strong paradigm that it requires the overall architecture to be aligned with it. When that occurs, you get tremendous benefits from using messaging within service boundaries as well.

    Finally, the main point is to understand the different contexts for making decisions. Between services, under no circumstances should RPC be used - unless its an insignificant implementation detail in supporting a higher level messaging infrastructure (MSMQ makes use of RPC under the covers).

    Hope that clears it up.

    I’ll check on the comment feed, thanks.


  13. Colin Jack Says:

    @udidahan
    Would it be fair to say that the upper layers mainly communicate with the Query services synchronously? I’m thinking here of getting all Customers, getting a Customer to edit and so on.


  14. udidahan Says:

    Colin,

    That’s correct.


  15. SOA, EDA, and CEP a winning combo Says:

    […] How client interaction fits with SOA […]


Your comment...



If this is your first time commenting, it may take a while to show up.
I'm working to make that better.

Subscribe here to receive updates on comments.
  
   


Don't miss my best content
 
Locations of visitors to this page

Recommendations

Sam Gentile Sam Gentile, Independent WCF & SOA Expert
“Udi, one of the great minds in this area.
A man I respect immensely.”





Simon Segal Simon Segal, CTO at IT Results Pty Ltd
“Udi is one of the outstanding software development minds in the world today, his vast insights into Service Oriented Architectures and Smart Clients in particular are indeed a rare commodity. Udi is also an exceptional teacher and can help lead teams to fall into the pit of success. I would recommend Udi to anyone considering some Architecural guidance and support in their next project.”

Ohad Israeli Ohad Israeli, Chief Architect at Hewlett-Packard, Indigo Division
“When you need a man to do the job Udi is your man! No matter if you are facing near deadline deadlock or at the early stages of your development, if you have a problem Udi is the one who will probably be able to solve it, with his large experience at the industry and his widely horizons of thinking , he is always full of just in place great architectural ideas.
I am honored to have Udi as a colleague and a friend (plus having his cell phone on my speed dial).”

Eli Brin, Program Manager at RISCO Group
“We hired Udi as a SOA specialist for a large scale project. The development is outsourced to India. SOA is a buzzword used almost for anything today. We wanted to understand what SOA really is, and what is the meaning and practice to develop a SOA based system.
We identified Udi as the one that can put some sense and order in our minds. We started with a private customized SOA training for the entire team in Israel. After that I had several focused sessions regarding our architecture and design.
I will summarize it simply (as he is the software simplist): We are very happy to have Udi in our project. It has a great benefit. We feel good and assured with the knowledge and practice he brings. He doesn’t talk over our heads. We assimilated nServicebus as the ESB of the project. I highly recommend you to bring Udi into your project.”

Yoel Arnon Yoel Arnon, MSMQ Expert
“Udi has a unique, in depth understanding of service oriented architecture and how it should be used in the real world, combined with excellent presentation skills. I think Udi should be a premier choice for a consultant or architect of distributed systems.”

Vadim Mesonzhnik, Development Project Lead at Polycom
“When we were faced with a task of creating a high performance server for a video-tele conferencing domain we decided to opt for a stateless cluster with SQL server approach. In order to confirm our decision we invited Udi.

After carefully listening for 2 hours he said: "With your kind of high availability and performance requirements you don’t want to go with stateless architecture."

One simple sentence saved us from implementing a wrong product and finding that out after years of development. No matter whether our former decisions were confirmed or altered, it gave us great confidence to move forward relying on the experience, industry best-practices and time-proven techniques that Udi shared with us.
It was a distinct pleasure and a unique opportunity to learn from someone who is among the best at what he does.”

Jack Van Hoof Jack Van Hoof, Enterprise Integration Architect at Dutch Railways
“Udi is a respected visionary on SOA and EDA, whose opinion I most of the time (if not always) highly agree with. The nice thing about Udi is that he is able to explain architectural concepts in terms of practical code-level examples.”

Sean Farmar Sean Farmar, Chief Technical Architect at Candidate Manager Ltd
“Udi has provided us with guidance in system architecture and supports our implementation of NServiceBus in our core business application.

He accompanied us in all stages of our development cycle and helped us put vision into real life distributed scalable software. He brought fresh thinking, great in depth of understanding software, and ongoing support that proved as valuable and cost effective.

Udi has the unique ability to analyze the business problem and come up with a simple and elegant solution for the code and the business alike.
With Udi's attention to details, and knowledge we avoided pit falls that would cost us dearly.”

Motty Cohen, SW Manager at KorenTec Technologies
“I know Udi very well from our mutual work at KorenTec. During the analysis and design of a complex, distributed C4I system - where the basic concepts of NServiceBus start to emerge - I gained a lot of "Udi's hours" so I can surely say that he is a professional, skilled architect with a fresh ideas and unique perspective for solving complex architecture challenges. His ideas, concepts and parts of the artifacts are the basis of several state-of-the-art C4I systems that I was involved in their architecture design.”

Aaron Jensen Aaron Jensen, VP of Engineering at Eleutian Technology
“Awesome. Just awesome.

We’d been meaning to delve into messaging at Eleutian after multiple discussions with and blog posts from Greg Young and Udi Dahan in the past. We weren’t entirely sure where to start, how to start, what tools to use, how to use them, etc. Being able to sit in a room with Udi for an entire week while he described exactly how, why and what he does to tackle a massive enterprise system was invaluable to say the least.

We now have a much better direction and, more importantly, have the confidence we need to start introducing these powerful concepts into production at Eleutian.”

Gad Rosenthal Gad Rosenthal, Department Manager at Retalix
“A thinking person. Brought fresh and valuable ideas that helped us in architecting our product. When recommending a solution he supports it with evidence and detail so you can successfully act based on it. Udi's support "comes on all levels" - As the solution architect through to the detailed class design. Trustworthy!”

Robert Lewkovich, Product / Development Manager at Eggs Overnight
“Udi's advice and consulting were a huge time saver for the project I'm responsible for. The $ spent were well worth it and provided me with a more complete understanding of nServiceBus and most importantly in helping make the correct architectural decisions earlier thereby reducing later, and more expensive, rework.”

Ray Houston Ray Houston, Director of Development at TOPAZ Technologies
“Udi's SOA class made me smart - it was awesome.

The class was very well put together. The materials were clear and concise and Udi did a fantastic job presenting it. It was a good mixture of lecture, coding, and question and answer. I fully expected that I would be taking notes like crazy, but it was so well laid out that the only thing I wrote down the entire course was what I wanted for lunch. Udi provided us with all the lecture materials and everyone has access to all of the samples which are in the nServiceBus trunk.

Now I know why Udi is the "Software Simplist." I was amazed to find that all the code and solutions were indeed very simple. The patterns that Udi presented keep things simple by isolating complexity so that it doesn't creep into your day to day code. The domain code looks the same if it's running in a single process or if it's running in 100 processes.”

Liron Levy, Team Leader at Rafael
“I've met Udi when I worked as a team leader in Rafael. One of the most senior managers there knew Udi because he was doing superb architecture job in another Rafael project and he recommended bringing him on board to help the project I was leading.
Udi brought with him fresh solutions and invaluable deep architecture insights. He is an authority on SOA (service oriented architecture) and this was a tremendous help in our project.
On the personal level - Udi is a great communicator and can persuade even the most difficult audiences (I was part of such an audience myself..) by bringing sound explanations that draw on his extensive knowledge in the software business. Working with Udi was a great learning experience for me, and I'll be happy to work with him again in the future.”

Eytan Michaeli Eytan Michaeli, CTO Korentec
“Udi was responsible for a major project in the company, and as a chief architect designed a complex multi server C4I system with many innovations and excellent performance.”

Evgeny-Hen Osipow, Head of R&D at PCLine
“Udi has helped PCLine on projects by implementing architectural blueprints demonstrating the value of simple design and code.”

Nimrod Peleg Nimrod Peleg, Lab Engineer at Technion IIT
“One of the best programmers and software engineer I've ever met, creative, knows how to design and implemet, very collaborative and finally - the applications he designed implemeted work for many years without any problems!”

Consult with Udi

Guest Authored Books
Chapter: Introduction to SOA    Article: The Enterprise Service Bus and Your SOA



Creative Commons License  © Copyright 2008, Udi Dahan.