SlideShare une entreprise Scribd logo
1  sur  47
CQRS:
Command / Query
Responsibility Segregation
A brief introduction to a scalable pattern for building large multi-user
system
Francesco Garavaglia
07/2016
o Photographer
o High-Aggressive-I-eat-you-
German-Shepherd-
Protected-by
I’m Francesco Garavaglia
o over 10 years of experience in IT consulting
companies.
o Took part in large scale projects (Energy
Markets, Bank, Insurance)
o Pay attention to Software architecture and
Business value
Agenda
 What is CQRS anyway?
 Why is it needed?
 How does CQRS work?
 When should I use CQRS?
 Review example implementation
What is CQSR?1
“
CQRS is simply the creation of two
objects where there was previously
only one.
The separation occurs based upon
whether the methods are a command
or a query :
▫ a command is any method that
mutates state
▫ a query is any method that returns a
value).
From Wikipedia:
So What??
SO WHAT IS CQRS?
Put another way:
Command/Query Responsibility Segregation
(CQRS) is the idea that you can use a
different model to update information than
the model you use to read information.
In this context,
o Commands = Writes
o Queries = Reads
Pioneered by Greg Young & Udi Dahan
OK, Got It. Then?
Why CQRS is needed?2
WHY CQRS IS NEEDE?
Let’s take a step back. Why do we
build applications like we do today?
It started with a stack of paper…
…that needed to be keyed into the
machine…and along came
the CRUD app!
WHY CQRS IS NEEDE?
Being good developers, we didn’t stop there. We built
various models to protect us from change at different layers
of the application.
WHY CQRS IS NEEDE?
But this wasn’t scalable…so we add more layers.
Not only did we add layers, but also complexity.
WHY CQRS IS NEEDE?
All of this to provide
scalability & a
consistent view of
the data.
But did we succeed?
WHY CQRS IS NEEDE?
Back to CRUD Applications: Where is the consistency? We
have stale data all over the place!
?
?
?
??
?
WHY CQRS IS NEEDE?
To understand this better, let’s look at a basic multi-user
system.
Retrieve data
Retrieve data
Modify data
User is looking at stale data
Stale data is inherent in a multi-user system. The machine
is now the source of truth…not a piece of paper.
WHY CQRS IS NEEDE?
Which begs the
question:
Is the data the user
is looking at right
now stale?
Absolutely YES
And Now?
Since stale data
always exists, is all
of this complexity
really needed to
scale?
WHY CQRS IS NEEDED?
No, we need a
different approach.
One that…
o Offers extreme
scalability
o Inherently handle
multiple users
o Can grow to handle
complex problems
without growing
development costs
How does CQRS work?3
HOW DOES CQRS WORK?
Persistent View Model
schema matches UI view
model
A queue can be
utilized to optimize
write performance
Scale
out as
many
copies
as
needed
Command captures
the intent of the user
After database is
updated, publish
result to view model
Diagram from Rinat Abdullin
http://abdullin.com/cqrs
HOW DOES CQRS WORK?
Let’s break it down…
Common components of the CQRS
pattern:
o Task-based UI
o Commands
o Domain Objects
o Events
o Persistent View Model
HOW DOES CQRS WORK – Task-based UI
HOW DOES CQRS WORK – Task-based UI
Why rethink the UI?
Grid doesn’t capture
user intent
GRID = CRUD
HOW DOES CQRS WORK – Task-based UI
Re-thinking the User Interface
o Adjust UI design to capture intent
o what did the user really mean?
o intent becomes a command
Why is intent important?
o Last name changed because of misspelling
o Last name changed because of marriage
o Last name changed because of divorce
o User interface can affect your architecture
HOW DOES CQRS WORK – Task-based UI
Validation
o increase likelihood of command succeeding
o validate client-side
o optimize validation using persistent view model
What about user feedback?
o Polling: wait until read model is updated
o Use asynchronous messaging such as email
“Your request is being processed. You will receive
an email when it is completed”
o Just fake it!
Scope the change to the current user. Update a
local in-memory model
HOW DOES CQRS WORK – Commands
HOW DOES CQRS WORK – Commands
o Commands encapsulate the user’s intent but do not
contain business logic, only enough data for the
command
o What makes a good command?
A command is an action – starts with a verb
The kind you can reply with: “Thank you. Your
confirmation email will arrive shortly”.
Inherently asynchronous.
o Commands can be considered messages
o Messaging provides an asynchronous delivery
mechanism for the commands. As a message, it can
be routed, queued, and transformed all independent
of the sender & receiver
HOW DOES CQRS WORK – Commands & Domain Objects
o The domain model is utilized for processing
commands; it is unnecessary for queries.
o Unlike entity objects you may be used to,
aggregate roots in CQRS only have
methods (no getters/setters)
Aggregate Roots
Some things belong together, like Apple Pie and Ice Cream, or Sonny and Cher. And so it is
with Entities and Value Objects (VOs) – some of them belong together. Aggregates are
groups of things that belong together. An Aggregate Root is the thing that holds them all
together.
Example: OrderLines have no reason to exist without their parent Order, nor can they
belong to any other Order. In this case, Order and OrderLines would be an Aggregate, and
the Order would be the Aggregate Root
“
o Setters are an anti pattern in your domain. DDD
is not about modeling data, or nouns. It is about
modeling behaviors that are solving the domain
problem, or verbs.
o The public interface of your domain should
solely consist in public methods on your
aggregate roots. The idea is that each method
represents a use case.
o From a design perspective, it is also the only
way to ensure your objects invariants. That way,
your aggregates are always fully consistent –
they valid state at all times.
o If DDD is about behavior, then getters also
should be an anti pattern. And they are.
Julienn Letrouit http://julienletrouit.com/?p=22
HOW DOES CQRS WORK – Events
HOW DOES CQRS WORK – Events
o Events describe changes in the system state
o An Event Bus can be utilized to dispatch events
to subscribers
o Events primary purpose update the read model
o Events can also provider integration with
external systems
o CQRS can also be used in conjunction with Event
Sourcing.
Event Sourcing
Captures all changes to an application state as a sequence of events. The current state is
constructed by applying the events in the order they were recorded. Not only does it give us
the current state, but we can also use the event log to reconstruct past states, and as a
foundation to automatically adjust the state to cope with retroactive changes.
Summarized from Martin Fowler – http://martinfowler.com/eaaDev/EventSourcing.html
HOW DOES CQRS WORK – Persistent View Model
HOW DOES CQRS WORK – Persistent View Model
o Reads are usually the most common activity
– many times 80-90%. Why not optimize
them?
o Read model is based on how the user wants
to see the data.
o Read model can be denormalized RDBMS,
document store, etc.
o Reads from the view model don’t need to be
loaded into the domain model, they can be
bond directly to the UI.
HOW DOES CQRS WORK – Persistent View Model
Persistent View Model
UI
Query only…keep it simple
For each view in the UI,
have a view/table in the database
HOW DOES CQRS WORK – Persistent View Model
Data Duplicated,
No Relationships,
Data Pre-Calculated
Customer Service Rep view Supervisor view
When I Should use CQRS?4
WHEN I SHOULD USE CQRS?
First off, When I should avoid it?
o CQRS can be overkill for simple applications.
o Don’t use it in a non-collaborative domain or
where you can horizontally add more
database servers to support more
users/requests/data at the same time you’re
adding web servers – there is no real
scalability problem – Udi Dahan
WHEN I SHOULD USE CQRS?
CQRS is a pattern that is usually leveraged for
a portion of a system.
o This builds on a concept from Domain
Driven Design (DDD) known as a Bounded
Context.
Bounded Context
A Bounded Context is an area of your application which has explicitly defined
borders, has it’s own model, has it’s own Model, and maintains it’s own code. -
Jak Charlton
A Bounded Context can be considered as a miniature application, containing it’s
own domain, code and persistence mechanisms. Within a Bounded Context,
there should be logical consistency, each Bounded Context should be
independent of any other Bounded Context. - ThinkDDD.org
WHEN I SHOULD USE CQRS?
Guidelines for using CQRS:
o Large, multi-user systems CQRS is designed to
address concurrency issues.
o Scalability matters With CQRS you can achieve
great read and write performance. The system
intrinsically supports scaling out. By separating
read & write operations, each can be optimized.
o Difficult business logic CQRS forces you to not
mix domain logic and infrastructural operations.
o Large or Distributed teams you can split
development tasks between different teams
with defined interfaces.
Examples of Implementation5
EXAMPLE OF IMPLEMENTATION
EXAMPLE OF IMPLEMENTATION - NCQRS
Commands are simple object that contain all the data to
perform the underlying action. They also express intent
by there name.
EXAMPLE OF IMPLEMENTATION - NCQRS
An Command Executors accepts commands of a certain
type and performs a corresponding action. The action
should not contain business logic and should directly use
the domain.
EXAMPLE OF IMPLEMENTATION - NCQRS
All events that have occurred end up in the event store. It
contains all the event that represents the state changes in
the system. These can be used to build up the current state
by replaying them all. This store can also be used to fill up
new or repair existing read model.
EXAMPLE OF IMPLEMENTATION - NCQRS
o NCQRS provides a base class for denormalizers that
allows them
o to be subscribed to the event bus.
Any Questions?
Thanks

Contenu connexe

En vedette

Apadrinament lector ESC Collserola
Apadrinament lector ESC CollserolaApadrinament lector ESC Collserola
Apadrinament lector ESC Collserolacrpsantcugat
 
Dr.Saroj datar "disclosing your green side"
Dr.Saroj datar  "disclosing your green side"Dr.Saroj datar  "disclosing your green side"
Dr.Saroj datar "disclosing your green side"Dr. saroj Datar- Apte
 
Medicinal cannabis -the_evidence_v1.1
Medicinal cannabis -the_evidence_v1.1Medicinal cannabis -the_evidence_v1.1
Medicinal cannabis -the_evidence_v1.1Sue Rosen RN CLNC
 
Little Lady Burlesque Dance Class Program
Little Lady Burlesque Dance Class ProgramLittle Lady Burlesque Dance Class Program
Little Lady Burlesque Dance Class ProgramLittle Lady Burlesque
 
Growing Asian Demand In Physical Gold And Its Impact On Gold Prices
Growing Asian Demand In Physical Gold And Its Impact On Gold PricesGrowing Asian Demand In Physical Gold And Its Impact On Gold Prices
Growing Asian Demand In Physical Gold And Its Impact On Gold PricesKirill Klip
 
ILC PP July 2015
ILC PP July 2015ILC PP July 2015
ILC PP July 2015Kirill Klip
 
General Service Contractors Presentation
General Service Contractors Presentation General Service Contractors Presentation
General Service Contractors Presentation Julia Albaugh
 
Monitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura itMonitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura itStefano Arduini
 
47 Sylvan Ave, Pleasant Ridge, Forsale2
47 Sylvan Ave, Pleasant Ridge, Forsale247 Sylvan Ave, Pleasant Ridge, Forsale2
47 Sylvan Ave, Pleasant Ridge, Forsale2Julie Thayer
 
IM value creation paper
IM value creation paperIM value creation paper
IM value creation paperFelix Schlumpf
 
Дайджест мероприятий 1-5 декабря
Дайджест мероприятий 1-5 декабряДайджест мероприятий 1-5 декабря
Дайджест мероприятий 1-5 декабряAnastasiia Moroz
 
Use cases for secure Sms chat - im - mms in support of patient adherence
Use cases for secure Sms chat - im - mms in support of patient adherenceUse cases for secure Sms chat - im - mms in support of patient adherence
Use cases for secure Sms chat - im - mms in support of patient adherenceRaymond Silk
 
Kirei EchoPanel SpecShee 04 15
Kirei EchoPanel SpecShee 04 15Kirei EchoPanel SpecShee 04 15
Kirei EchoPanel SpecShee 04 15John Stein
 

En vedette (17)

Zak Precast Concrete India Conference
Zak Precast Concrete India ConferenceZak Precast Concrete India Conference
Zak Precast Concrete India Conference
 
AllCells Overview
AllCells OverviewAllCells Overview
AllCells Overview
 
Apadrinament lector ESC Collserola
Apadrinament lector ESC CollserolaApadrinament lector ESC Collserola
Apadrinament lector ESC Collserola
 
Dr.Saroj datar "disclosing your green side"
Dr.Saroj datar  "disclosing your green side"Dr.Saroj datar  "disclosing your green side"
Dr.Saroj datar "disclosing your green side"
 
Medicinal cannabis -the_evidence_v1.1
Medicinal cannabis -the_evidence_v1.1Medicinal cannabis -the_evidence_v1.1
Medicinal cannabis -the_evidence_v1.1
 
Osterman media summary
Osterman media summaryOsterman media summary
Osterman media summary
 
Little Lady Burlesque Dance Class Program
Little Lady Burlesque Dance Class ProgramLittle Lady Burlesque Dance Class Program
Little Lady Burlesque Dance Class Program
 
Growing Asian Demand In Physical Gold And Its Impact On Gold Prices
Growing Asian Demand In Physical Gold And Its Impact On Gold PricesGrowing Asian Demand In Physical Gold And Its Impact On Gold Prices
Growing Asian Demand In Physical Gold And Its Impact On Gold Prices
 
ILC PP July 2015
ILC PP July 2015ILC PP July 2015
ILC PP July 2015
 
Who am i bread
Who am i   breadWho am i   bread
Who am i bread
 
General Service Contractors Presentation
General Service Contractors Presentation General Service Contractors Presentation
General Service Contractors Presentation
 
Monitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura itMonitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura it
 
47 Sylvan Ave, Pleasant Ridge, Forsale2
47 Sylvan Ave, Pleasant Ridge, Forsale247 Sylvan Ave, Pleasant Ridge, Forsale2
47 Sylvan Ave, Pleasant Ridge, Forsale2
 
IM value creation paper
IM value creation paperIM value creation paper
IM value creation paper
 
Дайджест мероприятий 1-5 декабря
Дайджест мероприятий 1-5 декабряДайджест мероприятий 1-5 декабря
Дайджест мероприятий 1-5 декабря
 
Use cases for secure Sms chat - im - mms in support of patient adherence
Use cases for secure Sms chat - im - mms in support of patient adherenceUse cases for secure Sms chat - im - mms in support of patient adherence
Use cases for secure Sms chat - im - mms in support of patient adherence
 
Kirei EchoPanel SpecShee 04 15
Kirei EchoPanel SpecShee 04 15Kirei EchoPanel SpecShee 04 15
Kirei EchoPanel SpecShee 04 15
 

Similaire à Workshop - cqrs brief introduction

CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationBrian Ritchie
 
Cqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For DevelopersCqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For Developerswojtek_s
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patternsMd. Sadhan Sarker
 
MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...
MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...
MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...Jitendra Bafna
 
A Developer's Guide to CQRS Using .NET Core and MediatR
A Developer's Guide to CQRS Using .NET Core and MediatRA Developer's Guide to CQRS Using .NET Core and MediatR
A Developer's Guide to CQRS Using .NET Core and MediatRBình Trọng Án
 
The Clean Architecture
The Clean ArchitectureThe Clean Architecture
The Clean ArchitectureDmytro Turskyi
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
Architectural Design Report G4
Architectural Design Report G4Architectural Design Report G4
Architectural Design Report G4Prizzl
 
Agile architecture upload
Agile architecture uploadAgile architecture upload
Agile architecture uploadThe Real Dyl
 
Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...
Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...
Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...David J Rosenthal
 
Microservices in a netshell
Microservices in a netshellMicroservices in a netshell
Microservices in a netshellKnoldus Inc.
 
Reactive - Is it really a Magic Pill?
Reactive - Is it really a Magic Pill?Reactive - Is it really a Magic Pill?
Reactive - Is it really a Magic Pill?Tech Triveni
 
The "Why", "What" & "How" of Microservices - short version
The "Why", "What" & "How" of Microservices - short versionThe "Why", "What" & "How" of Microservices - short version
The "Why", "What" & "How" of Microservices - short versionINPAY
 
What is Data as a Service by T-Mobile Principle Technical PM
What is Data as a Service by T-Mobile Principle Technical PMWhat is Data as a Service by T-Mobile Principle Technical PM
What is Data as a Service by T-Mobile Principle Technical PMProduct School
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureMohamed Galal
 
Espresso: LinkedIn's Distributed Data Serving Platform (Paper)
Espresso: LinkedIn's Distributed Data Serving Platform (Paper)Espresso: LinkedIn's Distributed Data Serving Platform (Paper)
Espresso: LinkedIn's Distributed Data Serving Platform (Paper)Amy W. Tang
 

Similaire à Workshop - cqrs brief introduction (20)

CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility Segregation
 
CQRS
CQRSCQRS
CQRS
 
Cqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For DevelopersCqrs and Event Sourcing Intro For Developers
Cqrs and Event Sourcing Intro For Developers
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...
MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...
MuleSoft Surat Virtual Meetup#32 - Implementing Command and Query Responsibil...
 
A Developer's Guide to CQRS Using .NET Core and MediatR
A Developer's Guide to CQRS Using .NET Core and MediatRA Developer's Guide to CQRS Using .NET Core and MediatR
A Developer's Guide to CQRS Using .NET Core and MediatR
 
The Clean Architecture
The Clean ArchitectureThe Clean Architecture
The Clean Architecture
 
What are microservices
What are microservicesWhat are microservices
What are microservices
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
Architectural Design Report G4
Architectural Design Report G4Architectural Design Report G4
Architectural Design Report G4
 
Agile architecture upload
Agile architecture uploadAgile architecture upload
Agile architecture upload
 
Orchestration, the conductor's score
Orchestration, the conductor's scoreOrchestration, the conductor's score
Orchestration, the conductor's score
 
Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...
Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...
Cloud Design Patterns - PRESCRIPTIVE ARCHITECTURE GUIDANCE FOR CLOUD APPLICAT...
 
Microservices in a netshell
Microservices in a netshellMicroservices in a netshell
Microservices in a netshell
 
Reactive - Is it really a Magic Pill?
Reactive - Is it really a Magic Pill?Reactive - Is it really a Magic Pill?
Reactive - Is it really a Magic Pill?
 
The "Why", "What" & "How" of Microservices - short version
The "Why", "What" & "How" of Microservices - short versionThe "Why", "What" & "How" of Microservices - short version
The "Why", "What" & "How" of Microservices - short version
 
What is Data as a Service by T-Mobile Principle Technical PM
What is Data as a Service by T-Mobile Principle Technical PMWhat is Data as a Service by T-Mobile Principle Technical PM
What is Data as a Service by T-Mobile Principle Technical PM
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean Architecture
 
Espresso: LinkedIn's Distributed Data Serving Platform (Paper)
Espresso: LinkedIn's Distributed Data Serving Platform (Paper)Espresso: LinkedIn's Distributed Data Serving Platform (Paper)
Espresso: LinkedIn's Distributed Data Serving Platform (Paper)
 

Dernier

2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 

Dernier (20)

2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 

Workshop - cqrs brief introduction

  • 1. CQRS: Command / Query Responsibility Segregation A brief introduction to a scalable pattern for building large multi-user system Francesco Garavaglia 07/2016
  • 2. o Photographer o High-Aggressive-I-eat-you- German-Shepherd- Protected-by I’m Francesco Garavaglia o over 10 years of experience in IT consulting companies. o Took part in large scale projects (Energy Markets, Bank, Insurance) o Pay attention to Software architecture and Business value
  • 3. Agenda  What is CQRS anyway?  Why is it needed?  How does CQRS work?  When should I use CQRS?  Review example implementation
  • 5. “ CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query : ▫ a command is any method that mutates state ▫ a query is any method that returns a value). From Wikipedia:
  • 7. SO WHAT IS CQRS? Put another way: Command/Query Responsibility Segregation (CQRS) is the idea that you can use a different model to update information than the model you use to read information. In this context, o Commands = Writes o Queries = Reads Pioneered by Greg Young & Udi Dahan
  • 8. OK, Got It. Then?
  • 9. Why CQRS is needed?2
  • 10. WHY CQRS IS NEEDE? Let’s take a step back. Why do we build applications like we do today? It started with a stack of paper… …that needed to be keyed into the machine…and along came the CRUD app!
  • 11. WHY CQRS IS NEEDE? Being good developers, we didn’t stop there. We built various models to protect us from change at different layers of the application.
  • 12. WHY CQRS IS NEEDE? But this wasn’t scalable…so we add more layers. Not only did we add layers, but also complexity.
  • 13. WHY CQRS IS NEEDE? All of this to provide scalability & a consistent view of the data. But did we succeed?
  • 14. WHY CQRS IS NEEDE? Back to CRUD Applications: Where is the consistency? We have stale data all over the place! ? ? ? ?? ?
  • 15. WHY CQRS IS NEEDE? To understand this better, let’s look at a basic multi-user system. Retrieve data Retrieve data Modify data User is looking at stale data Stale data is inherent in a multi-user system. The machine is now the source of truth…not a piece of paper.
  • 16. WHY CQRS IS NEEDE? Which begs the question: Is the data the user is looking at right now stale?
  • 18. Since stale data always exists, is all of this complexity really needed to scale? WHY CQRS IS NEEDED? No, we need a different approach. One that… o Offers extreme scalability o Inherently handle multiple users o Can grow to handle complex problems without growing development costs
  • 19. How does CQRS work?3
  • 20. HOW DOES CQRS WORK? Persistent View Model schema matches UI view model A queue can be utilized to optimize write performance Scale out as many copies as needed Command captures the intent of the user After database is updated, publish result to view model Diagram from Rinat Abdullin http://abdullin.com/cqrs
  • 21. HOW DOES CQRS WORK? Let’s break it down… Common components of the CQRS pattern: o Task-based UI o Commands o Domain Objects o Events o Persistent View Model
  • 22. HOW DOES CQRS WORK – Task-based UI
  • 23. HOW DOES CQRS WORK – Task-based UI Why rethink the UI? Grid doesn’t capture user intent GRID = CRUD
  • 24. HOW DOES CQRS WORK – Task-based UI Re-thinking the User Interface o Adjust UI design to capture intent o what did the user really mean? o intent becomes a command Why is intent important? o Last name changed because of misspelling o Last name changed because of marriage o Last name changed because of divorce o User interface can affect your architecture
  • 25. HOW DOES CQRS WORK – Task-based UI Validation o increase likelihood of command succeeding o validate client-side o optimize validation using persistent view model What about user feedback? o Polling: wait until read model is updated o Use asynchronous messaging such as email “Your request is being processed. You will receive an email when it is completed” o Just fake it! Scope the change to the current user. Update a local in-memory model
  • 26. HOW DOES CQRS WORK – Commands
  • 27. HOW DOES CQRS WORK – Commands o Commands encapsulate the user’s intent but do not contain business logic, only enough data for the command o What makes a good command? A command is an action – starts with a verb The kind you can reply with: “Thank you. Your confirmation email will arrive shortly”. Inherently asynchronous. o Commands can be considered messages o Messaging provides an asynchronous delivery mechanism for the commands. As a message, it can be routed, queued, and transformed all independent of the sender & receiver
  • 28. HOW DOES CQRS WORK – Commands & Domain Objects o The domain model is utilized for processing commands; it is unnecessary for queries. o Unlike entity objects you may be used to, aggregate roots in CQRS only have methods (no getters/setters) Aggregate Roots Some things belong together, like Apple Pie and Ice Cream, or Sonny and Cher. And so it is with Entities and Value Objects (VOs) – some of them belong together. Aggregates are groups of things that belong together. An Aggregate Root is the thing that holds them all together. Example: OrderLines have no reason to exist without their parent Order, nor can they belong to any other Order. In this case, Order and OrderLines would be an Aggregate, and the Order would be the Aggregate Root
  • 29. “ o Setters are an anti pattern in your domain. DDD is not about modeling data, or nouns. It is about modeling behaviors that are solving the domain problem, or verbs. o The public interface of your domain should solely consist in public methods on your aggregate roots. The idea is that each method represents a use case. o From a design perspective, it is also the only way to ensure your objects invariants. That way, your aggregates are always fully consistent – they valid state at all times. o If DDD is about behavior, then getters also should be an anti pattern. And they are. Julienn Letrouit http://julienletrouit.com/?p=22
  • 30. HOW DOES CQRS WORK – Events
  • 31. HOW DOES CQRS WORK – Events o Events describe changes in the system state o An Event Bus can be utilized to dispatch events to subscribers o Events primary purpose update the read model o Events can also provider integration with external systems o CQRS can also be used in conjunction with Event Sourcing. Event Sourcing Captures all changes to an application state as a sequence of events. The current state is constructed by applying the events in the order they were recorded. Not only does it give us the current state, but we can also use the event log to reconstruct past states, and as a foundation to automatically adjust the state to cope with retroactive changes. Summarized from Martin Fowler – http://martinfowler.com/eaaDev/EventSourcing.html
  • 32. HOW DOES CQRS WORK – Persistent View Model
  • 33. HOW DOES CQRS WORK – Persistent View Model o Reads are usually the most common activity – many times 80-90%. Why not optimize them? o Read model is based on how the user wants to see the data. o Read model can be denormalized RDBMS, document store, etc. o Reads from the view model don’t need to be loaded into the domain model, they can be bond directly to the UI.
  • 34. HOW DOES CQRS WORK – Persistent View Model Persistent View Model UI Query only…keep it simple For each view in the UI, have a view/table in the database
  • 35. HOW DOES CQRS WORK – Persistent View Model Data Duplicated, No Relationships, Data Pre-Calculated Customer Service Rep view Supervisor view
  • 36. When I Should use CQRS?4
  • 37. WHEN I SHOULD USE CQRS? First off, When I should avoid it? o CQRS can be overkill for simple applications. o Don’t use it in a non-collaborative domain or where you can horizontally add more database servers to support more users/requests/data at the same time you’re adding web servers – there is no real scalability problem – Udi Dahan
  • 38. WHEN I SHOULD USE CQRS? CQRS is a pattern that is usually leveraged for a portion of a system. o This builds on a concept from Domain Driven Design (DDD) known as a Bounded Context. Bounded Context A Bounded Context is an area of your application which has explicitly defined borders, has it’s own model, has it’s own Model, and maintains it’s own code. - Jak Charlton A Bounded Context can be considered as a miniature application, containing it’s own domain, code and persistence mechanisms. Within a Bounded Context, there should be logical consistency, each Bounded Context should be independent of any other Bounded Context. - ThinkDDD.org
  • 39. WHEN I SHOULD USE CQRS? Guidelines for using CQRS: o Large, multi-user systems CQRS is designed to address concurrency issues. o Scalability matters With CQRS you can achieve great read and write performance. The system intrinsically supports scaling out. By separating read & write operations, each can be optimized. o Difficult business logic CQRS forces you to not mix domain logic and infrastructural operations. o Large or Distributed teams you can split development tasks between different teams with defined interfaces.
  • 42. EXAMPLE OF IMPLEMENTATION - NCQRS Commands are simple object that contain all the data to perform the underlying action. They also express intent by there name.
  • 43. EXAMPLE OF IMPLEMENTATION - NCQRS An Command Executors accepts commands of a certain type and performs a corresponding action. The action should not contain business logic and should directly use the domain.
  • 44. EXAMPLE OF IMPLEMENTATION - NCQRS All events that have occurred end up in the event store. It contains all the event that represents the state changes in the system. These can be used to build up the current state by replaying them all. This store can also be used to fill up new or repair existing read model.
  • 45. EXAMPLE OF IMPLEMENTATION - NCQRS o NCQRS provides a base class for denormalizers that allows them o to be subscribed to the event bus.