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.
Jeppe CramonWhat SOA do you have?
Problems with SOA• Systems are more fragile• Development and Maintenance costs are higher• Your services are not being reu...
If you have arrived at the realizationthat SOA is a pain and costs toomuch without enabling businessagility or reducing yo...
Let’s take a trip back in time
And look at how we could do business
Sales DepartmentOld style SOADesign Department Customer Department Finance Department Fabric DepartmentThe CustomerCreate ...
This is slow
We are not selling enough!!
Sales DepartmentOld style SOA IIDesign Department Customer Department Finance Department Fabric DepartmentCreate Sales Order
We need to speed things up!Hackel walks between desks?Way too slow.
We need to speed things up!He needs to call So we make sure thathe canActually, call a lot!
We need to speed things up!But Hackel still have to wait Even if we get creative
We need to speed things up!Somethingneeds to bedone!!
Speed up even more!Lets get an automatic switchboard!
Speed up even more!New technology, sameproblemEven if we get creativeagain
Or do things AsyncSo Hackel can send requestto Ingeborg and Krestenwhich can respond toHackel when they’ve got ananswerBut...
Speed up even more!So Kresten and Ingeborg adds more staff
Scalability is expensiveSales DepartmentDesign Department Customer Department Finance Department Fabric DepartmentCoordina...
Same problem different technologyDataStorageDataStorageDataStorageFinanceServiceDataServiceDesignServiceHackel Coordinator...
Resemble much?
Now back to the story…• Scaling up Sales requires scaling up otherdepartments relatively much• People cost money and why h...
Sales DepartmentEvent Driven SOA and local cachingDesign Department Customer Department Finance Department Fabric Departme...
Scalability is cheaperSales DepartmentDesign Department Customer Department Finance Department Fabric Department
This is just the beginning
Have our mindset changed overthe last 40 years?
Paper work, file cabinets and manual workflowsInventory ShippingPurchaseManual workflow Manual workflow
Next step was automating paper forms(aka. The birth of CRUD)Inventory ShippingPurchaseManual workflow Manual workflow
Database integrationInventory ShippingPurchaseDatabaseIntegrationDatabaseIntegration
Enterprise Application Integration (EAI)Inventory ShippingPurchaseApplicationIntegrationApplicationIntegration
WebServices to the Rescue?SOA Web of MessInventoryPurchaseShippingPortal
ESB’s the the Rescue?SOA Web of Mess hidden by ESBInventoryPurchaseShippingPortalESB
ESB RealitySOA Web of Mess hidden by ESBInventoryPurchaseShippingPortalESB
I’ve got a cheaper solution
To be clear – none of the examplesrepresent in my opinion SOA4 tenets of SOA:• Boundaries are explicit• Services share sch...
What we’ve seen is just old EAIwine on new SOA bottles
Can’t we just avoid Services andmake one big application?
Retail DomainInvoicingSubdomainProductCatalogSubdomainShippingSubdomainSales (Order)SubdomainInventorySubdomainPricing
One Domain Model to Rule them All?Combining subdomains into one bigdomain model increases complexity aseverything tends to...
One big model to capture it ALL?….…..…..….…..…..….…..…..….…..…..
Result: Our queries get messy
ONE MODEL TO RULE THEM ALLONE MODEL TO FIND THEMONE MODEL TO BRING THEM ALLAND IN THE DARKNESS BIND THEM
The database determines our scalability
And databases often scale poorlyTo solve the performanceproblems for a few, youhave to upgrade it all
Do not design for locality and try todistributeDesign for distribution, take advantageof locality
Alternatively we can use Read replicasMaster Slave SlaveSlaveSlaveYou’re now eventually consistent
Or introduce caching…What’s your synchronization mechanism??
Many perspectives on dataCustomerRetail SystemPricingInventorySalesProductUnit PricePromotional PricePromotion End DateSto...
Smaller models & clear data ownershipSalesProductProductIDNameDescriptionQuantity Ordered…SalesInventoryProductProductIDSK...
Autonomy becomes the next(and biggest) problemCan you rely on others?
Data LayerService Orchestration issueData Access LayerService LayerInterface/DisplayLayerSystem CSystem BSystem AUIService...
Service autonomyService B Service CService ASystem XService ASystem YService B Service CSystem XSlow/unreliable networkDif...
Orchestration using synchronouscommunication and local transactionsSystem CSystem BSystem AUIService ServiceDAL DAL DALSch...
Solution for when going distributed?Can’t we just distributed transactions?(XA / 2 phase commit)
Distributed Transactions…. Oh mySales systemSaleDeliverysystem DeliveriesCustomer/CRM system CustomerSAP BookkeepingComple...
What’s wrong with distributed transactions?• Transactions lock resources while active• Services are autonomous– Can’t be e...
Orchestration using synchronouscommunication and without distributed transactionsSystem CSystem BSystem AUIService Service...
More of the same clearly can’t beThe answer…
The more autonomous services are, themore loosely coupled they are.Loose coupling is what drives businessagility – which i...
Loose couplingRequires good encapsulation andhigh cohesion
Return of the SILOS!!!!
We need SMALL SILOS thatSHARE very LITTLE with each otherSales Pricing InventoryShipping✕ ✕ ✕
A silo/bounded-context contains all parts related to itDB SchemaDomainServicesApplicationServicesDomainModelAggregates, En...
A silos parts are not limited to deploymentat a single locationSubdomainUserInterfaceIntegrationEndpoints(REST,SOAP,Pub/Su...
What should our silos share?BoundedContext
Degrees of couplingUIUIServiceServiceDataData EventsEvents
Composite UI’sRetail SystemSales Pricing InventoryWeb/ApplicationtierBackground servertierStorage tierComposite UIUI Layer...
Composite UI - exampleContext:BookISBN-10 0-321-12521-5
Composite UI - HTML#DIV – BookReviews#DIV – BookImage#DIV – BookTitleAndAuthor#DIV – BookPricing#DIV – BookAvailability#DI...
Composite UI
That covers data presentationWhat about transactions?
Next Step – Event Driven ArchitectureSalesProductSKUNamePriceQuantity Ordered…Inventory Service (SAP)ProductSKUQOHLocation...
Let’s make the implicit explicit!Old wisdom seems to have been forgotten. Let’s introduce:Domain EventsWhich:• Signal that...
Domain EventsEvents allows us to implement BusinessProcesses and quickly alter themThat gives us Business Agility
Introducing Choreographing ProcessesSales ServiceOrderAcceptedBilling ServiceShippingProcess ManagerShipping ServiceOnline...
Business EventsEvents also allows us to decentralize data in bestMaster Data Management (MDM) style wherenecessary data is...
MDM using EventsNote: This solution doesn’t apply theComposite UI due to the nature of theSystems being integrated
Sales DepartmentEvent Driven SOA and local cachingDesign Department Customer Department Finance Department Fabric Departme...
How to support an EDAfrom within a Bounded Context?
Typical One size fits all ”architecture”ClientRemote FacadeApplication ServiceData Access LayerData StorageDomainObjectDom...
THE Solution?
Same procedure as last year?Same procedure as every year!!!
Open to new ideas?Paul, you idiot, whats that!?You should only bring things wecan eat!
IT exists to support the business bysupport various usecasesUsecases can be categorized as either• ”User” intent to manipu...
CQSSeparation offunctions that write&functions that readFunctions that write are called Command methodsand must not return...
CQSUI Application Domain DataCommands – Change dataUI Application DataQueries – Ask for data (no side effects)
CQS from a code perspectivepublic class CustomerService{// Commandsvoid MakeCustomerPreferred(CustomerId)void ChangeCustom...
SO WHAT IS CQRS?CQRS is simply the creation of two objectswhere there was previously only oneGreg Young
CQRSIn its simplest formpublic class CustomerWriteService{// Commandsvoid MakeCustomerPreferred(CustomerId)void ChangeCust...
CommandsA Command’s primary goal is to capture USER INTENTA Command supports a single usecase and targets asingle Aggregat...
Thin Layers of complexityUI DataPro: Easy and simpleCon: Scales poorly for complex domainsLanguage ofthedatabase
Next step – more layersUI Application Domain DataPro: Handles complex domains better bySeparating usecase and domain logic...
Anemic Domain ModelThe Good parts• All Order logic is called in ONEclass• Lower entry level for juniordevelopersThe bad pa...
We need a rich domain modelAggregate with Order as Aggregate Root• Order forms our Unit of consistency, which controls our...
LET’S HAVE A LOOK AT A DIFFERENTTYPE OF ARCHITECTURE
Circular architectureTask basedUIDomainModelRead Model
1. RealizationCommands and Queriessupport very different usecases
A single model cannot beappropriate for reporting, searchingand transactional behaviorGreg Young, 2008
2. realizationQuery results contain only data – no logic• Give me the customer with his last 10 orders• Give me the custom...
Things to think about in relation toQueries• Why take the pain of performing JOINS and/orUNIONS of our nicely normalized R...
So how is this relevant in the real world?Let’s look at a real life scenario
Collaborative domains1. Read 2. Read4. Update3. Coffee time5. Stale data
We’re working with stale data
We’re always working with stale data!20 ms1 ms100 ms100 ms100 ms1 ms20 msAt this point our data is at least120 ms stale+Th...
LET’S USE STALE DATA TO OURADVANTAGE BY OFFLOADING THEDATABASE BY USING OUR READ MODELSUI Application Domain WritemodelCom...
ALL WE NEED IS A GOOD WAY TOSYNCHRONIZE OUR WRITE AND READMODELSUI Application Domain WritemodelCommands – Change dataUI A...
Let’s make the implicit explicit!The original DDD book left out a very important concept:Domain EventsWhich:• Signal that ...
Commands & Events• Commands mutate Aggregate state whichresults in one or more Events beingissued/published.Command Event(...
With Domain Events we now have amechanism to support our denormalizedView/Query models
Read modelRead modelCommands, Events and Query ModelsEventsUIDomain modelQuery model”AcceptOrder”command”OrderAccepted”eve...
Messaging ArchitecturesMost CQRS implementations see Commandsand Events as (asynchronous) Messagespublic class CreateCusto...
CQRS Building blocksClientCommandsCommandBusSendsCommandHandlersModifyRepositoriesRead WriteDatastoreEventBusCommand Servi...
LET’S TAKE IT A STEP FURTHER
Event SourcingAggregates track their own Domain Eventsand derive state from themOrderCreated ProductAdded ProductAdded Pro...
Full CQRSWith EventSourcingUI DomainEventStoreCommands – Change dataCommands EventsSQL DB Document DB Graph DBUI DataQueri...
public class CustomerCommandHandler {private Repository<Customer> customerRepository;public CustomerCommandHandler(Reposit...
Testing CQRS BDD style@Testpublic void a_signedup_customer_can_unsign() {UUID customerId = UUID.randomUuid().toString();Fi...
CQRS / BDD Report generated based on theprevious testScenario: A signed-up customer can unsignGiven a Customer with id ”ab...
SOA / IntegrationCommands, Queries and Events form naturalintegration interfacesSo integration is backed in from the begin...
What about Scalability?CAP Theorem• Consistency: All nodes in the cluster seeexactly the same data at any point in time• A...
CAP theoremSource: http://bit.ly/QUurnYStrong  Weak  Eventual ConsistencyACID systemsare hard andexpensive toscaleLatenc...
BASEBasically Available Soft-state Eventually consistentEventually Consistency levels:• Causal consistency: This involves ...
CQRS can give us BASE at thearchitectural level throughasynchronous Commands and EventsThis gives the business and IT cont...
Questions?@TigerTeamDK on TwitterEmail: jeppe@tigerteam.dkWeb: http://www.tigerteam.dk @jeppec on Twitter
What SOA do you have (with extended EDA and CQRS material)
Upcoming SlideShare
Loading in …5
×

What SOA do you have (with extended EDA and CQRS material)

10,091 views

Published on

Most companies today use SOA to integrate their systems or mobile applications, or do they?
Join me on a historical trip where we will see how integration has remained stuck in the same patterns and we will also take a look at the emperors new clothes (or SOA as it’s practiced today).
After this we will look at how to do SOA better and the principles that will make this transition possible (keywords: Event Driven Architecture, Domain Driven Design, Composite UI’s and CQRS).
Slides and Video here: http://www.tigerteam.dk/talks/IDDD-What-SOA-do-you-have-talk/

Published in: Technology
  • Be the first to comment

What SOA do you have (with extended EDA and CQRS material)

  1. 1. Jeppe CramonWhat SOA do you have?
  2. 2. Problems with SOA• Systems are more fragile• Development and Maintenance costs are higher• Your services are not being reused• You thought SOA would solve your integrationproblems, but they’ve gotten worse• No one wants to build or maintain services• System performance is worse
  3. 3. If you have arrived at the realizationthat SOA is a pain and costs toomuch without enabling businessagility or reducing your costs, youare not the only one.You will have to change yourapproach to achieve the benefits ofSOA
  4. 4. Let’s take a trip back in time
  5. 5. And look at how we could do business
  6. 6. Sales DepartmentOld style SOADesign Department Customer Department Finance Department Fabric DepartmentThe CustomerCreate Sales Order
  7. 7. This is slow
  8. 8. We are not selling enough!!
  9. 9. Sales DepartmentOld style SOA IIDesign Department Customer Department Finance Department Fabric DepartmentCreate Sales Order
  10. 10. We need to speed things up!Hackel walks between desks?Way too slow.
  11. 11. We need to speed things up!He needs to call So we make sure thathe canActually, call a lot!
  12. 12. We need to speed things up!But Hackel still have to wait Even if we get creative
  13. 13. We need to speed things up!Somethingneeds to bedone!!
  14. 14. Speed up even more!Lets get an automatic switchboard!
  15. 15. Speed up even more!New technology, sameproblemEven if we get creativeagain
  16. 16. Or do things AsyncSo Hackel can send requestto Ingeborg and Krestenwhich can respond toHackel when they’ve got ananswerBut even that doesn’tscale well, there’s still onlyone Ingeborg and Kresten
  17. 17. Speed up even more!So Kresten and Ingeborg adds more staff
  18. 18. Scalability is expensiveSales DepartmentDesign Department Customer Department Finance Department Fabric DepartmentCoordinator Hackel
  19. 19. Same problem different technologyDataStorageDataStorageDataStorageFinanceServiceDataServiceDesignServiceHackel CoordinatorServiceHackel CoordinatorServiceSales OrderServiceSales OrderServiceCustomer CustomerFabricServiceCustomerServiceDataStorageClientProcess Service layerActivity Service layerData Service layer
  20. 20. Resemble much?
  21. 21. Now back to the story…• Scaling up Sales requires scaling up otherdepartments relatively much• People cost money and why have 9 Financepeople for every 10 sales people just toanswer questions about pricing• There’s got to be a better way to handle this• And there is 
  22. 22. Sales DepartmentEvent Driven SOA and local cachingDesign Department Customer Department Finance Department Fabric DepartmentThe CustomerCreate Sales Order
  23. 23. Scalability is cheaperSales DepartmentDesign Department Customer Department Finance Department Fabric Department
  24. 24. This is just the beginning
  25. 25. Have our mindset changed overthe last 40 years?
  26. 26. Paper work, file cabinets and manual workflowsInventory ShippingPurchaseManual workflow Manual workflow
  27. 27. Next step was automating paper forms(aka. The birth of CRUD)Inventory ShippingPurchaseManual workflow Manual workflow
  28. 28. Database integrationInventory ShippingPurchaseDatabaseIntegrationDatabaseIntegration
  29. 29. Enterprise Application Integration (EAI)Inventory ShippingPurchaseApplicationIntegrationApplicationIntegration
  30. 30. WebServices to the Rescue?SOA Web of MessInventoryPurchaseShippingPortal
  31. 31. ESB’s the the Rescue?SOA Web of Mess hidden by ESBInventoryPurchaseShippingPortalESB
  32. 32. ESB RealitySOA Web of Mess hidden by ESBInventoryPurchaseShippingPortalESB
  33. 33. I’ve got a cheaper solution
  34. 34. To be clear – none of the examplesrepresent in my opinion SOA4 tenets of SOA:• Boundaries are explicit• Services share schema and contract, not class• Service compatibility is based on policy• Services are autonomous
  35. 35. What we’ve seen is just old EAIwine on new SOA bottles
  36. 36. Can’t we just avoid Services andmake one big application?
  37. 37. Retail DomainInvoicingSubdomainProductCatalogSubdomainShippingSubdomainSales (Order)SubdomainInventorySubdomainPricing
  38. 38. One Domain Model to Rule them All?Combining subdomains into one bigdomain model increases complexity aseverything tends to be connected toand depend on everything else
  39. 39. One big model to capture it ALL?….…..…..….…..…..….…..…..….…..…..
  40. 40. Result: Our queries get messy
  41. 41. ONE MODEL TO RULE THEM ALLONE MODEL TO FIND THEMONE MODEL TO BRING THEM ALLAND IN THE DARKNESS BIND THEM
  42. 42. The database determines our scalability
  43. 43. And databases often scale poorlyTo solve the performanceproblems for a few, youhave to upgrade it all
  44. 44. Do not design for locality and try todistributeDesign for distribution, take advantageof locality
  45. 45. Alternatively we can use Read replicasMaster Slave SlaveSlaveSlaveYou’re now eventually consistent
  46. 46. Or introduce caching…What’s your synchronization mechanism??
  47. 47. Many perspectives on dataCustomerRetail SystemPricingInventorySalesProductUnit PricePromotional PricePromotion End DateStock Keeping Unit (SKU)Quantity On Hand (QOH)Location CodePriceQuantity OrderedNameThe lifecycle for Data is VERY important!Forecasting?
  48. 48. Smaller models & clear data ownershipSalesProductProductIDNameDescriptionQuantity Ordered…SalesInventoryProductProductIDSKUQOHLocation Code… InventoryPricingProductProductIDUnit PricePromotional Price…PricingDDD:BoundedContextSOA:ServiceRetail SystemShared Entity identity
  49. 49. Autonomy becomes the next(and biggest) problemCan you rely on others?
  50. 50. Data LayerService Orchestration issueData Access LayerService LayerInterface/DisplayLayerSystem CSystem BSystem AUIService ServiceDAL DAL DALSchema Schema SchemaLocal transactionspanning allmodulesService
  51. 51. Service autonomyService B Service CService ASystem XService ASystem YService B Service CSystem XSlow/unreliable networkDifferent SLASlow system
  52. 52. Orchestration using synchronouscommunication and local transactionsSystem CSystem BSystem AUIService ServiceDAL DAL DALSchema Schema SchemaB:Service()call C:Service()call B:DAL()call A:Service()commit()Service
  53. 53. Solution for when going distributed?Can’t we just distributed transactions?(XA / 2 phase commit)
  54. 54. Distributed Transactions…. Oh mySales systemSaleDeliverysystem DeliveriesCustomer/CRM system CustomerSAP BookkeepingCompletePurchaseTransactionCoordinatorTransactionalResourcePreparePhaseCommitPhase2 Phase Commit
  55. 55. What’s wrong with distributed transactions?• Transactions lock resources while active• Services are autonomous– Can’t be expected to finish within a certain timeinterval• Locking keeps other transactions fromcompleting their job• Locking doesn’t scale• X Phase Commit is fragile by design
  56. 56. Orchestration using synchronouscommunication and without distributed transactionsSystem CSystem BSystem AUIService ServiceDAL DAL DALSchema Schema SchemaServiceB:Service()call C:Service()call B:DAL()call A:Service()if (A:Call-Failed?)call A:Service()if (A:Call-Failed?)Wait-A-While()call A:Service()if (A:Call-Failed-Due-To-IO?)Save-We-Need-Check-If-Call-A-Succeded-After-AllAND We-Need-To-Retry call C:Service and call B:DALAND Tell-Customer-That-This-Operation-Perhaps-Went-Wellif (A:Call-Went-Well)commit()
  57. 57. More of the same clearly can’t beThe answer…
  58. 58. The more autonomous services are, themore loosely coupled they are.Loose coupling is what drives businessagility – which is why we wanted SOA in thefirst place
  59. 59. Loose couplingRequires good encapsulation andhigh cohesion
  60. 60. Return of the SILOS!!!!
  61. 61. We need SMALL SILOS thatSHARE very LITTLE with each otherSales Pricing InventoryShipping✕ ✕ ✕
  62. 62. A silo/bounded-context contains all parts related to itDB SchemaDomainServicesApplicationServicesDomainModelAggregates, Entities,ValueObjects,EventsIntegrationEndpoints(REST,SOAP,Pub/Sub)UserInterfaceSilo
  63. 63. A silos parts are not limited to deploymentat a single locationSubdomainUserInterfaceIntegrationEndpoints(REST,SOAP,Pub/Sub)DomainServicesApplicationServicesAggregates,Entities, ValueObjects, EventsDBSchemaUnits of individual deployment
  64. 64. What should our silos share?BoundedContext
  65. 65. Degrees of couplingUIUIServiceServiceDataData EventsEvents
  66. 66. Composite UI’sRetail SystemSales Pricing InventoryWeb/ApplicationtierBackground servertierStorage tierComposite UIUI LayeredApplicationData Access LayerReadmodelWritemodel✕ ✕
  67. 67. Composite UI - exampleContext:BookISBN-10 0-321-12521-5
  68. 68. Composite UI - HTML#DIV – BookReviews#DIV – BookImage#DIV – BookTitleAndAuthor#DIV – BookPricing#DIV – BookAvailability#DIV - Header#DIV - Body
  69. 69. Composite UI
  70. 70. That covers data presentationWhat about transactions?
  71. 71. Next Step – Event Driven ArchitectureSalesProductSKUNamePriceQuantity Ordered…Inventory Service (SAP)ProductSKUQOHLocation Code…Pricing ServiceProductSKUUnit PricePromotional Price…InventoryPricingSalesCustomersOrderAcceptedEventMessageBusWhocoordinates thesales process?Online Ordering SystemWeb Shop(Composite UI)Sales UI
  72. 72. Let’s make the implicit explicit!Old wisdom seems to have been forgotten. Let’s introduce:Domain EventsWhich:• Signal that something has happened• Closely aligned to the Domain Model• Are handled by a messaging system• They are in the past tense:– CustomerBilled– ParcelShipped– CustomerCreated– ReviewCreated– CommentAdded– CommentDeleted
  73. 73. Domain EventsEvents allows us to implement BusinessProcesses and quickly alter themThat gives us Business Agility
  74. 74. Introducing Choreographing ProcessesSales ServiceOrderAcceptedBilling ServiceShippingProcess ManagerShipping ServiceOnline Ordering SystemMessageBusOrderAcceptedOrderAcceptedCustomerBilledCustomerBilledOrderReady forShippingOrderReady forShipping
  75. 75. Business EventsEvents also allows us to decentralize data in bestMaster Data Management (MDM) style wherenecessary data is cached locally in other servicesto breakLike in the Matador example
  76. 76. MDM using EventsNote: This solution doesn’t apply theComposite UI due to the nature of theSystems being integrated
  77. 77. Sales DepartmentEvent Driven SOA and local cachingDesign Department Customer Department Finance Department Fabric DepartmentThe CustomerCreate Sales Order
  78. 78. How to support an EDAfrom within a Bounded Context?
  79. 79. Typical One size fits all ”architecture”ClientRemote FacadeApplication ServiceData Access LayerData StorageDomainObjectDomainObjectDTO DTO
  80. 80. THE Solution?
  81. 81. Same procedure as last year?Same procedure as every year!!!
  82. 82. Open to new ideas?Paul, you idiot, whats that!?You should only bring things wecan eat!
  83. 83. IT exists to support the business bysupport various usecasesUsecases can be categorized as either• ”User” intent to manipulate information• ”User” intent to find and read informationWe already support this in OO at a Property level:• Setter (or mutator) methods Manipulate data• Getter (or accessor) methods Read dataLet’s raise it to a higher Level
  84. 84. CQSSeparation offunctions that write&functions that readFunctions that write are called Command methodsand must not return a valueFunctions that read are called Query methods andmust have no side effects
  85. 85. CQSUI Application Domain DataCommands – Change dataUI Application DataQueries – Ask for data (no side effects)
  86. 86. CQS from a code perspectivepublic class CustomerService{// Commandsvoid MakeCustomerPreferred(CustomerId)void ChangeCustomerLocale(CustomerId, NewLocale)void CreateCustomer(Customer)void EditCustomerDetails(CustomerDetails)// QueriesCustomer GetCustomer(CustomerId)CustomerSet GetCustomersWithName(Name)CustomerSet GetPreferredCustomers()}From: https://gist.github.com/1964094
  87. 87. SO WHAT IS CQRS?CQRS is simply the creation of two objectswhere there was previously only oneGreg Young
  88. 88. CQRSIn its simplest formpublic class CustomerWriteService{// Commandsvoid MakeCustomerPreferred(CustomerId)void ChangeCustomerLocale(CustomerId, NewLocale)void CreateCustomer(CreateCustomer)void EditCustomerDetails(CustomerDetails)}public class CustomerReadService{// QueriesCustomer GetCustomer(CustomerId)CustomerSet GetCustomersWithName(Name)CustomerSet GetPreferredCustomers()}From: https://gist.github.com/1964094
  89. 89. CommandsA Command’s primary goal is to capture USER INTENTA Command supports a single usecase and targets asingle AggregateCommands are stated in the imperative:– DoStuff– CreateCustomer– ShipOrder– AddComment– DeleteComment
  90. 90. Thin Layers of complexityUI DataPro: Easy and simpleCon: Scales poorly for complex domainsLanguage ofthedatabase
  91. 91. Next step – more layersUI Application Domain DataPro: Handles complex domains better bySeparating usecase and domain logicCon: Increasing complexity. Risk of AnemicDomain model combined withtransaction-script.TimeComplexityLanguage ofDTO’sLanguage ofgetters andsettersLanguage ofORM magic
  92. 92. Anemic Domain ModelThe Good parts• All Order logic is called in ONEclass• Lower entry level for juniordevelopersThe bad parts• Hard to test• Hard to maintain• Code dupliction• An exposed domain model is likewalking around without clothes –everyone can access your privateparts and violate your invariants
  93. 93. We need a rich domain modelAggregate with Order as Aggregate Root• Order forms our Unit of consistency, which controls our invariants• Order and OrderLines are created, updated and deleted together
  94. 94. LET’S HAVE A LOOK AT A DIFFERENTTYPE OF ARCHITECTURE
  95. 95. Circular architectureTask basedUIDomainModelRead Model
  96. 96. 1. RealizationCommands and Queriessupport very different usecases
  97. 97. A single model cannot beappropriate for reporting, searchingand transactional behaviorGreg Young, 2008
  98. 98. 2. realizationQuery results contain only data – no logic• Give me the customer with his last 10 orders• Give me the customer with total sum of ordersfor the last year• Give me the complete order• Give me the shipping status for the order• Give me the customers last reviewSo why go through the domain layer?UI Application Data
  99. 99. Things to think about in relation toQueries• Why take the pain of performing JOINS and/orUNIONS of our nicely normalized RelationalModel?• Why not having a completely denormalized datamodel (or View) to support our Query?• When we completely denormalize our data, dowe really need a relational database or could weuse a Key/Value- or Document Store?• Do we really need our Read Data to be to themicrosecond consistent with our Write data?
  100. 100. So how is this relevant in the real world?Let’s look at a real life scenario
  101. 101. Collaborative domains1. Read 2. Read4. Update3. Coffee time5. Stale data
  102. 102. We’re working with stale data
  103. 103. We’re always working with stale data!20 ms1 ms100 ms100 ms100 ms1 ms20 msAt this point our data is at least120 ms stale+Thinking time+ thinking time (1000-1500 ms)
  104. 104. LET’S USE STALE DATA TO OURADVANTAGE BY OFFLOADING THEDATABASE BY USING OUR READ MODELSUI Application Domain WritemodelCommands – Change dataUI Application ReadmodelsQueries – Ask for data (no side effects)
  105. 105. ALL WE NEED IS A GOOD WAY TOSYNCHRONIZE OUR WRITE AND READMODELSUI Application Domain WritemodelCommands – Change dataUI Application ReadmodelsQueries – Ask for data (no side effects)
  106. 106. Let’s make the implicit explicit!The original DDD book left out a very important concept:Domain EventsWhich:• Signal that something has happened• Closely aligned to the Domain Model• Are handled by a messaging system• They are in the past tense:– CustomerBilled– ParcelShipped– CustomerCreated– ReviewCreated– CommentAdded– CommentDeleted
  107. 107. Commands & Events• Commands mutate Aggregate state whichresults in one or more Events beingissued/published.Command Event(s)AcceptOrder OrderAcceptedShipOrder OrderShippedAddComment CommentAddedQuarantineReview ReviewQuarantinedUnquarantineReview ReviewUnquarantined
  108. 108. With Domain Events we now have amechanism to support our denormalizedView/Query models
  109. 109. Read modelRead modelCommands, Events and Query ModelsEventsUIDomain modelQuery model”AcceptOrder”command”OrderAccepted”event”Find allAccepted Orders”QueryCommands are Imperative: DoStuffEvents are Past tense: StuffDone
  110. 110. Messaging ArchitecturesMost CQRS implementations see Commandsand Events as (asynchronous) Messagespublic class CreateCustomer{public final Guid CustomerId;public final Name CustomerName;…}public class CustomerCreated{public final Guid CustomerId;public final DateTime CreationDateTime;public final Name CustomerName;}CommandEventDifference:INTENT
  111. 111. CQRS Building blocksClientCommandsCommandBusSendsCommandHandlersModifyRepositoriesRead WriteDatastoreEventBusCommand ServicesEvent HandlersEventsRead storeQuery HandlersQuery ResultsQueriesQuery ServicesEventsDomain
  112. 112. LET’S TAKE IT A STEP FURTHER
  113. 113. Event SourcingAggregates track their own Domain Eventsand derive state from themOrderCreated ProductAdded ProductAdded ProductRemoved ProductAdded OrderAcceptedTime07:39Time07:40Time07:41Time07:45Time07:46Time07:50
  114. 114. Full CQRSWith EventSourcingUI DomainEventStoreCommands – Change dataCommands EventsSQL DB Document DB Graph DBUI DataQueries – Ask for dataEventsQuery BuildOur singlesource of truth
  115. 115. public class CustomerCommandHandler {private Repository<Customer> customerRepository;public CustomerCommandHandler(Repository<Customer> customerRepository) {this.customerRepository = customerRepository;}@CommandHandlerpublic void handle(UnsignCustomer cmd) {Customer customer = repository.load(cmd.getCustomerId());customer.unsign();}}public class Customer {private boolean signedUp;public void unsign() {if (signedUp) {apply(new CustomerUnsignedEvent());}}@EventHandlerprivate void handle(CustomerUnsignedEvent event) {signedUp = false;}}
  116. 116. Testing CQRS BDD style@Testpublic void a_signedup_customer_can_unsign() {UUID customerId = UUID.randomUuid().toString();FixtureConfiguration fixture = Fixtures.newGivenWhenThenFixture();fixture.registerAnnotatedCommandHandler(new CustomerCommandHandler(fixture.createGenericRepository(Customer.class)));fixture.setAggregateIdentifier(customerId);fixture.given(TestFactory.customerCreatedEvent(customerId),TestFactory.customerSignedUpEvent(customerId)).when(TestFactory.unsignCustomerCommand(customerId)).expectEvents(TestFactory.customerUnsignedEvent(customerId));}
  117. 117. CQRS / BDD Report generated based on theprevious testScenario: A signed-up customer can unsignGiven a Customer with id ”abc1234” thathas been created and a customer with id”abc1234” that is signed-upWhen a request for Customer with id”abcd1234” to be unsigned is receivedThen the Customer with id ”abcd1234” isunsigned
  118. 118. SOA / IntegrationCommands, Queries and Events form naturalintegration interfacesSo integration is backed in from the beginning!
  119. 119. What about Scalability?CAP Theorem• Consistency: All nodes in the cluster seeexactly the same data at any point in time• Availability: Failure of a node does not renderthe entire system inoperative• Partition tolerance: Nodes can still functionwhen communication with other groups ofnodes is lostYou can’t have all three!
  120. 120. CAP theoremSource: http://bit.ly/QUurnYStrong  Weak  Eventual ConsistencyACID systemsare hard andexpensive toscaleLatencyconcernsUnless you usePessimisticLocking – alldata is stale(and eventualconsistentwhen deliveredto the user)
  121. 121. BASEBasically Available Soft-state Eventually consistentEventually Consistency levels:• Causal consistency: This involves a signal being sentfrom between application session indicating that achange has occurred. From that point on the receivingsession will always see the updated value.• Read your own writes: In this mode of consistency, asession that performs a change to the database willimmediately see that change, even if other sessionsexperience a delay.• Monotonic consistency: In this mode, A session willnever see data revert to an earlier point in time. Oncewe read a value, we will never see an earlier value.See http://www.allthingsdistributed.com/2008/12/eventually_consistent.html for more
  122. 122. CQRS can give us BASE at thearchitectural level throughasynchronous Commands and EventsThis gives the business and IT control overwhere to spend money to scaleour solution - instead of trying to buy abigger database server.
  123. 123. Questions?@TigerTeamDK on TwitterEmail: jeppe@tigerteam.dkWeb: http://www.tigerteam.dk @jeppec on Twitter

×