Need help to understanding CQRS architecture - cqrs

I try to under cqrs architecture style. I found sample image of cqrs architecture.
http://blog.trifork.com//wp-content/uploads/2010/01/cqrs_architecturehighlevel.png
If command handling is persisting data to database, why event handling update storage to?
Example:
If I have CreateUserCommand, where place the persistent, in command handling or event handling.
Thank You

From the diagram, it looks to me like a CQRS and event sourced architecture. This means that the domain model will generate events in response to commands. Unlike DTO or view models, you store them in an event store. The event store holds the state transitions for the domain but is not used for the front end. For the front end you need a read model. You generate a read model from the events. Hence the need for the event handlers to write to the database. Of course they are writing to the read model not the event store. I have a similar diagram with more detailed explanation at my blog. You can find the post here: CQRS: A Step by Step Guide to The Flow of a Typical Application. I hope you find the helpful.

Related

Understanding AKKA persistence and ES and CQRS principles

I have recently watched several videos about ES and CQRS models as well as I have watched few talks about AKKA persistence. I know what they are about but I have issues writing actual code that will execute.
I have few questions though.
How should i make view and event stack communicate?
Will events be passed between view and persistent actor of same persistence id passed?
What are persistent actor and view responsible for according to the model?
Edit: Where should i place my business logic? According to model i should do that in write, but what if i need to check something in read to validate cmd?
You shouldn't need to check something in your read mode to validate a command - your command would execute against your write model.
Your business logic would go in your write side, if using Akka then inside an Actor.
You haven't said what your view is so there could be multiple ways of communicating - for example, if a web page you could do req/res, or use something like SignalR

CQRS - is it allowed to call the read side from the write side?

I started with reading about CQRS and I'm little confused.
Is it allowed to call the read side within the write side for getting additional informations?
http://cqrs.nu/Faq/command-handlers here they say it is not allowed, but in the cqrs journey code I found that they call a service 'IPricingService' which internally uses a DAO service class.
So what I must do to get additional informations inside my aggregation root?
CQRS Journey should not be seen as a manual. This is just a story of some team fighting their way to CQRS and having all limitations of using only Microsoft stack. Per se you should not use your read model in the command handlers or domain logic. But you can query your read model from the client to fetch the data you need in for your command and to validate the command.
Since I got some downvotes on this answer, I need to point, that what I wrote is the established practice within the pattern. Neither read side accesses the write side, not write side gets data from the read side.
However, the definition of "client" could be a subject of discussion. For example, I would not trust a public facing JS browser application to be a proper "client". Instead, I would use my REST API layer to be the "client" in CQRS and the web application would be just a UI layer for this client. In this case, the REST API service call processing will be a legitimate read side reader since it needs to validate all what UI layer send to prevent forgery and validate some business rules. When this work is done, the command is formed and sent over to the write side. The validations and everything else is synchronous and command handling is then asynchronous.
UPDATE: In the light of some disagreements below, I would like to point to Udi's article from 2009 talking about CQRS in general, commands and validation in particular.
The CQRS FAQ (http://cqrs.nu/Faq) suggests:
"How can I communicate between bounded contexts?
Exclusively in terms of their public API. This could involve subscribing to events coming from another bounded context. Or one bounded context could act like a regular client of another, sending commands and queries."
So although within one BC its not possible to use read-side from write-side and vice-versa, another bounded context or service could. In essence, this would be acting like a human using the user interface.
Yes assuming you have accepted the eventual consistency of the read side. Now the question is where. Although there is no hard rule on this, it is preferable to pass the data to command handler as opposed to retrieving it inside. From my observation there are two ways:
Do it on domain service
Basically create a layer where you execute necessary queries to build the data. This is as straightforward as doing API calls. However if you have your microservices running on Lambda/Serverless it's probably not a great fit as we tend to avoid a situation where lambda is calling another lambda.
Do it on the client side
Have the client query the data then pass it to you. To prevent tampering, encrypt it. You can implement the decryption in the same place you validate and transform the DTO to a command. To me this is a better alternative as it requires fewer moving parts.
I think it depends.
If in your architecture the "command side" updates the projections on real-time (synchronously) you could do that calling the query api. (although that seems strange)
But, if your projections (query side) is updated asyncronously would a bad idea to do it. Would be a posibility to get a "unreal" data.
Maybe this situation suggests a design problem that you should solve.
For instance: If from one context/domain you think you need information from another, could a domain definition problem.
I assume this, because read data from itself (same domain) during a command operation doesn't make much sense. (in this case could be a API design problem)

iOS Client: "Caching" Server-side data to persistent storage

I'm building an iOS client app to interface with an existing backend architecture. To reduce latency, API calls and payloads, it'd be nice to "cache" model data client-side for faster indexing and then make updates to both client/server sides accordingly as needed.
The current theoretical stack would look something like this:
Server Side >>>>>>>>>>>>>>>>> Client Side
-----------------------------------------
PHP >> JSON >> CORE DATA >> UIKit Objects
NOTE: It's also worth noting that the iOS client, while itself adhering to MVC internally would in essence be a "View" in a larger MVC client-server architecture. Thus, just like one updates the model after a user action or updates the view after a model change, the server would need to sync with a client change and the client would need to sync with a server-side change.
Some Context:
A. Many diverse data structures may be coming over the pipe and would have to be constructed into UIViews dynamically. A schema will likely have to be defined (I'm not sure if there's a "best way" to adhere to a JSON schema client-side other than remembering what the acceptable object structures are). I've realized the need to separate model data pertaining to the creation of custom views ("View" Models) from model data of what will be presented in those views ("Regular" Models).
B. End-users should be able to immediately CRUD (create, read, update, destroy) most data presented in these views (but not CRUD the views themselves). They may later need to view this in a web interface or other context.
C. RestKit looks like a good candidate for getting from the API to JSON to COREDATA. I need to find out if it structurally supports callbacks when client model copies need to be pushed to the server. Perhaps the best way is noting in the client model when a change has occurred and notifying whatever RestKit-based HTTP manager to pass it along to the server.
Ultimate Question:
Can anyone speak to best practices, pitfalls, tips, and frameworks with this type of architecture? (Particularly when it comes to performance and the distribution of work between client and server, but general advice is also much appreciated.)
I've done some work around this, hopefully I can provide some insight.
In regards to A) Yes if you're planning to use CoreData (or RestKit) you'll need to know you schema up front. You'll have no way to map dynamic objects otherwise unless you have some generic object type where you're just stashing the JSON string or something, but this doesn't sound like what you're trying to do since you mention users editing those objects.
B) RestKit will handle pushing to the server for you, but you'll still want some control over this I imagine. We handled it by always saving locally first then pushing up to the server on a successful save. This also enabled us to work when there's no network. You'll just have to handle the edge cases of what happens when the server rejects the update / create / delete your user is performing.
C) RestKit will likely get you 80% of the way there, as it did for us. Just having something to understand REST endpoints and object mapping, and abstracting the HTTP requests was a huge help. In terms of the system understanding changes, we kept a flag on managed objects as to whether the object needed a sync or not. We could fetch based on those flags and push the server up.
One thing with RestKit is that you can have other attributes in your CoreData model that aren't necessarily a part of the JSON schema, but you might need within your app. For instance I already mentioned the flag for knowing whether an object needed sync. We also kept pre-computed fields that we used to search on and some other random pieces of information for determining the order of objects to push up to the server (dependencies).
Hope this helps. If you have more specific questions I might have more answers.

CQRS and service bus

CQRS is about separating commands and queries. We can add it easily using several patterns & technologies like Event Sourcing, DDD, NoSQL, etc... but is ServiceBus mandatory?
I'd say messaging and a service bus is optional.
CQRS simply means decomposing your application so that the Read and Write parts of your application can be optimized for the respective concern. Commands can be handled directy, even Events, if you decide to use them, can be dispatched synchronously.
A good reference for using an internal dispatcher is Greg Young's simple examle.
Update: Rob Ashton has just posted a very good article on what CQRS is and how not to make it more complicated than it actually is.
No serviceBus is not mandatory, it's simply one of the technologies that be used to implement CQRS, for example Event Pub/Sub. If anything, Event Sourcing & DDD have a closer relationship to CQRS than ServiceBus.
No. You can use CQRS without service bus. In your case you only need the command dispatcher and the query dispatcher

How do you handle change tracking in MVVM?

I have written a small helper for doing client-side change tracking objects/dtos to use in my ViewModels (see http://viss.be/2009/04/02/modelviewcontext-client-side-change-tracking/)
I didn't find a lot of resources about the subject. So I wonder; how do you typically handle it?
Thanks,
Marc
A ViewModel is all about binding the View (UI) to the Model (data). So it should not be responsible for tracking changes, that is something you should be doing inside of you Model classes as they contain the data.
To notify the UI both Model and ViewModel implement INotyfyPorpertyChanged. The ViewModel catches the Model events and propagates them to the View as needed.
See http://msmvps.com/blogs/theproblemsolver/archive/2009/04/07/using-model-view-viewmodel-with-silverlight.aspx for a more complete example.
I didn't find a lot of resources about
the subject.
I too want to see more discussion on this topic
So I wonder; how do you typically handle it?
Just use DataSet.
Keep looking for solutions.