SlideShare uma empresa Scribd logo
1 de 68
Baixar para ler offline
CQRS and Event Sourcing
by example of
Multi-Source Inventory
Igor Miniailo
Software Architect | Magento Commerce
@iminyaylo atTwitter
#MM18DE
Classical N-layered architecture
#MM18DE
Classical N-layered architecture
• Presentation (Block classes)
• Application processing (Controllers and
Model classes)
• Data management functions (Resource
Model classes)
are physically separated
#MM18DE
#MM18DE
Magento 2 + Dependency Injection-
nothing stays buried forever
Big Ball of Mud
SOLID comes to rescue
Magento Technical Guidelines
#MM18DE
Command–query separation (CQS) is a principle
of imperative computer programming. It was devised
by Bertrand Meyer as part of his pioneering work on
the Eiffel programming language.
It states that every method should either be
a command that performs an action, or a query that
returns data to the caller, but not both. In other
words, Asking a question should not change the answer.
CQS
#MM18DE
class UserAccount
{
/**
* @var boolean
*/
private $isActive;
/**
* @return boolean Return true if active; otherwise return false
*/
public function isActive()
{
return $this->isActive;
}
/**
* @return void
*/
public function activate()
{
$this->isActive = true;
}
}
• Command methods change the state
• Commands do not return value (only
void)
• Query methods read the state
• Queries do not change the state of data
being used
• One object in a code for state changing
and querying data
CQRS
Command Query
Responsibility Segregation
#MM18DE
Magento Technical Guidelines
#MM18DE
CQRS
“Two objects where there previously was just one” (c)
Greg Young
#MM18DE
#MM18DE
#MM18DE
#MM18DE
CQRS as simple as to draw an owl
#MM18DE
Actually, not so easy
Applying CQRS you should think about design of
Domain Model first (Command)
#MM18DE
CQRS and Domain Driven Design
#MM18DE
And that’s not all
#MM18DE
#MM18DE
User Interfaces
(с) Cayetano de Arquer Buigas
#MM18DE
CRUD Based UI
CQRS does not fit for
CRUD applications
(“forms over data”)
#MM18DE
Task Based UI
#MM18DE
Task Based UI / Inductive User Interface
CAPTheorem
Eventual Consistency
http://www.enterpriseintegrationpatterns.com/docs/IEEE_Software_Design_2PC.pdf
CQRS over HTTP
•GET (safe) – Query
•POST/PUT/DELETE/PATCH (not safe) – Command
CQRS and MVC
Incorrect
CQRS and MVC
Correct
(c) https://antonkril.github.io/mvc-http-cqrs
CQRS + Event Sourcing
• History
• Rebuild the State for any given point of time
• High Scalability
• Append Only operations
• Low-latency writes
• Allows asynchronous processing
Micro services
Microservice architecture as an alternative to
monolith
Monoliths vs Microservices. Scalability
Conway’s Law
Any organization that designs a
system (defined broadly) will
produce a design whose structure
is a copy of the organization's
communication structure.
-- Melvyn Conway, 1967
Conway’s Law. Cross-functional teams
MSI
#MM18DE
Where did we start?
West
Central
East
Requests from
merchants and
partners
• Need Multiple
warehouses
• Can’t split inventory
for a single product
Current state
• Single stock only
• Must customize or
extend
• Can be complex to
manage and upgrade
Multiple types
needed
• Warehouses
• Stores
• Distribution Centers
• Drop Shipping
Increasingly common
• Even for smaller
merchants
• Applies to both B2C
and B2B
#MM18DE
The MSI “Story”
Original artwork ©2012 Seth Wolfshornd
#MM18DE
A little bit of history
#MM18DE
Original internal Epic MAGETWO-14308
Progress!
Source management
Assign products and quantity
to sources
Priority-based selection
algorithm for shipment
Original internal Epic MAGETWO-14308
#MM18DE
Performance Degradation on order placement
which can’t be controlled, as computation of
Source Selection could be very time consuming
#MM18DE
And let’s get back to nowadays
#MM18DE
Igor Miniailo@RicTempesta
600
601
15
16
69
70 Submitted
Pull Requests
Individual
Contributors
Agencies
Represented
MSI Project Contributions
interjar
#MM18DE
#MM18DE
Technical Overview
• MSI is a brand new way to handle inventory
• Event Sourcing + CQRS architecture
• Scalable Multi-Dimensional indexes for Stocks
• Usage of PHP 7.1 features
• Highly modular design
#MM18DE
Size of MSI Project
33 modules created in the scope of the project
Current Codebase of MSI Modules:
57 518 lines of PHP code
It is ~12% of the whole Magento Modules codebase
#MM18DE
#MM18DE
Inventory Reservations in MSI
• When an order is placed, a reservation is made
to ensure there will be enough quantity
available to fulfill the order
• Reservations are append only operations to
prevent blocking operations and race conditions
at checkout
• The reservations table is periodically cleaned of
reservations that sum to zero
Merchant Benefits
Performant checkout even with high concurrent sessions
Prevents overselling available inventory
#MM18DE
Reservation Example – Step 1
France Warehouse
SKU-1: 5 qty
EU Stock
SKU-1: 15 qty
Italy Warehouse
SKU-1: 10 qty
Raw data Index Reservations
Salable Qty: 15 (data from index, empty reservations)
#MM18DE
Reservation Example – Step 2
Action: Customer buys 5 products on
frontend (SKU-1)
#MM18DE
Reservation Example – Step 3
France Warehouse
SKU-1: 5 qty
EU Stock
SKU-1: 15 qty
Italy Warehouse
SKU-1: 10 qty
Raw data Index Reservations
Salable Qty: 10 (data from index: 15, apply all reservations: -5)
Data is NOT changed
SKU-1: -5 Order #001
Reservation has been added
#MM18DE
Reservation Example – Step 4
Actions: From the original order of 5 products, 3 are returned
#MM18DE
Reservation Example – Step 5
France Warehouse
SKU-1: 5 qty
EU Stock
SKU-1: 15 qty
Italy Warehouse
SKU-1: 10 qty
Raw data Index Reservations
Salable Qty: 13 (data from index: 15, apply all reservations: -5+3)
Data is NOT changed Reservation has been added
SKU-1: -5
SKU-1: +3
Order #001
Return #001
#MM18DE
Reservation Example – Step 6
Actions:
• Admin ships remaining items in order (qty 2)
• Reindex on shipment of order
#MM18DE
Source Selection Algorithm
#MM18DE
Reservation Example – Step 7
France Warehouse
SKU-1: 3 qty
EU Stock
SKU-1: 13 qty
Italy Warehouse
SKU-1: 10 qty
Raw data Index Reservations
Salable Qty: 13 (data from index: 13, apply all reservations: -5+3+2=0)
Data is CHANGED
SKU-1: -5
SKU-1: +3
SKU-1: +2
Order #001
Return #001
Order #001 Shipment
Reservation has been added
#MM18DE
Reservation_id Stock_id sku quantity metadata
1 2 SKU-1 -5.000 order_placed:order:1
2 2 SKU-1 3.000 order_cancelled:order:1
3 2 SKU-1 2.000 shipment_created:order:1
Reservation Example – Step 8
Action:
• Reservation cleaning
• Looping through these reservations we can find reservations which
in sum return 0 (Zero) and remove them
#MM18DE
Reservation Example – Step 9 (like Step 1)
France Warehouse
SKU-1: 3 qty
EU Stock
SKU-1: 13 qty
Italy Warehouse
SKU-1: 10 qty
Raw data Index Reservations
Salable Qty: 13 (data from index, empty reservations table)
Data is NOT changed Reservations have been
removed
#MM18DE
Extension points and APIs in MSI
• For integration with ERP and PIM systems
• Inventory Sales API (Reservations placement)
• For extension developers
• Source Selection AlgorithmAPIs to provide own more efficient and business
oriented choice of Sources for order fulfillment
Microservices and MSI
• InventoryApi (APIs)
• Inventory
(Implementation for
APIs)
• InventoryAdminUi
• InventoryFrontendUi
Microservices and Multi-Source Inventory
Q & A
iminiailo@magento.com
@iminyaylo atTwitter

Mais conteúdo relacionado

Semelhante a CQRS and Event-Sourcing in Magento2 by examples of MSI

Application Assessment - Executive Summary Report
Application Assessment - Executive Summary ReportApplication Assessment - Executive Summary Report
Application Assessment - Executive Summary Report
CAST
 

Semelhante a CQRS and Event-Sourcing in Magento2 by examples of MSI (20)

PLC AND SCADA
PLC AND SCADA PLC AND SCADA
PLC AND SCADA
 
Azure Industrial Iot Edge
Azure Industrial Iot EdgeAzure Industrial Iot Edge
Azure Industrial Iot Edge
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
Smart factory Presentation
Smart factory PresentationSmart factory Presentation
Smart factory Presentation
 
Computer Architecture and Organization
Computer Architecture and OrganizationComputer Architecture and Organization
Computer Architecture and Organization
 
Simplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseSimplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data Warehouse
 
Pragmatic Optimization in Modern Programming - Ordering Optimization Approaches
Pragmatic Optimization in Modern Programming - Ordering Optimization ApproachesPragmatic Optimization in Modern Programming - Ordering Optimization Approaches
Pragmatic Optimization in Modern Programming - Ordering Optimization Approaches
 
Nesma autumn conference 2015 - Is FPA a valuable addition to predictable agil...
Nesma autumn conference 2015 - Is FPA a valuable addition to predictable agil...Nesma autumn conference 2015 - Is FPA a valuable addition to predictable agil...
Nesma autumn conference 2015 - Is FPA a valuable addition to predictable agil...
 
Migration of a high-traffic E-commerce website from Legacy Monolith to Micros...
Migration of a high-traffic E-commerce website from Legacy Monolith to Micros...Migration of a high-traffic E-commerce website from Legacy Monolith to Micros...
Migration of a high-traffic E-commerce website from Legacy Monolith to Micros...
 
Flink Forward Berlin 2018: Olga Slenders, Gijsbert van Vliet - "Exploiting Ap...
Flink Forward Berlin 2018: Olga Slenders, Gijsbert van Vliet - "Exploiting Ap...Flink Forward Berlin 2018: Olga Slenders, Gijsbert van Vliet - "Exploiting Ap...
Flink Forward Berlin 2018: Olga Slenders, Gijsbert van Vliet - "Exploiting Ap...
 
Mtc strategy-briefing-houston-pd m-05212018-3
Mtc strategy-briefing-houston-pd m-05212018-3Mtc strategy-briefing-houston-pd m-05212018-3
Mtc strategy-briefing-houston-pd m-05212018-3
 
Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...
 
Macy's: Changing Engines in Mid-Flight
Macy's: Changing Engines in Mid-FlightMacy's: Changing Engines in Mid-Flight
Macy's: Changing Engines in Mid-Flight
 
GCC Summit 2010
GCC Summit 2010GCC Summit 2010
GCC Summit 2010
 
How to create a Vue Storefront theme
How to create a Vue Storefront themeHow to create a Vue Storefront theme
How to create a Vue Storefront theme
 
Real-Time Health Score Application using Apache Spark on Kubernetes
Real-Time Health Score Application using Apache Spark on KubernetesReal-Time Health Score Application using Apache Spark on Kubernetes
Real-Time Health Score Application using Apache Spark on Kubernetes
 
How Sensor Data Can Help Manufacturers Gain Insight to Reduce Waste, Energy C...
How Sensor Data Can Help Manufacturers Gain Insight to Reduce Waste, Energy C...How Sensor Data Can Help Manufacturers Gain Insight to Reduce Waste, Energy C...
How Sensor Data Can Help Manufacturers Gain Insight to Reduce Waste, Energy C...
 
Ii3DS novitech-midih_presentation_oc2
Ii3DS novitech-midih_presentation_oc2Ii3DS novitech-midih_presentation_oc2
Ii3DS novitech-midih_presentation_oc2
 
Application Assessment - Executive Summary Report
Application Assessment - Executive Summary ReportApplication Assessment - Executive Summary Report
Application Assessment - Executive Summary Report
 
Big Data, Bigger Analytics
Big Data, Bigger AnalyticsBig Data, Bigger Analytics
Big Data, Bigger Analytics
 

Mais de Elogic Magento Development

Mais de Elogic Magento Development (16)

Magento Technical guidelines
Magento Technical guidelinesMagento Technical guidelines
Magento Technical guidelines
 
Миграция кода с Magento 1 на Magento 2
Миграция кода с Magento 1 на Magento 2Миграция кода с Magento 1 на Magento 2
Миграция кода с Magento 1 на Magento 2
 
Introduction to Magento Community
Introduction to Magento Community Introduction to Magento Community
Introduction to Magento Community
 
Chernivtsi Magento Meetup&Contribution day. Naida V.
Chernivtsi Magento Meetup&Contribution day. Naida V.Chernivtsi Magento Meetup&Contribution day. Naida V.
Chernivtsi Magento Meetup&Contribution day. Naida V.
 
Chernivtsi Magento Meetup&Contribution day. Miniailo.I.
Chernivtsi Magento Meetup&Contribution day. Miniailo.I. Chernivtsi Magento Meetup&Contribution day. Miniailo.I.
Chernivtsi Magento Meetup&Contribution day. Miniailo.I.
 
Chernivtsi Magento Meetup&Contribution day. V. Kublytskyi
 Chernivtsi Magento Meetup&Contribution day. V. Kublytskyi Chernivtsi Magento Meetup&Contribution day. V. Kublytskyi
Chernivtsi Magento Meetup&Contribution day. V. Kublytskyi
 
The process of a Lean Magento development
The process of a Lean Magento developmentThe process of a Lean Magento development
The process of a Lean Magento development
 
12 Ways to Improve Magento 2 Security and Performance
12 Ways to Improve Magento 2 Security and Performance12 Ways to Improve Magento 2 Security and Performance
12 Ways to Improve Magento 2 Security and Performance
 
MMnl Pavlo Okhrem
MMnl Pavlo Okhrem MMnl Pavlo Okhrem
MMnl Pavlo Okhrem
 
LIOF 2016
LIOF 2016LIOF 2016
LIOF 2016
 
Payment integration patterns в Magento2
Payment integration patterns в Magento2Payment integration patterns в Magento2
Payment integration patterns в Magento2
 
Как благодаря композеру использовать сторонние компоненты в Magento 2
Как благодаря композеру использовать сторонние компоненты в Magento 2Как благодаря композеру использовать сторонние компоненты в Magento 2
Как благодаря композеру использовать сторонние компоненты в Magento 2
 
Magento 2 - the future of eCommerce
Magento 2 - the future of eCommerceMagento 2 - the future of eCommerce
Magento 2 - the future of eCommerce
 
RequireJS і Magento 2
RequireJS і Magento 2RequireJS і Magento 2
RequireJS і Magento 2
 
Як перехід на Magento допоміг нам стати лідером
Як перехід на Magento допоміг нам стати лідеромЯк перехід на Magento допоміг нам стати лідером
Як перехід на Magento допоміг нам стати лідером
 
Как переписать модуль с Magento 1 на Magento 2
Как переписать модуль с Magento 1 на Magento 2Как переписать модуль с Magento 1 на Magento 2
Как переписать модуль с Magento 1 на Magento 2
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

CQRS and Event-Sourcing in Magento2 by examples of MSI