SlideShare a Scribd company logo
CQRS & Commended
Brought to you by Lei Zhou
1
THIS TALK…
• … understand the basic idea of ES/CQRS
• … know about the advantages of ES/CQRS
• … learn about the issues that come with ES
• … build app (implemented with Commanded lib)
2
Event Sourcing
3
Active Record Pattern
• A database table or view is wrapped into a class, an object instance is tied to a single
row in the table.
4
Event Sourcing is di erent
• Don’t save the current state of objects
• Save the events that lead to the current state
• Event: Something that happened in the past. e.g.
5
How does Event Sourcing work?
•
• Create an event of every state change of the object
• Persist this stream of events, preserving event order
6
Restoring objects 7
Restoring objects 8
Restoring objects 9
Restoring objects 10
Restoring objects 11
Event Sourcing
• Sn = apply(Sn-1, En)
• Sn = reduce(E, S0, apply)
• S: state, E: event
12
The advantages of Event Sourcing
• Complete log of every state change ever
• Traceability and debug-ability
• Very good performance characteristics
• No more mapping objections to tables
13
Real World Example
14
Event Sourcing
• git
• State: Files
• Events: Commits
15
Event Sourcing
• Blockchain
• State: Balance
• Events: Transaction
16
Event Sourcing
• Write ahead logging
• State: DB
• Events: changes (recorded in the log)
• Must be written to a stable storage before converted unto a disk
• Purpose: when the machine it is running on loses power
17
Questions
• Questions - query:
• give a account with balance over 1000
• apply all the events and find ?
• e.g. Sn = reduce(E, S0, apply)
• Solution:
• How about saving in a relational database
• to feed your events ?
18
Welcome to CQRS
19
Welcome to CQRS
• Command
• Query
• Responsibility
• Segregation
• Separate Query and Command objects to retrieve and modify data, respectively
20
CQRS
• Separate write and read models
• Trandationally, databases are:
• fast to write, slow to read
• slow to write, fast to read
• CQRS allows us to be FAST TO WRITE AND FAST TO READ.
21
CQRS
•
22
CQRS
• Commands: Represent requests to action something made by the end user, that will
be processed by the application.
• Events: Changes made to the data , and are raised as a result of actioning Commands.
These classes are serialised into the Event Store.
• Aggregate: Comprised of its state, public command functions, and state mutators.
• Event Store: The place where the Events are stored
23
Commanded
• Elixir lib
• Helps you build the event source command side of application
• Use Commanded to build Elixir applications following the CQRS/ES pattern
24
What are Commands?
• Commands are requests sent by the end user to the application, instructing the app to
do something.
• When our application receives a command
• process it to figure out what the end-user wanted the app to do
• then raise the appropriate Events to accomplish that task
25
What are Commands?
• Defining the Commands
• Create a module per command and define the fields using defstruct
defmodule Coins.Commands do
defmodule MineCoin do
defstruct [
:account_id,
:nonce
]
end
end
defmodule Coins do
def mine_coin(account_id, nonce) do
%Commands.MineCoin{
account_id: account_id,
nonce: nonce
}
end
end
26
What are Commands?
• A request
• e.g. MineCoin(account_id:1234, nonce:“nonce”)
• May fail
27
What are Events?
• Changes made to the state of the system that result from the end-user issuing
Commands.
• Serialised and stored in the Event Store, so that they can be recalled and re-executed
at a later time
• Named in the past tense: account registered; funds transferred…
28
What are Events?
• Defining the Events
• Defining the Commands
defmodule Coins.Events do
defmodule CoinMined do
defstruct [
:account_id,
:nonce
]
end
end
defmodule Coins.Commands do
defmodule MineCoin do
defstruct [
:account_id,
:nonce
]
end
29
What are Events?
• A fact
• In the past
• e.g. CoinMined(account_id:1234, nonce:“nonce”)
30
Aggregates
• Command Handlers
• raise corresponding Events
• state changes with Events
31
Aggregates
• For business rule violations and errors
• State of an aggregate can only be mutated by applying a domain event to its state
@spec execute(state, command)
::{ok, [event]}
| {:error, term()}
@spec apply(state, event) ::state
32
Aggregates
defmodule Coins.Account do
def execute(%{last_nonce: ln}, %MineCoin{nonce: n})
when n < ln,
do: {:error, :used_nonce}
def execute(_, %MineCoin{} = cmd) do
# if Proof.proof(cmd.nonce)
%CoinMined{
#...
}
else
{:error, :invalid_nonce}
end
end
def apply(state, %CoinMined{} = evt) do
%Account{state | last_nonce: evt.nonce}
end
end
33
Aggregates
• Command functions
• receives the aggregate’s state and the command to execute
• return the resultant domain events
• State mutators
• mutated by applying a domain event to its state
34
Now we have…
• Command
• Event
• Aggregate
• how to dispatch command to event?
35
Then we need …
• Router a command directly to an aggregate
defmodule Coins.Router do
use Commanded.Commands.Router
alias Coins.Account
alias Coins.Commands, as: C
dispatch(
[
C.MineCoin
],
to: Account,
identity: :account_id
)
end
alias Coins.{Commands, Router}
def mine_coin(account_id, nonce) do
%Commands.MineCoin{
account_id: account_id,
nonce: nonce
}
|> Router.dispatch()
end
36
Then we need … 37
Then we need …
• EventStore
• Uses PostgreSQL as the underlying storage engine
• Usage:
• Read all events from a single stream
38
Then we have …
iex(1)> Coins.mine_coin("monkey", 2)
:ok
iex(2)> Coins.mine_coin("monkey", 4)
:ok
iex(3)> Coins.mine_coin("monkey", 5)
{:error, :invalid_nonce}
iex(4)> EventStore.stream_all_forward() |> Enum.to_list()
[
# ...,
%EventStore.RecordedEvent{
created_at: ~N[2018-10-30 22:51:51.262611],
data: %Coins.Events.CoinMined{account_id: "monkey", nonce: 2},
event_id: "3d1d4ca2-b453-4f4b-9e0c-1fd8668e1ba6",
event_number: 11,
stream_uuid: "monkey",
stream_version: 1
},
%EventStore.RecordedEvent{
data: %Coins.Events.CoinMined{account_id: "monkey", nonce: 4},
event_number: 12,
stream_uuid: "monkey",
stream_version: 2
},
39
Then we have …
iex(5)> Coins.mine_coin("typewriter", 7)
{:error, :invalid_nonce}
iex(6)> Coins.mine_coin("typewriter", 6)
:ok
iex(7)> Coins.mine_coin("typewriter", 4)
{:error, :used_nonce}
iex(8)> EventStore.stream_all_forward() |> Enum.to_list()
[
# ....,
%EventStore.RecordedEvent{
data: %Coins.Events.CoinMined{account_id: "typewriter", nonce: 6},
event_id: "d0cec127-d69b-488c-b316-20b6ec66230d",
event_number: 13,
stream_uuid: "typewriter",
stream_version: 1
}
]
40
Then…Read model Projections
• Commanded Ecto projections
41
Then…
• Kafka
42
Questions?
43
Arcblock Learning Series - hack.arcblock.io/learning/
44
45

More Related Content

Similar to Introduction to CQRS & Commended

Reactive Design Patterns by Dr.Roland Kuhn
Reactive Design Patterns by Dr.Roland KuhnReactive Design Patterns by Dr.Roland Kuhn
Reactive Design Patterns by Dr.Roland Kuhn
J On The Beach
 
Reactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachReactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the Beach
Roland Kuhn
 
Introduction to ksqlDB and stream processing (Vish Srinivasan - Confluent)
Introduction to ksqlDB and stream processing (Vish Srinivasan  - Confluent)Introduction to ksqlDB and stream processing (Vish Srinivasan  - Confluent)
Introduction to ksqlDB and stream processing (Vish Srinivasan - Confluent)
KafkaZone
 
Event sourcing with reactor and spring statemachine
Event sourcing with reactor and spring statemachineEvent sourcing with reactor and spring statemachine
Event sourcing with reactor and spring statemachine
Jimmy Lu
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
Roy Russo
 
Activiti bpm
Activiti bpmActiviti bpm
Activiti bpm
vaibhav maniar
 
Mastering the Lightning Framework - Part 2
Mastering the Lightning Framework - Part 2Mastering the Lightning Framework - Part 2
Mastering the Lightning Framework - Part 2
Salesforce Developers
 
Collecting 600M events/day
Collecting 600M events/dayCollecting 600M events/day
Collecting 600M events/day
Lars Marius Garshol
 
Reactive Development: Commands, Actors and Events. Oh My!!
Reactive Development: Commands, Actors and Events.  Oh My!!Reactive Development: Commands, Actors and Events.  Oh My!!
Reactive Development: Commands, Actors and Events. Oh My!!
David Hoerster
 
Automated Cluster Management and Recovery for Large Scale Multi-Tenant Sea...
  Automated Cluster Management and Recovery  for Large Scale Multi-Tenant Sea...  Automated Cluster Management and Recovery  for Large Scale Multi-Tenant Sea...
Automated Cluster Management and Recovery for Large Scale Multi-Tenant Sea...
Lucidworks
 
Передача состояния с iPhone на Apple Watch
Передача состояния с iPhone на Apple WatchПередача состояния с iPhone на Apple Watch
Передача состояния с iPhone на Apple Watch
ru_Parallels
 
Data Stream Analytics - Why they are important
Data Stream Analytics - Why they are importantData Stream Analytics - Why they are important
Data Stream Analytics - Why they are important
Paris Carbone
 
Kafka summit SF 2019 - the art of the event-streaming app
Kafka summit SF 2019 - the art of the event-streaming appKafka summit SF 2019 - the art of the event-streaming app
Kafka summit SF 2019 - the art of the event-streaming app
Neil Avery
 
The art of the event streaming application: streams, stream processors and sc...
The art of the event streaming application: streams, stream processors and sc...The art of the event streaming application: streams, stream processors and sc...
The art of the event streaming application: streams, stream processors and sc...
confluent
 
What 100M downloads taught us about iOS architectures
What 100M downloads taught us about iOS architecturesWhat 100M downloads taught us about iOS architectures
What 100M downloads taught us about iOS architectures
Francesco Di Lorenzo
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobX
Darko Kukovec
 
TechEvent 2019: Whats new in biGENiUS; Robert Kranabether - Trivadis
TechEvent 2019: Whats new in biGENiUS; Robert Kranabether - TrivadisTechEvent 2019: Whats new in biGENiUS; Robert Kranabether - Trivadis
TechEvent 2019: Whats new in biGENiUS; Robert Kranabether - Trivadis
Trivadis
 
MobX: the way to simplicity
MobX: the way to simplicityMobX: the way to simplicity
MobX: the way to simplicity
Grid Dynamics
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Redux js
Redux jsRedux js
Redux js
Nils Petersohn
 

Similar to Introduction to CQRS & Commended (20)

Reactive Design Patterns by Dr.Roland Kuhn
Reactive Design Patterns by Dr.Roland KuhnReactive Design Patterns by Dr.Roland Kuhn
Reactive Design Patterns by Dr.Roland Kuhn
 
Reactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachReactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the Beach
 
Introduction to ksqlDB and stream processing (Vish Srinivasan - Confluent)
Introduction to ksqlDB and stream processing (Vish Srinivasan  - Confluent)Introduction to ksqlDB and stream processing (Vish Srinivasan  - Confluent)
Introduction to ksqlDB and stream processing (Vish Srinivasan - Confluent)
 
Event sourcing with reactor and spring statemachine
Event sourcing with reactor and spring statemachineEvent sourcing with reactor and spring statemachine
Event sourcing with reactor and spring statemachine
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 
Activiti bpm
Activiti bpmActiviti bpm
Activiti bpm
 
Mastering the Lightning Framework - Part 2
Mastering the Lightning Framework - Part 2Mastering the Lightning Framework - Part 2
Mastering the Lightning Framework - Part 2
 
Collecting 600M events/day
Collecting 600M events/dayCollecting 600M events/day
Collecting 600M events/day
 
Reactive Development: Commands, Actors and Events. Oh My!!
Reactive Development: Commands, Actors and Events.  Oh My!!Reactive Development: Commands, Actors and Events.  Oh My!!
Reactive Development: Commands, Actors and Events. Oh My!!
 
Automated Cluster Management and Recovery for Large Scale Multi-Tenant Sea...
  Automated Cluster Management and Recovery  for Large Scale Multi-Tenant Sea...  Automated Cluster Management and Recovery  for Large Scale Multi-Tenant Sea...
Automated Cluster Management and Recovery for Large Scale Multi-Tenant Sea...
 
Передача состояния с iPhone на Apple Watch
Передача состояния с iPhone на Apple WatchПередача состояния с iPhone на Apple Watch
Передача состояния с iPhone на Apple Watch
 
Data Stream Analytics - Why they are important
Data Stream Analytics - Why they are importantData Stream Analytics - Why they are important
Data Stream Analytics - Why they are important
 
Kafka summit SF 2019 - the art of the event-streaming app
Kafka summit SF 2019 - the art of the event-streaming appKafka summit SF 2019 - the art of the event-streaming app
Kafka summit SF 2019 - the art of the event-streaming app
 
The art of the event streaming application: streams, stream processors and sc...
The art of the event streaming application: streams, stream processors and sc...The art of the event streaming application: streams, stream processors and sc...
The art of the event streaming application: streams, stream processors and sc...
 
What 100M downloads taught us about iOS architectures
What 100M downloads taught us about iOS architecturesWhat 100M downloads taught us about iOS architectures
What 100M downloads taught us about iOS architectures
 
React state management with Redux and MobX
React state management with Redux and MobXReact state management with Redux and MobX
React state management with Redux and MobX
 
TechEvent 2019: Whats new in biGENiUS; Robert Kranabether - Trivadis
TechEvent 2019: Whats new in biGENiUS; Robert Kranabether - TrivadisTechEvent 2019: Whats new in biGENiUS; Robert Kranabether - Trivadis
TechEvent 2019: Whats new in biGENiUS; Robert Kranabether - Trivadis
 
MobX: the way to simplicity
MobX: the way to simplicityMobX: the way to simplicity
MobX: the way to simplicity
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
 
Redux js
Redux jsRedux js
Redux js
 

More from ArcBlock

ArcBlock Introduction to Blockchain
ArcBlock Introduction to BlockchainArcBlock Introduction to Blockchain
ArcBlock Introduction to Blockchain
ArcBlock
 
Forge blockchain deployment made easy
Forge  blockchain deployment made easyForge  blockchain deployment made easy
Forge blockchain deployment made easy
ArcBlock
 
Designing Decentralized Apps: Programmable Tokens
Designing Decentralized Apps: Programmable TokensDesigning Decentralized Apps: Programmable Tokens
Designing Decentralized Apps: Programmable Tokens
ArcBlock
 
Build a Decentralized, public verifiable Database with ex_abci and Tendermint
Build a Decentralized, public verifiable Database with ex_abci and TendermintBuild a Decentralized, public verifiable Database with ex_abci and Tendermint
Build a Decentralized, public verifiable Database with ex_abci and Tendermint
ArcBlock
 
ArcBlock Presents 5 Winning Factors to Building a Successful DApp
ArcBlock Presents 5 Winning Factors to Building a Successful DAppArcBlock Presents 5 Winning Factors to Building a Successful DApp
ArcBlock Presents 5 Winning Factors to Building a Successful DApp
ArcBlock
 
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity Verification
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity VerificationQRCodes are Fun, Easy, and Useful for Links, Payments and Identity Verification
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity Verification
ArcBlock
 
Designing Decentralized Applications (DApps)
Designing Decentralized Applications (DApps) Designing Decentralized Applications (DApps)
Designing Decentralized Applications (DApps)
ArcBlock
 
Cryptography for everyone
Cryptography for everyoneCryptography for everyone
Cryptography for everyone
ArcBlock
 
Introduction to HTTP/2 and How To Use It
Introduction to HTTP/2 and How To Use ItIntroduction to HTTP/2 and How To Use It
Introduction to HTTP/2 and How To Use It
ArcBlock
 
IPFS: A Whole New World
IPFS: A Whole New WorldIPFS: A Whole New World
IPFS: A Whole New World
ArcBlock
 
Ethereum virtual machine for Developers Part 1
Ethereum virtual machine for Developers Part 1Ethereum virtual machine for Developers Part 1
Ethereum virtual machine for Developers Part 1
ArcBlock
 
Understanding hd wallets design and implementation
Understanding hd wallets  design and implementationUnderstanding hd wallets  design and implementation
Understanding hd wallets design and implementation
ArcBlock
 
Technical Learning Series - Elixir ExUnit
Technical Learning Series - Elixir ExUnitTechnical Learning Series - Elixir ExUnit
Technical Learning Series - Elixir ExUnit
ArcBlock
 
Tendermint in a nutshell
Tendermint in a nutshellTendermint in a nutshell
Tendermint in a nutshell
ArcBlock
 
Decipher Multi-Factor Authentication - A Developers Introduction
Decipher Multi-Factor Authentication - A Developers IntroductionDecipher Multi-Factor Authentication - A Developers Introduction
Decipher Multi-Factor Authentication - A Developers Introduction
ArcBlock
 
Introduction to aws data pipeline services
Introduction to aws data pipeline servicesIntroduction to aws data pipeline services
Introduction to aws data pipeline services
ArcBlock
 
Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts
ArcBlock
 
ArcBlock Presents An Introduction to Blockchain
ArcBlock Presents An Introduction to BlockchainArcBlock Presents An Introduction to Blockchain
ArcBlock Presents An Introduction to Blockchain
ArcBlock
 

More from ArcBlock (18)

ArcBlock Introduction to Blockchain
ArcBlock Introduction to BlockchainArcBlock Introduction to Blockchain
ArcBlock Introduction to Blockchain
 
Forge blockchain deployment made easy
Forge  blockchain deployment made easyForge  blockchain deployment made easy
Forge blockchain deployment made easy
 
Designing Decentralized Apps: Programmable Tokens
Designing Decentralized Apps: Programmable TokensDesigning Decentralized Apps: Programmable Tokens
Designing Decentralized Apps: Programmable Tokens
 
Build a Decentralized, public verifiable Database with ex_abci and Tendermint
Build a Decentralized, public verifiable Database with ex_abci and TendermintBuild a Decentralized, public verifiable Database with ex_abci and Tendermint
Build a Decentralized, public verifiable Database with ex_abci and Tendermint
 
ArcBlock Presents 5 Winning Factors to Building a Successful DApp
ArcBlock Presents 5 Winning Factors to Building a Successful DAppArcBlock Presents 5 Winning Factors to Building a Successful DApp
ArcBlock Presents 5 Winning Factors to Building a Successful DApp
 
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity Verification
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity VerificationQRCodes are Fun, Easy, and Useful for Links, Payments and Identity Verification
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity Verification
 
Designing Decentralized Applications (DApps)
Designing Decentralized Applications (DApps) Designing Decentralized Applications (DApps)
Designing Decentralized Applications (DApps)
 
Cryptography for everyone
Cryptography for everyoneCryptography for everyone
Cryptography for everyone
 
Introduction to HTTP/2 and How To Use It
Introduction to HTTP/2 and How To Use ItIntroduction to HTTP/2 and How To Use It
Introduction to HTTP/2 and How To Use It
 
IPFS: A Whole New World
IPFS: A Whole New WorldIPFS: A Whole New World
IPFS: A Whole New World
 
Ethereum virtual machine for Developers Part 1
Ethereum virtual machine for Developers Part 1Ethereum virtual machine for Developers Part 1
Ethereum virtual machine for Developers Part 1
 
Understanding hd wallets design and implementation
Understanding hd wallets  design and implementationUnderstanding hd wallets  design and implementation
Understanding hd wallets design and implementation
 
Technical Learning Series - Elixir ExUnit
Technical Learning Series - Elixir ExUnitTechnical Learning Series - Elixir ExUnit
Technical Learning Series - Elixir ExUnit
 
Tendermint in a nutshell
Tendermint in a nutshellTendermint in a nutshell
Tendermint in a nutshell
 
Decipher Multi-Factor Authentication - A Developers Introduction
Decipher Multi-Factor Authentication - A Developers IntroductionDecipher Multi-Factor Authentication - A Developers Introduction
Decipher Multi-Factor Authentication - A Developers Introduction
 
Introduction to aws data pipeline services
Introduction to aws data pipeline servicesIntroduction to aws data pipeline services
Introduction to aws data pipeline services
 
Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts Introduction to Ethereum Smart Contracts
Introduction to Ethereum Smart Contracts
 
ArcBlock Presents An Introduction to Blockchain
ArcBlock Presents An Introduction to BlockchainArcBlock Presents An Introduction to Blockchain
ArcBlock Presents An Introduction to Blockchain
 

Recently uploaded

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 

Introduction to CQRS & Commended

  • 1. CQRS & Commended Brought to you by Lei Zhou 1
  • 2. THIS TALK… • … understand the basic idea of ES/CQRS • … know about the advantages of ES/CQRS • … learn about the issues that come with ES • … build app (implemented with Commanded lib) 2
  • 4. Active Record Pattern • A database table or view is wrapped into a class, an object instance is tied to a single row in the table. 4
  • 5. Event Sourcing is di erent • Don’t save the current state of objects • Save the events that lead to the current state • Event: Something that happened in the past. e.g. 5
  • 6. How does Event Sourcing work? • • Create an event of every state change of the object • Persist this stream of events, preserving event order 6
  • 12. Event Sourcing • Sn = apply(Sn-1, En) • Sn = reduce(E, S0, apply) • S: state, E: event 12
  • 13. The advantages of Event Sourcing • Complete log of every state change ever • Traceability and debug-ability • Very good performance characteristics • No more mapping objections to tables 13
  • 15. Event Sourcing • git • State: Files • Events: Commits 15
  • 16. Event Sourcing • Blockchain • State: Balance • Events: Transaction 16
  • 17. Event Sourcing • Write ahead logging • State: DB • Events: changes (recorded in the log) • Must be written to a stable storage before converted unto a disk • Purpose: when the machine it is running on loses power 17
  • 18. Questions • Questions - query: • give a account with balance over 1000 • apply all the events and find ? • e.g. Sn = reduce(E, S0, apply) • Solution: • How about saving in a relational database • to feed your events ? 18
  • 20. Welcome to CQRS • Command • Query • Responsibility • Segregation • Separate Query and Command objects to retrieve and modify data, respectively 20
  • 21. CQRS • Separate write and read models • Trandationally, databases are: • fast to write, slow to read • slow to write, fast to read • CQRS allows us to be FAST TO WRITE AND FAST TO READ. 21
  • 23. CQRS • Commands: Represent requests to action something made by the end user, that will be processed by the application. • Events: Changes made to the data , and are raised as a result of actioning Commands. These classes are serialised into the Event Store. • Aggregate: Comprised of its state, public command functions, and state mutators. • Event Store: The place where the Events are stored 23
  • 24. Commanded • Elixir lib • Helps you build the event source command side of application • Use Commanded to build Elixir applications following the CQRS/ES pattern 24
  • 25. What are Commands? • Commands are requests sent by the end user to the application, instructing the app to do something. • When our application receives a command • process it to figure out what the end-user wanted the app to do • then raise the appropriate Events to accomplish that task 25
  • 26. What are Commands? • Defining the Commands • Create a module per command and define the fields using defstruct defmodule Coins.Commands do defmodule MineCoin do defstruct [ :account_id, :nonce ] end end defmodule Coins do def mine_coin(account_id, nonce) do %Commands.MineCoin{ account_id: account_id, nonce: nonce } end end 26
  • 27. What are Commands? • A request • e.g. MineCoin(account_id:1234, nonce:“nonce”) • May fail 27
  • 28. What are Events? • Changes made to the state of the system that result from the end-user issuing Commands. • Serialised and stored in the Event Store, so that they can be recalled and re-executed at a later time • Named in the past tense: account registered; funds transferred… 28
  • 29. What are Events? • Defining the Events • Defining the Commands defmodule Coins.Events do defmodule CoinMined do defstruct [ :account_id, :nonce ] end end defmodule Coins.Commands do defmodule MineCoin do defstruct [ :account_id, :nonce ] end 29
  • 30. What are Events? • A fact • In the past • e.g. CoinMined(account_id:1234, nonce:“nonce”) 30
  • 31. Aggregates • Command Handlers • raise corresponding Events • state changes with Events 31
  • 32. Aggregates • For business rule violations and errors • State of an aggregate can only be mutated by applying a domain event to its state @spec execute(state, command) ::{ok, [event]} | {:error, term()} @spec apply(state, event) ::state 32
  • 33. Aggregates defmodule Coins.Account do def execute(%{last_nonce: ln}, %MineCoin{nonce: n}) when n < ln, do: {:error, :used_nonce} def execute(_, %MineCoin{} = cmd) do # if Proof.proof(cmd.nonce) %CoinMined{ #... } else {:error, :invalid_nonce} end end def apply(state, %CoinMined{} = evt) do %Account{state | last_nonce: evt.nonce} end end 33
  • 34. Aggregates • Command functions • receives the aggregate’s state and the command to execute • return the resultant domain events • State mutators • mutated by applying a domain event to its state 34
  • 35. Now we have… • Command • Event • Aggregate • how to dispatch command to event? 35
  • 36. Then we need … • Router a command directly to an aggregate defmodule Coins.Router do use Commanded.Commands.Router alias Coins.Account alias Coins.Commands, as: C dispatch( [ C.MineCoin ], to: Account, identity: :account_id ) end alias Coins.{Commands, Router} def mine_coin(account_id, nonce) do %Commands.MineCoin{ account_id: account_id, nonce: nonce } |> Router.dispatch() end 36
  • 37. Then we need … 37
  • 38. Then we need … • EventStore • Uses PostgreSQL as the underlying storage engine • Usage: • Read all events from a single stream 38
  • 39. Then we have … iex(1)> Coins.mine_coin("monkey", 2) :ok iex(2)> Coins.mine_coin("monkey", 4) :ok iex(3)> Coins.mine_coin("monkey", 5) {:error, :invalid_nonce} iex(4)> EventStore.stream_all_forward() |> Enum.to_list() [ # ..., %EventStore.RecordedEvent{ created_at: ~N[2018-10-30 22:51:51.262611], data: %Coins.Events.CoinMined{account_id: "monkey", nonce: 2}, event_id: "3d1d4ca2-b453-4f4b-9e0c-1fd8668e1ba6", event_number: 11, stream_uuid: "monkey", stream_version: 1 }, %EventStore.RecordedEvent{ data: %Coins.Events.CoinMined{account_id: "monkey", nonce: 4}, event_number: 12, stream_uuid: "monkey", stream_version: 2 }, 39
  • 40. Then we have … iex(5)> Coins.mine_coin("typewriter", 7) {:error, :invalid_nonce} iex(6)> Coins.mine_coin("typewriter", 6) :ok iex(7)> Coins.mine_coin("typewriter", 4) {:error, :used_nonce} iex(8)> EventStore.stream_all_forward() |> Enum.to_list() [ # ...., %EventStore.RecordedEvent{ data: %Coins.Events.CoinMined{account_id: "typewriter", nonce: 6}, event_id: "d0cec127-d69b-488c-b316-20b6ec66230d", event_number: 13, stream_uuid: "typewriter", stream_version: 1 } ] 40
  • 41. Then…Read model Projections • Commanded Ecto projections 41
  • 44. Arcblock Learning Series - hack.arcblock.io/learning/ 44
  • 45. 45