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
CQRS and Event-Sourcing in Magento2 by examples of MSI
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
CQRS and Event-Sourcing in Magento2 by examples of MSI
• 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
CQRS and Event-Sourcing in Magento2 by examples of MSI
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

More Related Content

PDF
The lessons I learned contributing to #MagentoMSI
PDF
Some lessons learned contributing to #MagentoMSI
PPTX
Igor Miniailo - Magento 2 API Design Best Practices
PPTX
Magento Technical guidelines
PPTX
Multi-Source Inventory. Imagine. Las Vegas. 2018
PPTX
Applying Code Customizations to Magento 2
PDF
How I ended up touching Magento core
PPTX
Testing in Magento 2
The lessons I learned contributing to #MagentoMSI
Some lessons learned contributing to #MagentoMSI
Igor Miniailo - Magento 2 API Design Best Practices
Magento Technical guidelines
Multi-Source Inventory. Imagine. Las Vegas. 2018
Applying Code Customizations to Magento 2
How I ended up touching Magento core
Testing in Magento 2

Similar to CQRS and Event-Sourcing in Magento2 by examples of MSI (20)

PPTX
API design best practices
PDF
How I ended up contributing to Magento core
PDF
Happy Together: Creating Successful Magento ERP Integrations | Imagine 2013…
PPTX
Magento 2 Automated Testing via examples of Multi-Source Inventory (MSI)
PPTX
Automated Testing in Magento 2
PPTX
MidwestPHP - Getting Started with Magento 2
PPTX
Magento Multi-Source Inventory (MSI)
PPTX
Awesome Architectures in Magento 2.3
PPTX
CQRS recipes or how to cook your architecture
PDF
"Database isolation: how we deal with hundreds of direct connections to the d...
PDF
Magento Order Management Workshop - Meet Magento India 2019
PPTX
Backward Compatibility Developer's Guide in Magento 2
PDF
Magento 2 Backend Development Essentials
PPTX
Backward Compatibility Developer's Guide in Magento 2. #MM17CZ
PDF
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
PPTX
Zendcon magento101
PPTX
Multi Source Inventory (MSI) - Magento 2.3.x
PDF
Refacoring vs Rewriting WixStores
PPTX
Architecture and workflow of Multi-Source Inventory
PPTX
Effective Microservices In a Data-centric World
API design best practices
How I ended up contributing to Magento core
Happy Together: Creating Successful Magento ERP Integrations | Imagine 2013…
Magento 2 Automated Testing via examples of Multi-Source Inventory (MSI)
Automated Testing in Magento 2
MidwestPHP - Getting Started with Magento 2
Magento Multi-Source Inventory (MSI)
Awesome Architectures in Magento 2.3
CQRS recipes or how to cook your architecture
"Database isolation: how we deal with hundreds of direct connections to the d...
Magento Order Management Workshop - Meet Magento India 2019
Backward Compatibility Developer's Guide in Magento 2
Magento 2 Backend Development Essentials
Backward Compatibility Developer's Guide in Magento 2. #MM17CZ
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Zendcon magento101
Multi Source Inventory (MSI) - Magento 2.3.x
Refacoring vs Rewriting WixStores
Architecture and workflow of Multi-Source Inventory
Effective Microservices In a Data-centric World
Ad

More from Elogic Magento Development (15)

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

Recently uploaded (20)

PDF
Five Habits of High-Impact Board Members
PDF
Unlock new opportunities with location data.pdf
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
August Patch Tuesday
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
STKI Israel Market Study 2025 version august
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Five Habits of High-Impact Board Members
Unlock new opportunities with location data.pdf
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Group 1 Presentation -Planning and Decision Making .pptx
Hindi spoken digit analysis for native and non-native speakers
Chapter 5: Probability Theory and Statistics
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Developing a website for English-speaking practice to English as a foreign la...
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
WOOl fibre morphology and structure.pdf for textiles
DP Operators-handbook-extract for the Mautical Institute
August Patch Tuesday
sustainability-14-14877-v2.pddhzftheheeeee
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
STKI Israel Market Study 2025 version august
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
A comparative study of natural language inference in Swahili using monolingua...
Getting started with AI Agents and Multi-Agent Systems
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game

CQRS and Event-Sourcing in Magento2 by examples of MSI