Introduction to CQRS - command and query responsibility segregation

55
CQRS Command & Query Responsibility Segregation

description

A high level introduction to CQRS (command and query responsibility segregation), CQS (command query separation), DDD (domain driven design), DDD-D ...with distributed, and how all those weave together.

Transcript of Introduction to CQRS - command and query responsibility segregation

Page 1: Introduction to CQRS - command and query responsibility segregation

CQRSCommand & Query Responsibility

Segregation

Page 2: Introduction to CQRS - command and query responsibility segregation

Andrew Siemerhttp://about.me/andrewsiemer

ASP InsiderMicrosoft V-TSP

Father of 6Jack of all trades, master of some.

Page 3: Introduction to CQRS - command and query responsibility segregation
Page 4: Introduction to CQRS - command and query responsibility segregation

We are hiring!!!

Page 5: Introduction to CQRS - command and query responsibility segregation

CQRS“…two objects where there

previously was one!”

Page 6: Introduction to CQRS - command and query responsibility segregation

CQRS“Segregate operations that read data from operations that update data by using separate interfaces. This pattern can maximize performance, scalability, and security; support evolution of the system over time through higher flexibility; and prevent update commands from causing merge conflicts at the domain level.”

Page 7: Introduction to CQRS - command and query responsibility segregation

Goals

• Introduction• Up to speed on the concepts• Won’t be an expert after this talk• But will be able to identify your next steps

Page 8: Introduction to CQRS - command and query responsibility segregation

What CQRS is not

• Not a framework• Not an architecture• Not a specific tool• Not a BEST PRACTICE

Page 9: Introduction to CQRS - command and query responsibility segregation

Not a best practice

• I always start the CQRS conversation with

“THIS IS LIKELY NOT FOR YOU”

• CQRS is great when it is justifiably needed• Due to high complexity, not a buzz word you want “just cause”

Page 10: Introduction to CQRS - command and query responsibility segregation

What CQRS is

• CQRS is a pattern• CQRS ends up being a composition of tools and concepts• No two CQRS implementations are identical

Page 11: Introduction to CQRS - command and query responsibility segregation

How we got to the CQRS pattern

• CQS was a good enough pattern• DDD made sense and became popular• DDDD: the 4th “D” represents Distributed as apps got bigger• Greg Young first to name CQRS

• Others to get behind it• Udi Dahan• Eric Evans• Martin Fowler

Page 12: Introduction to CQRS - command and query responsibility segregation

In case you fall asleep

Super quick take aways…

Page 13: Introduction to CQRS - command and query responsibility segregation

TraditionalStandard three tier app, everything goes in and out

Page 14: Introduction to CQRS - command and query responsibility segregation

CQSCommand Query Separation

C Q

Page 15: Introduction to CQRS - command and query responsibility segregation

CQRSCommand & Query Responsibility Segregation

C Q

Page 16: Introduction to CQRS - command and query responsibility segregation

Data

BL

UI

Traditional

Page 17: Introduction to CQRS - command and query responsibility segregation

Data

BL

UI

CQSC Q

Page 18: Introduction to CQRS - command and query responsibility segregation

Data

UI

CQRSW R

C Q

Page 19: Introduction to CQRS - command and query responsibility segregation

Data

UI

CQRS

Data

W R

C Q

Page 20: Introduction to CQRS - command and query responsibility segregation

Data

UI

CQRS

Data

W R

C Q

E

Page 21: Introduction to CQRS - command and query responsibility segregation

Data

UI

CQRS

Data

W R

C Q

E

Page 22: Introduction to CQRS - command and query responsibility segregation

Event Source

W

UI

CQRSR

C Q

DataE

E

Page 23: Introduction to CQRS - command and query responsibility segregation

Why?ScalabilityFlexibilityReduced complexityFocus on businessTask based UI

Page 24: Introduction to CQRS - command and query responsibility segregation

CQS was first on the scene

Page 25: Introduction to CQRS - command and query responsibility segregation

What is CQS?

• CQS: Command Query Separation• Command methods change state• Query methods read state• One object in code for state change and querying works• Using the same data store is ok• Supports shared schema with read replica concepts

Page 26: Introduction to CQRS - command and query responsibility segregation

CQS in code: NOT

public class User

{public string Address { get; set; }

} Yuck

!

Page 27: Introduction to CQRS - command and query responsibility segregation

CQS in code: BETTER

public class Entity{

//...public void Move(string newAddress){//changes state}

public string GetAddress(){//queries state}

}

Andrew Siemer
Page 28: Introduction to CQRS - command and query responsibility segregation

DDD: Quick Primer

Page 29: Introduction to CQRS - command and query responsibility segregation

DDD: At a high level

• CQRS is based on DDD• DDD is used to address complexity• Aggregate Roots• Bounded Contexts• Domain Events

Page 30: Introduction to CQRS - command and query responsibility segregation

DDD: Ubiquitous Language

• Domain experts• Technical team• Shared language• Model based on the shared language

Page 31: Introduction to CQRS - command and query responsibility segregation

DDD: Entities

• Have identity• Items like • User• Product• Order

Page 32: Introduction to CQRS - command and query responsibility segregation

DDD: Value Objects

• Have value, no identity• Items like• User.Address• Product.TechNotes• Order.OrderItem

Page 33: Introduction to CQRS - command and query responsibility segregation

DDD: Aggregates and their Root

• An aggregate of one or more Entities and Value objects• One Entity is the Root that is used to reference the aggregate• Conceptual boundary by root• Consistency boundary• transactional

Order

OrderHeader

OrderItem

Page 34: Introduction to CQRS - command and query responsibility segregation

DDD: Bounded Context

• Two or more distinct (obviously related) models• Interactions between them• Usually delineated by business groups or tasks

HotelBookings

Order

OrderHeader

OrderItem

Availability

Reservation

Property

Payment

Processor

HotelMarketing

Content Campaign

Property

Page 35: Introduction to CQRS - command and query responsibility segregation

DDD: Domain Event

• Represents something that happened in the past• Immutable• Historical record

PlaceOrder Command

PlaceOrderHandler

OrderPlaced Event

Would like to do... Am doing... Is done.

Page 36: Introduction to CQRS - command and query responsibility segregation

DDD: Visualized

Application

Page 37: Introduction to CQRS - command and query responsibility segregation

DDD: Visualized

Application

Bounded Context

Page 38: Introduction to CQRS - command and query responsibility segregation

DDD: Visualized

Application

Bounded Context

Business Component

Page 39: Introduction to CQRS - command and query responsibility segregation

DDD: Visualized

Application

Bounded ContextBusiness

Component

Autonomous Business

Component

Page 40: Introduction to CQRS - command and query responsibility segregation

Back to CQRS

Page 41: Introduction to CQRS - command and query responsibility segregation

What is CQRS?

• CQRS: Command & Query Responsibility Segregation

“Two objects where there once was one”

• Command objects change state• Query objects read state• Two objects represented in code • One for state change • One for querying data

• Decoupled model for different concerns

Page 42: Introduction to CQRS - command and query responsibility segregation

CQRS in code

public class UserWriteService{

// Commandspublic void Move(User user, string newAddress);//...

} public class UserReadService{

// Queriespublic User GetUser(int userId);//...

}

Page 43: Introduction to CQRS - command and query responsibility segregation

Segregation opens doors

• Scale reads from writes independently• Remove contention• Decouple read model from write model • Different data shapes• Flexibility in modeling different concerns

• Ability to capture with why the state changed• Not just changing the state

Page 44: Introduction to CQRS - command and query responsibility segregation

CQRS: Command

• Message• Handler changes state• Always returns void (nothing)• Works with business intent, not just a record• Not a CRUD style operation

Page 45: Introduction to CQRS - command and query responsibility segregation

CQRS: Command in code

public class MoveCustomerCommand : Command{

public Address NewAddress { get; set; }}

Page 46: Introduction to CQRS - command and query responsibility segregation

CQRS: Query

• Does not change state• Has return value• Also a type of message

Page 47: Introduction to CQRS - command and query responsibility segregation

CQS vs. CQRS: Feature matrixCQS CQRS

Zero coupling between domain logic (state) and reporting (read) concerns X

More robust scalability options X

Decouples domain concerns from display concerns X

Object model specific to its responsibility X

Different data stores/shapes for domain logic and reporting concerns X

Option to performance optimize data storage for write and read layer(s) X X

Can be used with a message based architecture X X

Easy deployment story X

Less code complexity X

Less pieces to manage X

Coupled read and write model X

Page 48: Introduction to CQRS - command and query responsibility segregation

Let’s take a closer look!

Page 49: Introduction to CQRS - command and query responsibility segregation

What does CQS look like?

• Data shape IS the same• Client creates data through one set of methods• Client reads data through another set of methods• Likely the same object model• The read and write model are likely the same• Or a sub-set thereof

• Can support read replicas (at DB)• Doesn’t support multiple different containers of data

Data Store

Client

Server

Read Operations

Write Operations

Data Store

Page 50: Introduction to CQRS - command and query responsibility segregation

What does CQRS look like at a high level?

DataStore

Service

Query Model

Command Model

Potential for composite views

Application routeschange information

Client

Command model executes validations,

and consequential logic

Can be same store or different store, but is guaranteed to be different schema and different data shape

Opportunity for message oriented architecture

• Store can be the same• Data shape IS different• Data flow is different• Zero model concerns

are leaked to view concerns

Page 51: Introduction to CQRS - command and query responsibility segregation

CQRS: Myth busting

• CQRS requires Event Sourcing• Requires an eventual consistent read store• Requires a bus/queues/asynchronous messaging• Commands are fire and forget• Escapes consistency problems and eliminate concurrency violations• CQRS is easy!

Page 52: Introduction to CQRS - command and query responsibility segregation

What does CQRS look like for us?

View 2Denormalizer

Read Store

ServiceService

Queue Store

Client

API/Web Server

NSBSagaStore

Service

Source of Truth

API/Web Server

Read Store

Data Warehouse

Rich Domain ModelRead/Write

Queue Store

NSB

View 1Denormalizer

Warehouse Denormalizer

View 2Denormalizer

NSB

Two camps1) One table per view

2) Composite view

Can be same code base, can be deployed separately and segregatedat the action level with routing foo

Denormalizers can read from “rich domain model” to “enrich” message in hand.

Potential to supportread replicas

• Store for each• Rich domain• View concerns• Reporting concerns

• Data shape IS different• Messaging for distribution• Lots of scalability options• Supports different storage mechanisms

Page 53: Introduction to CQRS - command and query responsibility segregation

Anything else about CQRS?

• UI workflow might be different• Synchronous UI flow: view form > submit > confirmation page• Asynchronous UI flow: view form > submit > processing > email confirmation

• Not every avenue through your code has to be CQRS!• Sometimes there business needs that might like a more direct route

• Move work out of process only when needed, distributed is harder• This can be done with an in memory bus

Page 54: Introduction to CQRS - command and query responsibility segregation

Worth reading

• Microsoft: CQRS Journey• Jimmy Bogard: Busting some CQRS myths

Page 55: Introduction to CQRS - command and query responsibility segregation

Any questions?

Code and slides: https://github.com/asiemer/IntroToCQRS

[email protected]@asiemer