SlideShare a Scribd company logo
@crichardson
Using sagas to maintain data
consistency in a microservice
architecture
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
Why 2PC is not an option
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
@crichardson
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
The microservice architecture
structures
an application as a
set of loosely coupled
services
@crichardson
Microservices = modularity
Tackles complexity:
Division of knowledge
Division of labor
* might improve scalability too
@crichardson
Microservices accelerate software
development through parallelization
Customer
Service
Order
Service


Customer
Team
Order
Team


Team
@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
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
Agenda
ACID is not an option
Overview of sagas
Coordinating sagas
@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
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
Sagas complicate the
business logic
Changes are committed by each step of the saga
Other transactions see “inconsistent” data, e.g. Order.state =
PENDING more complex logic
Interaction between sagas and other operations
e.g. 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
@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
Order Service
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
Complex coordination logic is
centralized 😀
@crichardson
Services expose APIs that are
invoked by saga 😄
@crichardson
Order Service
CreateOrderSaga orchestrator
Customer Service
Create Order
Customer
creditLimit
creditReservations
...
Order
state
total

reserveCredit()
CreateOrderSaga
OrderService
create()
create()
approve()
creditReserved()
@crichardson
Saga orchestrators are state
machines
RESERVING
CREDIT
APPROVED
REJECTED
/ customerService.
reserveCredit()
credit reserved
/ order.approve()
credit limit exceed
/ order.reject()
event [guard] / action
Initial action
reply and action
@crichardson
Create Order Saga code
Enum Persistent data
Stateless singleton: Behavior
Eventuate Saga framework
State
@crichardson
Create Order Saga
State machine deïŹnition
Specify reply handlers
@crichardson
Initializing the saga
Invoke saga participant
Initialize state
Create order
@crichardson
Handling a reply
Change state
Update Order
@crichardson
Customer Service - command
handling
Reserve credit
@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
@crichardson
Create Order Saga messaging
Order Service
Message Broker
Customer Service
Begin TXN
Read data
Send reply
Commit TXN
Credit Reserved
Credit Limit Exceeded
Create Order
Saga
Orchestrator
reserve credit
Customer Service
Request Channel
Customer Service
Reply Channel
Order
create()
approve()
reject()
Commands
Replies
@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?

More Related Content

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

What's hot (20)

PDF
#JaxLondon keynote: Developing applications with a microservice architecture
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
PDF
OReilly SACON2018 - Events on the outside, on the inside, and at the core
PDF
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
PDF
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
PDF
Developing microservices with aggregates (melbourne)
PDF
A Pattern Language for Microservices (@futurestack)
PDF
Designing loosely coupled services
PDF
Futures and Rx Observables: powerful abstractions for consuming web services ...
PDF
Spring Days NYC - A pattern language for microservices
PDF
Kong Summit 2018 - Microservices: decomposing applications for testability an...
PDF
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
PDF
YOW! Perth: Cubes, Hexagons, Triangles, and More: Understanding the Microserv...
PDF
Oracle CodeOne 2019: Decompose Your Monolith: Strategies for Migrating to Mic...
PDF
A Pattern Language for Microservices
PDF
Events on the outside, on the inside and at the core (jfokus jfokus2016)
PDF
SVCC Developing Asynchronous, Message-Driven Microservices
PDF
Oracle CodeOne 2019: Descending the Testing Pyramid: Effective Testing Strate...
PDF
Events to the rescue: solving distributed data problems in a microservice arc...
PDF
Developing event-driven microservices with event sourcing and CQRS (london Ja...
#JaxLondon keynote: Developing applications with a microservice architecture
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
OReilly SACON2018 - Events on the outside, on the inside, and at the core
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
Developing microservices with aggregates (melbourne)
A Pattern Language for Microservices (@futurestack)
Designing loosely coupled services
Futures and Rx Observables: powerful abstractions for consuming web services ...
Spring Days NYC - A pattern language for microservices
Kong Summit 2018 - Microservices: decomposing applications for testability an...
Decompose that WAR? A pattern language for microservices (@QCON @QCONSP)
YOW! Perth: Cubes, Hexagons, Triangles, and More: Understanding the Microserv...
Oracle CodeOne 2019: Decompose Your Monolith: Strategies for Migrating to Mic...
A Pattern Language for Microservices
Events on the outside, on the inside and at the core (jfokus jfokus2016)
SVCC Developing Asynchronous, Message-Driven Microservices
Oracle CodeOne 2019: Descending the Testing Pyramid: Effective Testing Strate...
Events to the rescue: solving distributed data problems in a microservice arc...
Developing event-driven microservices with event sourcing and CQRS (london Ja...
Ad

Similar to Gluecon: Using sagas to maintain data consistency in a microservice architecture (20)

PDF
microXchg: Managing data consistency in a microservice architecture using Sagas
PDF
Saturn 2018: Managing data consistency in a microservice architecture using S...
PDF
MicroCPH - Managing data consistency in a microservice architecture using Sagas
PDF
Solving distributed data management problems in a microservice architecture (...
PDF
Mucon: Not Just Events: Developing Asynchronous Microservices
PDF
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
PDF
YOW2018 - Events and Commands: Developing Asynchronous Microservices
PDF
Microservices + Events + Docker = A Perfect Trio by Docker Captain Chris Rich...
PDF
More the merrier: a microservices anti-pattern
PDF
Developing event-driven microservices with event sourcing and CQRS (Shanghai)
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
PDF
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
PDF
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
PDF
Building microservices with Scala, functional domain models and Spring Boot (...
PDF
Developing Event-driven Microservices with Event Sourcing & CQRS (gotoams)
PDF
Dark energy, dark matter and microservice architecture collaboration patterns
PDF
Developing microservices with aggregates (devnexus2017)
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
PDF
Building microservices with Scala, functional domain models and Spring Boot
PDF
Developing microservices with aggregates (SpringOne platform, #s1p)
microXchg: Managing data consistency in a microservice architecture using Sagas
Saturn 2018: Managing data consistency in a microservice architecture using S...
MicroCPH - Managing data consistency in a microservice architecture using Sagas
Solving distributed data management problems in a microservice architecture (...
Mucon: Not Just Events: Developing Asynchronous Microservices
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
YOW2018 - Events and Commands: Developing Asynchronous Microservices
Microservices + Events + Docker = A Perfect Trio by Docker Captain Chris Rich...
More the merrier: a microservices anti-pattern
Developing event-driven microservices with event sourcing and CQRS (Shanghai)
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Building microservices with Scala, functional domain models and Spring Boot (...
Developing Event-driven Microservices with Event Sourcing & CQRS (gotoams)
Dark energy, dark matter and microservice architecture collaboration patterns
Developing microservices with aggregates (devnexus2017)
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
Building microservices with Scala, functional domain models and Spring Boot
Developing microservices with aggregates (SpringOne platform, #s1p)
Ad

More from Chris Richardson (18)

PDF
The microservice architecture: what, why, when and how?
PDF
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
PDF
Dark Energy, Dark Matter and the Microservices 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
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?
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
Dark Energy, Dark Matter and the Microservices 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...
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
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Transform Your Business with a Software ERP System
PPTX
ai tools demonstartion for schools and inter college
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
AI in Product Development-omnex systems
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Introduction to Artificial Intelligence
PDF
System and Network Administration Chapter 2
PDF
Understanding Forklifts - TECH EHS Solution
PDF
medical staffing services at VALiNTRY
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
PTS Company Brochure 2025 (1).pdf.......
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Transform Your Business with a Software ERP System
ai tools demonstartion for schools and inter college
How to Migrate SBCGlobal Email to Yahoo Easily
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
Online Work Permit System for Fast Permit Processing
Upgrade and Innovation Strategies for SAP ERP Customers
AI in Product Development-omnex systems
Wondershare Filmora 15 Crack With Activation Key [2025
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Introduction to Artificial Intelligence
System and Network Administration Chapter 2
Understanding Forklifts - TECH EHS Solution
medical staffing services at VALiNTRY
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
CHAPTER 2 - PM Management and IT Context
PTS Company Brochure 2025 (1).pdf.......

Gluecon: Using sagas to maintain data consistency in a microservice architecture