SlideShare a Scribd company logo
PHPers #10 Poznań
Idempotency of
commands
in distributed systems
Max Małecki 22.02.2023
Good morning!
I’m Max
As the Last
PHPdeveloper
Warmup Questions!
Who is running
microservices in production?
bro...
Microservices?
So again. Who is running
microservices in production?
You got in the project:
●
Purgers?
●
DataFixers?
●
DataCleaners?
Did your project:
●
Spams sentry with
UniqueConstraintViolations without any
reason?
●
Does your endpoints often return 500 status on
retry?
PHPers #10 Poznań
Idempotency of
commands
in distributed systems
Max Małecki 22.02.2023
Let’s start from the
very beginning
CQRS
Command Query Responsibility Segregation
00
CQRS
© codeopinion.com
Command
It’s a class that represents a change to be made
in the system.
00
Query
It’s a class that is responsible for data retrival.
00
Command Bus
This is a class that contains all the information
about commands and handler assigned to them.
00
Command Handler
This is a class responsible for handling the
command.
00
Now you can CQRS
Idempotence
It’s a characteristic of a single argument function
that the equation below is true.
01
f (f (x))=f (x)
Noooo!
Not Math again
Idempotence
Command called that can be called
multiple times and another calls
doesn’t change the result of the first
execution.
02
Life example
Black Friday
send Request
POST /order
TIMEOUT
php-fpm don’t
respond to ngnix
Retry Request
POST /order
What a bargin!
We just bought
same thing twice!
And we need to pay
for the return
delivery.
TIMEOUT
PDO responded with
timeout of
transaction.
Idempotentność w Black Friday
Idempotency of commands in distributed systems
Idempotence?
404 – Not fo
Maybe something
more microserviceish?
Producer Broker
X
2. Append X
1. Send(X)
X
Producer Broker
X Y
4. Send(Y)
6
.
A
c
k
(
Y
)
X Y Y
2. Append (Y)
1. Send(Y)
Idempotency of commands in distributed systems
Yes. This producer
isn’t idempotent
We reach the new
frontier.
frontier of youtube tutorials .
Warning!
Idempotency of commands in distributed systems
CQRS i REST
04 Commands instead of verbs!
Idempotency of commands in distributed systems
Idempotentność
Command Bus
1) Calls the handler
Handler
1) Execute the business logic
for given command.
2) In case of failure it throws
Exceptions
3) It triggers events
Controller
1) Validates the input
2) Builds a command
3) Dispatches command to
Command Bus
4) Catches exceptions
5) Returns an response
CQRS & REST
Classical REST CRUD
Idempotency of commands in distributed systems
Idempotence
REST CRUD
HTTP Path Action Command
GET
/product/{id}
/products
::show($id)
::index()
POST /product ::new()
CreateProductCommand($name, $desc, $price,
$stock, $status)
PUT /product/{id} ::edit($id)
UpdateProductCommand($name, $desc, $price,
$stock, $status)
PATCH /product/{id} ::edit($id)
EnableProductCommand($id)
DisableProductCommand($id)
UpdateProductPriceCommand($id, $price)
DELETE /product/{id} delete($id) RemoveProductCommand($id)
Let’s do this with
Commands.
Shall we?
Idempotence
CQRS & REST
HTTP Path Command
POST /createProduct
CreateProductCommand($name, $desc, $price,
$stock, $status)
POST /product/{id}
UpdateProductCommand($name, $desc, $price,
$stock, $status)
POST /product/{id}/enable
EnableProductCommand($id)
POST /product/{id}/disable DisableProductCommand($id)
POST /product/{id}/remove RemoveProductCommand($id)
Now we gonna take
care of Idempotence
Idempotence
CQRS & REST
HTTP Path Command
POST /product/create_or_update
CreateOrUpdateProductCommand($name, $desc,
$price, $stock, $status)
POST /product/{id}
UpdateProductCommand($name, $desc, $price,
$stock, $status)
POST /product/{id}/update_price UpdateProductPriceCommand($id, $price)
POST /product/{id}/enable
EnableProductCommand($id)
POST /product/{id}/disable DisableProductCommand($id)
POST /product/{id}/remove RemoveProductCommand($id)
Idempotency of commands in distributed systems
Pros:
●
While building the REST we create
commands. So our commands are transport
agnostic. CLI / Messages / API
●
Getting rid of big fat controllers
●
Controller is only for validation and response
●
We can trigger REST purists
Cons:
●
Don’t see any.
Cool. But where are
microservices?
Message
Bus / Broker
05 from Command Bus to Message Bus
What a name. But we are changing only
the transport.
Idempotency of commands in distributed systems
Okay. Not only
But thanks to that we can delegate workloads to other
microservices
Communication between microservices
Message Bus
1) We’re adding another interface in
app besides CLI i HTTP
2) Thanks to that our command are
not limited by HTTP that adds 1
second for TCP frame
3) We can copy-paste message
contract from our api
documentation
4) Our commands start to be
asynchronous
Let’s add
some
events!
Event
Driven
Architecture
06 In the way to event bus
Event Driven Architecture
●
In our context:
– Every Command Handler emits an Events.
– Events can be local – and go to the event store
– Events can be global – and they go to the EventBus
– Global Event should have contract
– Global Event can be listened by Event Subscribers
from many different micro-services in our system.
Event Bus
Event Bus
microservice #1 microservice #2
microservice #3
EventPublisher EventSubscriber
EventSubscriber
●
Can listen to multiple events
●
Can dispatch a command on command bus
●
Can’t emit another event.
Event Handler
Indepotent
Consumer
Pattern
07 Yes it exists
●
Why is it special:
– It works like every consumer.
– It deduplicates Messages and Events.
●
What it needs?
– Unique id for each processed message
– Repository of a message ids that been already processed (table
in db, index in redis/memchache), to keep the idempotency betw
Idempotent Consumer
Idempotent Consumer
Start
Check
UniqueID
Stop
Duplicate Execute
Commit
Done?
Rollback
False
True
Indepotent Consumer
●
Distributed system are using message brookers,
who try to deliver message at least once.
●
Consumer can recognize duplicates and process a
message just once skipping detected duplicates.
●
When you scale your consumers, you must
remember that duplicate storage must be shared.
Summary
08
Idempontency Pros
●
We’re increasing system resilience
– Just sopped spamming errors in the logs
– In case of fire we allow ourselves to retry request/command
●
Parallel processing is possible now!
– We can accept same event/message from multiple instances
– But remember it isn’t a cure for every consumer race condition.
●
Finally we take care of data consistency
– Each request (no matter it’s quantity) only represent single entity/resource in
the system
What
Next?
09
What next?
●
You may check how Apache Kafka is dealing
with idempotency in consumers and producers
●
Check in your projects how many times you
implement idempotent commands without
realizing they are idempotent
Questions?
10
Yes this presentation will be available online.
Yes the code example is on mine github.
https://github.com/emgiezet/phpers10
THANK YOU
maxmalecki.com
twitter: @mgz
github: @emgiezet

More Related Content

PDF
Working Effectively With Legacy Perl Code
PPTX
Presentation of OrientDB v2.2 - Webinar
PDF
Do you know what your drupal is doing? Observe it!
PDF
Open Source ERP Technologies for Java Developers
PDF
Porting Rails Apps to High Availability Systems
PPT
Multi-tenancy with Rails
KEY
Código Saudável => Programador Feliz - Rs on Rails 2010
PDF
Osiąganie mądrej architektury z Symfony2
Working Effectively With Legacy Perl Code
Presentation of OrientDB v2.2 - Webinar
Do you know what your drupal is doing? Observe it!
Open Source ERP Technologies for Java Developers
Porting Rails Apps to High Availability Systems
Multi-tenancy with Rails
Código Saudável => Programador Feliz - Rs on Rails 2010
Osiąganie mądrej architektury z Symfony2

Similar to Idempotency of commands in distributed systems (20)

PDF
PuppetDB: Sneaking Clojure into Operations
PPTX
Harmonious Development: Via Vagrant and Puppet
PDF
Divide and Conquer – Microservices with Node.js
PDF
[xp2013] Narrow Down What to Test
PPT
DDD Framework for Java: JdonFramework
PDF
Symfony2 - from the trenches
PPTX
Low latency in java 8 by Peter Lawrey
PPTX
Puppet At Twitter - Puppet Camp Silicon Valley
PPTX
Puppet for Developers
PPTX
Low latency in java 8 v5
PDF
The 1990s Called. They Want Their Code Back.
PDF
Penetration Testing for Easy RM to MP3 Converter Application and Post Exploit
PDF
CoreOS, or How I Learned to Stop Worrying and Love Systemd
DOCX
Repository Pattern in MVC3 Application with Entity Framework
PPTX
drupal ci cd concept cornel univercity.pptx
PPT
Azure Cloud Patterns
PDF
Analysis of bugs in Orchard CMS
PPTX
Docker Swarm secrets for creating great FIWARE platforms
PDF
Bt0083 server side programing
ODP
Content Staging in Drupal 8
PuppetDB: Sneaking Clojure into Operations
Harmonious Development: Via Vagrant and Puppet
Divide and Conquer – Microservices with Node.js
[xp2013] Narrow Down What to Test
DDD Framework for Java: JdonFramework
Symfony2 - from the trenches
Low latency in java 8 by Peter Lawrey
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet for Developers
Low latency in java 8 v5
The 1990s Called. They Want Their Code Back.
Penetration Testing for Easy RM to MP3 Converter Application and Post Exploit
CoreOS, or How I Learned to Stop Worrying and Love Systemd
Repository Pattern in MVC3 Application with Entity Framework
drupal ci cd concept cornel univercity.pptx
Azure Cloud Patterns
Analysis of bugs in Orchard CMS
Docker Swarm secrets for creating great FIWARE platforms
Bt0083 server side programing
Content Staging in Drupal 8
Ad

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Big Data Technologies - Introduction.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
Understanding_Digital_Forensics_Presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Modernizing your data center with Dell and AMD
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
Digital-Transformation-Roadmap-for-Companies.pptx
Empathic Computing: Creating Shared Understanding
NewMind AI Monthly Chronicles - July 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
Review of recent advances in non-invasive hemoglobin estimation
Big Data Technologies - Introduction.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
A Presentation on Artificial Intelligence
NewMind AI Weekly Chronicles - August'25 Week I
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
Approach and Philosophy of On baking technology
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Ad

Idempotency of commands in distributed systems