SlideShare a Scribd company logo
@crichardson
ACID Is So Yesterday:
Maintaining Data Consistency
with Sagas
Chris Richardson
Founder of Eventuate.io
Founder of the original CloudFoundry.com
Author of POJOs in Action
@crichardson
chris@chrisrichardson.net
http://eventuate.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 simpliïŹes the development of
transactional microservices
(http://eventuate.io)
@crichardson
For more information
http://learnmicroservices.io
ctwjavaone17
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
Sagas and inter-service communication
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
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
Sagas and inter-service communication
@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
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()
@crichardson
If only it were this easy

@crichardson
Rollback using compensating
transactions
ACID transactions can simply rollback
BUT
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
InsufïŹcient credit
@crichardson
Sagas complicate API design
Synchronous API vs Asynchronous Saga
Request initiates the saga. When to send back the response?
Option #1: Send response when saga completes:
+ Response speciïŹes the outcome
- Reduced availability
Option #2: Send response immediately after creating the saga
(recommended):
+ Improved availability
- Response does not specify the outcome. Client must poll or be notiïŹed
@crichardson
Revised Create Order API
createOrder()
returns id of newly created order
NOT fully validated
getOrder(id)
Called periodically by client to get outcome of validation
@crichardson
Minimal impact on UI
UI hides asynchronous API from the user
Saga will usually appear instantaneous (<= 100ms)
If it takes longer UI displays “processing” popup
Server can push notiïŹcation to UI
@crichardson
Interwoven sagas complicate
business logic
Order Service
Local transaction
Order
state=PENDING
createOrder()
Customer Service
Local transaction
Customer
reserveCredit()
Order Service
Local transaction
cancelOrder()
?
@crichardson
How handle interwoven
sagas?
What does it mean to cancel a PENDING Order?
“Interrupt” the Create Order saga?
Wait for the Create Order saga to complete?
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
Sagas and inter-service communication
@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()
BeneïŹts and drawbacks of
choreography
BeneïŹts
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
@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
@crichardson
A saga (orchestrator)
is a persistent object
that
tracks the state of the saga
and
invokes the participants
@crichardson
Saga behavior
On create:
Invokes a saga participant
On reply:
Determine which saga participant to invoke next
Invokes saga participant
Updates its state


@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 deïŹnition
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
Coming next week to
https://github.com/eventuate-tram
BeneïŹts and drawbacks of
orchestration
BeneïŹts
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
Sagas and inter-service communication
@crichardson
Saga
Participant
About Saga orchestrator
participant communication
Saga
Orchestrator
Saga
Participant
command
reply
Saga must complete even if there are transient failures
@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
Customer
Request
Channel
Saga Reply
Channel
Reserve
Credit
Reserve
Credit
Reply
@crichardson
Messaging must be
transactional
Service
Database Message Broker
update publish
How to
make atomic
without 2PC?
@crichardson
Option #1: Use database
table as a message queue
ACID
transaction
See BASE: An Acid Alternative, http://bit.ly/ebaybase
DELETE
Customer
Service
ORDER_ID CUSTOMER_ID TOTAL
99
CUSTOMER_CREDIT_RESERVATIONS table
101 1234
ID TYPE DATA DESTINATION
MESSAGE table
84784 OrderCreated {
} 

INSERT INSERT
Message
Publisher
QUERY
Message
Broker
Publish
Local transaction
?
@crichardson
Publishing messages
Poll the MESSAGE table
OR
Tail the database transaction log
@crichardson
Option #2: Event sourcing:
event-centric persistence
Service
Event Store
save events
and
publish
Event table
Entity type
Event
id
Entity
id
Event
data
Order 902101 
OrderApproved
Order 903101 
OrderShipped
Event
type
Order 901101 
OrderCreated
Every state change event
@crichardson
Summary
Microservices tackle complexity and accelerate development
Database per service is essential for loose coupling
Use sagas to maintain data consistency across services
Use transactional messaging to make sagas reliable
@crichardson
@crichardson chris@chrisrichardson.net
http://learnmicroservices.io
Questions? ctwjavaone17

More Related Content

PDF
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
PDF
Omnikron webbinar - Microservices: enabling the rapid, frequent, and reliable...
PDF
There is no such thing as a microservice! (oracle code nyc)
PDF
Gluecon: Using sagas to maintain data consistency in a microservice architecture
PDF
Developing microservices with aggregates (melbourne)
PDF
QCONSF - ACID Is So Yesterday: Maintaining Data Consistency with Sagas
PDF
ArchSummit Shenzhen - Using sagas to maintain data consistency in a microserv...
PDF
Microservices + Events + Docker = A Perfect Trio (dockercon)
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Omnikron webbinar - Microservices: enabling the rapid, frequent, and reliable...
There is no such thing as a microservice! (oracle code nyc)
Gluecon: Using sagas to maintain data consistency in a microservice architecture
Developing microservices with aggregates (melbourne)
QCONSF - ACID Is So Yesterday: Maintaining Data Consistency with Sagas
ArchSummit Shenzhen - Using sagas to maintain data consistency in a microserv...
Microservices + Events + Docker = A Perfect Trio (dockercon)

What's hot (20)

PDF
microXchg: Managing data consistency in a microservice architecture using Sagas
PDF
A Pattern Language for Microservices (@futurestack)
PDF
Microservices in Java and Scala (sfscala)
PDF
Oracle Code One: Events and commands: developing asynchronous microservices
PDF
OReilly SACON2018 - Events on the outside, on the inside, and at the core
PDF
#JaxLondon keynote: Developing applications with a microservice architecture
PDF
NodeJS: the good parts? A skeptic’s view (jax jax2013)
PDF
Mucon: Not Just Events: Developing Asynchronous Microservices
PDF
Spring Days NYC - A pattern language for microservices
PDF
Kong Summit 2018 - Microservices: decomposing applications for testability an...
PDF
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
PDF
Developing event-driven microservices with event sourcing and CQRS (london Ja...
PDF
Microservices and Redis #redisconf Keynote
PDF
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
PDF
YOW! Perth: Cubes, Hexagons, Triangles, and More: Understanding the Microserv...
PDF
SVCC Developing Asynchronous, Message-Driven Microservices
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
PDF
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
PDF
Events to the rescue: solving distributed data problems in a microservice arc...
microXchg: Managing data consistency in a microservice architecture using Sagas
A Pattern Language for Microservices (@futurestack)
Microservices in Java and Scala (sfscala)
Oracle Code One: Events and commands: developing asynchronous microservices
OReilly SACON2018 - Events on the outside, on the inside, and at the core
#JaxLondon keynote: Developing applications with a microservice architecture
NodeJS: the good parts? A skeptic’s view (jax jax2013)
Mucon: Not Just Events: Developing Asynchronous Microservices
Spring Days NYC - A pattern language for microservices
Kong Summit 2018 - Microservices: decomposing applications for testability an...
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
Developing event-driven microservices with event sourcing and CQRS (london Ja...
Microservices and Redis #redisconf Keynote
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
YOW! Perth: Cubes, Hexagons, Triangles, and More: Understanding the Microserv...
SVCC Developing Asynchronous, Message-Driven Microservices
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
Events to the rescue: solving distributed data problems in a microservice arc...
Ad

Viewers also liked (20)

PDF
Event Storming and Saga
PDF
CQRS and Event Sourcing
PDF
Exception handling & logging in Java - Best Practices (Updated)
PPTX
DDD架構蚭蚈
PPTX
Building Secure User Interfaces With JWTs (JSON Web Tokens)
PDF
Nanoservices and Microservices with Java
PPTX
Token Based Authentication Systems with AngularJS & NodeJS
PPTX
Performance Testing for Scalable Microservices - Martin Kulov
PDF
Building Scalable Micro-services with Nodejs
PDF
Cloud Native Camel Design Patterns
PDF
Culture craft humantalks
PDF
A Pattern Language for Microservices
PPTX
Windows Containers and Docker: Why You Should Care
PDF
Faible latence haut debit Devoxx FR 2014
PPTX
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
PDF
Faible latence, haut debit PerfUG (Septembre 2014)
PDF
Coder sans peur du changement avec la meme pas mal hexagonal architecture
PDF
TDD is dead?!? Let's do an autospy (ncrafts.io)
PDF
.NET Inside - Microservices, .NET Core e Serverless
PDF
Sortir de notre zone de confort
Event Storming and Saga
CQRS and Event Sourcing
Exception handling & logging in Java - Best Practices (Updated)
DDD架構蚭蚈
Building Secure User Interfaces With JWTs (JSON Web Tokens)
Nanoservices and Microservices with Java
Token Based Authentication Systems with AngularJS & NodeJS
Performance Testing for Scalable Microservices - Martin Kulov
Building Scalable Micro-services with Nodejs
Cloud Native Camel Design Patterns
Culture craft humantalks
A Pattern Language for Microservices
Windows Containers and Docker: Why You Should Care
Faible latence haut debit Devoxx FR 2014
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
Faible latence, haut debit PerfUG (Septembre 2014)
Coder sans peur du changement avec la meme pas mal hexagonal architecture
TDD is dead?!? Let's do an autospy (ncrafts.io)
.NET Inside - Microservices, .NET Core e Serverless
Sortir de notre zone de confort
Ad

Similar to JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas (20)

PDF
Saturn 2018: Managing data consistency in a microservice architecture using S...
PDF
MicroCPH - Managing data consistency in a microservice architecture using Sagas
PDF
YOW2018 - Events and Commands: Developing Asynchronous Microservices
PDF
Solving distributed data management problems in a microservice architecture (...
PDF
Saga transactions msa_ architecture
PPTX
Saga about distributed business transactions in microservices world
PDF
MuleSoft Nashik Virtual Meetup#2 - API Led Connectivity Integration:SAGA
PPTX
Microservices Coordination using Saga
KEY
Dropping ACID - Building Scalable Systems That Work
PPTX
Event Driven Microservices architecture
PDF
Lost in transaction - Strategies to deal with (in)consistency in distributed ...
PDF
Overview of the Eventuate Tram Customers and Orders application
PDF
DDD Europe 2019: Lost in transaction
PPTX
Event Driven Architecture
PDF
Microservice
PDF
Introducing Saga Pattern in Microservices with Spring Statemachine
PDF
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
PPTX
Journey of saga pattern in microservice architecture
PPTX
“Controlling of messages flow in Microservices architecture” by Andris Lubans...
PDF
2019 03-13-implementing microservices by ddd
Saturn 2018: Managing data consistency in a microservice architecture using S...
MicroCPH - Managing data consistency in a microservice architecture using Sagas
YOW2018 - Events and Commands: Developing Asynchronous Microservices
Solving distributed data management problems in a microservice architecture (...
Saga transactions msa_ architecture
Saga about distributed business transactions in microservices world
MuleSoft Nashik Virtual Meetup#2 - API Led Connectivity Integration:SAGA
Microservices Coordination using Saga
Dropping ACID - Building Scalable Systems That Work
Event Driven Microservices architecture
Lost in transaction - Strategies to deal with (in)consistency in distributed ...
Overview of the Eventuate Tram Customers and Orders application
DDD Europe 2019: Lost in transaction
Event Driven Architecture
Microservice
Introducing Saga Pattern in Microservices with Spring Statemachine
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
Journey of saga pattern in microservice architecture
“Controlling of messages flow in Microservices architecture” by Andris Lubans...
2019 03-13-implementing microservices by ddd

More from Chris Richardson (20)

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
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
PDF
Designing loosely coupled services
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
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
Oracle CodeOne 2019: Descending the Testing Pyramid: Effective Testing Strate...
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
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Designing loosely coupled services
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...
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)
Oracle CodeOne 2019: Descending the Testing Pyramid: Effective Testing Strate...

Recently uploaded (20)

PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
top salesforce developer skills in 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Introduction to Artificial Intelligence
PDF
medical staffing services at VALiNTRY
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Transform Your Business with a Software ERP System
PDF
System and Network Administration Chapter 2
PDF
Digital Strategies for Manufacturing Companies
PDF
Nekopoi APK 2025 free lastest update
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
L1 - Introduction to python Backend.pptx
PDF
AI in Product Development-omnex systems
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Odoo POS Development Services by CandidRoot Solutions
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
ManageIQ - Sprint 268 Review - Slide Deck
top salesforce developer skills in 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Introduction to Artificial Intelligence
medical staffing services at VALiNTRY
How to Choose the Right IT Partner for Your Business in Malaysia
Odoo Companies in India – Driving Business Transformation.pdf
How Creative Agencies Leverage Project Management Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Transform Your Business with a Software ERP System
System and Network Administration Chapter 2
Digital Strategies for Manufacturing Companies
Nekopoi APK 2025 free lastest update
How to Migrate SBCGlobal Email to Yahoo Easily
L1 - Introduction to python Backend.pptx
AI in Product Development-omnex systems
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
Odoo POS Development Services by CandidRoot Solutions

JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas