SlideShare ist ein Scribd-Unternehmen logo
116 VictorRentea.ro
a training by
Consistency
Pa-erns
Maintaining Consistency across distributed systems
117 VictorRentea.ro
a training by
Either Consistent or Available
when Par33oned
CAP Theorem
118 VictorRentea.ro
a training by
2-Phase-Commit (2PC)
118
119 VictorRentea.ro
a training by
1) Vo&ng Phase
- All par6cipants no6fy the coordinator if their local transac6on would commit OK
2) Commit Phase:
- Coordinator decides to commit if all voted "Yes" or rollback; no6fies all par6cipants
§Downsides
- Can s6ll fail, requiring recovery steps
- Involves locking, doesn't scale well
- Not supported by some resources: requires XA drivers, and a JTA coordinator
- Requires direct connec6on to remote DB
2-Phase-Commit (2PC)
119
120 VictorRentea.ro
a training by
Scenario #1
@Entity // in user-api
public class User {
@Id @GeneratedValue
private long id;
private String name;
private LocalDateTime lastMessageTime;
}
@Entity // in message-api
public class Message {
@Id @GeneratedValue
private long id;
private long userId;
private String contents;
private LocalDateTime messageTimestamp;
}
121 VictorRentea.ro
a training by
POST message-api/messages ...
§Sync call to sync state
- PUT user-api/users/{uid}/lastMessageTimestamp
- Fragile: What if user-api is down? Retry? For how long?
§Async send a message via durable queue (eg. Rabbit)
- eg. MessageSentEvent
- What if MQ broker is down? è
§Avoid synchroniza&on: redesign the service boundaries
- GET message-api/lastMessageTimestamp?user={uid}
Scenario #1 - Consistency Strategies
122 VictorRentea.ro
a training by
A call failed or ,med out
Let me try again...
Is the opera,on IDEMPOTENT?
Retry
DUP:REMOVE
123 VictorRentea.ro
a training by
= can be applied many .mes without changing the result. Examples:
§Get Product by id via GET ?
- ✅ YES: the call does not change any data on the server
§Cancel Payment by id via DELETE
- ✅ YES: canceling it again has no addi1onal effect
§Update Product price by id via PUT
- ✅ YES: we would just set the same price again
§Place Order { items: [..] } via POST or MQ
- ❌ NO if retry would create a second order
- ✅ YES, if we deduplicate via lastPlacedOrders = Map<custId, List<orderJsonHash>> (TTL 1h)
§Place Order { items: [..], clickId/messageID: UUID } via POST or MQ
- ✅ YES if we deduplicate via Set<lastSeenClickIds>
§Place Order { id: UUID, items: [..] } via PUT or MQ = Client-generated ID 🤔
- ✅ YES: a duplicate would cause a PK/UK viola1on
Idempotent OperaAon
In DB: alternate UK, next to numeric PK
DUP:REMOVE
124 VictorRentea.ro
a training by
Update DB and send a Message
void f() {
mq.send(..);
repo.save(..)
}
@TransacDonal
void f() {
repo.saveAndFlush(..)
mq.send(..);
}
@TransacDonalEventListener(AFTER_COMMIT)
void aOerCommit(..) {
mq.send(..);
}
db.update(data);
db.commit;
mq.send(message);💥
db.update(data);
mq.send(message);
db.commit;💥
mq.send(message);
db.update(data);💥
db.commit;💥
125 VictorRentea.ro
a training by
Receive a Message and Update DB
If ack is not sent, MQ would retry the message
è Listeners should be idempotent
SEEN_MESSAGES_IDS
db.update(data);
mq.ack(message);💥
mq.ack(message);
db.update(data);💥
126 VictorRentea.ro
a training by
TransacAonal Outbox Table
Problem: update DB and send message atomically.
2PC is not an opNon.
Solu/on:
§Instead of sending the message, INSERT it in 'MESSAGES_TO_SEND' table
§A scheduler polls this table, sends messages in order and removes them
§A form of 'persistent retry'
§Can raise alarms if message is delayed too much
§:/ Could send duplicate messages
127 VictorRentea.ro
a training by
TransacAonal Outbox Table
⏱
Change Data Capture (CDC)
h"p://debezium.io
tails the transac7on log and
publishes every change to a Ka<a topic
128 VictorRentea.ro
a training by
Saga PaJern
Problem: Run a business transacNon across mulNple services (separate DB)
Solu/on: Saga PaYern
§Implement the business transacNon as a sequence of local transacNons
§Each local transacNon updates the DB and sends a message
(command or event) to trigger the next local transacNon to take place
§If a local transacNon fails, the saga executes compensa/ng transac/ons to
undo the previously commiYed transacNons
§CompensaNng acNons must be retry-able
§Use reserva/on (Nmed) for non-reversible steps + confirmaNon/cancel
129 VictorRentea.ro
a training by
2-Phase Commit (2PC)
DB
DB
DB
DB
Orchestrator
Sync RPC
TransacDon
130 VictorRentea.ro
a training by
Each party commits then calls next step.
On error, each party must call undo on
all previously completed steps.
++COUPLING
Orchestrator calls all parDes synchronously.
On error: orchestrator calls compensaDng 'undo'
endpoints for previously completed steps.
NOT SCALABLE, FRAGILE
Sync Saga
Sync RPC
TransacDon
Orchestrated Choreographed
131 VictorRentea.ro
a training by
Orchestrated
Choreographed
Async Saga
Orchestrator sends messages to par6es.
On error: it sends compensa)ng command
messages to previously completed steps
Async Message
TransacDon
Each service commits and sends a message
to the next service
On error, a party:
a) publishes a failure event,
listened by all previous par6es (coupling++)
b) sends compensa)ng commands to all
par6es stamped on message (Rou6ng Slip)
c) no6fies a Saga Execu)on Coordinator
132 VictorRentea.ro
a training by
Image source: https://www.baeldung.com/cs/saga-pattern-microservices
133 VictorRentea.ro
a training by
§Rou&ng Slip PaAern = Accumulate all previous "undo" ac<ons
- Each service appends its own "undo" informa6on to the message sent forward
- On any error on received message => call/message all UNDO ac6ons
§Error Event upstream
- All previous steps undo on LegalCheckFailedEvent{orderId}
Choreographed Compensations
Stock
Payment
Legal
1) cancel stock reserva6on
2) undo payment
134 VictorRentea.ro
a training by
locked
state
unlocked
state
push in stack
insert coin
insert coin
push in stack
/capture coin
Side-effect / Ac6on
/release coin
External signal
ini2al state
A state machine reacts to various
external signals (inputs)
in different ways (outputs),
depending on its current state
/🤨
/🤨
UML State Diagram:
135 VictorRentea.ro
a training by
Exercise: Food Delivery App
136 VictorRentea.ro
a training by
Feed hungry people with food from restaurants delivered by couriers.
Assume customer, restaurants and couriers have an app installed.
High level flow:
1.hungry customer orders Food FF from Restaurant RR
2.accept card payment via external payment gateway
3.tell RR to cook FF
4.find a courier CC
5.CC picks FF from RR
6.CC delivers food to customer
7.charge a fee to RR for the service
Exercise: Food Delivery App
137 VictorRentea.ro
a training by
Sagas are Hard
§Keep hard consistency constraints within the boundary of one service.
- (that is, don't distribute)
§Manual intervenNon could be cheaper(eg: by 2nd level support)
- eg. log.error("[CALL-SUPPORT] Out of stock for order {}", ...);
- Implement a Saga to recover from frequent or expensive failures
§Use a Saga framework (or learn from it)
- Orchestrated: Camunda , Apache Camel
- Choreographed: Eventuate. Seata, Axon Saga
138 VictorRentea.ro
a training by
Thank You!

Weitere ähnliche Inhalte

Was ist angesagt?

Reverse proxies & Inconsistency
Reverse proxies & InconsistencyReverse proxies & Inconsistency
Reverse proxies & Inconsistency
GreenD0g
 
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4hackers.com
 
Cross Site Scripting
Cross Site ScriptingCross Site Scripting
Cross Site ScriptingAli Mattash
 
Living off the land and fileless attack techniques
Living off the land and fileless attack techniquesLiving off the land and fileless attack techniques
Living off the land and fileless attack techniques
Symantec Security Response
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
Geoffrey Filippi
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
Rodolfo Assis (Brute)
 
The Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better AutomationThe Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better Automation
Applitools
 
Introduction to CSRF Attacks & Defense
Introduction to CSRF Attacks & DefenseIntroduction to CSRF Attacks & Defense
Introduction to CSRF Attacks & Defense
Surya Subhash
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Security Vulnerabilities
Security VulnerabilitiesSecurity Vulnerabilities
Security Vulnerabilities
Marius Vorster
 
Aem asset optimizations & best practices
Aem asset optimizations & best practicesAem asset optimizations & best practices
Aem asset optimizations & best practices
Kanika Gera
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
Napendra Singh
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
XSS and CSRF with HTML5
XSS and CSRF with HTML5XSS and CSRF with HTML5
XSS and CSRF with HTML5Shreeraj Shah
 
FE로 취업 전에 알았으면 좋았을 것들
FE로 취업 전에 알았으면 좋았을 것들FE로 취업 전에 알았으면 좋았을 것들
FE로 취업 전에 알았으면 좋았을 것들
Taegon Kim
 
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat Security Conference
 
Sql injection
Sql injectionSql injection
Sql injection
Sasha-Leigh Garret
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDD
Dennis Doomen
 
A8 cross site request forgery (csrf) it 6873 presentation
A8 cross site request forgery (csrf)   it 6873 presentationA8 cross site request forgery (csrf)   it 6873 presentation
A8 cross site request forgery (csrf) it 6873 presentation
Albena Asenova-Belal
 

Was ist angesagt? (20)

Reverse proxies & Inconsistency
Reverse proxies & InconsistencyReverse proxies & Inconsistency
Reverse proxies & Inconsistency
 
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
 
Cross Site Scripting
Cross Site ScriptingCross Site Scripting
Cross Site Scripting
 
Living off the land and fileless attack techniques
Living off the land and fileless attack techniquesLiving off the land and fileless attack techniques
Living off the land and fileless attack techniques
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
The Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better AutomationThe Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better Automation
 
Introduction to CSRF Attacks & Defense
Introduction to CSRF Attacks & DefenseIntroduction to CSRF Attacks & Defense
Introduction to CSRF Attacks & Defense
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Security Vulnerabilities
Security VulnerabilitiesSecurity Vulnerabilities
Security Vulnerabilities
 
Aem asset optimizations & best practices
Aem asset optimizations & best practicesAem asset optimizations & best practices
Aem asset optimizations & best practices
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
 
Cross site scripting XSS
Cross site scripting XSSCross site scripting XSS
Cross site scripting XSS
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
XSS and CSRF with HTML5
XSS and CSRF with HTML5XSS and CSRF with HTML5
XSS and CSRF with HTML5
 
FE로 취업 전에 알았으면 좋았을 것들
FE로 취업 전에 알았으면 좋았을 것들FE로 취업 전에 알았으면 좋았을 것들
FE로 취업 전에 알았으면 좋았을 것들
 
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
 
Sql injection
Sql injectionSql injection
Sql injection
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDD
 
A8 cross site request forgery (csrf) it 6873 presentation
A8 cross site request forgery (csrf)   it 6873 presentationA8 cross site request forgery (csrf)   it 6873 presentation
A8 cross site request forgery (csrf) it 6873 presentation
 

Ähnlich wie Distributed Consistency.pdf

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
Victor Rentea
 
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
Databricks
 
Two phase commit protocol in dbms
Two phase commit protocol in dbmsTwo phase commit protocol in dbms
Two phase commit protocol in dbms
Dilouar Hossain
 
Formal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction ContractsFormal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction ContractsGera Shegalov
 
9 queuing
9 queuing9 queuing
9 queuing
ashish61_scs
 
hbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACL
hbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACLhbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACL
hbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACL
Michael Stack
 
Tracon
TraconTracon
Tracon
sami_11
 
Full rack access guide 1
Full rack access guide 1Full rack access guide 1
Full rack access guide 1
networkershome
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStack
Love Nyberg
 
Gearmanpresentation 110308165409-phpapp01
Gearmanpresentation 110308165409-phpapp01Gearmanpresentation 110308165409-phpapp01
Gearmanpresentation 110308165409-phpapp01
longtuan
 
Formal Verification of Transactional Interaction Contract
Formal Verification of Transactional Interaction ContractFormal Verification of Transactional Interaction Contract
Formal Verification of Transactional Interaction ContractGera Shegalov
 
A short tale about state machine
A short tale about state machineA short tale about state machine
A short tale about state machine
Łukasz Chruściel
 
Micronaut Webinar 2021 - Process Automation Introduction
Micronaut Webinar 2021 - Process Automation IntroductionMicronaut Webinar 2021 - Process Automation Introduction
Micronaut Webinar 2021 - Process Automation Introduction
Bernd Ruecker
 
Taming event-driven software via formal verification
Taming event-driven software via formal verificationTaming event-driven software via formal verification
Taming event-driven software via formal verification
AdaCore
 
Memcache as udp traffic reflector
Memcache as udp traffic reflectorMemcache as udp traffic reflector
Memcache as udp traffic reflector
Bangladesh Network Operators Group
 
Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...
Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...
Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...
Lionel Briand
 
BKK16-312 Integrating and controlling embedded devices in LAVA
BKK16-312 Integrating and controlling embedded devices in LAVABKK16-312 Integrating and controlling embedded devices in LAVA
BKK16-312 Integrating and controlling embedded devices in LAVA
Linaro
 
Debugging varnish
Debugging varnishDebugging varnish
Debugging varnish
Varnish Software
 

Ähnlich wie Distributed Consistency.pdf (20)

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
 
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
 
Two phase commit protocol in dbms
Two phase commit protocol in dbmsTwo phase commit protocol in dbms
Two phase commit protocol in dbms
 
Formal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction ContractsFormal Verification of Web Service Interaction Contracts
Formal Verification of Web Service Interaction Contracts
 
9 queuing
9 queuing9 queuing
9 queuing
 
hbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACL
hbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACLhbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACL
hbaseconasia2019 The Procedure v2 Implementation of WAL Splitting and ACL
 
Tracon
TraconTracon
Tracon
 
Full rack access guide 1
Full rack access guide 1Full rack access guide 1
Full rack access guide 1
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStack
 
Gearmanpresentation 110308165409-phpapp01
Gearmanpresentation 110308165409-phpapp01Gearmanpresentation 110308165409-phpapp01
Gearmanpresentation 110308165409-phpapp01
 
Less09 Data
Less09 DataLess09 Data
Less09 Data
 
Formal Verification of Transactional Interaction Contract
Formal Verification of Transactional Interaction ContractFormal Verification of Transactional Interaction Contract
Formal Verification of Transactional Interaction Contract
 
A short tale about state machine
A short tale about state machineA short tale about state machine
A short tale about state machine
 
Micronaut Webinar 2021 - Process Automation Introduction
Micronaut Webinar 2021 - Process Automation IntroductionMicronaut Webinar 2021 - Process Automation Introduction
Micronaut Webinar 2021 - Process Automation Introduction
 
Taming event-driven software via formal verification
Taming event-driven software via formal verificationTaming event-driven software via formal verification
Taming event-driven software via formal verification
 
Memcache as udp traffic reflector
Memcache as udp traffic reflectorMemcache as udp traffic reflector
Memcache as udp traffic reflector
 
Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...
Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...
Leveraging Natural-language Requirements for Deriving Better Acceptance Crite...
 
BKK16-312 Integrating and controlling embedded devices in LAVA
BKK16-312 Integrating and controlling embedded devices in LAVABKK16-312 Integrating and controlling embedded devices in LAVA
BKK16-312 Integrating and controlling embedded devices in LAVA
 
Debugging varnish
Debugging varnishDebugging varnish
Debugging varnish
 
05 Transactions
05 Transactions05 Transactions
05 Transactions
 

Mehr von Victor Rentea

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Victor Rentea
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
Victor Rentea
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
Victor Rentea
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
Victor Rentea
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
Victor Rentea
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
Victor Rentea
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
Victor Rentea
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
Victor Rentea
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
Victor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
Victor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
Victor Rentea
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
Victor Rentea
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
Victor Rentea
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
Victor Rentea
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
Victor Rentea
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
Victor Rentea
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
Victor Rentea
 

Mehr von Victor Rentea (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
 

Kürzlich hochgeladen

Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Kürzlich hochgeladen (20)

Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

Distributed Consistency.pdf

  • 1. 116 VictorRentea.ro a training by Consistency Pa-erns Maintaining Consistency across distributed systems
  • 2. 117 VictorRentea.ro a training by Either Consistent or Available when Par33oned CAP Theorem
  • 3. 118 VictorRentea.ro a training by 2-Phase-Commit (2PC) 118
  • 4. 119 VictorRentea.ro a training by 1) Vo&ng Phase - All par6cipants no6fy the coordinator if their local transac6on would commit OK 2) Commit Phase: - Coordinator decides to commit if all voted "Yes" or rollback; no6fies all par6cipants §Downsides - Can s6ll fail, requiring recovery steps - Involves locking, doesn't scale well - Not supported by some resources: requires XA drivers, and a JTA coordinator - Requires direct connec6on to remote DB 2-Phase-Commit (2PC) 119
  • 5. 120 VictorRentea.ro a training by Scenario #1 @Entity // in user-api public class User { @Id @GeneratedValue private long id; private String name; private LocalDateTime lastMessageTime; } @Entity // in message-api public class Message { @Id @GeneratedValue private long id; private long userId; private String contents; private LocalDateTime messageTimestamp; }
  • 6. 121 VictorRentea.ro a training by POST message-api/messages ... §Sync call to sync state - PUT user-api/users/{uid}/lastMessageTimestamp - Fragile: What if user-api is down? Retry? For how long? §Async send a message via durable queue (eg. Rabbit) - eg. MessageSentEvent - What if MQ broker is down? è §Avoid synchroniza&on: redesign the service boundaries - GET message-api/lastMessageTimestamp?user={uid} Scenario #1 - Consistency Strategies
  • 7. 122 VictorRentea.ro a training by A call failed or ,med out Let me try again... Is the opera,on IDEMPOTENT? Retry DUP:REMOVE
  • 8. 123 VictorRentea.ro a training by = can be applied many .mes without changing the result. Examples: §Get Product by id via GET ? - ✅ YES: the call does not change any data on the server §Cancel Payment by id via DELETE - ✅ YES: canceling it again has no addi1onal effect §Update Product price by id via PUT - ✅ YES: we would just set the same price again §Place Order { items: [..] } via POST or MQ - ❌ NO if retry would create a second order - ✅ YES, if we deduplicate via lastPlacedOrders = Map<custId, List<orderJsonHash>> (TTL 1h) §Place Order { items: [..], clickId/messageID: UUID } via POST or MQ - ✅ YES if we deduplicate via Set<lastSeenClickIds> §Place Order { id: UUID, items: [..] } via PUT or MQ = Client-generated ID 🤔 - ✅ YES: a duplicate would cause a PK/UK viola1on Idempotent OperaAon In DB: alternate UK, next to numeric PK DUP:REMOVE
  • 9. 124 VictorRentea.ro a training by Update DB and send a Message void f() { mq.send(..); repo.save(..) } @TransacDonal void f() { repo.saveAndFlush(..) mq.send(..); } @TransacDonalEventListener(AFTER_COMMIT) void aOerCommit(..) { mq.send(..); } db.update(data); db.commit; mq.send(message);💥 db.update(data); mq.send(message); db.commit;💥 mq.send(message); db.update(data);💥 db.commit;💥
  • 10. 125 VictorRentea.ro a training by Receive a Message and Update DB If ack is not sent, MQ would retry the message è Listeners should be idempotent SEEN_MESSAGES_IDS db.update(data); mq.ack(message);💥 mq.ack(message); db.update(data);💥
  • 11. 126 VictorRentea.ro a training by TransacAonal Outbox Table Problem: update DB and send message atomically. 2PC is not an opNon. Solu/on: §Instead of sending the message, INSERT it in 'MESSAGES_TO_SEND' table §A scheduler polls this table, sends messages in order and removes them §A form of 'persistent retry' §Can raise alarms if message is delayed too much §:/ Could send duplicate messages
  • 12. 127 VictorRentea.ro a training by TransacAonal Outbox Table ⏱ Change Data Capture (CDC) h"p://debezium.io tails the transac7on log and publishes every change to a Ka<a topic
  • 13. 128 VictorRentea.ro a training by Saga PaJern Problem: Run a business transacNon across mulNple services (separate DB) Solu/on: Saga PaYern §Implement the business transacNon as a sequence of local transacNons §Each local transacNon updates the DB and sends a message (command or event) to trigger the next local transacNon to take place §If a local transacNon fails, the saga executes compensa/ng transac/ons to undo the previously commiYed transacNons §CompensaNng acNons must be retry-able §Use reserva/on (Nmed) for non-reversible steps + confirmaNon/cancel
  • 14. 129 VictorRentea.ro a training by 2-Phase Commit (2PC) DB DB DB DB Orchestrator Sync RPC TransacDon
  • 15. 130 VictorRentea.ro a training by Each party commits then calls next step. On error, each party must call undo on all previously completed steps. ++COUPLING Orchestrator calls all parDes synchronously. On error: orchestrator calls compensaDng 'undo' endpoints for previously completed steps. NOT SCALABLE, FRAGILE Sync Saga Sync RPC TransacDon Orchestrated Choreographed
  • 16. 131 VictorRentea.ro a training by Orchestrated Choreographed Async Saga Orchestrator sends messages to par6es. On error: it sends compensa)ng command messages to previously completed steps Async Message TransacDon Each service commits and sends a message to the next service On error, a party: a) publishes a failure event, listened by all previous par6es (coupling++) b) sends compensa)ng commands to all par6es stamped on message (Rou6ng Slip) c) no6fies a Saga Execu)on Coordinator
  • 17. 132 VictorRentea.ro a training by Image source: https://www.baeldung.com/cs/saga-pattern-microservices
  • 18. 133 VictorRentea.ro a training by §Rou&ng Slip PaAern = Accumulate all previous "undo" ac<ons - Each service appends its own "undo" informa6on to the message sent forward - On any error on received message => call/message all UNDO ac6ons §Error Event upstream - All previous steps undo on LegalCheckFailedEvent{orderId} Choreographed Compensations Stock Payment Legal 1) cancel stock reserva6on 2) undo payment
  • 19. 134 VictorRentea.ro a training by locked state unlocked state push in stack insert coin insert coin push in stack /capture coin Side-effect / Ac6on /release coin External signal ini2al state A state machine reacts to various external signals (inputs) in different ways (outputs), depending on its current state /🤨 /🤨 UML State Diagram:
  • 20. 135 VictorRentea.ro a training by Exercise: Food Delivery App
  • 21. 136 VictorRentea.ro a training by Feed hungry people with food from restaurants delivered by couriers. Assume customer, restaurants and couriers have an app installed. High level flow: 1.hungry customer orders Food FF from Restaurant RR 2.accept card payment via external payment gateway 3.tell RR to cook FF 4.find a courier CC 5.CC picks FF from RR 6.CC delivers food to customer 7.charge a fee to RR for the service Exercise: Food Delivery App
  • 22. 137 VictorRentea.ro a training by Sagas are Hard §Keep hard consistency constraints within the boundary of one service. - (that is, don't distribute) §Manual intervenNon could be cheaper(eg: by 2nd level support) - eg. log.error("[CALL-SUPPORT] Out of stock for order {}", ...); - Implement a Saga to recover from frequent or expensive failures §Use a Saga framework (or learn from it) - Orchestrated: Camunda , Apache Camel - Choreographed: Eventuate. Seata, Axon Saga