SlideShare uma empresa Scribd logo
1 de 55
CQRS 
Command & Query Responsibility 
Segregation
Andrew Siemer 
http://about.me/andrewsiemer 
ASP Insider 
Microsoft V-TSP 
Father of 6 
Jack of all trades, master of some.
 We are hiring!!!
CQRS 
“…two objects where there 
previously was one!”
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.”
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
What CQRS is not 
• Not a framework 
• Not an architecture 
• Not a specific tool 
• Not a BEST PRACTICE
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”
What CQRS is 
• CQRS is a pattern 
• CQRS ends up being a composition of tools and concepts 
• No two CQRS implementations are identical
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
In case you fall 
asleep 
Super quick take aways…
Traditional 
Standard three tier app, 
everything goes in and out
CQS 
Command Query Separation 
C Q
CQRS 
Command & Query Responsibility Segregation 
C Q
Data 
BL 
UI 
Traditional
Data 
BL 
UI 
CQS 
C Q
Data 
UI 
CQRS 
W R 
C Q
Data 
UI 
CQRS 
Data 
W R 
C Q
Data 
E 
UI 
CQRS 
Data 
W R 
C Q
Data 
UI 
CQRS 
Data 
E 
W R 
C Q
Event 
Source 
W 
UI 
CQRS 
R 
C Q 
Data 
E 
E
Why? 
Scalability 
Flexibility 
Reduced complexity 
Focus on business 
Task based UI
CQS was first on 
the scene
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
CQS in code: NOT 
public class User 
{ 
public string Address { get; set; } 
}
CQS in code: BETTER 
public class Entity 
{ 
//... 
public void Move(string newAddress) 
{ 
//changes state 
} 
public string GetAddress() 
{ 
//queries state 
} 
}
DDD: Quick Primer
DDD: At a high level 
• CQRS is based on DDD 
• DDD is used to address complexity 
• Aggregate Roots 
• Bounded Contexts 
• Domain Events
DDD: Ubiquitous Language 
• Domain experts 
• Technical team 
• Shared language 
• Model based on the shared language
DDD: Entities 
• Have identity 
• Items like 
• User 
• Product 
• Order
DDD: Value Objects 
• Have value, no identity 
• Items like 
• User.Address 
• Product.TechNotes 
• Order.OrderItem
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
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 
Property 
Reservation 
Payment 
Processor 
HotelMarketing 
Content Campaign 
Property
DDD: Domain Event 
• Represents something that happened in the past 
• Immutable 
• Historical record 
Would like to do... Am doing... Is done. 
PlaceOrder 
Command 
PlaceOrder 
Handler 
OrderPlaced 
Event
DDD: Visualized 
Application
DDD: Visualized 
Application 
Bounded 
Context
DDD: Visualized 
Application 
Bounded 
Context 
Business 
Component
DDD: Visualized 
Application 
Bounded 
Context 
Business 
Component 
Autonomous 
Business 
Component
Back to CQRS
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
CQRS in code 
public class UserWriteService 
{ 
// Commands 
public void Move(User user, string newAddress); 
//... 
} 
public class UserReadService 
{ 
// Queries 
public User GetUser(int userId); 
//... 
}
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
CQRS: Command 
• Message 
• Handler changes state 
• Always returns void (nothing) 
• Works with business intent, not just a record 
• Not a CRUD style operation
CQRS: Command in code 
public class MoveCustomerCommand : Command 
{ 
public Address NewAddress { get; set; } 
}
CQRS: Query 
• Does not change state 
• Has return value 
• Also a type of message
CQS vs. CQRS: Feature matrix 
CQS 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
Let’s take a 
closer look!
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 
Data Store 
Server 
Client 
Read 
Operations 
Write 
Operations
What does CQRS look like at a high level? 
Data 
Store 
Query Model 
Command Model 
Service 
Potential for 
composite views 
Application routes 
change 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
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!
What does CQRS look like for us? 
Warehouse 
Denormalizer 
View 2 
Denormalizers can read 
from “rich domain 
mo del” to “enrich” 
message in hand. 
Denormalizer 
Data 
Warehouse 
Read 
Store 
Service 
Service 
Queue Store 
Client 
API/Web Server 
NSB 
Saga 
Store 
Service 
Source 
of Truth 
Read 
Store 
API/Web Server 
Rich Domain 
Read/Write Model 
Queue Store 
NSB 
View 1 
Denormalizer 
View 2 
Denormalizer 
NSB 
Two camps 
1) One table per view 
2) Composite view 
Can be same code base, can be 
deployed separately and segregated 
at the action level with routing foo 
Potential to support 
read 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
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
Worth reading 
• Microsoft: CQRS Journey 
• Jimmy Bogard: Busting some CQRS myths
Any questions? 
Code and slides: 
https://github.com/asiemer/IntroToCQRS 
andrew@clear-measure.com 
@asiemer

Mais conteúdo relacionado

Mais procurados

10 minutes fun with Cloud API comparison
10 minutes fun with Cloud API comparison10 minutes fun with Cloud API comparison
10 minutes fun with Cloud API comparisonLaurent Cerveau
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.jsratankadam
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeAndrus Adamchik
 
Document Databases & RavenDB
Document Databases & RavenDBDocument Databases & RavenDB
Document Databases & RavenDBBrian Ritchie
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
The Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with AzureThe Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with AzureIdo Flatow
 
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the FieldMigrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the FieldIdo Flatow
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
How to Use OWASP Security Logging
How to Use OWASP Security LoggingHow to Use OWASP Security Logging
How to Use OWASP Security LoggingMilton Smith
 
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...Bob Pusateri
 
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...44CON
 
No Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueNo Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueAndrus Adamchik
 
How would ESBs look like, if they were done today.
How would ESBs look like, if they were done today.How would ESBs look like, if they were done today.
How would ESBs look like, if they were done today.Markus Eisele
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server DatabasesColdFusionConference
 
Scala play-framework
Scala play-frameworkScala play-framework
Scala play-frameworkAbdhesh Kumar
 
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...MongoDB
 

Mais procurados (20)

CQRS
CQRSCQRS
CQRS
 
10 minutes fun with Cloud API comparison
10 minutes fun with Cloud API comparison10 minutes fun with Cloud API comparison
10 minutes fun with Cloud API comparison
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.js
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
 
Document Databases & RavenDB
Document Databases & RavenDBDocument Databases & RavenDB
Document Databases & RavenDB
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
Introduction to CQ5
Introduction to CQ5Introduction to CQ5
Introduction to CQ5
 
The Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with AzureThe Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with Azure
 
RavenDB Overview
RavenDB OverviewRavenDB Overview
RavenDB Overview
 
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the FieldMigrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
How to Use OWASP Security Logging
How to Use OWASP Security LoggingHow to Use OWASP Security Logging
How to Use OWASP Security Logging
 
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
 
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
44CON 2014 - Pentesting NoSQL DB's Using NoSQL Exploitation Framework, Franci...
 
No Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with BootiqueNo Container: a Modern Java Stack with Bootique
No Container: a Modern Java Stack with Bootique
 
How would ESBs look like, if they were done today.
How would ESBs look like, if they were done today.How would ESBs look like, if they were done today.
How would ESBs look like, if they were done today.
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 
Scala play-framework
Scala play-frameworkScala play-framework
Scala play-framework
 
Why Play Framework is fast
Why Play Framework is fastWhy Play Framework is fast
Why Play Framework is fast
 
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
Lessons Learned from Building a Multi-Tenant Saas Content Management System o...
 

Destaque

CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationBrian Ritchie
 
CQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architectureCQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architectureThomas Jaskula
 
CQRS + Event Sourcing
CQRS + Event SourcingCQRS + Event Sourcing
CQRS + Event SourcingMike Bild
 
Beyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO codeBeyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO codeMatthias Noback
 
ISTA 2016: Event Sourcing
ISTA 2016: Event SourcingISTA 2016: Event Sourcing
ISTA 2016: Event SourcingVladik Khononov
 
Сommand Query Responsibility Segregation (CQRS) - Отделяем Мух от Котлет
Сommand Query Responsibility Segregation (CQRS) - Отделяем Мух от КотлетСommand Query Responsibility Segregation (CQRS) - Отделяем Мух от Котлет
Сommand Query Responsibility Segregation (CQRS) - Отделяем Мух от КотлетIgor Miniailo
 
An Introduction To CQRS
An Introduction To CQRSAn Introduction To CQRS
An Introduction To CQRSNeil Robbins
 
Cqrs, event sourcing and microservices
Cqrs, event sourcing and microservicesCqrs, event sourcing and microservices
Cqrs, event sourcing and microservicesMarcelo Cure
 
A Visual Introduction to Event Sourcing and CQRS by Lorenzo Nicora
A Visual Introduction to Event Sourcing and CQRS by Lorenzo NicoraA Visual Introduction to Event Sourcing and CQRS by Lorenzo Nicora
A Visual Introduction to Event Sourcing and CQRS by Lorenzo NicoraOpenCredo
 
When cqrs meets event sourcing
When cqrs meets event sourcingWhen cqrs meets event sourcing
When cqrs meets event sourcingManel Sellés
 
CQRS and Event Sourcing with MongoDB and PHP
CQRS and Event Sourcing with MongoDB and PHPCQRS and Event Sourcing with MongoDB and PHP
CQRS and Event Sourcing with MongoDB and PHPDavide Bellettini
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTPRoland Kuhn
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationSamuel ROZE
 
Microservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingMicroservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingBen Wilcock
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDDennis Doomen
 
Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"
Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"
Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"LogeekNightUkraine
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...Chris Richardson
 

Destaque (18)

CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility Segregation
 
CQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architectureCQRS recipes or how to cook your architecture
CQRS recipes or how to cook your architecture
 
CQRS + Event Sourcing
CQRS + Event SourcingCQRS + Event Sourcing
CQRS + Event Sourcing
 
Pegando carona no Command Bus
Pegando carona no Command BusPegando carona no Command Bus
Pegando carona no Command Bus
 
Beyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO codeBeyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO code
 
ISTA 2016: Event Sourcing
ISTA 2016: Event SourcingISTA 2016: Event Sourcing
ISTA 2016: Event Sourcing
 
Сommand Query Responsibility Segregation (CQRS) - Отделяем Мух от Котлет
Сommand Query Responsibility Segregation (CQRS) - Отделяем Мух от КотлетСommand Query Responsibility Segregation (CQRS) - Отделяем Мух от Котлет
Сommand Query Responsibility Segregation (CQRS) - Отделяем Мух от Котлет
 
An Introduction To CQRS
An Introduction To CQRSAn Introduction To CQRS
An Introduction To CQRS
 
Cqrs, event sourcing and microservices
Cqrs, event sourcing and microservicesCqrs, event sourcing and microservices
Cqrs, event sourcing and microservices
 
A Visual Introduction to Event Sourcing and CQRS by Lorenzo Nicora
A Visual Introduction to Event Sourcing and CQRS by Lorenzo NicoraA Visual Introduction to Event Sourcing and CQRS by Lorenzo Nicora
A Visual Introduction to Event Sourcing and CQRS by Lorenzo Nicora
 
When cqrs meets event sourcing
When cqrs meets event sourcingWhen cqrs meets event sourcing
When cqrs meets event sourcing
 
CQRS and Event Sourcing with MongoDB and PHP
CQRS and Event Sourcing with MongoDB and PHPCQRS and Event Sourcing with MongoDB and PHP
CQRS and Event Sourcing with MongoDB and PHP
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTP
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony application
 
Microservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event SourcingMicroservice Architecture with CQRS and Event Sourcing
Microservice Architecture with CQRS and Event Sourcing
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDD
 
Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"
Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"
Andrii Gryshchenko: "An Overview of CQRS and Event Sourcing"
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
 

Semelhante a Introduction to CQRS - command and query responsibility segregation

8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development SecuritySam Bowne
 
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...Thibaud Desodt
 
CISSP Prep: Ch 9. Software Development Security
CISSP Prep: Ch 9. Software Development SecurityCISSP Prep: Ch 9. Software Development Security
CISSP Prep: Ch 9. Software Development SecuritySam Bowne
 
Azure Cosmos DB - The Swiss Army NoSQL Cloud Database
Azure Cosmos DB - The Swiss Army NoSQL Cloud DatabaseAzure Cosmos DB - The Swiss Army NoSQL Cloud Database
Azure Cosmos DB - The Swiss Army NoSQL Cloud DatabaseBizTalk360
 
8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development SecuritySam Bowne
 
Reactive Development: Commands, Actors and Events. Oh My!!
Reactive Development: Commands, Actors and Events.  Oh My!!Reactive Development: Commands, Actors and Events.  Oh My!!
Reactive Development: Commands, Actors and Events. Oh My!!David Hoerster
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesMahmoudZidan41
 
Javascript on Server-Side
Javascript on Server-SideJavascript on Server-Side
Javascript on Server-SideASIMYILDIZ
 
CQRS - Eine Einführung - NOUG 2011
CQRS - Eine Einführung - NOUG 2011CQRS - Eine Einführung - NOUG 2011
CQRS - Eine Einführung - NOUG 2011Dennis Traub
 
Microservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsMicroservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsŁukasz Sowa
 
Enterprise Software Development Patterns
Enterprise Software Development PatternsEnterprise Software Development Patterns
Enterprise Software Development PatternsJosh Lane
 
The impact of cloud NSBCon NY by Yves Goeleven
The impact of cloud NSBCon NY by Yves GoelevenThe impact of cloud NSBCon NY by Yves Goeleven
The impact of cloud NSBCon NY by Yves GoelevenParticular Software
 
Cloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsCloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsPushkar Chivate
 
SQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveSQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveIBM Cloud Data Services
 
Designing microservices part2
Designing microservices part2Designing microservices part2
Designing microservices part2Masashi Narumoto
 
Marco Mancuso - Data Context Interaction
Marco Mancuso - Data Context InteractionMarco Mancuso - Data Context Interaction
Marco Mancuso - Data Context InteractioncosenzaLab
 
MongoDB 4.0 새로운 기능 소개
MongoDB 4.0 새로운 기능 소개MongoDB 4.0 새로운 기능 소개
MongoDB 4.0 새로운 기능 소개Ha-Yang(White) Moon
 
Got documents - The Raven Bouns Edition
Got documents - The Raven Bouns EditionGot documents - The Raven Bouns Edition
Got documents - The Raven Bouns EditionMaggie Pint
 
Got documents Code Mash Revision
Got documents Code Mash RevisionGot documents Code Mash Revision
Got documents Code Mash RevisionMaggie Pint
 

Semelhante a Introduction to CQRS - command and query responsibility segregation (20)

8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development Security
 
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
 
CISSP Prep: Ch 9. Software Development Security
CISSP Prep: Ch 9. Software Development SecurityCISSP Prep: Ch 9. Software Development Security
CISSP Prep: Ch 9. Software Development Security
 
Azure Cosmos DB - The Swiss Army NoSQL Cloud Database
Azure Cosmos DB - The Swiss Army NoSQL Cloud DatabaseAzure Cosmos DB - The Swiss Army NoSQL Cloud Database
Azure Cosmos DB - The Swiss Army NoSQL Cloud Database
 
8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development Security
 
Reactive Development: Commands, Actors and Events. Oh My!!
Reactive Development: Commands, Actors and Events.  Oh My!!Reactive Development: Commands, Actors and Events.  Oh My!!
Reactive Development: Commands, Actors and Events. Oh My!!
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Javascript on Server-Side
Javascript on Server-SideJavascript on Server-Side
Javascript on Server-Side
 
CQRS - Eine Einführung - NOUG 2011
CQRS - Eine Einführung - NOUG 2011CQRS - Eine Einführung - NOUG 2011
CQRS - Eine Einführung - NOUG 2011
 
Microservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problemsMicroservices - opportunities, dilemmas and problems
Microservices - opportunities, dilemmas and problems
 
Enterprise Software Development Patterns
Enterprise Software Development PatternsEnterprise Software Development Patterns
Enterprise Software Development Patterns
 
The impact of cloud NSBCon NY by Yves Goeleven
The impact of cloud NSBCon NY by Yves GoelevenThe impact of cloud NSBCon NY by Yves Goeleven
The impact of cloud NSBCon NY by Yves Goeleven
 
Cloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsCloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure tools
 
SQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveSQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The Move
 
Designing microservices part2
Designing microservices part2Designing microservices part2
Designing microservices part2
 
Marco Mancuso - Data Context Interaction
Marco Mancuso - Data Context InteractionMarco Mancuso - Data Context Interaction
Marco Mancuso - Data Context Interaction
 
MongoDB 4.0 새로운 기능 소개
MongoDB 4.0 새로운 기능 소개MongoDB 4.0 새로운 기능 소개
MongoDB 4.0 새로운 기능 소개
 
Got documents - The Raven Bouns Edition
Got documents - The Raven Bouns EditionGot documents - The Raven Bouns Edition
Got documents - The Raven Bouns Edition
 
Got documents Code Mash Revision
Got documents Code Mash RevisionGot documents Code Mash Revision
Got documents Code Mash Revision
 
Extending your data to the cloud
Extending your data to the cloudExtending your data to the cloud
Extending your data to the cloud
 

Mais de Andrew Siemer

20 tips for website performance
20 tips for website performance20 tips for website performance
20 tips for website performanceAndrew Siemer
 
Microservices pros and cons - houston tech fest
Microservices pros and cons - houston tech festMicroservices pros and cons - houston tech fest
Microservices pros and cons - houston tech festAndrew Siemer
 
Microservices pros and cons dark
Microservices pros and cons darkMicroservices pros and cons dark
Microservices pros and cons darkAndrew Siemer
 
Microservices pros and cons
Microservices pros and consMicroservices pros and cons
Microservices pros and consAndrew Siemer
 
Reigniting the Volusion platform
Reigniting the Volusion platformReigniting the Volusion platform
Reigniting the Volusion platformAndrew Siemer
 
Grokking microservices in 5 minutes
Grokking microservices in 5 minutesGrokking microservices in 5 minutes
Grokking microservices in 5 minutesAndrew Siemer
 
Making your API behave like a big boy
Making your API behave like a big boyMaking your API behave like a big boy
Making your API behave like a big boyAndrew Siemer
 
Load testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerLoad testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerAndrew Siemer
 
Test driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBTest driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBAndrew Siemer
 
A tale of two clouds
A tale of two cloudsA tale of two clouds
A tale of two cloudsAndrew Siemer
 

Mais de Andrew Siemer (10)

20 tips for website performance
20 tips for website performance20 tips for website performance
20 tips for website performance
 
Microservices pros and cons - houston tech fest
Microservices pros and cons - houston tech festMicroservices pros and cons - houston tech fest
Microservices pros and cons - houston tech fest
 
Microservices pros and cons dark
Microservices pros and cons darkMicroservices pros and cons dark
Microservices pros and cons dark
 
Microservices pros and cons
Microservices pros and consMicroservices pros and cons
Microservices pros and cons
 
Reigniting the Volusion platform
Reigniting the Volusion platformReigniting the Volusion platform
Reigniting the Volusion platform
 
Grokking microservices in 5 minutes
Grokking microservices in 5 minutesGrokking microservices in 5 minutes
Grokking microservices in 5 minutes
 
Making your API behave like a big boy
Making your API behave like a big boyMaking your API behave like a big boy
Making your API behave like a big boy
 
Load testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerLoad testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew Siemer
 
Test driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBTest driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDB
 
A tale of two clouds
A tale of two cloudsA tale of two clouds
A tale of two clouds
 

Último

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Último (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

Introduction to CQRS - command and query responsibility segregation

  • 1. CQRS Command & Query Responsibility Segregation
  • 2. Andrew Siemer http://about.me/andrewsiemer ASP Insider Microsoft V-TSP Father of 6 Jack of all trades, master of some.
  • 3.
  • 4.  We are hiring!!!
  • 5. CQRS “…two objects where there previously was one!”
  • 6. 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.”
  • 7. 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
  • 8. What CQRS is not • Not a framework • Not an architecture • Not a specific tool • Not a BEST PRACTICE
  • 9. 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”
  • 10. What CQRS is • CQRS is a pattern • CQRS ends up being a composition of tools and concepts • No two CQRS implementations are identical
  • 11. 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
  • 12. In case you fall asleep Super quick take aways…
  • 13. Traditional Standard three tier app, everything goes in and out
  • 14. CQS Command Query Separation C Q
  • 15. CQRS Command & Query Responsibility Segregation C Q
  • 16. Data BL UI Traditional
  • 17. Data BL UI CQS C Q
  • 18. Data UI CQRS W R C Q
  • 19. Data UI CQRS Data W R C Q
  • 20. Data E UI CQRS Data W R C Q
  • 21. Data UI CQRS Data E W R C Q
  • 22. Event Source W UI CQRS R C Q Data E E
  • 23. Why? Scalability Flexibility Reduced complexity Focus on business Task based UI
  • 24. CQS was first on the scene
  • 25. 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
  • 26. CQS in code: NOT public class User { public string Address { get; set; } }
  • 27. CQS in code: BETTER public class Entity { //... public void Move(string newAddress) { //changes state } public string GetAddress() { //queries state } }
  • 29. DDD: At a high level • CQRS is based on DDD • DDD is used to address complexity • Aggregate Roots • Bounded Contexts • Domain Events
  • 30. DDD: Ubiquitous Language • Domain experts • Technical team • Shared language • Model based on the shared language
  • 31. DDD: Entities • Have identity • Items like • User • Product • Order
  • 32. DDD: Value Objects • Have value, no identity • Items like • User.Address • Product.TechNotes • Order.OrderItem
  • 33. 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
  • 34. 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 Property Reservation Payment Processor HotelMarketing Content Campaign Property
  • 35. DDD: Domain Event • Represents something that happened in the past • Immutable • Historical record Would like to do... Am doing... Is done. PlaceOrder Command PlaceOrder Handler OrderPlaced Event
  • 37. DDD: Visualized Application Bounded Context
  • 38. DDD: Visualized Application Bounded Context Business Component
  • 39. DDD: Visualized Application Bounded Context Business Component Autonomous Business Component
  • 41. 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
  • 42. CQRS in code public class UserWriteService { // Commands public void Move(User user, string newAddress); //... } public class UserReadService { // Queries public User GetUser(int userId); //... }
  • 43. 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
  • 44. CQRS: Command • Message • Handler changes state • Always returns void (nothing) • Works with business intent, not just a record • Not a CRUD style operation
  • 45. CQRS: Command in code public class MoveCustomerCommand : Command { public Address NewAddress { get; set; } }
  • 46. CQRS: Query • Does not change state • Has return value • Also a type of message
  • 47. CQS vs. CQRS: Feature matrix CQS 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
  • 48. Let’s take a closer look!
  • 49. 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 Data Store Server Client Read Operations Write Operations
  • 50. What does CQRS look like at a high level? Data Store Query Model Command Model Service Potential for composite views Application routes change 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
  • 51. 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!
  • 52. What does CQRS look like for us? Warehouse Denormalizer View 2 Denormalizers can read from “rich domain mo del” to “enrich” message in hand. Denormalizer Data Warehouse Read Store Service Service Queue Store Client API/Web Server NSB Saga Store Service Source of Truth Read Store API/Web Server Rich Domain Read/Write Model Queue Store NSB View 1 Denormalizer View 2 Denormalizer NSB Two camps 1) One table per view 2) Composite view Can be same code base, can be deployed separately and segregated at the action level with routing foo Potential to support read 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
  • 53. 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
  • 54. Worth reading • Microsoft: CQRS Journey • Jimmy Bogard: Busting some CQRS myths
  • 55. Any questions? Code and slides: https://github.com/asiemer/IntroToCQRS andrew@clear-measure.com @asiemer

Notas do Editor

  1. Introduction to CQRS Break down the acronym: command and query responsibility segregation
  2. Andrew Siemer, obstacle races, ranching, shooting, ASP Insider, Microsoft Virtual Technology Solution Professional
  3. Some books I have written or am writing, heavy focus on asp.net and web programming
  4. Some places I have worked and some projects I have worked in the past. ClearMeasure is always hiring the best! Become a part of our family.
  5. Mention Greg Young’s concept of “CQRS is simply the creation of two objects where there was previously only one”
  6. Break down what exactly does CQRS mean in three sentences or less.
  7. Introduction – We will take a look at what CQRS is, what it isn’t, how it came to be, and where it fits. This talk will get you up to speed well enough that you can think about CQRS, but implementing CQRS means something different to everyone. You should be able to pick and choose which ideas that tend to surround CQRS are right for you. But you will likely need more study to implement this idea correctly.
  8. Framework – While there are frameworks you can get to make implementing a given notion about CQRS quicker, it is not a framework Architecture – Think about CQRS being something you can do as a piece of your overall architecture Tool – And while there are tools to help you implement pieces of CQRS it is not a tool Best – CQRS if far from the best thing for most projects and we will see why
  9. A best practice is an approach to be used to solve a specific problem. CQRS can cause you more problems that it can solve pretty quickly once you start down this rabbit hole. Be cautious.
  10. Coined by Bertrand Meyer Command returns nothing Query has return value Query does not change state Command does change state
  11. Domain Driven Design was to some a revelation in how we structure our applications. But once distrusted became a mainstream concept DDDD started to show up where the fourth D is distributed. CQS became popular but still semi-dirty with models being mixed for reads and writes. Once it was seen that the responsibility of reads and writes needed to change…we were off. Decoupling the two concerns yields more flexibility.
  12. Traditional multi-tier app, all reads and writes goes through the same plumbing
  13. Separation between reads and writes, but same middle layer
  14. Separation at a code for reads vs writes
  15. The ability to separate the database for reads and writes
  16. We can add events and support read layers for different purposes
  17. Async eventing becomes easier too!
  18. With this model you can then also move to event sourcing
  19. With this model you can then also move to event sourcing
  20. Changing the state of the user’s address loses all intent as to why the change was made Was the address changed due to a typo, did they move, did they get married No separation between state change and queries – forced coupling of model Can’t scale any of this independently
  21. This is allows you separate how you read and write. Which is better. But you lose the intent. Why did this entity move?
  22. Essential part of DDD Breaks business concerns into appropriately sized buckets Principles: Intention-revealing Side-effect free functions Clear encapsulation
  23. A single language that all involved parties can use to talk about the business.
  24. Used to describe the important things in your model as it pertains to a given business area.
  25. The important, albeit less important, things that dangle from your Entities. The meta data used to describe an entity in full.
  26. Used as the primary point of interaction with a set of entities that are closely related. A consistency boundary Has identity, rather than value. Introduction of Entity/Value type just to describe aggregates
  27. As you model out a business area you might quickly find that a “Product” to one part of your business is not the “Product” that another business area describes. It is entirely acceptable to have multiple representations of similar items that exist in your business language. They may share an ID across boundaries (a correlation ID)…but their state is likely stored separately.
  28. Hotel management application
  29. An application can have many bounded contexts Hotel management might have Property management: what rooms are available Content management: what are the various room amenities Deal management: what rooms would we like to get filled
  30. A bounded context can have many business components Within property management we may need to answer questions like What rooms are available with 2 queen beds Smoking or non-smoking rooms available Handicap accessible UI to database in a business component
  31. A business component can have many separately deployable autonomous business components An end point that serves data An end point that servces UI A service that processes commands and events
  32. The topic of CQRS really is about what possibilities this segregation offers. Reduces accidental restrictions through the promotion of explicitness and separation of concerns.
  33. What we’ve seen so far are implicit commands. CQRS uses the well-known Command Message Pattern. Makes *intent of change* explicit Not just a ChangeRecordCommand A “correct address” task—which technically identical—is separate from a “move” task
  34. The opposite of a Command is query Gets state, does not change state.
  35. Event Sourcing has nothing to do with CQRS…but they do play well together Eventual consistency is not required by CQRS –that is a side effect of a truly distributed non-RPC style application You can make a synchronous CQRS system where a command is fired and you wait for all work to be completed A bus, messaging, etc. is not required by CQRS. But CQRS is modeled in such a way that slipping in messaging and a bus fits nicely Do be aware that anything eventually consistent adds to the complexity of what you need to handle on your side Anything that will eventually be worked on means that they could fail in an unexpected way. If your user has already moved on, you need to handle success/fail scenarios. You must plan down to the most minute detail to ensure that all scenarios are handled. Network unplugged? Message delivered more than once? Price updated – data not replicated? As with any added widgets to track and handle – complexity goes up. Number of widgets to build is greater. Test area grows. Deployment complexity increases.