SlideShare a Scribd company logo
Simplify Complex Query with
CQRS
- Jacky Lai
Optimization is about Resource Trade-off
• The performance of an application is based on
• Memory Resource
• Computing Resource
• Network Resource
• Developer Resource
• Disk space Resource
• Disk space resource is relatively the cheapest resource compared to
others.
Example Requirement: Find Shipping
Methods
• During checkout process, user will be presented a list of shipping
methods to choose from, based on the product and shipping address.
• shippingMethods = findShippingMethodsBy(product,
shippingAddress);
Example Requirement: Request Payload
Request Json Payload:
{
"productId": ”aabbcc",
"address": ”123 Freedom Cir., Santa Clara, CA 95123"
}
Common Strategy: Back-end Processing
• Upon receiving request payload:
// step 1: construct hierarchical object graph, an expensive operation.
product = productRepository.findBy(productId);
shippingAddress = new Address(address);
// step 2: find shipping methods.
shippingMethods = findShippingMethodsBy(product, shippingAddress);
Common Strategy: ER Diagram
product
warehouse
product_type
shipping_method
n
1
nn
n
n
• restricted? giftCard?
• address
• size – LARGE? SMALL?
• delivery period
Common Strategy - Modeling
• Model with Hierarchical Data object, e.g.
• Product
• size (LARGE, SMALL)
• type (GIFT_CARD, RESTRICTED)
• warehouses
• address
• shipping methods
• Shipping Address
Issue #1: Network Traffic Increment.
• For each request, application layer has to fetch huge amount of data across network from
database, and process the data at Application layer.
Question:
Which is the best layer to filter data?
Issue #2:
Read Speed or Write Speed, Pick One.
• We cannot optimize both Read and Write speed at the same time.
• Without adding index,
• time complexity for read = O(n)
• After adding index,
• time complexity for read = O(log n)
Issue #2:
Read Speed or Write Speed, Pick One. – Cont.
• Performance Summary from “The Performance Impact of Adding
MySQL Indexes”
• http://logicalread.solarwinds.com/impact-of-adding-mysql-indexes-
mc12/#.VmkYP51Viko
• For a table with 553875 rows.
Before Adding Indexes After Adding Indexes
Insert Operation (sec) 7.14 24.77 (3x)
Data (mb) 33.56 33.56
Index (mb) 13.52 95.70 (7x)
Total = Data + Index (mb) 47.08 129.27
Issue #2:
Read Speed or Write Speed, Pick One. – Cont.
• What if we use Cache to reduce DB read?
• Cache is a Key-Value DB.
• Let’s say it takes 32 DB calls to build a complex object graph:
• Best case: 32 cache hits.
• Worst case: 32 cache misses + 32 DB calls.
• Network IO delays is unavoidable.
• There is another challenge: Cache Consistency.
There are only two hard
things in Computer Science:
cache invalidation and
naming things.
-- Phil Karlton
Issue #2:
Read Speed or Write Speed, Pick One. – Cont.
We need to maintain consistency for both normalized DB and denormalized DB, and this is tricky.
Overall Consistency = Consistency (Normalized) && Consistency (Denormalized)
Issue #3:
“Join” logic has to be at both sides (W, R)
product
warehouse
product_typemanufacture
product
warehouse
product_typemanufacturer
join join
wrong join
join
WRITE
Wrong READ
Database
Database
CQRS Comes to Rescue
• Proposed by Greg Young.
• Probably the best innovation from C# community to Java community.
• Command-Query Responsibility Segregation.
• Command -> Write
• Query -> Read
• Separate design for Write Operation and Read Operation.
• For Write, we want consistency.
• For Read, we want speed.
Common Strategy:
product
warehous
e
“write” join
Write Operation:
Write
data
Read Operation: Read
data
“read” join
Read:
O(log n) if it is indexed correctly,
O(n) without index.
CQRS:
product warehouse
“write”
join
Write Operation: Write Data
Read Operation: denormalized_warehouse_by_productRead Data
NO READ JOIN REQUIRED.
Broadcast Event
WRITE
WRITE
READ
Benefit #1: Fast Read
• Simple read. No join operation.
• We can achieve O(1) time complexity by using appropriate database.
• Minimized data transfer – reduced network IO delay.
• Reduced memory requirement – reduced GC.
Data filtering
Benefit #2: Fast Write
• Less indexes created.
• Tables (for write operation) are not polluted by Indexes (which are
created for read operation).
Benefit #3: Simple Read Logic
• Less convoluted Read-logic.
• Simple logic reduces mistakes.
• It promotes knowledge sharing among team members.
• Shorten development time.
product warehouse
“write”
join
Write Operation:
Write
data
Read Operation: MySQL:
denormalized_warehouse_by_product
Read
data
NO READ JOIN REQUIRED.
Broadcast: WAREHOUSE_CREATED_EVENT
Read Operation: C*, Solr:
denormalized_warehouse_by_product
Read
data
Benefit #4: Flexibility - Different Databases
Benefit #5: Consistency
• With CQRS, we only need to maintain consistency at 1 side (WRITE).
Normalized Tables
Write
data
Read
data
Consistency logic 1
Consistency logic 2
Normalized Tables
Write
data
Read
data
Consistency logic
Denormalized Tables
No consistency logic
Common Design CQRS
Event
The End.

More Related Content

PDF
tdtechtalk20160330johan
PDF
Mux loves Clickhouse. By Adam Brown, Mux founder
PDF
https://docs.google.com/presentation/d/1DcL4zK6i3HZRDD4xTGX1VpSOwyu2xBeWLT6a_...
PDF
Speed Up Your Existing Relational Databases with Hazelcast and Speedment
PDF
Building a Versatile Analytics Pipeline on Top of Apache Spark with Mikhail C...
PPTX
GlobusWorld 2020 Keynote
PPTX
The CIOs Guide to NoSQL
PPTX
Globus: Beyond File Transfer
tdtechtalk20160330johan
Mux loves Clickhouse. By Adam Brown, Mux founder
https://docs.google.com/presentation/d/1DcL4zK6i3HZRDD4xTGX1VpSOwyu2xBeWLT6a_...
Speed Up Your Existing Relational Databases with Hazelcast and Speedment
Building a Versatile Analytics Pipeline on Top of Apache Spark with Mikhail C...
GlobusWorld 2020 Keynote
The CIOs Guide to NoSQL
Globus: Beyond File Transfer

What's hot (20)

PDF
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
PDF
What's new in MongoDB 2.6 at India event by company
PDF
Analyzing MySQL Logs with ClickHouse, by Peter Zaitsev
PDF
ClickHouse Paris Meetup. Pragma Analytics Software Suite w/ClickHouse, by Mat...
PDF
HTTP Analytics for 6M requests per second using ClickHouse, by Alexander Boc...
PDF
Using Embulk at Treasure Data
PDF
Voldemort on Solid State Drives
PPTX
Serverless ETL and Optimization on ML pipeline
PPTX
How to build analytics for 100bn logs a month with ClickHouse. By Vadim Tkach...
PDF
User Defined Partitioning on PlazmaDB
PDF
MongoDB .local Bengaluru 2019: Using MongoDB Services in Kubernetes: Any Plat...
PDF
Optimizing Elastic for Search at McQueen Solutions
PPTX
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
PDF
Cloud Databases in Research and Practice
PPTX
Cloud Dataflow - A Unified Model for Batch and Streaming Data Processing
PDF
GumGum: Multi-Region Cassandra in AWS
PDF
Mongo presentation conf
PDF
SAP Open Source meetup/Speedment - Palo Alto 2015
PDF
5 levels of high availability from multi instance to hybrid cloud
PPTX
Meetup#2: Building responsive Symbology & Suggest WebService
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
What's new in MongoDB 2.6 at India event by company
Analyzing MySQL Logs with ClickHouse, by Peter Zaitsev
ClickHouse Paris Meetup. Pragma Analytics Software Suite w/ClickHouse, by Mat...
HTTP Analytics for 6M requests per second using ClickHouse, by Alexander Boc...
Using Embulk at Treasure Data
Voldemort on Solid State Drives
Serverless ETL and Optimization on ML pipeline
How to build analytics for 100bn logs a month with ClickHouse. By Vadim Tkach...
User Defined Partitioning on PlazmaDB
MongoDB .local Bengaluru 2019: Using MongoDB Services in Kubernetes: Any Plat...
Optimizing Elastic for Search at McQueen Solutions
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Cloud Databases in Research and Practice
Cloud Dataflow - A Unified Model for Batch and Streaming Data Processing
GumGum: Multi-Region Cassandra in AWS
Mongo presentation conf
SAP Open Source meetup/Speedment - Palo Alto 2015
5 levels of high availability from multi instance to hybrid cloud
Meetup#2: Building responsive Symbology & Suggest WebService
Ad

Viewers also liked (7)

PDF
TrendForecasting Handbook
RTF
PPTX
Is energy storage the magic bullet for renewables?
DOC
Alif_Resume
PDF
52309 cm 9161_nss_sd_review_web_only
PDF
Administrative Transcript 8 January 2016
PPTX
Kesaktian pancasila
TrendForecasting Handbook
Is energy storage the magic bullet for renewables?
Alif_Resume
52309 cm 9161_nss_sd_review_web_only
Administrative Transcript 8 January 2016
Kesaktian pancasila
Ad

Similar to Simplify Complex Query with CQRS (20)

PPT
5 Pitfalls to Avoid with MongoDB
PDF
Average Active Sessions - OaktableWorld 2013
PPTX
SQL To NoSQL - Top 6 Questions Before Making The Move
KEY
DjangoCon 2010 Scaling Disqus
PDF
Transactional writes to cloud storage with Eric Liang
PDF
Buildingsocialanalyticstoolwithmongodb
PDF
Building a High Performance Analytics Platform
PDF
Golang in TiDB (GopherChina 2017)
PPTX
Dev Jumpstart: Build Your First App with MongoDB
PPTX
Boosting the Performance of your Rails Apps
PPTX
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
PDF
Resilient Predictive Data Pipelines (GOTO Chicago 2016)
PPT
Wmware NoSQL
PDF
Advanced Benchmarking at Parse
PDF
Benchmarking at Parse
PDF
Lens: Data exploration with Dask and Jupyter widgets
PDF
Internals of Presto Service
PPTX
Data Analytics using sparkabcdefghi.pptx
PPT
Apache Cassandra training. Overview and Basics
5 Pitfalls to Avoid with MongoDB
Average Active Sessions - OaktableWorld 2013
SQL To NoSQL - Top 6 Questions Before Making The Move
DjangoCon 2010 Scaling Disqus
Transactional writes to cloud storage with Eric Liang
Buildingsocialanalyticstoolwithmongodb
Building a High Performance Analytics Platform
Golang in TiDB (GopherChina 2017)
Dev Jumpstart: Build Your First App with MongoDB
Boosting the Performance of your Rails Apps
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
Resilient Predictive Data Pipelines (GOTO Chicago 2016)
Wmware NoSQL
Advanced Benchmarking at Parse
Benchmarking at Parse
Lens: Data exploration with Dask and Jupyter widgets
Internals of Presto Service
Data Analytics using sparkabcdefghi.pptx
Apache Cassandra training. Overview and Basics

More from Jacky Lai (6)

PDF
Searching and reporting with splunk 6.x e learning
PDF
Using splunk 6.4 e learning
PDF
Effective Unit Test Style Guide
PDF
Apache hadoop2xdeveloperjava
PDF
0536 lai
PPTX
Cache invalidation
Searching and reporting with splunk 6.x e learning
Using splunk 6.4 e learning
Effective Unit Test Style Guide
Apache hadoop2xdeveloperjava
0536 lai
Cache invalidation

Recently uploaded (20)

PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Introduction to Artificial Intelligence
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Nekopoi APK 2025 free lastest update
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
System and Network Administration Chapter 2
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
L1 - Introduction to python Backend.pptx
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Understanding Forklifts - TECH EHS Solution
Wondershare Filmora 15 Crack With Activation Key [2025
Introduction to Artificial Intelligence
How to Migrate SBCGlobal Email to Yahoo Easily
Nekopoi APK 2025 free lastest update
Design an Analysis of Algorithms I-SECS-1021-03
Odoo POS Development Services by CandidRoot Solutions
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Odoo Companies in India – Driving Business Transformation.pdf
ai tools demonstartion for schools and inter college
System and Network Administration Chapter 2
Upgrade and Innovation Strategies for SAP ERP Customers
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Operating system designcfffgfgggggggvggggggggg
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
L1 - Introduction to python Backend.pptx
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Understanding Forklifts - TECH EHS Solution

Simplify Complex Query with CQRS

  • 1. Simplify Complex Query with CQRS - Jacky Lai
  • 2. Optimization is about Resource Trade-off • The performance of an application is based on • Memory Resource • Computing Resource • Network Resource • Developer Resource • Disk space Resource • Disk space resource is relatively the cheapest resource compared to others.
  • 3. Example Requirement: Find Shipping Methods • During checkout process, user will be presented a list of shipping methods to choose from, based on the product and shipping address. • shippingMethods = findShippingMethodsBy(product, shippingAddress);
  • 4. Example Requirement: Request Payload Request Json Payload: { "productId": ”aabbcc", "address": ”123 Freedom Cir., Santa Clara, CA 95123" }
  • 5. Common Strategy: Back-end Processing • Upon receiving request payload: // step 1: construct hierarchical object graph, an expensive operation. product = productRepository.findBy(productId); shippingAddress = new Address(address); // step 2: find shipping methods. shippingMethods = findShippingMethodsBy(product, shippingAddress);
  • 6. Common Strategy: ER Diagram product warehouse product_type shipping_method n 1 nn n n • restricted? giftCard? • address • size – LARGE? SMALL? • delivery period
  • 7. Common Strategy - Modeling • Model with Hierarchical Data object, e.g. • Product • size (LARGE, SMALL) • type (GIFT_CARD, RESTRICTED) • warehouses • address • shipping methods • Shipping Address
  • 8. Issue #1: Network Traffic Increment. • For each request, application layer has to fetch huge amount of data across network from database, and process the data at Application layer.
  • 9. Question: Which is the best layer to filter data?
  • 10. Issue #2: Read Speed or Write Speed, Pick One. • We cannot optimize both Read and Write speed at the same time. • Without adding index, • time complexity for read = O(n) • After adding index, • time complexity for read = O(log n)
  • 11. Issue #2: Read Speed or Write Speed, Pick One. – Cont. • Performance Summary from “The Performance Impact of Adding MySQL Indexes” • http://logicalread.solarwinds.com/impact-of-adding-mysql-indexes- mc12/#.VmkYP51Viko • For a table with 553875 rows. Before Adding Indexes After Adding Indexes Insert Operation (sec) 7.14 24.77 (3x) Data (mb) 33.56 33.56 Index (mb) 13.52 95.70 (7x) Total = Data + Index (mb) 47.08 129.27
  • 12. Issue #2: Read Speed or Write Speed, Pick One. – Cont. • What if we use Cache to reduce DB read? • Cache is a Key-Value DB. • Let’s say it takes 32 DB calls to build a complex object graph: • Best case: 32 cache hits. • Worst case: 32 cache misses + 32 DB calls. • Network IO delays is unavoidable. • There is another challenge: Cache Consistency. There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton
  • 13. Issue #2: Read Speed or Write Speed, Pick One. – Cont. We need to maintain consistency for both normalized DB and denormalized DB, and this is tricky. Overall Consistency = Consistency (Normalized) && Consistency (Denormalized)
  • 14. Issue #3: “Join” logic has to be at both sides (W, R) product warehouse product_typemanufacture product warehouse product_typemanufacturer join join wrong join join WRITE Wrong READ Database Database
  • 15. CQRS Comes to Rescue • Proposed by Greg Young. • Probably the best innovation from C# community to Java community. • Command-Query Responsibility Segregation. • Command -> Write • Query -> Read • Separate design for Write Operation and Read Operation. • For Write, we want consistency. • For Read, we want speed.
  • 16. Common Strategy: product warehous e “write” join Write Operation: Write data Read Operation: Read data “read” join Read: O(log n) if it is indexed correctly, O(n) without index.
  • 17. CQRS: product warehouse “write” join Write Operation: Write Data Read Operation: denormalized_warehouse_by_productRead Data NO READ JOIN REQUIRED. Broadcast Event WRITE WRITE READ
  • 18. Benefit #1: Fast Read • Simple read. No join operation. • We can achieve O(1) time complexity by using appropriate database. • Minimized data transfer – reduced network IO delay. • Reduced memory requirement – reduced GC. Data filtering
  • 19. Benefit #2: Fast Write • Less indexes created. • Tables (for write operation) are not polluted by Indexes (which are created for read operation).
  • 20. Benefit #3: Simple Read Logic • Less convoluted Read-logic. • Simple logic reduces mistakes. • It promotes knowledge sharing among team members. • Shorten development time.
  • 21. product warehouse “write” join Write Operation: Write data Read Operation: MySQL: denormalized_warehouse_by_product Read data NO READ JOIN REQUIRED. Broadcast: WAREHOUSE_CREATED_EVENT Read Operation: C*, Solr: denormalized_warehouse_by_product Read data Benefit #4: Flexibility - Different Databases
  • 22. Benefit #5: Consistency • With CQRS, we only need to maintain consistency at 1 side (WRITE). Normalized Tables Write data Read data Consistency logic 1 Consistency logic 2 Normalized Tables Write data Read data Consistency logic Denormalized Tables No consistency logic Common Design CQRS Event