SlideShare a Scribd company logo
@crichardson
Managing data consistency in a
microservice architecture using
Sagas
Chris Richardson
Founder of eventuate.io
Author of Microservices Patterns
Founder of the original CloudFoundry.com
Author of POJOs in Action
@crichardson
chris@chrisrichardson.net
http://eventuate.io http://learn.microservices.io
@crichardson
Presentation goal
Distributed data management challenges
in a microservice architecture
Sagas as the transaction model
@crichardson
About Chris
@crichardson
About Chris
Consultant and trainer
focusing on modern
application architectures
including microservices
(http://www.chrisrichardson.net/)
@crichardson
About Chris
Founder of a startup that is creating
an open-source/SaaS platform
that simplifies the development of
transactional microservices
(http://eventuate.io)
@crichardson
For more information
http://learn.microservices.io
40% off
ctwmicroxchg18
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
Countermeasures for data anomalies
The microservice architecture
structures
an application as a
set of loosely coupled
services
@crichardson
Microservices enable
continuous delivery/deployment
Process:
Continuous delivery/deployment
Organization:
Small, agile, autonomous,
cross functional teams
Architecture:
Microservice architecture
Enables
Enables
Enables
Successful
Software
Development
Services
=
testability
and
deployability
Teams own services
@crichardson
Microservice architecture
Browser
Mobile
Device
Store
Front UI
API
Gateway
Customer
Service
Order
Service
…
Service
Customer
Database
Order
Database
…
Database
HTML
REST
REST
Database per service
@crichardson
Private database
!=
private database server
@crichardson
Loose coupling =
encapsulated data
Order Service Customer Service
Order Database Customer Database
Order table
Customer
table
orderTotal creditLimit
@crichardson
How to maintain data
consistency?!?!?
Invariant:
sum(open order.total) <= customer.creditLimit
@crichardson
Cannot use ACID transactions
that span services
BEGIN TRANSACTION
…
SELECT ORDER_TOTAL
FROM ORDERS WHERE CUSTOMER_ID = ?
…
SELECT CREDIT_LIMIT
FROM CUSTOMERS WHERE CUSTOMER_ID = ?
…
INSERT INTO ORDERS …
…
COMMIT TRANSACTION
Private to the
Order Service
Private to the
Customer Service
Distributed transactions
@crichardson
2PC is not an option
Guarantees consistency
BUT
2PC coordinator is a single point of failure
Chatty: at least O(4n) messages, with retries O(n^2)
Reduced throughput due to locks
Not supported by many NoSQL databases (or message brokers)
CAP theorem 2PC impacts availability
….
@crichardson
Basically
Available
Soft state
Eventually consistent
http://queue.acm.org/detail.cfm?id=1394128
ACID
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
Countermeasures for data anomalies
@crichardson
From a 1987 paper
@crichardson
Saga
Use Sagas instead of 2PC
Distributed transaction
Service A Service B
Service A
Local
transaction
Service B
Local
transaction
Service C
Local
transaction
X Service C
@crichardson
Saga step = a transaction
local to a service
Service
Database Message Broker
update publish message/event
Transactional DB: BEGIN … COMMIT
DDD: Aggregate
NoSQL: single ‘record’
How to
make atomic
without 2PC?
@crichardson
Order Service
Create Order Saga
Local transaction
Order
state=PENDING
createOrder()
Customer Service
Local transaction
Customer
reserveCredit()
Order Service
Local transaction
Order
state=APPROVED
approve
order()
createOrder() Initiates saga
@crichardson
But what about rollback?
BEGIN TRANSACTION
…
UPDATE …
…
INSERT ….
…
…. BUSINESS RULE VIOLATED!!!!
…
ROLLBACK TRANSACTION
Really simple!
@crichardson
Rolling back sagas
Use compensating transactions
Developer must write application logic to “rollback” eventually
consistent transactions
Careful design required!
@crichardson
Saga: Every Ti has a Ci
T1 T2 …
C1 C2
Compensating transactions
T1 T2 C1
FAILS
@crichardson
Order Service
Create Order Saga - rollback
Local transaction
Order
createOrder()
Customer Service
Local transaction
Customer
reserveCredit()
Order Service
Local transaction
Order
reject
order()
createOrder()
FAIL
Insufficient credit
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
Countermeasures for data anomalies
@crichardson
How to sequence the saga
transactions?
After the completion of transaction Ti “something” must
decide what step to execute next
Success: which T(i+1) - branching
Failure: C(i - 1)
@crichardson
Choreography: distributed decision making
vs.
Orchestration: centralized decision making
@crichardson
Option #1: Choreography-based
coordination using events
Order
Service
Customer
Service
Order created
Credit Reserved
Credit Limit Exceeded
Create Order
OR
Customer
creditLimit
creditReservations
Order
state
total
create()
reserveCredit()
approve()/
reject()
Order events channel
Customer events channel
@crichardson
Order Service: publishing
domain events
Publish event
@crichardson
Customer Service: consuming
domain events
https://github.com/eventuate-tram/eventuate-tram-examples-customers-and-orders
Subscribe to event
Benefits and drawbacks of
choreography
Benefits
Simple, especially when
using event sourcing
Participants are loosely
coupled
Drawbacks
Cyclic dependencies -
services listen to each
other’s events
Overloads domain objects,
e.g. Order and Customer
know too much
Events = indirect way to
make something happen
https://github.com/eventuate-examples/eventuate-examples-java-customers-and-orders
@crichardson
Order Service
Option #2: Orchestration-based saga
coordination
Local transaction
Order
state=PENDING
createOrder()
Customer Service
Local transaction
Customer
reserveCredit()
Order Service
Local transaction
Order
state=APPROVED
approve
order()
createOrder()
CreateOrderSaga
InvokesInvokesInvokes
@crichardson
A saga (orchestrator)
is a persistent object
that
tracks the state of the saga
and
invokes the participants
Saga behavior
On create:
Invokes a saga
participant
Wait for a reply
On reply:
Determine which saga
participant to invoke next
Invokes saga participant
Updates its state
Wait for a reply
…
@crichardson
Order Service
CreateOrderSaga orchestrator
Customer Service
Create Order
Customer
creditLimit
creditReservations
...
Order
state
total…
reserveCredit()
CreateOrder
Saga
OrderService
create()
create()
approve()
creditReserved()
@crichardson
CreateOrderSaga definition
Sequence of
steps
step = (Ti, Ci)
Build command
to send
Saga’s Data
@crichardson
Customer Service command
handler Route command
to handler
Reserve
credit
Make reply message
@crichardson
Eventuate Tram Sagas
Open-source Saga orchestration framework
Currently for Java
https://github.com/eventuate-tram/eventuate-tram-sagas
https://github.com/eventuate-tram/eventuate-tram-sagas-
examples-customers-and-orders
@crichardson
Use asynchronous messaging
Ensures sagas complete when
participants are temporarily unavailable
@crichardson
Create Order Saga -
messaging
Order Service
Create
Order
Saga
Message
Broker
Customer
Service
Customer
Reserve
Credit
Reserve
Credit
Reply
Customer Request
Channel
Saga Reply
Channel
Order Request
Channel
Approve
Order
Benefits and drawbacks of
orchestration
Benefits
Centralized coordination
logic is easier to understand
Reduced coupling, e.g.
Customer knows less
Reduces cyclic
dependencies
Drawbacks
Risk of smart sagas
directing dumb services
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
Countermeasures for data anomalies
@crichardson
Lack of isolation complicates business
logic
Order Service
Local transaction
Order
state=PENDING
createOrder()
Customer Service
Local transaction
Customer
reserveCredit()
Order Service
Local transaction
cancelOrder()
?
Time
@crichardson
How to cancel a PENDING
Order?
Don’t throw an OrderNotCancellableException
Questionable user experience
“Interrupt” the Create Order saga?
Cancel Order Saga: set order.state = CANCELLED
Causes Create Order Saga to rollback
But is that enough to cancel the order?
Cancel Order saga waits for the Create Order saga to complete?
Suspiciously like a distributed lock
But perhaps that is ok
@crichardson
Countermeasure Transaction
Model
http://bit.ly/semantic-acid-ctm - paywall 😥
@crichardson
Sagas are ACD
Atomicity
Saga implementation ensures that all transactions are
executed OR all are compensated
Consistency
Referential integrity within a service handled by local databases
Referential integrity across services handled by application
Durability
Durability handled by local databases
@crichardson
Lack of I anomalies
@crichardson
Anomaly: Lost update
Ti: Create
Order
Tj: Approve
Order
Ti: Cancel
Order
Saga 1
Saga 2
Time
Overwrites
cancelled order
@crichardson
Anomaly: Dirty reads
Ti: Reserve
Credit
Ci: Unreserve
credit
Ti: Reserve
Credit
Reads
uncommitted
changes
Saga 1
Saga 2
Order rejected unnecessarily OR Credit limit exceeded
Time
@crichardson
Anomaly: non-repeatable/
fuzzy read
Ti: Begin
Revise Order
Tj: Finalize
Revise Order
Ti: Update
Order
Time
Order has changed
since Ti
Saga 1
Saga 2
@crichardson
Countermeasures for
reducing impact
of isolation anomalies…
*
i.e. good enough, eventually consistent application
Saga structure
T1 C1
…
T2 C2
Tn+1
Tn+2
….
Compensatable transactions
Pivot transaction = GO/NO GO
Retriable transactions that can’t fail
Countermeasure: Semantic
lock
Compensatable transaction sets flag,
retriable transaction releases it
Indicates a possible dirty read
Flag = lock:
prevents other transactions from
accessing it
Require deadlock detection, e.g.
timeout
Flag = warning - treat the data
differently, e.g.
Order.state = PENDING
a pending deposit
… …
…
Approve Order
Create Pending
Order
Reject Order
Order.state =
PENDING
Order.state =
REJECTED
Order.state =
APPROVED
@crichardson
Countermeasure:
Commutative updates
Commutative: g(f(x)) = f(g(x))
For example:
Account.debit() compensates for Account.credit()
Account.credit() compensates for Account.debit()
Avoids lost updates
@crichardson
Countermeasure: Pessimistic
view
Increase avail.
credit
Reduce avail.
credit
Cancel Order Delivery
Cancel Order
Reorder saga
to
reduce risk
Cancel Order Delivery
Cancel Order
Increase avail. credit
… …… …
Won’t be compensated,
so no dirty read
@crichardson
Countermeasure: Re-read
value
Ti: Read
Order
Tj: Re-read, then
update Order
Ti: Update
Order
Time
Saga 1
Saga 2
Verify unchanged, possibly restart
Prevents lost update
~Offline optimistic lock pattern
@crichardson
Countermeasure: version file
Ti: Create
Order
Tj: Authorize
Credit Card
Ti: Cancel
Order
Time
Saga 1
Saga 2
Tj: Reserve
Credit
Tj: Reverse
Credit Card
Payment
1. reverse()
2. authorize()
“log” of changes:
Enables operations to commute
@crichardson
Countermeasure: By value
Business risk determines strategy
Low risk => semantic ACID
High risk => use 2PC/distributed transaction
@crichardson
Summary
Microservices tackle complexity and accelerate development
Database per service is essential for loose coupling
Use orchestration-based or choreography-based sagas to
maintain data consistency across services
Use countermeasures to reduce impact of anomalies caused
by lack of isolation
@crichardson
@crichardson chris@chrisrichardson.net
http://learn.microservices.io
Questions?
40% off
ctwmicroxchg18

More Related Content

PDF
There is no such thing as a microservice! (oracle code nyc)
PDF
QCONSF - ACID Is So Yesterday: Maintaining Data Consistency with Sagas
PDF
YOW! Perth: Cubes, Hexagons, Triangles, and More: Understanding the Microserv...
PDF
Omnikron webbinar - Microservices: enabling the rapid, frequent, and reliable...
PDF
Kong Summit 2018 - Microservices: decomposing applications for testability an...
PDF
Mucon: Not Just Events: Developing Asynchronous Microservices
PDF
Spring Days NYC - A pattern language for microservices
PDF
MicroCPH - Managing data consistency in a microservice architecture using Sagas
There is no such thing as a microservice! (oracle code nyc)
QCONSF - ACID Is So Yesterday: Maintaining Data Consistency with Sagas
YOW! Perth: Cubes, Hexagons, Triangles, and More: Understanding the Microserv...
Omnikron webbinar - Microservices: enabling the rapid, frequent, and reliable...
Kong Summit 2018 - Microservices: decomposing applications for testability an...
Mucon: Not Just Events: Developing Asynchronous Microservices
Spring Days NYC - A pattern language for microservices
MicroCPH - Managing data consistency in a microservice architecture using Sagas

What's hot (20)

PDF
Oracle CodeOne 2019: Descending the Testing Pyramid: Effective Testing Strate...
PDF
Saturn2017: No such thing as a microservice!
PDF
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
PDF
SVCC Developing Asynchronous, Message-Driven Microservices
PDF
Oracle Code Sydney - There is no such thing as a microservice!
PDF
Oracle Code One: Events and commands: developing asynchronous microservices
PDF
Solving distributed data management problems in a microservice architecture (...
PDF
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
PDF
ArchSummit Shenzhen - Using sagas to maintain data consistency in a microserv...
PDF
Events to the rescue: solving distributed data problems in a microservice arc...
PDF
YOW2018 - Events and Commands: Developing Asynchronous Microservices
PDF
A Pattern Language for Microservices
PDF
Gluecon: Using sagas to maintain data consistency in a microservice architecture
PDF
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
PDF
OReilly SACON2018 - Events on the outside, on the inside, and at the core
PDF
Oracle CodeOne 2019: Decompose Your Monolith: Strategies for Migrating to Mic...
PDF
Designing loosely coupled services
PDF
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
PDF
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
PDF
Developing microservices with aggregates (melbourne)
Oracle CodeOne 2019: Descending the Testing Pyramid: Effective Testing Strate...
Saturn2017: No such thing as a microservice!
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
SVCC Developing Asynchronous, Message-Driven Microservices
Oracle Code Sydney - There is no such thing as a microservice!
Oracle Code One: Events and commands: developing asynchronous microservices
Solving distributed data management problems in a microservice architecture (...
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
ArchSummit Shenzhen - Using sagas to maintain data consistency in a microserv...
Events to the rescue: solving distributed data problems in a microservice arc...
YOW2018 - Events and Commands: Developing Asynchronous Microservices
A Pattern Language for Microservices
Gluecon: Using sagas to maintain data consistency in a microservice architecture
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
OReilly SACON2018 - Events on the outside, on the inside, and at the core
Oracle CodeOne 2019: Decompose Your Monolith: Strategies for Migrating to Mic...
Designing loosely coupled services
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Developing microservices with aggregates (melbourne)
Ad

Similar to microXchg: Managing data consistency in a microservice architecture using Sagas (20)

PDF
Saturn 2018: Managing data consistency in a microservice architecture using S...
PDF
Saga transactions msa_ architecture
PPTX
Saga about distributed business transactions in microservices world
PPTX
Journey of saga pattern in microservice architecture
KEY
Dropping ACID - Building Scalable Systems That Work
PDF
Introducing Saga Pattern in Microservices with Spring Statemachine
PPTX
Event Driven Microservices architecture
PDF
MuleSoft Nashik Virtual Meetup#2 - API Led Connectivity Integration:SAGA
PPTX
Microservices Coordination using Saga
PDF
Lost in transaction - Strategies to deal with (in)consistency in distributed ...
PDF
Developing microservices with aggregates (devnexus2017)
PDF
DDD Europe 2019: Lost in transaction
PPTX
Distributed data management challenges
PDF
2019 03-13-implementing microservices by ddd
ODP
Distributed Transactions: Saga Patterns
PDF
Event Storming and Saga
PPTX
Saga pattern
PDF
Developing microservices with aggregates (SpringOne platform, #s1p)
PDF
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
PDF
Microservice
Saturn 2018: Managing data consistency in a microservice architecture using S...
Saga transactions msa_ architecture
Saga about distributed business transactions in microservices world
Journey of saga pattern in microservice architecture
Dropping ACID - Building Scalable Systems That Work
Introducing Saga Pattern in Microservices with Spring Statemachine
Event Driven Microservices architecture
MuleSoft Nashik Virtual Meetup#2 - API Led Connectivity Integration:SAGA
Microservices Coordination using Saga
Lost in transaction - Strategies to deal with (in)consistency in distributed ...
Developing microservices with aggregates (devnexus2017)
DDD Europe 2019: Lost in transaction
Distributed data management challenges
2019 03-13-implementing microservices by ddd
Distributed Transactions: Saga Patterns
Event Storming and Saga
Saga pattern
Developing microservices with aggregates (SpringOne platform, #s1p)
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
Microservice
Ad

More from Chris Richardson (19)

PDF
The microservice architecture: what, why, when and how?
PDF
More the merrier: a microservices anti-pattern
PDF
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
PDF
Dark Energy, Dark Matter and the Microservices Patterns?!
PDF
Dark energy, dark matter and microservice architecture collaboration patterns
PDF
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
PDF
Using patterns and pattern languages to make better architectural decisions
PDF
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
PDF
A pattern language for microservices - June 2021
PDF
Microservices - an architecture that enables DevOps (T Systems DevOps day)
PDF
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
PDF
Decompose your monolith: Six principles for refactoring a monolith to microse...
PDF
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
PDF
Overview of the Eventuate Tram Customers and Orders application
PDF
An overview of the Eventuate Platform
PDF
#DevNexus202 Decompose your monolith
PDF
JFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
PDF
Decompose your monolith: strategies for migrating to microservices (Tide)
PDF
Melbourne Jan 2019 - Microservices adoption anti-patterns: Obstacles to decom...
The microservice architecture: what, why, when and how?
More the merrier: a microservices anti-pattern
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
Dark Energy, Dark Matter and the Microservices Patterns?!
Dark energy, dark matter and microservice architecture collaboration patterns
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
Using patterns and pattern languages to make better architectural decisions
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
A pattern language for microservices - June 2021
Microservices - an architecture that enables DevOps (T Systems DevOps day)
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
Decompose your monolith: Six principles for refactoring a monolith to microse...
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
Overview of the Eventuate Tram Customers and Orders application
An overview of the Eventuate Platform
#DevNexus202 Decompose your monolith
JFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
Decompose your monolith: strategies for migrating to microservices (Tide)
Melbourne Jan 2019 - Microservices adoption anti-patterns: Obstacles to decom...

Recently uploaded (20)

PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Introduction to Artificial Intelligence
PPTX
ai tools demonstartion for schools and inter college
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Digital Strategies for Manufacturing Companies
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PTS Company Brochure 2025 (1).pdf.......
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
How to Choose the Right IT Partner for Your Business in Malaysia
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Navsoft: AI-Powered Business Solutions & Custom Software Development
Design an Analysis of Algorithms I-SECS-1021-03
Introduction to Artificial Intelligence
ai tools demonstartion for schools and inter college
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Operating system designcfffgfgggggggvggggggggg
VVF-Customer-Presentation2025-Ver1.9.pptx
Digital Strategies for Manufacturing Companies
2025 Textile ERP Trends: SAP, Odoo & Oracle
Odoo Companies in India – Driving Business Transformation.pdf
How Creative Agencies Leverage Project Management Software.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus

microXchg: Managing data consistency in a microservice architecture using Sagas