SlideShare a Scribd company logo
1 of 23
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

What's hot

ClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander ZaitsevClickHouse in Real Life. Case Studies and Best Practices, by Alexander Zaitsev
ClickHouse in Real Life. Case Studies and Best Practices, by Alexander ZaitsevAltinity Ltd
 
What's new in MongoDB 2.6 at India event by company
What's new in MongoDB 2.6 at India event by companyWhat's new in MongoDB 2.6 at India event by company
What's new in MongoDB 2.6 at India event by companyMongoDB APAC
 
Analyzing MySQL Logs with ClickHouse, by Peter Zaitsev
Analyzing MySQL Logs with ClickHouse, by Peter ZaitsevAnalyzing MySQL Logs with ClickHouse, by Peter Zaitsev
Analyzing MySQL Logs with ClickHouse, by Peter ZaitsevAltinity Ltd
 
ClickHouse Paris Meetup. Pragma Analytics Software Suite w/ClickHouse, by Mat...
ClickHouse Paris Meetup. Pragma Analytics Software Suite w/ClickHouse, by Mat...ClickHouse Paris Meetup. Pragma Analytics Software Suite w/ClickHouse, by Mat...
ClickHouse Paris Meetup. Pragma Analytics Software Suite w/ClickHouse, by Mat...Altinity Ltd
 
HTTP Analytics for 6M requests per second using ClickHouse, by Alexander Boc...
HTTP Analytics for 6M requests per second using ClickHouse, by  Alexander Boc...HTTP Analytics for 6M requests per second using ClickHouse, by  Alexander Boc...
HTTP Analytics for 6M requests per second using ClickHouse, by Alexander Boc...Altinity Ltd
 
Voldemort on Solid State Drives
Voldemort on Solid State DrivesVoldemort on Solid State Drives
Voldemort on Solid State DrivesVinoth Chandar
 
Serverless ETL and Optimization on ML pipeline
Serverless ETL and Optimization on ML pipelineServerless ETL and Optimization on ML pipeline
Serverless ETL and Optimization on ML pipelineShu-Jeng Hsieh
 
How to build analytics for 100bn logs a month with ClickHouse. By Vadim Tkach...
How to build analytics for 100bn logs a month with ClickHouse. By Vadim Tkach...How to build analytics for 100bn logs a month with ClickHouse. By Vadim Tkach...
How to build analytics for 100bn logs a month with ClickHouse. By Vadim Tkach...Valery Tkachenko
 
User Defined Partitioning on PlazmaDB
User Defined Partitioning on PlazmaDBUser Defined Partitioning on PlazmaDB
User Defined Partitioning on PlazmaDBKai Sasaki
 
MongoDB .local Bengaluru 2019: Using MongoDB Services in Kubernetes: Any Plat...
MongoDB .local Bengaluru 2019: Using MongoDB Services in Kubernetes: Any Plat...MongoDB .local Bengaluru 2019: Using MongoDB Services in Kubernetes: Any Plat...
MongoDB .local Bengaluru 2019: Using MongoDB Services in Kubernetes: Any Plat...MongoDB
 
Optimizing Elastic for Search at McQueen Solutions
Optimizing Elastic for Search at McQueen SolutionsOptimizing Elastic for Search at McQueen Solutions
Optimizing Elastic for Search at McQueen SolutionsElasticsearch
 
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...
Maintaining Consistency Across Data Centers (Randy Fradin, BlackRock) | Cassa...DataStax
 
Cloud Databases in Research and Practice
Cloud Databases in Research and PracticeCloud Databases in Research and Practice
Cloud Databases in Research and PracticeFelix Gessert
 
Cloud Dataflow - A Unified Model for Batch and Streaming Data Processing
Cloud Dataflow - A Unified Model for Batch and Streaming Data ProcessingCloud Dataflow - A Unified Model for Batch and Streaming Data Processing
Cloud Dataflow - A Unified Model for Batch and Streaming Data ProcessingDoiT International
 
GumGum: Multi-Region Cassandra in AWS
GumGum: Multi-Region Cassandra in AWSGumGum: Multi-Region Cassandra in AWS
GumGum: Multi-Region Cassandra in AWSDataStax Academy
 
Mongo presentation conf
Mongo presentation confMongo presentation conf
Mongo presentation confShridhar Joshi
 
SAP Open Source meetup/Speedment - Palo Alto 2015
SAP Open Source meetup/Speedment - Palo Alto 2015SAP Open Source meetup/Speedment - Palo Alto 2015
SAP Open Source meetup/Speedment - Palo Alto 2015Speedment, Inc.
 
5 levels of high availability from multi instance to hybrid cloud
5 levels of high availability  from multi instance to hybrid cloud5 levels of high availability  from multi instance to hybrid cloud
5 levels of high availability from multi instance to hybrid cloudRafał Leszko
 
Meetup#2: Building responsive Symbology & Suggest WebService
Meetup#2: Building responsive Symbology & Suggest WebServiceMeetup#2: Building responsive Symbology & Suggest WebService
Meetup#2: Building responsive Symbology & Suggest WebServiceMinsk MongoDB User Group
 

What's hot (20)

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

Viewers also liked

TrendForecasting Handbook
TrendForecasting Handbook TrendForecasting Handbook
TrendForecasting Handbook Sam Fullwood
 
Is energy storage the magic bullet for renewables?
Is energy storage the magic bullet for renewables?Is energy storage the magic bullet for renewables?
Is energy storage the magic bullet for renewables?Entelligent
 
52309 cm 9161_nss_sd_review_web_only
52309 cm 9161_nss_sd_review_web_only52309 cm 9161_nss_sd_review_web_only
52309 cm 9161_nss_sd_review_web_onlychrisseth
 
Administrative Transcript 8 January 2016
Administrative Transcript 8 January 2016Administrative Transcript 8 January 2016
Administrative Transcript 8 January 2016David Draker
 
Kesaktian pancasila
Kesaktian pancasilaKesaktian pancasila
Kesaktian pancasilaman_sur
 

Viewers also liked (7)

TrendForecasting Handbook
TrendForecasting Handbook TrendForecasting Handbook
TrendForecasting Handbook
 
Resume
ResumeResume
Resume
 
Is energy storage the magic bullet for renewables?
Is energy storage the magic bullet for renewables?Is energy storage the magic bullet for renewables?
Is energy storage the magic bullet for renewables?
 
Alif_Resume
Alif_ResumeAlif_Resume
Alif_Resume
 
52309 cm 9161_nss_sd_review_web_only
52309 cm 9161_nss_sd_review_web_only52309 cm 9161_nss_sd_review_web_only
52309 cm 9161_nss_sd_review_web_only
 
Administrative Transcript 8 January 2016
Administrative Transcript 8 January 2016Administrative Transcript 8 January 2016
Administrative Transcript 8 January 2016
 
Kesaktian pancasila
Kesaktian pancasilaKesaktian pancasila
Kesaktian pancasila
 

Similar to Simplify Complex Query with CQRS

5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDBTim Callaghan
 
Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013John Beresniewicz
 
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013Amazon Web Services
 
SQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveSQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveIBM Cloud Data Services
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Transactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric LiangTransactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric LiangDatabricks
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbMongoDB APAC
 
Building a High Performance Analytics Platform
Building a High Performance Analytics PlatformBuilding a High Performance Analytics Platform
Building a High Performance Analytics PlatformSantanu Dey
 
Golang in TiDB (GopherChina 2017)
Golang in TiDB  (GopherChina 2017)Golang in TiDB  (GopherChina 2017)
Golang in TiDB (GopherChina 2017)PingCAP
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Boosting the Performance of your Rails Apps
Boosting the Performance of your Rails AppsBoosting the Performance of your Rails Apps
Boosting the Performance of your Rails AppsMatt Kuklinski
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?DATAVERSITY
 
Resilient Predictive Data Pipelines (GOTO Chicago 2016)
Resilient Predictive Data Pipelines (GOTO Chicago 2016)Resilient Predictive Data Pipelines (GOTO Chicago 2016)
Resilient Predictive Data Pipelines (GOTO Chicago 2016)Sid Anand
 
Benchmarking at Parse
Benchmarking at ParseBenchmarking at Parse
Benchmarking at ParseTravis Redman
 
Advanced Benchmarking at Parse
Advanced Benchmarking at ParseAdvanced Benchmarking at Parse
Advanced Benchmarking at ParseMongoDB
 
Lens: Data exploration with Dask and Jupyter widgets
Lens: Data exploration with Dask and Jupyter widgetsLens: Data exploration with Dask and Jupyter widgets
Lens: Data exploration with Dask and Jupyter widgetsVíctor Zabalza
 

Similar to Simplify Complex Query with CQRS (20)

5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB
 
Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013Average Active Sessions - OaktableWorld 2013
Average Active Sessions - OaktableWorld 2013
 
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
SmugMug: From MySQL to Amazon DynamoDB (DAT204) | AWS re:Invent 2013
 
SQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveSQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The Move
 
OMP GSE
OMP GSEOMP GSE
OMP GSE
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Transactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric LiangTransactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric Liang
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 
Building a High Performance Analytics Platform
Building a High Performance Analytics PlatformBuilding a High Performance Analytics Platform
Building a High Performance Analytics Platform
 
Golang in TiDB (GopherChina 2017)
Golang in TiDB  (GopherChina 2017)Golang in TiDB  (GopherChina 2017)
Golang in TiDB (GopherChina 2017)
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Boosting the Performance of your Rails Apps
Boosting the Performance of your Rails AppsBoosting the Performance of your Rails Apps
Boosting the Performance of your Rails Apps
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
 
Resilient Predictive Data Pipelines (GOTO Chicago 2016)
Resilient Predictive Data Pipelines (GOTO Chicago 2016)Resilient Predictive Data Pipelines (GOTO Chicago 2016)
Resilient Predictive Data Pipelines (GOTO Chicago 2016)
 
Wmware NoSQL
Wmware NoSQLWmware NoSQL
Wmware NoSQL
 
Benchmarking at Parse
Benchmarking at ParseBenchmarking at Parse
Benchmarking at Parse
 
Advanced Benchmarking at Parse
Advanced Benchmarking at ParseAdvanced Benchmarking at Parse
Advanced Benchmarking at Parse
 
Deep Dive on Amazon DynamoDB
Deep Dive on Amazon DynamoDBDeep Dive on Amazon DynamoDB
Deep Dive on Amazon DynamoDB
 
Lens: Data exploration with Dask and Jupyter widgets
Lens: Data exploration with Dask and Jupyter widgetsLens: Data exploration with Dask and Jupyter widgets
Lens: Data exploration with Dask and Jupyter widgets
 
Internals of Presto Service
Internals of Presto ServiceInternals of Presto Service
Internals of Presto Service
 

More from Jacky Lai

Searching and reporting with splunk 6.x e learning
Searching and reporting with splunk 6.x   e learningSearching and reporting with splunk 6.x   e learning
Searching and reporting with splunk 6.x e learningJacky Lai
 
Using splunk 6.4 e learning
Using splunk 6.4   e learningUsing splunk 6.4   e learning
Using splunk 6.4 e learningJacky Lai
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 
Apache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjavaApache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjavaJacky Lai
 
Cache invalidation
Cache invalidationCache invalidation
Cache invalidationJacky Lai
 

More from Jacky Lai (6)

Searching and reporting with splunk 6.x e learning
Searching and reporting with splunk 6.x   e learningSearching and reporting with splunk 6.x   e learning
Searching and reporting with splunk 6.x e learning
 
Using splunk 6.4 e learning
Using splunk 6.4   e learningUsing splunk 6.4   e learning
Using splunk 6.4 e learning
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Apache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjavaApache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjava
 
0536 lai
0536 lai0536 lai
0536 lai
 
Cache invalidation
Cache invalidationCache invalidation
Cache invalidation
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
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...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

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