0% found this document useful (0 votes)
413 views55 pages

CQRS for Developers and Architects

This document provides an overview of Command Query Responsibility Segregation (CQRS). CQRS is a pattern that separates operations that read data from operations that update data by using separate interfaces. This allows the read and write models to evolve independently for better performance, scalability, security and flexibility over time. The document discusses how CQRS evolved from earlier patterns like Command Query Separation (CQS) and Domain-Driven Design (DDD). It highlights that CQRS is not a framework or architecture but a pattern, and that implementations can vary.

Uploaded by

Prakash Kapadia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
413 views55 pages

CQRS for Developers and Architects

This document provides an overview of Command Query Responsibility Segregation (CQRS). CQRS is a pattern that separates operations that read data from operations that update data by using separate interfaces. This allows the read and write models to evolve independently for better performance, scalability, security and flexibility over time. The document discusses how CQRS evolved from earlier patterns like Command Query Separation (CQS) and Domain-Driven Design (DDD). It highlights that CQRS is not a framework or architecture but a pattern, and that implementations can vary.

Uploaded by

Prakash Kapadia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

CQRS

Command & Query Responsibility


Segregation
http://about.me/andrewsiemer

Andrew Siemer 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 C Q

Command Query Separation


CQRS C Q
Command & Query Responsibility Segregation
Data

BL

Traditional
UI
Data

BL

CQS
C Q

UI
Data

W R

CQRS
C Q

UI
Data Data

W R

CQRS
C Q

UI
Data Data

W R

CQRS
C Q

UI
Data Data

W R

CQRS
C Q

UI
Event
Data
Source
E

W R

CQRS
C Q

UI
Scalability
Flexibility

Why? 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
Order
• Consistency boundary
OrderHeader
• transactional

OrderItem
DDD: Bounded Context
• Two or more distinct (obviously related) models
• Interactions between them
• Usually delineated by business groups or tasks
HotelBookings

Order Availability Payment HotelMarketing

OrderHeader
Property Processor Content Campaign

Reservation
Property
OrderItem
DDD: Domain Event
• Represents something that happened in the past
• Immutable
• Historical record

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

PlaceOrder PlaceOrder OrderPlaced


Command Handler 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 Data Store
Data Store

• Client reads data through another set of methods


• Likely the same object model Read Write

• The read and write model are likely the same


Operations Operations

Server

• Or a sub-set thereof
• Can support read replicas (at DB) Client

• Doesn’t support multiple different containers of data


What does CQRS look like at a high level?
Can be same store

• Store can be the same or different store,


but is guaranteed
to be different
Query Model

schema and

• Data shape IS different


different data
shape
Potential for
composite views

• Data flow is different


• Zero model concerns
are leaked to Data
Store Command Model
Client

view concerns
Application routes
change information
Command model
executes validations,
and consequential Opportunity for
logic message oriented
architecture

Service
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? Denormalizers can read
from “rich domain
model” to “enrich”
mess age in hand.

Warehouse Data

• Store for each


Denormalizer Warehouse
Rich Domain NSB Queue Store
Source View 1
Read/Write Model
of Truth Denormalizer
Service
Service

• Rich domain
Service
Read Potential to support
View22
View Read read rep licas
Store
NSB Denormalizer
Denormalizer Store

• View concerns Queue Store


Saga
Store
Two camps
1) One table per view

• Reporting concerns 2) Composite view

NSB
• Data shape IS different API/Web Server
Can be same code base, can be
deployed separately and segregated
at the action level with routing foo
API/Web Server

• Messaging for distribution


• Lots of scalability options
• Supports different storage mechanisms Client
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

You might also like