Command Query Responsibility Segregation (CQRS) and Event Sourcing: A Comprehensive Guide, Slides von Informatik

Toggle sidebar
bg1
CQRS Documents by Greg Young
http://cqrsinfo.com Page 1
Contents
A Stereotypical Architecture ......................................................................................................................... 2
Application Server ................................................................................................................................. 2
Client Interaction .................................................................................................................................. 3
Analysis of the Stereotypical Architecture ........................................................................................... 5
Summary ............................................................................................................................................... 7
Works Cited ................................................................................................................................................... 8
Task Based User Interface ............................................................................................................................. 9
Commands .......................................................................................................................................... 11
User Interface ..................................................................................................................................... 13
Works Cited ................................................................................................................................................. 16
Command and Query Responsibility Segregation ...................................................................................... 17
Origins ................................................................................................................................................. 17
The Query Side .................................................................................................................................... 20
The Command Side ............................................................................................................................. 22
Events as a Storage Mechanism ................................................................................................................. 25
What is a Domain Event? .................................................................................................................... 25
Other Definitions and Discussion ........................................................................................................ 26
Events as a Mechanism for Storage .................................................................................................... 27
There is no Delete ............................................................................................................................... 31
Performance and Scalability ............................................................................................................... 32
Rolling Snapshots ................................................................................................................................ 33
Impedance Mismatch ......................................................................................................................... 36
Business Value of the Event Log ......................................................................................................... 37
Works Cited ................................................................................................................................................. 40
Building an Event Storage ........................................................................................................................... 41
Structure ............................................................................................................................................. 41
Operations .......................................................................................................................................... 42
Rolling Snapshots ................................................................................................................................ 44
Event Storage as a Queue ................................................................................................................... 46
CQRS and Event Sourcing ............................................................................................................................ 50
Cost Analysis ....................................................................................................................................... 51
Integration .......................................................................................................................................... 52
Differences in Work Habits ................................................................................................................. 53
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38

Unvollständige Textvorschau

Nur auf Docsity: Lade Command Query Responsibility Segregation (CQRS) and Event Sourcing: A Comprehensive Guide und mehr Slides als PDF für Informatik herunter!

Contents

  • A Stereotypical Architecture
    • Application Server
    • Client Interaction
    • Analysis of the Stereotypical Architecture
    • Summary
  • Works Cited
  • Task Based User Interface
    • Commands
    • User Interface
  • Works Cited
  • Command and Query Responsibility Segregation
    • Origins
    • The Query Side
    • The Command Side
  • Events as a Storage Mechanism
    • What is a Domain Event?
    • Other Definitions and Discussion........................................................................................................
    • Events as a Mechanism for Storage
    • There is no Delete
    • Performance and Scalability
    • Rolling Snapshots
    • Impedance Mismatch
    • Business Value of the Event Log
  • Works Cited
  • Building an Event Storage
    • Structure
    • Operations
    • Rolling Snapshots
    • Event Storage as a Queue
  • CQRS and Event Sourcing............................................................................................................................
    • Cost Analysis
    • Integration
    • Differences in Work Habits

A Stereotypical Architecture

Before moving into architectures for Domain Driven Design based projects it is important to start off by analyzing what is generally considered to be the standard architecture that many try to apply to projects. We can from that point attempt to improve upon the stereotypical architecture in small rational steps while trying to minimize the cost in terms of productivity for each step towards a better architecture.

Below is shown a diagram of a stereotypical architecture.

Figure 1 A Stereotypical Architecture

Application Server The above architecture is centered upon a backing data storage system. This system although typically a RDBMS does not have to be, it could just as easily be a key/value store, and object database, or even plain XML files. The important aspect of the backing store is that it is representing the current state of objects in the domain.

Figure 2 Typical Client Interaction

The basic interaction of the client can be described as a DTO (Data Transfer Object) up/down interaction. Going through the lifecycle of an operation is the easiest way to show the functioning of the API. A user goes to a screen, perhaps to edit a customer. The client sends a request to the remote facade for a DTO representing Customer #id. The Remote facade loads up the domain objects required, and maps the domain objects to a DTO that is then returned to the client. An example of DTO in XML format can be seen in Figure 3 but the basic explanation is that the DTO in this stereotypical architecture contains the current state of the object in questions.

The client will then display the information received from the Remote Facade on the screen allowing the user to interact with it. This is very often done utilizing a view model and/or data binding with the view.

At some point the user will be complete with the editing of the data on the screen and will through some action cause the UI to “Save” the data. Generally this is implemented through a “Save Button” although some User Interfaces will instead just have you leave the current data which forces a save.

The process of sav

The processing of a Save on the client will take the data that has been edited by the user on the screen, pack it back into a DTO (usually identical to the DTO it requested from the Remote Façade for displaying to the user ). It will then send this DTO back up to the Application Server.

The Application Server receiving the DTO will then start a transaction/session, map the DTO back to the domain objects, allow the domain objects to verify any changes, then save the changes within the domain objects back to the data storage likely through the use of something like an Object Relational Mapper that has the ability to distinguish what has changed in the domain objects and update the data storage accordingly. The Application Server will return to the client either an Acknowledgement (Ack) that the change has been persisted or it will return a series of errors as to why it was unable to persist the changes.

Analysis of the Stereotypical Architecture The architecture provided above as with any architecture has many properties. Some of these properties are good under certain scenarios and other properties can be extremely bad in others. As architects we should really be trying to align many of these properties to best fit our needs.

Simplicity When looking at properties it is important to note what the most likely property is for a given architecture becoming popular. In the architecture above the most likely property defining its popularity is that it is simple. One could teach a Junior developer how to interact with a system built using this architecture in a very short period of time. Going along with the simplicity, the architecture is completely generic. One could use this architecture on every project. Along with being able to use it on every project, because many people are doing it, its likely that if a team brings on a new member the new member will be intimately familiar with the general architecture of their system again lowering on ramp up costs.

The combination of these two items allows teams to become extremely adept at applying this architecture and more important it allows them to use it as a default architecture. The thought process

Greg Young

111 Some St. Vernon CT 06066 USA

Figure 3 Example in XML of a DTO

are littered with getters and setters to be used in the mapping process. There is a structure to the domain showing how objects relate with one another but …

One cannot even create and Anemic Domain Model with this architecture as then all of the business logic would be in services, here the services themselves are really just mapping DTO’s to domain objects, there is no actual business logic in them. In this case a large amount of business logic is not existing in the domain at all, nor in the Application Server, it may exist on the client but more likely it exists on either pieces of paper in a manual or in the heads of the people using the system.

Architectures like the one being viewed tend to come with instructions of how to complete complex tasks by editing data in many parts of the system. A stereotypical example of this would be when changing the sex of an employee you must after go edit their health insurance information. This is far worse than the creation of an anemic model, this is the creation of a glorified excel spreadsheet.

Scaling When one looks at the architecture provided above in the context of scaling one will quickly notice that there is a large bottle neck. The bottleneck in terms of scaling is the data storage. When using a RDBMS as 90%+ currently use this becomes even more of a problem most RDBMS are at this point not horizontally scalable and vertically scaling becomes prohibitively expensive very quickly. It is however also extremely important to remember that most systems do not need to scale and as such scalability is really not a grave issue in all cases.

Summary The DTO up/down architecture employed on many projects is capable of being used for many applications and can offer many benefits in terms of simplicity for teams to work with. It cannot however be used with a Domain Driven Design based project, to attempt so will bring failure to your efforts at applying Domain Driven Design.

This architecture does however make a good baseline and the rest of this document will be focused on improving this architecture in incremental steps while attempting to limit or remove cost while adding business value at each additional step.

Works Cited

Fowler, M. (2003, 11 25). MF Bliki: AnemicDomainModel. Retrieved from Bliki: http://martinfowler.com/bliki/anemicdomainmodel

Figure 4 Interaction in a DTO Up/Down Architecture

The basic explanation of the operation is that the UI will request a DTO, say for Customer 1234 from the Application Server. This DTO will be returned to the client and then shown on the screen. The user will interact with the DTO in some way (likely either directly or through a View Model). Eventually the client will click Save or some other trigger will occur and the client will take the DTO and send it back up to the Application Server. The Application Server will then internally map the data back to the domain model and save the changes returning a success or failure.

As discussed the intention of the user is being lost because a DTO is being sent up that just represents the current state of the object after the client’s actions are completed. It is possible to bring forward the intention of the user; this will allow the Application Server to process behaviors as opposed to saving data. Figure shows an interaction capturing intent.

Figure 5 Behavioral Interface

Capturing intent the client interaction is very similar to the DTO up/down methodology in terms of interactions. The client first quests a DTO from the Application Server for instance Customer 1234. The Application Server returns a DTO representing the customer that is then shown on the screen for the user to interact with usually either directly or through a View Model. The similarities however stop at this point.

Instead of simply sending the same DTO back up when the user is completed with their action the client needs to send a message to the Application Server telling it to do something. It could be to “Complete a Sale”, “Approve a Purchase Order”, “Submit a Loan Application”. Said simply the client needs to send a message to the Application Server to have it complete the task that the user would like to complete. By telling the Application Server what the user would like to do, it is possible to know the intention of the user.

Commands The method through which the Application Server will be told what to do is through the use of a Command. A command is a simple object with a name of an operation and the data required to perform that operation. Many think of Commands as being Serializable Method Calls. Listing 1 includes the code of a basic command.

It is quite common for developers to learn about Commands and to very quickly start creating Commands using vocabulary familiar to them such as “ChangeAddress”, “CreateUser”, or “DeleteClass”. This should be avoided as a default. Instead a team should be focused on what the use case really is.

Is it “ChangeAddress”? Is there a difference between “Correcting an Address” and “Relocating the Customer”? It likely will be if the domain in question is for a telephone company that sends the yellow pages to a customer when they move to a new location.

Is it “CreateUser” or is it “RegisterUser”? “DeleteClass” or “DeregisterStudent”. This process in naming can lead to great amounts of domain insight. To begin defining Commands, the best place to begin is in defining use cases, as generally a Command and a use case align.

It is also important to note that sometimes the only use case that exists for a portion of data is to “create”, “edit”, “update”, “change”, or “delete” it. All applications carry information that is simply supporting information. It is important though to not fall into the trap of mistaking places where there are use cases associated with intent for these CRUD only places.

Commands as a concept are not difficult but are different for many developers. Many developers see the creation of the Commands as a lot of work. If the creation of Commands is a bottleneck in the workflow, many of the ideas being discussed are likely being applied in an incorrect location.

User Interface In order to build up Commands the User Interface will generally work a bit differently than in a DTO up/down system. Because the UI must build Command objects it needs to be designed in such a way that the user intent can be derived from the actions of the user.

The way to solve this is to lean more towards a “Task Based User Interface” also known as an “Inductive User Interface” in the Microsoft world. This style of UI is not by any means new and offers a quite different perspective on the design of user interfaces. Microsoft identified three major problems with Deductive UIs when researching Inductive UIs.

Users don't seem to construct an adequate mental model of the product. The interface design for most current software products assumes that users will understand a conceptual model that the designers carefully crafted. Unfortunately, most users don't seem to ever acquire a mental model that is thorough and accurate enough to guide their navigation. These users aren't dumb — they are just very busy and overloaded with information. They do not have the time, energy, or desire to wonder about a conceptual model for their software.

Even many long-time users never master common procedures. Designers know that new users may have trouble at first, but expect these problems to vanish as users learn common tasks. Usability data indicates this often doesn't happen. In one study, researchers set up automated equipment to videotape users at home. The tapes showed that users focusing on the task at hand do not necessarily notice the procedure they are following and do not learn from the experience. The next time users perform the same operation, they may stumble through it in exactly the same way.

Users must work hard to figure out each feature or screen. Most software products are designed for (the few) users who understand its conceptual model and have mastered common procedures. For the majority of customers, each feature or procedure is a frustrating, unwanted puzzle. Users might assume these puzzles are an unavoidable cost of using computers, but they would certainly be happier without this burden. (Microsoft Corporation, 2001)

The basic idea behind a Task Based or Inductive UI is that its important to figure out how the users want to use the software and to make it guide them through those processes.

Many commercial software applications include user interfaces in which a screen presents a set of controls, but leaves it to the user to deduce the page's purpose and how to use the controls to accomplish that purpose. (Microsoft Corporation, 2001)

The goal is to guide the user through the process. An example of the differences can be seen in the DeactivateInventoryItem example previously shown. A typical deductive UI might have an editable data grid containing all of the inventory items. It would have editable fields for various data and perhaps a drop down for the status of the inventory item, deactivated being one of them. In order to deactivate an inventory item the user would have to go to the item in the grid, type in a comment as to why they were deactivating it and then change the drop down to the status of deactivated. A similar example could be where you click to a screen to edit an inventory item but go through the same process as seen in Figure

Figure 6 A CRUD screen for an Inventory Item

If the user attempts to submit an item that is “deactivated” and has not entered a comment they will receive an error saying that they must enter a comment as it is a mandatory field for a deactivated item. Some UIs might be a bit more user friendly, they may not show the comment field until the user selects deactivated from the drop down at which point it would appear on the screen. This is far more intuitive to the user as it is a cue that they should be putting data in that field but one can do even better.

Works Cited

Microsoft Corporation. (2001, Feb 9). Microsoft Inductive User Interface Guidelines. Retrieved from MSDN: http://msdn.microsoft.com/en-us/library/ms

Command and Query Responsibility Segregation

This chapter will introduce the concept of Command and Query Responsibility Segregation. It will look at how the separation of roles in the system can lead towards a much more effective architecture. It will also analyze some of the different architectural properties that exist in systems where CQRS has been applied.

Origins Command and Query Responsibility Segregation (CQRS) originated with Bertrand Meyer’s Command and Query Separation Principle. Wikipedia defines the principle as:

It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects. (Wikipedia)

Basically it boils down to. If you have a return value you cannot mutate state. If you mutate state your return type must be void. There can be some issues with this. Martin Fowler shows one example on the bliki with:

Meyer likes to use command-query separation absolutely, but there are 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. (Fowler)

Command and Query Responsibility Segregation was originally considered just to be an extension of this concept. For a long time it was discussed simply as CQS at a higher level. Eventually after much confusion between the two concepts it was correctly deemed to be a different pattern.

Command and Query Responsibility Segregation uses the same definition of Commands and Queries that Meyer used and maintains the viewpoint that they should be pure. The fundamental difference is that in CQRS objects are split into two objects, one containing the Commands one containing the Queries.

The pattern although not very interesting in and of itself becomes extremely interesting when viewed from an architectural point of view.

Applying CQRS on the CustomerService would result in two services as shown in Listing 2.

While a relatively simple process, this will solve many of the problems that existed in the stereotypical architecture. The service has been split into two separate services, a read side and a write side or the Command side and the Query side.

This separation enforces the notion that the Command side and the Query side have very different needs. The architectural properties associated with use cases on each side are tend to be quite different. Just to name a few:

Consistency Command: It is far easier to process transactions with consistent data than to handle all of the edge cases that eventual consistency can bring into play.

Query: Most systems can be eventually consistent on the Query side.

Data Storage Command: The Command side being a transaction processor in a relational structure would want to store data in a normalized way, probably near 3rd^ Normal Form (3NF)

Query: The Query side would want data in a denormalized way to minimize the number of joins needed to get a given set of data. In a relational structure likely in 1st^ Normal Form (1NF)

Scalability Command: In most systems, especially web systems, the Command side generally processes a very small number of transactions as a percentage of the whole. Scalability therefore is not always important.

Query: In most systems, especially web systems, the Query side generally processes a very large number of transactions as a percentage of the whole (often times 2 or more orders of magnitude). Scalabilityis most often needed for the query side.

CustomerWriteService void MakeCustomerPreferred(CustomerId) void ChangeCustomerLocale(CustomerId, NewLocale) void CreateCustomer(Customer) void EditCustomerDetails(CustomerDetails)

CustomerReadService Customer GetCustomer(CustomerId) CustomerSet GetCustomersWithName(Name) CustomerSet GetPreferredCustomers()

Listing 3 Customer Service after CQRS

It is not possible to create an optimal solution for searching, reporting, and processing transactions utilizing a single model.

The Query Side As stated, the Query side will only contain the methods for getting data. From the original architecture these would be all of the methods that return DTOs that the client consumes to show on the screen.

In the original architecture the building of DTOs was handled by projecting off of domain objects. This process can lead to a lot of pain. A large source of the pain is that the DTOs are a different model than the domain and as such require a mapping.

DTOs are optimally built to match the screens of the client to prevent multiple round trips with the server. In cases with many clients it may be better to build a canonical model that all of the clients use. In either case the DTO model is very different than the domain model that was built in order to represent and process transactions.

Common smells of the problems can be found in many domains.

 Large numbers of read methods on repositories often also including paging or sorting information.  Getters exposing the internal state of domain objects in order to build DTOs.  Use of prefetch paths on the read use cases as they require more data to be loaded by the ORM.  Loading of multiple aggregate roots to build a DTO causes non-optimal querying to the data model. Alternatively aggregate boundaries can be confused because of the DTO building operations

The largest smell though is that the optimization of queries is extremely difficult. Because queries are operating on an object model then being translated to a data model, likely by an ORM it can become difficult to optimize these queries. A developer needs to have intimate knowledge of the ORM and the database. The developer is dealing with a problem of Impedance Mismatch (for more discussion see “Events as a Storage Mechanism”).

After CQRS has been applied there is a natural boundary. Separate paths have been made explicit. It makes a lot of sense now to not use the domain to project DTOs. Instead it is possible to introduce a new way of projecting DTOs. Figure