SlideShare a Scribd company logo
1 of 34
Download to read offline
CQRS
Layered architecture
User Interface
Service layer
Data access layer
Domainmodel
Simple beginnings (agile)
Product
Customer
More and more entities: Complexity!
Product
Customer
Order
And a couple of iterations later...
OrderItem
Customer
Order
Product
Invoice
….
….
….
….
...
….
And after some more iterations...
OrderItem
Customer
Order
Product
Invoice
….
….
….
….
...
….
….
….
….
….
….
….
….
….
….
….
….
….
Complex data layer: Queries!
SELECT *
FROM ….
WHERE id IN (
SELECT id FROM product
INNER JOIN invoice …
INNER JOIN orderitem ...
INNER JOIN order
INNER JOIN …
INNER JOIN …
WHERE order.customerId = ?
AND …
AND …
) AND … IN (
SELECT id FROM product
INNER JOIN invoice …
INNER JOIN orderitem ...
WHERE …
) AND … IN (
SELECT id FROM product
INNER JOIN invoice …
INNER JOIN orderitem ...
WHERE …
)
…...
Complex service layer: Service dependencies!
class OrderService {
@Autowired
private ProductService productService;
@Autowired
private PaymentService paymentService;
@Autowired
private OrderItemService orderItemService;
@Autowired
private InvoiceService invoiceSerivce;
@Autowired
private SomeService someService;
@Autowired
private SomeService2 someService2;
…..
Anemic domain model
public class OrderLine {
private int quantity;
private BigDecimal price;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
Result
Data inconsistency!
● Domain constraints not enforced by all services
● Multiple concurrent transactions over huge relational data model lead to inconsistencies
Domain Driven Design - Eric Evans
Concrete example: Purchase order
Domain Driven Design:
It is difficult to guarantee the consistency of changes to objects in a model with
complex associations. Invariants need to be maintained that apply to closely
related groups of objects, not just discrete objects.
[Domain Driven Design - Eric Evans]
Solution: Aggregates
Aggregate
• The root ENTITY is ultimately responsible for checking invariants.
• Nothing outside the AGGREGATE boundary can hold a reference to anything inside, except to the
root ENTITY. The root ENTITY can hand references to the internal ENTITIES to other objects, but
those objects can use them only transiently, and they may not hold on to the reference.
• As a corollary to the previous rule, only AGGREGATE roots can be obtained directly with database
queries. All other objects must be found by traversal of associations.
• A delete operation must remove everything within the AGGREGATE boundary at once.
• When a change to any object within the AGGREGATE boundary is committed, all invariants of the
whole AGGREGATE must be satisfied.
[Domain driven design - Eric Evans]
Aggregate pitfalls
Don’t make your aggregates too big
● Remember editing an aggregate requires checking all business invariants which requires to
load all state of the aggregate.
● This results in huge transactions and memory usage
● Large aggregates means more chance that users interfere by editing parts of the same
aggregate
○ which should result in either an optimistic lock exception or in case of pessimistic locks
not being able to edit an aggregate.
Aggregate advantages
An aggregate is a small collection of entities that are kept consistent by invariant checking
● The aggregate can only check it invariants on its own internal state
● With (unit) tests you can easily prove that your aggregates stay consistent, because you don’t
need the state of any other part of the system
● Using small aggregates reduces the complexity of your application
○ Testing is simpler
○ Fewer moving state when processing an update
Long running business transactions across multiple
aggregates: Webshop
● A customer can only order a product if there is still stock in the inventory
● An order can only succeed if the customer has paid the order amount
Webshop
Product
product
amountInStock
productPrice
Order
(AggregateRoot)
orderLines
orderAmount
payment
OrderLine
product
amount
productPrice
Payment
amount
isPaid
Solution: Separate aggregates using eventual
consistency
Product
(AggregateRoot)
productId
amountInStock
productPrice
Payment
(AggregateRoot)
amount
isPaid
OrderManager
(AggregateRoot)
1. Order request
1.1 Reserve
Stock
1.1 Initiate
payment 2. Payment
Successful
3. Payment
failed
2.1 Order
fulfilled
3.1 Unreserve
stock
Invariants across multiple aggregates
Any rule that spans AGGREGATES will not be expected to be up-to-date at all times.
Through event processing, batch processing, or other update mechanisms, other
dependencies can be resolved within some specific time. [Domain Driven Design]
Introduction: CQRS
Example: CQRS shopping basket
Command Model
Shopping Basket
Command:
Add product to basket
Event:
Product added
CustomerViewShoppingBasket MarketingProductsAddedView
Query:
ShowCustomerShoppingBasket
Query:
ShowProductsAddedOverAllCustomers
Advantages CQRS
● We model business actions (commands) and important business events (event)
○ The intent of a business transactions is better captured in commands than in just crud
operations on a database
● Separate read model allows for scaling reads independently
● We can observe a business interaction from the outside (by observing the events) without
knowing the inner details of the aggregate (state and business invariants)
Eventually consistent webshop
Product
(AggregateRoot)
productId
amountInStock
productPrice
Payment
(AggregateRoot)
amount
isPaid
OrderManager
(AggregateRoot)
1. Order
requested
1.1 Reserve
Stock
1.1 Create
payment 2.Payment
successful
3. Cancel
payment
2.1 Order
Fulfilled3.1 Undo stock
reservation
Payment
(AggregateRoot)
amount
isPaid
OrderManager
(AggregateRoot)
reserveredStock
paymentReceived
1 Create
payment 2. Payment
successful
3. Payment
failed
Deposit
Deposit
Further reading
● Domain Driven Design - Eric Evans
● Domain Driven Design Distilled - Vaughn Vernon
● Implementing Domain Driven Design - Vaughn Vernon
Hands on!
Notes
● Command, events prevent distributed monolith
● Aggregates have nice boundaries for spreading across microservices

More Related Content

Similar to Workshop CQRS and DDD

MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB
 
Super market billing system using webcam
Super market billing system using webcam Super market billing system using webcam
Super market billing system using webcam SahithBeats
 
26 story slicing techniques for any scrum team
26 story slicing techniques for any scrum team26 story slicing techniques for any scrum team
26 story slicing techniques for any scrum teamagilebin
 
Project Management Practical 01 - 04 (Mumbai University)
Project Management Practical 01 - 04 (Mumbai University)Project Management Practical 01 - 04 (Mumbai University)
Project Management Practical 01 - 04 (Mumbai University)Satyendra Singh
 
Pragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecturePragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecturePiotr Pelczar
 
Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...
Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...
Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...Bernd Zuther
 
Object oriented design patterns for distributed systems
Object oriented design patterns for distributed systemsObject oriented design patterns for distributed systems
Object oriented design patterns for distributed systemsJordan McBain
 
Blazor, lo sapevi che...
Blazor, lo sapevi che...Blazor, lo sapevi che...
Blazor, lo sapevi che...Andrea Dottor
 
Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...
Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...
Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...Nagios
 
[WSO2Con USA 2018] Patterns for Building Streaming Apps
[WSO2Con USA 2018] Patterns for Building Streaming Apps[WSO2Con USA 2018] Patterns for Building Streaming Apps
[WSO2Con USA 2018] Patterns for Building Streaming AppsWSO2
 
Kks sre book_ch10
Kks sre book_ch10Kks sre book_ch10
Kks sre book_ch10Chris Huang
 
Software archiecture lecture08
Software archiecture   lecture08Software archiecture   lecture08
Software archiecture lecture08Luktalja
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIsPetter Holmström
 
Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...
Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...
Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...Mumbai B.Sc.IT Study
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in indiaEdhole.com
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019Dave Stokes
 

Similar to Workshop CQRS and DDD (20)

Microservices patterns
Microservices patternsMicroservices patterns
Microservices patterns
 
our srs (1).pdf
our srs (1).pdfour srs (1).pdf
our srs (1).pdf
 
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
 
Super market billing system using webcam
Super market billing system using webcam Super market billing system using webcam
Super market billing system using webcam
 
Onlineshopping
OnlineshoppingOnlineshopping
Onlineshopping
 
26 story slicing techniques for any scrum team
26 story slicing techniques for any scrum team26 story slicing techniques for any scrum team
26 story slicing techniques for any scrum team
 
Project Management Practical 01 - 04 (Mumbai University)
Project Management Practical 01 - 04 (Mumbai University)Project Management Practical 01 - 04 (Mumbai University)
Project Management Practical 01 - 04 (Mumbai University)
 
Pragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecturePragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecture
 
Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...
Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...
Javaland 2015 - Bernd Zuther - Die Jagd nach mehr Konversion - Fluch oder Seg...
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Object oriented design patterns for distributed systems
Object oriented design patterns for distributed systemsObject oriented design patterns for distributed systems
Object oriented design patterns for distributed systems
 
Blazor, lo sapevi che...
Blazor, lo sapevi che...Blazor, lo sapevi che...
Blazor, lo sapevi che...
 
Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...
Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...
Bryan Heden - Agile Networks - Using Nagios XI as the platform for Monitoring...
 
[WSO2Con USA 2018] Patterns for Building Streaming Apps
[WSO2Con USA 2018] Patterns for Building Streaming Apps[WSO2Con USA 2018] Patterns for Building Streaming Apps
[WSO2Con USA 2018] Patterns for Building Streaming Apps
 
Kks sre book_ch10
Kks sre book_ch10Kks sre book_ch10
Kks sre book_ch10
 
Software archiecture lecture08
Software archiecture   lecture08Software archiecture   lecture08
Software archiecture lecture08
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIs
 
Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...
Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...
Project Management (Practical Qustion Paper) [CBSGS - 75:25 Pattern] {2013-20...
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
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
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
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
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
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...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
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...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 

Workshop CQRS and DDD

  • 2. Layered architecture User Interface Service layer Data access layer Domainmodel
  • 4. More and more entities: Complexity! Product Customer Order
  • 5. And a couple of iterations later... OrderItem Customer Order Product Invoice …. …. …. …. ... ….
  • 6. And after some more iterations... OrderItem Customer Order Product Invoice …. …. …. …. ... …. …. …. …. …. …. …. …. …. …. …. …. ….
  • 7. Complex data layer: Queries! SELECT * FROM …. WHERE id IN ( SELECT id FROM product INNER JOIN invoice … INNER JOIN orderitem ... INNER JOIN order INNER JOIN … INNER JOIN … WHERE order.customerId = ? AND … AND … ) AND … IN ( SELECT id FROM product INNER JOIN invoice … INNER JOIN orderitem ... WHERE … ) AND … IN ( SELECT id FROM product INNER JOIN invoice … INNER JOIN orderitem ... WHERE … ) …...
  • 8.
  • 9. Complex service layer: Service dependencies! class OrderService { @Autowired private ProductService productService; @Autowired private PaymentService paymentService; @Autowired private OrderItemService orderItemService; @Autowired private InvoiceService invoiceSerivce; @Autowired private SomeService someService; @Autowired private SomeService2 someService2; …..
  • 10.
  • 11.
  • 12. Anemic domain model public class OrderLine { private int quantity; private BigDecimal price; public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
  • 13. Result Data inconsistency! ● Domain constraints not enforced by all services ● Multiple concurrent transactions over huge relational data model lead to inconsistencies
  • 14.
  • 15. Domain Driven Design - Eric Evans
  • 17. Domain Driven Design: It is difficult to guarantee the consistency of changes to objects in a model with complex associations. Invariants need to be maintained that apply to closely related groups of objects, not just discrete objects. [Domain Driven Design - Eric Evans]
  • 19.
  • 20. Aggregate • The root ENTITY is ultimately responsible for checking invariants. • Nothing outside the AGGREGATE boundary can hold a reference to anything inside, except to the root ENTITY. The root ENTITY can hand references to the internal ENTITIES to other objects, but those objects can use them only transiently, and they may not hold on to the reference. • As a corollary to the previous rule, only AGGREGATE roots can be obtained directly with database queries. All other objects must be found by traversal of associations. • A delete operation must remove everything within the AGGREGATE boundary at once. • When a change to any object within the AGGREGATE boundary is committed, all invariants of the whole AGGREGATE must be satisfied. [Domain driven design - Eric Evans]
  • 21. Aggregate pitfalls Don’t make your aggregates too big ● Remember editing an aggregate requires checking all business invariants which requires to load all state of the aggregate. ● This results in huge transactions and memory usage ● Large aggregates means more chance that users interfere by editing parts of the same aggregate ○ which should result in either an optimistic lock exception or in case of pessimistic locks not being able to edit an aggregate.
  • 22. Aggregate advantages An aggregate is a small collection of entities that are kept consistent by invariant checking ● The aggregate can only check it invariants on its own internal state ● With (unit) tests you can easily prove that your aggregates stay consistent, because you don’t need the state of any other part of the system ● Using small aggregates reduces the complexity of your application ○ Testing is simpler ○ Fewer moving state when processing an update
  • 23. Long running business transactions across multiple aggregates: Webshop ● A customer can only order a product if there is still stock in the inventory ● An order can only succeed if the customer has paid the order amount
  • 25. Solution: Separate aggregates using eventual consistency Product (AggregateRoot) productId amountInStock productPrice Payment (AggregateRoot) amount isPaid OrderManager (AggregateRoot) 1. Order request 1.1 Reserve Stock 1.1 Initiate payment 2. Payment Successful 3. Payment failed 2.1 Order fulfilled 3.1 Unreserve stock
  • 26. Invariants across multiple aggregates Any rule that spans AGGREGATES will not be expected to be up-to-date at all times. Through event processing, batch processing, or other update mechanisms, other dependencies can be resolved within some specific time. [Domain Driven Design]
  • 28. Example: CQRS shopping basket Command Model Shopping Basket Command: Add product to basket Event: Product added CustomerViewShoppingBasket MarketingProductsAddedView Query: ShowCustomerShoppingBasket Query: ShowProductsAddedOverAllCustomers
  • 29. Advantages CQRS ● We model business actions (commands) and important business events (event) ○ The intent of a business transactions is better captured in commands than in just crud operations on a database ● Separate read model allows for scaling reads independently ● We can observe a business interaction from the outside (by observing the events) without knowing the inner details of the aggregate (state and business invariants)
  • 30. Eventually consistent webshop Product (AggregateRoot) productId amountInStock productPrice Payment (AggregateRoot) amount isPaid OrderManager (AggregateRoot) 1. Order requested 1.1 Reserve Stock 1.1 Create payment 2.Payment successful 3. Cancel payment 2.1 Order Fulfilled3.1 Undo stock reservation
  • 32. Further reading ● Domain Driven Design - Eric Evans ● Domain Driven Design Distilled - Vaughn Vernon ● Implementing Domain Driven Design - Vaughn Vernon
  • 34. Notes ● Command, events prevent distributed monolith ● Aggregates have nice boundaries for spreading across microservices