Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to CQRS - command and query responsibility segregation

3,056 views

Published on

A high level introduction to CQRS (command and query responsibility segregation), CQS (command query separation), DDD (domain driven design), DDD-D ...with distributed, and how all those weave together.

Published in: Software
  • Be the first to comment

Introduction to CQRS - command and query responsibility segregation

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

×