SlideShare a Scribd company logo
Unless otherwise indicated, these slides are © 2013-2015 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/
SPRINGONE2GX
WASHINGTON, DC
Building Microservices with Event
Sourcing and CQRS
Michael Ploed - innoQ
@bitboss
IncidentSOAPEndpoint
IncidentBusinessService
IncidentDAO
Incident
Business
Model
Client
Incident

DTO
Incident

View

Model
RDBMS
Incident

ER-Model
Network
Network
Let’s review the
classical old
school N-Tier
architecture
Characteristics
1
We read and write data
through the same layers
IncidentSOAPEndpoint
IncidentBusinessService
IncidentDAO
Incident
Business Model
Client
Incident

DTO
Incident

View

Model
RDBMS
Incident

ER-Model
Network
Network
READ
WRITE
2
We use the same model

for read and write
access
IncidentSOAPEndpoint
IncidentBusinessService
IncidentDAO
Incident
Business Model
Client
Incident

DTO
Incident

View

Model
RDBMS
Incident

ER-Model
Network
Network
3
We use coarse grained
deployment units that
combine read and write
code
IncidentSOAPEndpoint
IncidentBusinessService
IncidentDAO
Client
RDBMS
4
We change datasets
directly
IncidentRestController
IncidentBusinessService
IncidentDAO
Incident
ID USER_ID DATE TEXT
1 23423 11.03.2014 Mouse is broken
2 67454 12.03.2014 EMail not working
3 93729 12.03.2014 Office license
… … … …
We’ve done that
for ages already and
it’s proven
Many applications will
run smooth and fine
with this kind of
approach
However there are
drawbacks to this kind
of architecture
1 The data model is a compromise
2 You can’t scale read and write independently
3 No data history, no snapshots, no replay
4 Tendency to a monolithic approach
Event Sourcing is an
architectural pattern in
which the state of the
application is being
determined by a
sequence of events
Building Blocks
Applications
Event
Queue
Applications issues
events to a queue
Event
Handler
Event
Store
Events are stored in
the event store
The Event handler is
processing the events
The sequence of events in the queue
is called event stream
t
now
EventEventEventEventEvent
IncidentCreatedEvent



incidentNumber: 1

userNumber: 23423
timestamp: 11.03.2014 12:23:23

text: „Mouse broken“
status: „open“
Event Stream Example
IncidentTextChangedEvent



incidentNumber: 1

text: „Left button of mouse broken“
IncidentClosedEvent



incidentNumber: 1

solution: „Mouse replaced“
status: „closed“
An event is something 

that happened in the past
t
now
EventEventEventEventEvent
The names of the events are part
of the

Ubiquitous Language
D D D
ShipmentDeliveredEvent

CustomerVerifiedEvent
CartCheckedOutEvent
CreateCustomerEvent

WillSaveItemEvent

DoStuffEvent
Code Example
public class CustomerVerifiedEvent {
private String eventId;
private Date eventDate;
private CustomerNumber customerNumber;
private String comment;
public CustomerVerifiedEvent(CustomerNumber custNum, 

String comment) {

this.customerNumber = cusNum;
this.comment = comment;
this.eventDate = new Date();
}
}
Scope your events based on

Aggregates
D D D
An Event is always immutable
!
There is no deletion of events
!
A delete is
just another
event
IncidentCreatedEvent



incidentNumber: 1

userNumber: 23423
timestamp: 11.03.2014 12:23:23

text: „Mouse is broken defekt“
status: „open“
IncidentChangedEvent



incidentNumber: 1

text: „Maus ist Kaputt“
IncidentRemovedEvent



incidentNumber: 1

The event bus is usually
implemented by a message
broker
t
now
EventEventEventEventEvent
Let’s reuse the ESB
from the failed SOA
project
NO
NO
NO
!
Prefer dumb pipes
with smart
endpoints as a
suitable message
broker architecture
1 Complete rebuild is possible
2 Temporal Queries
3 Event Replay
Well known examples
=

Version Control Systems

or
Database Transaction Logs
The Event
Store has a
very high
business value
Aren’t there performance
issues attached to this kind of
data storage?
YES!
Application
State
Think about application state
Application
Event
Queue
Event
Handler
Event
Store
Application
State
The application queries the
pre-processed application
state
CQRS
Command
Query
Responsibility
Separation
IncidentSOAPEndpoint
IncidentBusinessService
IncidentDAO
Incident
Business
Model
Client
Incident

DTO
Incident

View

Model
RDBMS
Incident

ER-Model
Network
Network
IncidentQueryEndpoint
IncidentQueryService
IncidentQueryDAO
RDBMS
Network
IncidentCommandEndpoint
IncidentCommandService
IncidentCommandDAO
Basically the idea behind CQRS is simple
Code Example
Classic Interface
public interface IncidentManagementService {
Incident saveIncident(Incident i);
void updateIncident(Incident i);
List<Incident> retrieveBySeverity(Severity s);
Incident retriveById(Long id);
}
CQRS-ified Interfaces
public interface IncidentManagementQueryService {
List<Incident> retrieveBySeverity(Severity s);
Incident retriveById(Long id);
}
public interface IncidentManagementCommandService {
Incident saveIncident(Incident i);
void updateIncident(Incident i);
}
Event Store
EventHandler EventsEvents
Event Sourcing & CQRS
IncidentCommandEndpoint
IncidentCommandService
IncidentCommandDAO
IncidentQueryEndpoint
IncidentQueryService
IncidentQueryDAO
Read Storage
Events
READ
1 Individual scalability and deployment
options
2
Technological freedom of choice for
command, query and event handler
code
3 Excellent Fit for Bounded Context
(Domain Driven Design)
Event Sourcing and CQRS
are interesting architectural
options. However there are
various challanges, that have
to be taken care of
1 Consistency
2 Validation
3 Parallel Updates
YES
!
Systems based on
CQRS and Event
Sourcing are
mostly eventually
consistent
Event Store
EventHandler EventsEvents
Eventual Consistency
IncidentCommandEndpoint
IncidentCommandService
IncidentCommandDAO
IncidentQueryEndpoint
IncidentQueryService
IncidentQueryDAO
Read Storage
Events
READ
BUT
!
You can build a 

fully consistent
system which
follows Event
Sourcing
principles
EventHandler
EventsEvents
Full Consistency
IncidentCommandEndpoint
IncidentCommandService
IncidentCommandDAO
IncidentQueryEndpoint
IncidentQueryService
IncidentQueryDAO
Read Storage
Events
Select * from
Event Store
Your business domain drives the level
of consistency not technology

Deeper Insight
D D D
Increased (but still eventual)
consistency
EventHandler
EventsEvents
IncidentCommandEndpoint
IncidentCommandService
IncidentCommandDAO
IncidentQueryEndpoint
IncidentQueryService
IncidentQueryDAO
Read Storage
Events
Select * from
Event Store
async
! There is no
standard solution
1 Consistency
2 Validation
3 Parallel Updates
Example Domain
User

Guid id
String email
String password
RegisterUserCommand ChangeEmailCommand
UserRegisteredEvent



Guid id
Date timestamp
String email
String password
EmailChangedEvent



Guid userId
Date timestamp
String email
We process 2
million+ registrations per
day. A user can change her
email address. However the
emails address must be
unique
?
How high is the
probability that a
validation fails
Which data is required
for the validation
Where is the required
data stored
$
What is the business
impact of a failed
validation that is not
recognized due to
eventual consistency
and how high is the
probability of failure
Your business domain drives the level
of consistency

Deeper Insight
D D D
1 Validate from Event Store
2 Validate from Read Store
3 Perform Validation in Event
Handler
Never validate
from the event
store
1 Consistency
2 Validation
3 Parallel Updates
Example Domain
User

Guid id
String email
String password
RegisterUserCommand ChangeEmailCommand
UserRegisteredEvent



Guid id
Date timestamp
String email
String password
EmailChangedEvent



Guid userId
Date timestamp
String email
What happens when Alice
and Bob share an account and
both update the email address at
the same time
?
What would we do
in a
„classic old school
architecture“
UserRestController
UserBusinessService
UserDAO
User
ID EMAIL PASSWORD
… … …
2341 alice_bob@xyz.com lksjdaslkdjas
… … …
Update
Pessimistic or optimistic locking
Your business domain drives the
locking quality

Deeper Insight
D D D
!
Pessimistic
locking on a
data-level will
hardly work in
event sourcing
architectures
EventHandler EventsEvents
Where to „pessimistically“ lock?
Read Storage
Events
Event Store
UserRestController
UserBusinessService
UserDAO
User
Commands
Consider a business lock
with a UserLockedEvent
?
Do you

REALLY
need a full lock
Most „classic
architecture“ applications
are already running fine
with optimistic locks
Introduce a version field for the domain
entity
User

Guid id
Long version
String email
String password
RegisterUserCommand ChangeEmailCommand
UserRegisteredEvent



Guid id
Date timestamp
String email
String password
EmailChangedEvent



Guid userId
Date timestamp
String email
Long version
Each writing event
increases the version
UserRegisteredEvent
{guid: 12, version: 0,

email: alicebob@xyz.com, password: werwe2343}
EmailChangedEvent
version: 0
EmailChangedEvent
version: 1
EmailChangedEvent
version: 1
{guid: 12, version: 1,

email: alice_bob@xyz.com, password: werwe2343}
{guid: 12, version: 2,

email: alice@xyz.com, password: werwe2343}
EmailChangeFailedEvent
Also here:

you should be as
consistent as
your domain
requires
Unless otherwise indicated, these slides are © 2013-2015 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/
SPRINGONE2GX
WASHINGTON, DC
Thank You!
Michael Ploed - innoQ


Twitter: @bitboss
Slides: http://slideshare.net/mploed

More Related Content

PDF
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
KEY
Event Driven Architecture
PDF
Event-driven Architecture
PDF
Event Driven Architecture
PPTX
Apache Kafka Best Practices
PDF
Distributed Tracing with Jaeger
PDF
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
PPTX
Microservices Architecture Part 2 Event Sourcing and Saga
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
Event Driven Architecture
Event-driven Architecture
Event Driven Architecture
Apache Kafka Best Practices
Distributed Tracing with Jaeger
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
Microservices Architecture Part 2 Event Sourcing and Saga

What's hot (20)

PDF
Introduction to Spring Framework
PDF
Spring Framework - AOP
PPTX
서버와 클라이언트 같은 엔진 사용하기
PDF
AWS Fargate on EKS 실전 사용하기
PDF
Kubernetes Security with Calico and Open Policy Agent
PPTX
Introduction to Apache Kafka
PPTX
REST-API introduction for developers
PDF
Common Patterns of Multi Data-Center Architectures with Apache Kafka
PDF
Apache Pulsar Development 101 with Python
PDF
AWS DirectConnect 구성 가이드 (김용우) - 파트너 웨비나 시리즈
PDF
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
PPTX
RabbitMQ interview Questions and Answers
PPTX
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
PDF
KAFKA 3.1.0.pdf
PDF
AWS Summit Seoul 2023 | AWS에서 OpenTelemetry 기반의 애플리케이션 Observability 구축/활용하기
PDF
Dapr - A 10x Developer Framework for Any Language
PDF
AWS 비용, 어떻게 사용하고 계신가요? - 비용 최적화를 위한 AWS의 다양한 툴 알아보기 – 허경원, AWS 클라우드 파이낸셜 매니저:...
PDF
Event-Driven Transformation in Banking and FSI
PPTX
Event-driven architecture
PDF
How to build massive service for advance
Introduction to Spring Framework
Spring Framework - AOP
서버와 클라이언트 같은 엔진 사용하기
AWS Fargate on EKS 실전 사용하기
Kubernetes Security with Calico and Open Policy Agent
Introduction to Apache Kafka
REST-API introduction for developers
Common Patterns of Multi Data-Center Architectures with Apache Kafka
Apache Pulsar Development 101 with Python
AWS DirectConnect 구성 가이드 (김용우) - 파트너 웨비나 시리즈
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
RabbitMQ interview Questions and Answers
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
KAFKA 3.1.0.pdf
AWS Summit Seoul 2023 | AWS에서 OpenTelemetry 기반의 애플리케이션 Observability 구축/활용하기
Dapr - A 10x Developer Framework for Any Language
AWS 비용, 어떻게 사용하고 계신가요? - 비용 최적화를 위한 AWS의 다양한 툴 알아보기 – 허경원, AWS 클라우드 파이낸셜 매니저:...
Event-Driven Transformation in Banking and FSI
Event-driven architecture
How to build massive service for advance
Ad

Viewers also liked (10)

PDF
Event Sourcing: Einführung und Best Practices
PDF
Migrating from Grails 2 to Grails 3
PDF
Hibernate Tuning
PDF
Introduction to Event Sourcing and CQRS
PDF
Event Sourcing - Greg Young
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
PDF
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
PDF
Anatomie von Microservice Landschaften
PDF
HBaseCon 2012 | HBase Schema Design - Ian Varley, Salesforce
PDF
Caching in Hibernate
Event Sourcing: Einführung und Best Practices
Migrating from Grails 2 to Grails 3
Hibernate Tuning
Introduction to Event Sourcing and CQRS
Event Sourcing - Greg Young
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Anatomie von Microservice Landschaften
HBaseCon 2012 | HBase Schema Design - Ian Varley, Salesforce
Caching in Hibernate
Ad

Similar to Building Microservices with Event Sourcing and CQRS (20)

PDF
Event Sourcing: Introduction & Challenges
PPTX
Spring I_O 2024 - Flexible Spring with Event Sourcing.pptx
PPTX
Brown bag eventdrivenmicroservices-cqrs
PPTX
Event sourcing
PDF
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
PDF
Event sourcing - what could possibly go wrong ? Devoxx PL 2021
PDF
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
PPTX
Cqrs and event sourcing in azure
PDF
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
PDF
Events on the outside, on the inside and at the core (jfokus jfokus2016)
PDF
The Fine Art of Time Travelling: implementing Event Sourcing
PDF
Event Sourcing - what could possibly go wrong?
PDF
The Fine Art of Time Travelling - Implementing Event Sourcing - Andrea Saltar...
PDF
Events on the outside, on the inside and at the core - Chris Richardson
PDF
Events on the outside, on the inside and at the core (jaxlondon)
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
PDF
Building and deploying microservices with event sourcing, CQRS and Docker (Me...
PDF
Event Sourcing - what could go wrong - Jfokus 2022
PDF
fram^ TechTalk #1 - CQRS and Event Sourcing (ES)
PDF
Data Microservices with Spring Cloud
Event Sourcing: Introduction & Challenges
Spring I_O 2024 - Flexible Spring with Event Sourcing.pptx
Brown bag eventdrivenmicroservices-cqrs
Event sourcing
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
Event sourcing - what could possibly go wrong ? Devoxx PL 2021
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Cqrs and event sourcing in azure
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
Events on the outside, on the inside and at the core (jfokus jfokus2016)
The Fine Art of Time Travelling: implementing Event Sourcing
Event Sourcing - what could possibly go wrong?
The Fine Art of Time Travelling - Implementing Event Sourcing - Andrea Saltar...
Events on the outside, on the inside and at the core - Chris Richardson
Events on the outside, on the inside and at the core (jaxlondon)
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
Building and deploying microservices with event sourcing, CQRS and Docker (Me...
Event Sourcing - what could go wrong - Jfokus 2022
fram^ TechTalk #1 - CQRS and Event Sourcing (ES)
Data Microservices with Spring Cloud

More from Michael Plöd (7)

PDF
Event Sourcing für reaktive Anwendungen
PDF
CQRS basierte Architekturen mit Microservices
PDF
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
PDF
Caching - Hintergründe, Patterns und Best Practices
PDF
Warum empfehle ich meinen Kunden das Spring Framework?
PDF
Bessere Präsentationen
KEY
Integrating Wicket with Java EE 6
Event Sourcing für reaktive Anwendungen
CQRS basierte Architekturen mit Microservices
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Caching - Hintergründe, Patterns und Best Practices
Warum empfehle ich meinen Kunden das Spring Framework?
Bessere Präsentationen
Integrating Wicket with Java EE 6

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Digital Strategies for Manufacturing Companies
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
top salesforce developer skills in 2025.pdf
PPTX
Introduction to Artificial Intelligence
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
ai tools demonstartion for schools and inter college
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
System and Network Administration Chapter 2
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
history of c programming in notes for students .pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Understanding Forklifts - TECH EHS Solution
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Digital Strategies for Manufacturing Companies
CHAPTER 2 - PM Management and IT Context
top salesforce developer skills in 2025.pdf
Introduction to Artificial Intelligence
Design an Analysis of Algorithms I-SECS-1021-03
ai tools demonstartion for schools and inter college
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Design an Analysis of Algorithms II-SECS-1021-03
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
How to Choose the Right IT Partner for Your Business in Malaysia
Softaken Excel to vCard Converter Software.pdf
How Creative Agencies Leverage Project Management Software.pdf
System and Network Administration Chapter 2
Operating system designcfffgfgggggggvggggggggg
wealthsignaloriginal-com-DS-text-... (1).pdf
history of c programming in notes for students .pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
2025 Textile ERP Trends: SAP, Odoo & Oracle
Understanding Forklifts - TECH EHS Solution

Building Microservices with Event Sourcing and CQRS