SlideShare a Scribd company logo
@crichardson
Events and Commands:
Developing Asynchronous
Microservices
Chris Richardson
Founder of Eventuate.io
Founder of the original CloudFoundry.com
Author of POJOs in Action and Microservices Patterns
@crichardson
chris@chrisrichardson.net
http://learn.microservices.io
Copyright © 2018 Chris Richardson Consulting, Inc. All rights reserved
@crichardson
Presentation goal
Implementing transactions and
queries in a microservice
architecture using
asynchronous messaging
@crichardson
Presentation goal
Microservices > REST
Microservices > Events
Microservices != Event Sourcing
Apache Kafka != Event Store
@crichardson
About Chris
microservices.io eventuate.io
@crichardson
About Chris
https://microservices.io/book
@crichardson
Agenda
Transactions, queries and microservices
Managing transactions with sagas
Implementing queries with CQRS
Implementing transactional messaging
The microservice architecture
structures
an application as a
set of loosely coupled
services
@crichardson
API
Service = independently deployable
component
Operations
Event
Publisher
Commands
Queries
Synchronous
REST/gRPC
Asynchronous
Messaging
Events
Event
Subscriber
API
Client
Invokes
Operations
Events
Service
Database
@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
Let’s imagine that you are
building an online store API
createCustomer(creditLimit)
createOrder(customerId, orderTotal)
findOrdersForCustomer(customerId)
findRecentCustomers()
Order
Management
Customer
Management
REST API
…
@crichardson
Order
Service
createCustomer()
createOrder()
findOrdersForCustomer()
findRecentCustomers()
API Gateway
createCustomer()
createOrder()
Order DatabaseCustomer Database
Order tableCustomer table
REST API
REST API
Essential for loose
coupling
Must reserve
customer’s credit
Retrieve data
from both
services
Customer
Service
REST API
availableCredit
….
orderTotal
….
@crichardson
No 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
Querying across services is
not straightforward
SELECT *
FROM CUSTOMER c, ORDER o
WHERE
c.id = o.ID
AND c.id = ?
Private to Customer
Service
Private to Order
Service
Find customer and their orders
@crichardson
Agenda
Transactions, queries and microservices
Managing transactions with sagas
Implementing queries with CQRS
Implementing transactional messaging
@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
https://microservices.io/patterns/data/saga.html
@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
Saga design challenges
API design
Synchronous REST API initiates asynchronous saga
When to send back a response?
Rollback compensating transactions
Sagas are ACD - No I
Sagas are interleaved anomalies, such as lost updates
Must use countermeasures
https://www.slideshare.net/chris.e.richardson/saturn-2018-managing-data-consistency-in-a-microservice-architecture-using-sagas
How do the saga participants
communicate?
Synchronous
communication, e.g. REST
= temporal coupling
Client and server need to
be both available
Customer Service fails
retry provided it’s
idempotent
Order Service fails Oops
Order
Service
createOrder()
REST
Customer
Service
reserveCredit()
REST
@crichardson
Collaboration using asynchronous,
broker-based messaging
Order Service
Customer
Service
….
Message broker
@crichardson
About the message broker
At least once delivery
Ensures a saga completes when its participants are temporarily
unavailable
Ordered delivery
Mechanism for scaling consumers that preserves ordering e.g.
Apache Kafka consumer group
ActiveMQ message group
…
@crichardson
Saga step = a transaction
local to a service
Service
Database Message Broker
update publish message/event
How to
make atomic
without 2PC?
@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
Transactions, queries and microservices
Managing transactions with sagas
Implementing queries with CQRS
Implementing transactional messaging
Overview
Choreography
Orchestration
Agenda
@crichardson
Message broker
Choreography-based Create Order
Saga
Order created
Credit Reserved
Credit Limit Exceeded
Create Order
OR
Customer
availableCredit
...
Order
state
total
create()
reserveCredit()
approve()/
reject()
Order events channel
Customer events channel
Order
Service
Customer
Service
Benefits and drawbacks of
choreography
Benefits
Simple, especially when using event
sourcing
Participants are loosely coupled
Drawbacks
Decentralized implementation -
potentially difficult to understand
Cyclic dependencies - services listen
to each other’s events, e.g.
Customer Service must know about
all Order events that affect credit
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
Agenda
Transactions, queries and microservices
Managing transactions with sagas
Implementing queries with CQRS
Implementing transactional messaging
Overview
Choreography
Orchestration
@crichardson
Order Service
Orchestration-based coordination using
command messages
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
implements a state machine
and
invokes the participants
Saga orchestrator behavior
On create:
Invokes a saga participant
Persists state in database
Wait for a reply
On reply:
Load state from database
Determine which saga
participant to invoke next
Invokes saga participant
Updates its state
Persists updated 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()
Credit Reserved
Customer command channel
Saga reply channel
https://github.com/eventuate-tram/eventuate-tram-sagas-examples-customers-and-orders
Benefits and drawbacks of
orchestration
Benefits
Centralized coordination
logic is easier to understand
Reduced coupling, e.g.
Customer Service knows
less. Simply has API for
managing available credit.
Reduces cyclic
dependencies
Drawbacks
Risk of smart sagas
directing dumb services
@crichardson
Agenda
Transactions, queries and microservices
Managing transactions with sagas
Implementing queries with CQRS
Implementing transactional messaging
@crichardson
Queries often retrieve data
owned by multiple services
@crichardson
API Composition pattern
Customer Service
Customer
…
Order Service
Order
…
API Gateway
findOrdersForCustomer(customerId)
GET /customer/id GET /orders?customerId=id
https://microservices.io/patterns/data/api-composition.html
@crichardson
Find recent, valuable
customers
SELECT *
FROM CUSTOMER c, ORDER o
WHERE
c.id = o.ID
AND o.ORDER_TOTAL > 100000
AND o.STATE = 'SHIPPED'
AND c.CREATION_DATE > ?
Customer
Service
Order Service
…. is even more difficult!
API Composition would be
inefficient
1 + N strategy:
Fetch recent customers
Iterate through customers
fetching their shipped
orders
Lots of round trips
high-latency
Alternative strategy:
Fetch recent customers
Fetch recent orders
Join
2 roundtrips but
potentially large datasets
inefficient
@crichardson
Using events to update a queryable
replica = CQRS
Order
Service
Customer
Service
Order events
Customer events
findCustomersAndOrders()
Order events channel
Customer events channel
Customer
Order
View
Service
Replica
View
Database
https://microservices.io/patterns/data/cqrs.html
@crichardson
Persisting a customer and
order history in MongoDB
{
"_id" : "0000014f9a45004b 0a00270000000000",
"name" : "Fred",
"creditLimit" : {
"amount" : "2000"
},
"orders" : {
"0000014f9a450063 0a00270000000000" : {
"state" : "APPROVED",
"orderId" : "0000014f9a450063 0a00270000000000",
"orderTotal" : {
"amount" : "1234"
}
},
"0000014f9a450063 0a00270000000001" : {
"state" : "REJECTED",
"orderId" : "0000014f9a450063 0a00270000000001",
"orderTotal" : {
"amount" : "3000"
}
}
}
}
Denormalized = efficient lookup
Customer
information
Order
information
@crichardson
Query side data model
Command Query Responsibility
Segregation (CQRS)
Command side data model
Commands
Aggregate
Message broker or Event Store
Events
Queries
(Materialized)
View
Events
POST
PUT
DELETE
GET
@crichardson
Queries database (type)
Command side
POST
PUT
DELETE
Aggregate
Event Store/Message Broker
Events
Query side
GET /customers/id
MongoDB
Query side
GET /orders?text=xyz
ElasticSearch
Query side
GET …
Neo4j
@crichardson
CQRS views are disposable
Rebuild when needed from source of truth
Using event sourcing
(Conceptually) replay all events from beginning of time
Using traditional persistence
“ETL” from source of truth databases
@crichardson
Handling replication lag
Lag between updating command side and CQRS view
Risk of showing stale data to user
Either:
Update UI/client-side model without querying
Use updated aggregate version to “wait” for query view to
be updated
@crichardson
Agenda
Transactions, queries and microservices
Managing transactions with sagas
Implementing queries with CQRS
Implementing transactional messaging
@crichardson
Messaging must be
transactional
Service
Database Message Broker
update publish
How to
make atomic
without 2PC?
Publish to message broker
first?
Guarantees atomicity
BUT
Service can’t read its own
writes
Difficult to write business
logic
Service
Database
Message Broker
update
publish
@crichardson
Option: Event sourcing
=
Event centric approach to
business logic and persistence
http://eventuate.io/
@crichardson
Event sourcing: persists an object
as a sequence of events
Event table
Entity type
Event
id
Entity
id
Event
data
Order 902101 …OrderApproved
Order 903101 …OrderShipped
Event
type
Order 901101 …OrderCreated
Order
create()
approve()
ship()
Event Store
@crichardson
Replay events to recreate in memory state
Order
state
apply(event)
Event table
Entity type
Event
id
Entity
id
Event
data
Order 902101 …OrderApproved
Order 903101 …OrderShipped
Event
type
Order 901101 …OrderCreated
Event Store
Load events by ID and call apply()
Instantiate with
default
constructor
Event store =
database
@crichardson
FYI:
Apache Kafka != event store
@crichardson
Event sourcing guarantees: state
change event is published
Event table
Entity type
Event
id
Entity
id
Event
data
Order 902101 …OrderApproved
Order 903101 …OrderShipped
Event
type
Order 901101 …OrderCreated
Event Store
Customer
Service
Subscribe
Event store =
message broker
@crichardson
Preserves history of domain objects
Supports temporal queries
Simplifies retroactive correction
Built-in auditing
Other benefits of event sourcing
@crichardson
Unfamiliar programming model
Evolving the schema of long-lived events
Event store only supports PK-based access
requires CQRS less consistent reads
Drawbacks of event sourcing
@crichardson
Good fit for choreography-based sagas
BUT orchestration is more challenging
Use event handler to translate event
into command/reply message
Drawbacks of event sourcing
@crichardson
Option:
Traditional persistence
(JPA, MyBatis,…)
+
Transactional outbox pattern
https://github.com/eventuate-tram/eventuate-tram-core
@crichardson
Spring Data for JPA example
Publish event
Save order
http://eventuate.io/exampleapps.html
@crichardson
Transactional outbox pattern
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 CreditReserved {…} …
INSERT INSERT
Message
Publisher
QUERY
Message
Broker
Publish
Local transaction
reserveCredit()
DomainEventPublisher
@crichardson
Transaction log tailing
Order
Service
Datastore
ORDER table
Transaction log
Update
Transaction log
miner
Message
Broker
Publish
Changes
MySQL binlog
Postgres WAL
AWS DynamoDB table streams
MongoDB change streams
http://eventuate.io/
@crichardson
Polling the message table
Simple
Works for all databases
BUT what about polling frequency
MESSAGE
Table
Message
Publisher
Message
Broker
SELECT * FROM MESSAGE…
UPDATE MESSAGE
@crichardson
Summary
Use asynchronous messaging to solve distributed data management problems
Services publish events to implement
choreography-based sagas
queries using CQRS views
Services send command/reply messages to implement orchestration-based
sagas
Services must atomically update state and send messages
Event sourcing
Transactional outbox
@crichardson
@crichardson chris@chrisrichardson.net
http://learn.microservices.io
Questions?

More Related Content

What's hot (20)

PDF
Introducing Saga Pattern in Microservices with Spring Statemachine
VMware Tanzu
 
PDF
Best Practices for Streaming IoT Data with MQTT and Apache Kafka
Kai Wähner
 
PDF
Escaping Dependency Hell: A deep dive into Gradle's dependency management fea...
Roberto Pérez Alcolea
 
KEY
Event Driven Architecture
Stefan Norberg
 
PPTX
Microservices
SmartBear
 
PPTX
Microservice vs. Monolithic Architecture
Paul Mooney
 
PDF
Microservice architecture
Žilvinas Kuusas
 
PPTX
Introduction to microservices
Anil Allewar
 
PPSX
Big Data Redis Mongodb Dynamodb Sharding
Araf Karsh Hamid
 
PPSX
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Araf Karsh Hamid
 
PPSX
Microservices, Containers, Kubernetes, Kafka, Kanban
Araf Karsh Hamid
 
PDF
30분만에 만드는 AWS 기반 빅데이터 분석 애플리케이션::안효빈::AWS Summit Seoul 2018
Amazon Web Services Korea
 
PDF
Chaos Engineering - The Art of Breaking Things in Production
Keet Sugathadasa
 
PPTX
Stability Patterns for Microservices
pflueras
 
PPSX
Cloud Architecture - Multi Cloud, Edge, On-Premise
Araf Karsh Hamid
 
PDF
Scalability, Availability & Stability Patterns
Jonas Bonér
 
PDF
Building Event-driven Architectures with Amazon EventBridge
James Beswick
 
PPTX
Introduction to Microservices
MahmoudZidan41
 
PPSX
Event Sourcing & CQRS, Kafka, Rabbit MQ
Araf Karsh Hamid
 
PPTX
Modern Enterprise integration Strategies
Jesus Rodriguez
 
Introducing Saga Pattern in Microservices with Spring Statemachine
VMware Tanzu
 
Best Practices for Streaming IoT Data with MQTT and Apache Kafka
Kai Wähner
 
Escaping Dependency Hell: A deep dive into Gradle's dependency management fea...
Roberto Pérez Alcolea
 
Event Driven Architecture
Stefan Norberg
 
Microservices
SmartBear
 
Microservice vs. Monolithic Architecture
Paul Mooney
 
Microservice architecture
Žilvinas Kuusas
 
Introduction to microservices
Anil Allewar
 
Big Data Redis Mongodb Dynamodb Sharding
Araf Karsh Hamid
 
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Araf Karsh Hamid
 
Microservices, Containers, Kubernetes, Kafka, Kanban
Araf Karsh Hamid
 
30분만에 만드는 AWS 기반 빅데이터 분석 애플리케이션::안효빈::AWS Summit Seoul 2018
Amazon Web Services Korea
 
Chaos Engineering - The Art of Breaking Things in Production
Keet Sugathadasa
 
Stability Patterns for Microservices
pflueras
 
Cloud Architecture - Multi Cloud, Edge, On-Premise
Araf Karsh Hamid
 
Scalability, Availability & Stability Patterns
Jonas Bonér
 
Building Event-driven Architectures with Amazon EventBridge
James Beswick
 
Introduction to Microservices
MahmoudZidan41
 
Event Sourcing & CQRS, Kafka, Rabbit MQ
Araf Karsh Hamid
 
Modern Enterprise integration Strategies
Jesus Rodriguez
 

Similar to YOW2018 - Events and Commands: Developing Asynchronous Microservices (20)

PDF
Oracle Code One: Events and commands: developing asynchronous microservices
Chris Richardson
 
PDF
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
Chris Richardson
 
PDF
Mucon: Not Just Events: Developing Asynchronous Microservices
Chris Richardson
 
PDF
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
Chris Richardson
 
PDF
Events to the rescue: solving distributed data problems in a microservice arc...
Chris Richardson
 
PDF
Solving distributed data management problems in a microservice architecture (...
Chris Richardson
 
PPTX
Event Driven Microservices architecture
NikhilBarthwal4
 
PDF
Gluecon: Using sagas to maintain data consistency in a microservice architecture
Chris Richardson
 
PDF
ArchSummit Shenzhen - Using sagas to maintain data consistency in a microserv...
Chris Richardson
 
PDF
microXchg: Managing data consistency in a microservice architecture using Sagas
Chris Richardson
 
PDF
MicroCPH - Managing data consistency in a microservice architecture using Sagas
Chris Richardson
 
PDF
Overview of the Eventuate Tram Customers and Orders application
Chris Richardson
 
PDF
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JSFestUA
 
PDF
Saga transactions msa_ architecture
Mauro Vocale
 
PDF
QCONSF - ACID Is So Yesterday: Maintaining Data Consistency with Sagas
Chris Richardson
 
PDF
Microservice
Viney Shih
 
PDF
Melbourne Jan 2019 - Microservices adoption anti-patterns: Obstacles to decom...
Chris Richardson
 
PPTX
Saga about distributed business transactions in microservices world
Mikalai Alimenkou
 
PDF
Events and microservices
Saul Caganoff
 
PDF
Komunikacja oparta o eventy w architekturze mikroserwisowej
The Software House
 
Oracle Code One: Events and commands: developing asynchronous microservices
Chris Richardson
 
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
Chris Richardson
 
Mucon: Not Just Events: Developing Asynchronous Microservices
Chris Richardson
 
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
Chris Richardson
 
Events to the rescue: solving distributed data problems in a microservice arc...
Chris Richardson
 
Solving distributed data management problems in a microservice architecture (...
Chris Richardson
 
Event Driven Microservices architecture
NikhilBarthwal4
 
Gluecon: Using sagas to maintain data consistency in a microservice architecture
Chris Richardson
 
ArchSummit Shenzhen - Using sagas to maintain data consistency in a microserv...
Chris Richardson
 
microXchg: Managing data consistency in a microservice architecture using Sagas
Chris Richardson
 
MicroCPH - Managing data consistency in a microservice architecture using Sagas
Chris Richardson
 
Overview of the Eventuate Tram Customers and Orders application
Chris Richardson
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JSFestUA
 
Saga transactions msa_ architecture
Mauro Vocale
 
QCONSF - ACID Is So Yesterday: Maintaining Data Consistency with Sagas
Chris Richardson
 
Microservice
Viney Shih
 
Melbourne Jan 2019 - Microservices adoption anti-patterns: Obstacles to decom...
Chris Richardson
 
Saga about distributed business transactions in microservices world
Mikalai Alimenkou
 
Events and microservices
Saul Caganoff
 
Komunikacja oparta o eventy w architekturze mikroserwisowej
The Software House
 
Ad

More from Chris Richardson (20)

PDF
The microservice architecture: what, why, when and how?
Chris Richardson
 
PDF
More the merrier: a microservices anti-pattern
Chris Richardson
 
PDF
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
Chris Richardson
 
PDF
Dark Energy, Dark Matter and the Microservices Patterns?!
Chris Richardson
 
PDF
Dark energy, dark matter and microservice architecture collaboration patterns
Chris Richardson
 
PDF
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
Chris Richardson
 
PDF
Using patterns and pattern languages to make better architectural decisions
Chris Richardson
 
PDF
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
Chris Richardson
 
PDF
A pattern language for microservices - June 2021
Chris Richardson
 
PDF
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
Chris Richardson
 
PDF
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Chris Richardson
 
PDF
Designing loosely coupled services
Chris Richardson
 
PDF
Microservices - an architecture that enables DevOps (T Systems DevOps day)
Chris Richardson
 
PDF
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
Chris Richardson
 
PDF
Decompose your monolith: Six principles for refactoring a monolith to microse...
Chris Richardson
 
PDF
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
Chris Richardson
 
PDF
An overview of the Eventuate Platform
Chris Richardson
 
PDF
#DevNexus202 Decompose your monolith
Chris Richardson
 
PDF
JFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
Chris Richardson
 
PDF
Decompose your monolith: strategies for migrating to microservices (Tide)
Chris Richardson
 
The microservice architecture: what, why, when and how?
Chris Richardson
 
More the merrier: a microservices anti-pattern
Chris Richardson
 
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
Chris Richardson
 
Dark Energy, Dark Matter and the Microservices Patterns?!
Chris Richardson
 
Dark energy, dark matter and microservice architecture collaboration patterns
Chris Richardson
 
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
Chris Richardson
 
Using patterns and pattern languages to make better architectural decisions
Chris Richardson
 
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
Chris Richardson
 
A pattern language for microservices - June 2021
Chris Richardson
 
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
Chris Richardson
 
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Chris Richardson
 
Designing loosely coupled services
Chris Richardson
 
Microservices - an architecture that enables DevOps (T Systems DevOps day)
Chris Richardson
 
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
Chris Richardson
 
Decompose your monolith: Six principles for refactoring a monolith to microse...
Chris Richardson
 
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
Chris Richardson
 
An overview of the Eventuate Platform
Chris Richardson
 
#DevNexus202 Decompose your monolith
Chris Richardson
 
JFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
Chris Richardson
 
Decompose your monolith: strategies for migrating to microservices (Tide)
Chris Richardson
 
Ad

Recently uploaded (20)

PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 

YOW2018 - Events and Commands: Developing Asynchronous Microservices

  • 1. @crichardson Events and Commands: Developing Asynchronous Microservices Chris Richardson Founder of Eventuate.io Founder of the original CloudFoundry.com Author of POJOs in Action and Microservices Patterns @crichardson [email protected] http://learn.microservices.io Copyright © 2018 Chris Richardson Consulting, Inc. All rights reserved
  • 2. @crichardson Presentation goal Implementing transactions and queries in a microservice architecture using asynchronous messaging
  • 3. @crichardson Presentation goal Microservices > REST Microservices > Events Microservices != Event Sourcing Apache Kafka != Event Store
  • 6. @crichardson Agenda Transactions, queries and microservices Managing transactions with sagas Implementing queries with CQRS Implementing transactional messaging
  • 7. The microservice architecture structures an application as a set of loosely coupled services
  • 8. @crichardson API Service = independently deployable component Operations Event Publisher Commands Queries Synchronous REST/gRPC Asynchronous Messaging Events Event Subscriber API Client Invokes Operations Events Service Database
  • 9. @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
  • 10. @crichardson Let’s imagine that you are building an online store API createCustomer(creditLimit) createOrder(customerId, orderTotal) findOrdersForCustomer(customerId) findRecentCustomers() Order Management Customer Management REST API …
  • 11. @crichardson Order Service createCustomer() createOrder() findOrdersForCustomer() findRecentCustomers() API Gateway createCustomer() createOrder() Order DatabaseCustomer Database Order tableCustomer table REST API REST API Essential for loose coupling Must reserve customer’s credit Retrieve data from both services Customer Service REST API availableCredit …. orderTotal ….
  • 12. @crichardson No 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
  • 13. @crichardson Querying across services is not straightforward SELECT * FROM CUSTOMER c, ORDER o WHERE c.id = o.ID AND c.id = ? Private to Customer Service Private to Order Service Find customer and their orders
  • 14. @crichardson Agenda Transactions, queries and microservices Managing transactions with sagas Implementing queries with CQRS Implementing transactional messaging
  • 16. @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 https://microservices.io/patterns/data/saga.html
  • 17. @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
  • 18. @crichardson Saga design challenges API design Synchronous REST API initiates asynchronous saga When to send back a response? Rollback compensating transactions Sagas are ACD - No I Sagas are interleaved anomalies, such as lost updates Must use countermeasures https://www.slideshare.net/chris.e.richardson/saturn-2018-managing-data-consistency-in-a-microservice-architecture-using-sagas
  • 19. How do the saga participants communicate? Synchronous communication, e.g. REST = temporal coupling Client and server need to be both available Customer Service fails retry provided it’s idempotent Order Service fails Oops Order Service createOrder() REST Customer Service reserveCredit() REST
  • 20. @crichardson Collaboration using asynchronous, broker-based messaging Order Service Customer Service …. Message broker
  • 21. @crichardson About the message broker At least once delivery Ensures a saga completes when its participants are temporarily unavailable Ordered delivery Mechanism for scaling consumers that preserves ordering e.g. Apache Kafka consumer group ActiveMQ message group …
  • 22. @crichardson Saga step = a transaction local to a service Service Database Message Broker update publish message/event How to make atomic without 2PC?
  • 23. @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)
  • 24. @crichardson Choreography: distributed decision making vs. Orchestration: centralized decision making
  • 25. @crichardson Transactions, queries and microservices Managing transactions with sagas Implementing queries with CQRS Implementing transactional messaging Overview Choreography Orchestration Agenda
  • 26. @crichardson Message broker Choreography-based Create Order Saga Order created Credit Reserved Credit Limit Exceeded Create Order OR Customer availableCredit ... Order state total create() reserveCredit() approve()/ reject() Order events channel Customer events channel Order Service Customer Service
  • 27. Benefits and drawbacks of choreography Benefits Simple, especially when using event sourcing Participants are loosely coupled Drawbacks Decentralized implementation - potentially difficult to understand Cyclic dependencies - services listen to each other’s events, e.g. Customer Service must know about all Order events that affect credit 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
  • 28. @crichardson Agenda Transactions, queries and microservices Managing transactions with sagas Implementing queries with CQRS Implementing transactional messaging Overview Choreography Orchestration
  • 29. @crichardson Order Service Orchestration-based coordination using command messages Local transaction Order state=PENDING createOrder() Customer Service Local transaction Customer reserveCredit() Order Service Local transaction Order state=APPROVED approve order() createOrder() CreateOrderSaga InvokesInvokesInvokes
  • 30. @crichardson A saga (orchestrator) is a persistent object that implements a state machine and invokes the participants
  • 31. Saga orchestrator behavior On create: Invokes a saga participant Persists state in database Wait for a reply On reply: Load state from database Determine which saga participant to invoke next Invokes saga participant Updates its state Persists updated state Wait for a reply …
  • 32. @crichardson Order Service CreateOrderSaga orchestrator Customer Service Create Order Customer creditLimit creditReservations ... Order state total… reserveCredit CreateOrder Saga OrderService create() create() approve() Credit Reserved Customer command channel Saga reply channel https://github.com/eventuate-tram/eventuate-tram-sagas-examples-customers-and-orders
  • 33. Benefits and drawbacks of orchestration Benefits Centralized coordination logic is easier to understand Reduced coupling, e.g. Customer Service knows less. Simply has API for managing available credit. Reduces cyclic dependencies Drawbacks Risk of smart sagas directing dumb services
  • 34. @crichardson Agenda Transactions, queries and microservices Managing transactions with sagas Implementing queries with CQRS Implementing transactional messaging
  • 35. @crichardson Queries often retrieve data owned by multiple services
  • 36. @crichardson API Composition pattern Customer Service Customer … Order Service Order … API Gateway findOrdersForCustomer(customerId) GET /customer/id GET /orders?customerId=id https://microservices.io/patterns/data/api-composition.html
  • 37. @crichardson Find recent, valuable customers SELECT * FROM CUSTOMER c, ORDER o WHERE c.id = o.ID AND o.ORDER_TOTAL > 100000 AND o.STATE = 'SHIPPED' AND c.CREATION_DATE > ? Customer Service Order Service …. is even more difficult!
  • 38. API Composition would be inefficient 1 + N strategy: Fetch recent customers Iterate through customers fetching their shipped orders Lots of round trips high-latency Alternative strategy: Fetch recent customers Fetch recent orders Join 2 roundtrips but potentially large datasets inefficient
  • 39. @crichardson Using events to update a queryable replica = CQRS Order Service Customer Service Order events Customer events findCustomersAndOrders() Order events channel Customer events channel Customer Order View Service Replica View Database https://microservices.io/patterns/data/cqrs.html
  • 40. @crichardson Persisting a customer and order history in MongoDB { "_id" : "0000014f9a45004b 0a00270000000000", "name" : "Fred", "creditLimit" : { "amount" : "2000" }, "orders" : { "0000014f9a450063 0a00270000000000" : { "state" : "APPROVED", "orderId" : "0000014f9a450063 0a00270000000000", "orderTotal" : { "amount" : "1234" } }, "0000014f9a450063 0a00270000000001" : { "state" : "REJECTED", "orderId" : "0000014f9a450063 0a00270000000001", "orderTotal" : { "amount" : "3000" } } } } Denormalized = efficient lookup Customer information Order information
  • 41. @crichardson Query side data model Command Query Responsibility Segregation (CQRS) Command side data model Commands Aggregate Message broker or Event Store Events Queries (Materialized) View Events POST PUT DELETE GET
  • 42. @crichardson Queries database (type) Command side POST PUT DELETE Aggregate Event Store/Message Broker Events Query side GET /customers/id MongoDB Query side GET /orders?text=xyz ElasticSearch Query side GET … Neo4j
  • 43. @crichardson CQRS views are disposable Rebuild when needed from source of truth Using event sourcing (Conceptually) replay all events from beginning of time Using traditional persistence “ETL” from source of truth databases
  • 44. @crichardson Handling replication lag Lag between updating command side and CQRS view Risk of showing stale data to user Either: Update UI/client-side model without querying Use updated aggregate version to “wait” for query view to be updated
  • 45. @crichardson Agenda Transactions, queries and microservices Managing transactions with sagas Implementing queries with CQRS Implementing transactional messaging
  • 46. @crichardson Messaging must be transactional Service Database Message Broker update publish How to make atomic without 2PC?
  • 47. Publish to message broker first? Guarantees atomicity BUT Service can’t read its own writes Difficult to write business logic Service Database Message Broker update publish
  • 48. @crichardson Option: Event sourcing = Event centric approach to business logic and persistence http://eventuate.io/
  • 49. @crichardson Event sourcing: persists an object as a sequence of events Event table Entity type Event id Entity id Event data Order 902101 …OrderApproved Order 903101 …OrderShipped Event type Order 901101 …OrderCreated Order create() approve() ship() Event Store
  • 50. @crichardson Replay events to recreate in memory state Order state apply(event) Event table Entity type Event id Entity id Event data Order 902101 …OrderApproved Order 903101 …OrderShipped Event type Order 901101 …OrderCreated Event Store Load events by ID and call apply() Instantiate with default constructor Event store = database
  • 52. @crichardson Event sourcing guarantees: state change event is published Event table Entity type Event id Entity id Event data Order 902101 …OrderApproved Order 903101 …OrderShipped Event type Order 901101 …OrderCreated Event Store Customer Service Subscribe Event store = message broker
  • 53. @crichardson Preserves history of domain objects Supports temporal queries Simplifies retroactive correction Built-in auditing Other benefits of event sourcing
  • 54. @crichardson Unfamiliar programming model Evolving the schema of long-lived events Event store only supports PK-based access requires CQRS less consistent reads Drawbacks of event sourcing
  • 55. @crichardson Good fit for choreography-based sagas BUT orchestration is more challenging Use event handler to translate event into command/reply message Drawbacks of event sourcing
  • 56. @crichardson Option: Traditional persistence (JPA, MyBatis,…) + Transactional outbox pattern https://github.com/eventuate-tram/eventuate-tram-core
  • 57. @crichardson Spring Data for JPA example Publish event Save order http://eventuate.io/exampleapps.html
  • 58. @crichardson Transactional outbox pattern 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 CreditReserved {…} … INSERT INSERT Message Publisher QUERY Message Broker Publish Local transaction reserveCredit() DomainEventPublisher
  • 59. @crichardson Transaction log tailing Order Service Datastore ORDER table Transaction log Update Transaction log miner Message Broker Publish Changes MySQL binlog Postgres WAL AWS DynamoDB table streams MongoDB change streams http://eventuate.io/
  • 60. @crichardson Polling the message table Simple Works for all databases BUT what about polling frequency MESSAGE Table Message Publisher Message Broker SELECT * FROM MESSAGE… UPDATE MESSAGE
  • 61. @crichardson Summary Use asynchronous messaging to solve distributed data management problems Services publish events to implement choreography-based sagas queries using CQRS views Services send command/reply messages to implement orchestration-based sagas Services must atomically update state and send messages Event sourcing Transactional outbox