SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Mehr von Dennis Doomen

Mehr von 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
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 

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

Hinweis der Redaktion

  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