SlideShare uma empresa Scribd logo
1 de 19
Command Query Separation

 And what it brings to your day job
        Dennis Doomen
About Me

• Principal Consultant     • Speaker
• 16 years IT experience   • Public initiatives
• C++ origins but since       – Silverlight Cookbook
  2001 addicated to C#        – C# Coding Guidelines
• Specialties                 – Fluent Assertions
   – Architecture          • Internet
   – Scrum/XP                 – www.dennisdoomen.net
   – ALM                      – DZone MVB
                              – @ddoomen
WHAT IS CQS AND WHY SHOULD
YOU USE IT?
“…asking a question
should not change the
      answer…”

PROF. BERTRAND MEYER
CQS IN PRACTICE

myObject
 .UseRepository("Stuff")
 .WithTransactionSupport()
  .Retries(3)
 .LogWarnings()
 .LogErrors();



var newObject = myObject
 .UseRepository("Stuff")
 .WithTransactionSupport()
  .Retries(3)
 .LogWarnings()
 .LogErrors();
AND ANOTHER EXAMPLE

void Push(T t);
T Pop();
bool IsEmpty { get; }



public interface IStack<T> :
IEnumerable<T>
  {
     IStack<T> Push(T value);
     IStack<T> Pop();
     T Peek();
     bool IsEmpty { get; }
   }
SO WHAT’S CQRS THEN?
“CQRS is a simple pattern that strictly
 segregates the responsibility of handling
    command input into an autonomous
system from the responsibility of handling
 side-effect-free query/read access on the
               same system.”

            CLEMENS VASTERS
CQRS = CQS on Architecture Level
                                           Front-End
                                                                                           Sustains
                                                                                           the user
  No O/R
                                                                                            intent
conversions            Queries                                Business Actions


               Projections                                        Commands



                        Query Service                  Command Service       Command Handlers

                      Data Access Layer                           Domain Model

 Optimized                                                          Repositories
for querying
                                                                                                       Optimized
                                                                                                          for
                                                                                                      consistency
                                          Changes                    Relational
                         Query Store
                                                                     Database
                      Query
                      Store
                                          Synchronous or
                                           asynchronous
Scaling Opportunities
                                      Front-End




                         Querying
                 Querying
                                                  Command Side
         Querying
 Querying




                        Query Store
                Query Store
                                                   Relational
        Query Store                                Database
Query Store
Myths of CQRS

• It is an architecture (style)
• It should be used by default
• It requires Event Sourcing
• It requires eventual consistency
• It requires a
  bus/queues/asynchrony
• Commands are fire-and-forget
• Solves all concurrency problems
• It is easy
HOW TO BUILD IT?
Approach

1. Decide if you need it
2. Reconsider if you need it
3. Design your domain using
   aggregates
4. Add commands
5. Add queries
Effective Aggregate Design
Effective Aggregate Design
 Model true                Design
invariants in              Small
consistency              Aggregates
 boundaries




                                        Reference
     Update single                        other
     aggregate per                    aggregates by
      transaction                        identity
How it works
                       Execute query             Front-End             Send command
                                                    App


  Query
Processor                                                                             Command
                                                                                       Service
                    Find query handler                       Find command handler

                                                  Registry

                                                                     Creates
                            Creates
 Query                                                                                 Command         Find by ID and/or version
Handler                                                                                 Handler

                                                                                     Invoke method                  Unit-of-
 LINQ, HQL, SQL                                                                                                      Work

                                            Domain           Send domain event         Aggregate
                                             Event                                                          Loads
     Simple Data                                                                         Root
                                            Handler
     Access Layer      Store denormalized
                              data                                                  Store normalized
                                                                                          data



       Read DB                                                                         Write DB
WebAPI,
                                                  What to use?
 WCF,
 POCO                                                    Front-End               WCF,
                                                            App                  POCO
                                      Autofac,
      Query                            Unity,
    Processor                      StructureMap                      Command
                                                                      Service

                                                          Registry



     Query                                                           Command
    Handler                                                           Handler

                      NHibernate                                                         Unit-of-
                      EF, Dapper                                                          Work

                                                     Domain
                                                                     Aggregate
                                                      Event
          Simple Data                                                  Root
                                                     Handler
          Access Layer

                                                  Udi Dahan’s
                                                   Domain
                                                    Event
            Read DB                                                  Write DB    SQL, Oracle,
                             SQL, Oracle,
                              RavenDB,                                            RavenDB,
                               NoSQL                                               NoSQL
Questions?

Email
dennis.doomen@avivasolutions.nl

Twitter
ddoomen

Sites
www.dennisdoomen.net
www.csharpcodingguidelines.com
fluentassertions.codeplex.com
silverlightcookbook.codeplex.com
Reading Material
• Effective Aggregate Design
  http://dddcommunity.org/library/vernon_2011
• Meanwhile…on the command side of my architecture
  http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91
• Meanwhile…on the query side of my architecture
  http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92
• Busting some CQRS myths
  http://lostechies.com/jimmybogard/2012/08/22/busting-some-cqrs-
  myths/
• Free MSDN eBook: Exploring CQRS and Event Sourcing
  http://www.microsoft.com/en-us/download/details.aspx?id=34774

Mais conteúdo relacionado

Mais de Dennis Doomen

Mais de Dennis Doomen (20)

What is the right unit in unit testing (UpdateConf 2022)
What is the right unit in unit testing (UpdateConf 2022)What is the right unit in unit testing (UpdateConf 2022)
What is the right unit in unit testing (UpdateConf 2022)
 
Slow Event Sourcing (re)projections - Just make them faster!
Slow Event Sourcing (re)projections - Just make them faster!Slow Event Sourcing (re)projections - Just make them faster!
Slow Event Sourcing (re)projections - Just make them faster!
 
50 things software teams should not do.pptx
50 things software teams should not do.pptx50 things software teams should not do.pptx
50 things software teams should not do.pptx
 
What is the right "unit" in unit testing and why it is not a class?
What is the right "unit" in unit testing and why it is not a class?What is the right "unit" in unit testing and why it is not a class?
What is the right "unit" in unit testing and why it is not a class?
 
A lab around the principles and practices for writing maintainable code
A lab around the principles and practices for writing maintainable codeA lab around the principles and practices for writing maintainable code
A lab around the principles and practices for writing maintainable code
 
How to Practice TDD Without Shooting Yourself in the Foot
How to Practice TDD Without Shooting Yourself in the FootHow to Practice TDD Without Shooting Yourself in the Foot
How to Practice TDD Without Shooting Yourself in the Foot
 
Decomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDecomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservices
 
Event Sourcing from the Trenches (DDD Europe 2020)
Event Sourcing from the Trenches (DDD Europe 2020)Event Sourcing from the Trenches (DDD Europe 2020)
Event Sourcing from the Trenches (DDD Europe 2020)
 
Practical introduction to DDD, CQRS and Event Sourcing
Practical introduction to DDD, CQRS and Event SourcingPractical introduction to DDD, CQRS and Event Sourcing
Practical introduction to DDD, CQRS and Event Sourcing
 
How to practice TDD without shooting yourself in the foot
How to practice TDD without shooting yourself in the footHow to practice TDD without shooting yourself in the foot
How to practice TDD without shooting yourself in the foot
 
Decomposing the Monolith (Riga Dev Days 2019)
Decomposing the Monolith (Riga Dev Days 2019)Decomposing the Monolith (Riga Dev Days 2019)
Decomposing the Monolith (Riga Dev Days 2019)
 
A lab around the principles and practices for writing maintainable code (2019)
A lab around the principles and practices for writing maintainable code (2019)A lab around the principles and practices for writing maintainable code (2019)
A lab around the principles and practices for writing maintainable code (2019)
 
Lessons learned from two decades of professional software development
Lessons learned from two decades of professional software developmentLessons learned from two decades of professional software development
Lessons learned from two decades of professional software development
 
The Good, The Bad and The Ugly of Event Sourcing
The Good, The Bad and The Ugly of Event Sourcing The Good, The Bad and The Ugly of Event Sourcing
The Good, The Bad and The Ugly of Event Sourcing
 
Event Sourcing from the Trenches (with examples from .NET)
Event Sourcing from the Trenches (with examples from .NET)Event Sourcing from the Trenches (with examples from .NET)
Event Sourcing from the Trenches (with examples from .NET)
 
How To Practice TDD Without Shooting Yourself In The Foot
How To Practice TDD Without Shooting Yourself In The FootHow To Practice TDD Without Shooting Yourself In The Foot
How To Practice TDD Without Shooting Yourself In The Foot
 
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
 
Strengths and weaknesses of dependency injection
Strengths and weaknesses of dependency injectionStrengths and weaknesses of dependency injection
Strengths and weaknesses of dependency injection
 
Build Libraries That People Love To use
Build Libraries That People Love To useBuild Libraries That People Love To use
Build Libraries That People Love To use
 
Decomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDecomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you pain
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Command Query Separation And How It Helps In Your Daily Job

  • 1. Command Query Separation And what it brings to your day job Dennis Doomen
  • 2. About Me • Principal Consultant • Speaker • 16 years IT experience • Public initiatives • C++ origins but since – Silverlight Cookbook 2001 addicated to C# – C# Coding Guidelines • Specialties – Fluent Assertions – Architecture • Internet – Scrum/XP – www.dennisdoomen.net – ALM – DZone MVB – @ddoomen
  • 3. WHAT IS CQS AND WHY SHOULD YOU USE IT?
  • 4. “…asking a question should not change the answer…” PROF. BERTRAND MEYER
  • 5. CQS IN PRACTICE myObject .UseRepository("Stuff") .WithTransactionSupport() .Retries(3) .LogWarnings() .LogErrors(); var newObject = myObject .UseRepository("Stuff") .WithTransactionSupport() .Retries(3) .LogWarnings() .LogErrors();
  • 6. AND ANOTHER EXAMPLE void Push(T t); T Pop(); bool IsEmpty { get; } public interface IStack<T> : IEnumerable<T> { IStack<T> Push(T value); IStack<T> Pop(); T Peek(); bool IsEmpty { get; } }
  • 8. “CQRS is a simple pattern that strictly segregates the responsibility of handling command input into an autonomous system from the responsibility of handling side-effect-free query/read access on the same system.” CLEMENS VASTERS
  • 9. CQRS = CQS on Architecture Level Front-End Sustains the user No O/R intent conversions Queries Business Actions Projections Commands Query Service Command Service Command Handlers Data Access Layer Domain Model Optimized Repositories for querying Optimized for consistency Changes Relational Query Store Database Query Store Synchronous or asynchronous
  • 10. Scaling Opportunities Front-End Querying Querying Command Side Querying Querying Query Store Query Store Relational Query Store Database Query Store
  • 11. Myths of CQRS • It is an architecture (style) • It should be used by default • It requires Event Sourcing • It requires eventual consistency • It requires a bus/queues/asynchrony • Commands are fire-and-forget • Solves all concurrency problems • It is easy
  • 13. Approach 1. Decide if you need it 2. Reconsider if you need it 3. Design your domain using aggregates 4. Add commands 5. Add queries
  • 15. Effective Aggregate Design Model true Design invariants in Small consistency Aggregates boundaries Reference Update single other aggregate per aggregates by transaction identity
  • 16. How it works Execute query Front-End Send command App Query Processor Command Service Find query handler Find command handler Registry Creates Creates Query Command Find by ID and/or version Handler Handler Invoke method Unit-of- LINQ, HQL, SQL Work Domain Send domain event Aggregate Event Loads Simple Data Root Handler Access Layer Store denormalized data Store normalized data Read DB Write DB
  • 17. WebAPI, What to use? WCF, POCO Front-End WCF, App POCO Autofac, Query Unity, Processor StructureMap Command Service Registry Query Command Handler Handler NHibernate Unit-of- EF, Dapper Work Domain Aggregate Event Simple Data Root Handler Access Layer Udi Dahan’s Domain Event Read DB Write DB SQL, Oracle, SQL, Oracle, RavenDB, RavenDB, NoSQL NoSQL
  • 19. Reading Material • Effective Aggregate Design http://dddcommunity.org/library/vernon_2011 • Meanwhile…on the command side of my architecture http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91 • Meanwhile…on the query side of my architecture http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92 • Busting some CQRS myths http://lostechies.com/jimmybogard/2012/08/22/busting-some-cqrs- myths/ • Free MSDN eBook: Exploring CQRS and Event Sourcing http://www.microsoft.com/en-us/download/details.aspx?id=34774

Notas do Editor

  1. DisadvantagesNo concurrency; conflicting service requests are simply rejectedStaleness ignored;Scalability limited; No domain verbs; domain model does contain concepts from the domain model, just not the business actionsGranularity DTOs; What operations to expose in your WCF service? What relations to include and when? What domain entities to flatten.Unneccesary DTO conversions; Conversions from/to domain model entities, traversing of relations, eager fatchingConflicting demands; query demands denormalized schema, commands require normalized integer schema
  2. DisadvantagesNo concurrency; conflicting service requests are simply rejectedStaleness ignored;Scalability limited; No domain verbs; domain model does contain concepts from the domain model, just not the business actionsGranularity DTOs; What operations to expose in your WCF service? What relations to include and when? What domain entities to flatten.Unneccesary DTO conversions; Conversions from/to domain model entities, traversing of relations, eager fatchingConflicting demands; query demands denormalized schema, commands require normalized integer schema