Event sourcing - what could possibly go wrong ? Devoxx PL 2021

Andrzej Ludwikowski
Andrzej LudwikowskiSoftware Journeyman at SoftwareMill (softwaremill.com)
Event Sourcing
what could possibly go wrong?
Andrzej Ludwikowski
About me
➔
➔ ludwikowski.info
➔ github.com/aludwiko
➔ @aludwikowski
➔ academy.softwaremill.com
SoftwareMill
SoftwareMill
SoftwareMill
SoftwareMill
JVM
BLOGGERS
SoftwareMill
● Hibernate Envers
● Alpakka Kafka
● Sttp
● Scala Clippy
● Quicklens
● MacWire
What is Event Sourcing?
DB
Order {
items=[itemA, itemB]
}
What is Event Sourcing?
DB
DB
Order {
items=[itemA, itemB]
}
ItemAdded(itemA)
ItemAdded(itemC)
ItemRemoved(itemC)
ItemAdded(itemB)
What is Event Sourcing?
DB
DB
Order {
items=[itemA, itemB]
}
ItemAdded(itemA)
ItemAdded(itemC)
ItemRemoved(itemC)
ItemAdded(itemB)
History
● 9000 BC, Mesopotamian Clay Tablets,
e.g. for market transactions
History
● 2005, Event Sourcing
“Enterprise applications that use Event Sourcing
are rarer, but I have seen a few applications (or
parts of applications) that use it.”
Why Event Sourcing?
● complete log of every state change
● debugging
● performance
● scalability
● microservices integration pattern
ES and CQRS
Client
Query Service
Data access
Queries
Read
model
Read
model
Read
models
Command Service
Domain
Events
Commands
ES and CQRS level 1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Transaction
Command Service
Domain
Events
Commands
ES and CQRS level 1
● Entry-level, synchronous & transactional event sourcing
● Implementing event sourcing using a relational database
● slick-eventsourcing
ES and CQRS level 1
+ easy to implement
+ easy to reason about
+ 0 eventual consistency
- performance
- scalability
ES and CQRS level 2
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
Transaction
Command Service
Domain
Events
Commands
ES and CQRS level 2
+/- performance
+/- scalability
- eventual consistency
- increased events DB load ?
- lags
ES and CQRS level 3
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
Transaction
event
bus
Command Service
Domain
Events
Commands
ES and CQRS level 3.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
Command Service
Domain
Events
Commands
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
Command Service
Domain
Events
Commands
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
At-least-once delivery
Command Service
Domain
Events
Commands
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
ES and CQRS level 3.1.1
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
?
ES and CQRS level 3.2
Events
Client
Query Service
Data access
Commands
Queries
Read
model
Read
model
Read
models
Projector
event
bus
Command Service
Domain
Command Service
Domain
Command Service
Domain
Transaction
`
Sharded
Cluster
ES and CQRS level 3.x
+ performance
+ scalability
- eventual consistency
- complex implementation
- locking vs Single Writer
ES and CQRS alternatives
● Change Capture Data (CDC) logging instead of event bus?
● event bus instead of DB?
Not covered but worth to check
● Command Sourcing
● Event Collaboration
ES implementation?
● custom
● library
● framework
ES from domain perspective
● commands, events, state
● 2 methods on state
○ process(command: Command): List[Event]
○ apply(event: Event): State
ES from application perspective
● snapshotting
● fail-over
● recover
● debugging
● sharding
● serialization & schema evolution
● concurrency access
● etc.
import javax.persistence.*;
import java.util.List;
@Entity
public class Issue {
@EmbeddedId
private IssueId id;
private String name;
private IssueStatus status;
@OneToMany(cascade = CascadeType.MERGE)
private List<IssueComment> comments;
...
public void changeStatusTo(IssueStatus newStatus) {
if (this.status == IssueStatus.DONE
&& newStatus == IssueStatus.NEW || this.status == IssueStatus.NEW
&& newStatus == IssueStatus.DONE) {
throw new RuntimeException(String.format("Cannot change issue status from %s to %s",
this.status, newStatus));
}
this.status = newStatus;
}
...
}
import javax.persistence.*;
import java.util.List;
@Entity
public class Issue {
@EmbeddedId
private IssueId id;
private String name;
private IssueStatus status;
@OneToMany(cascade = CascadeType.MERGE)
private List<IssueComment> comments;
...
public void changeStatusTo(IssueStatus newStatus) {
if (this.status == IssueStatus.DONE
&& newStatus == IssueStatus.NEW || this.status == IssueStatus.NEW
&& newStatus == IssueStatus.DONE) {
throw new RuntimeException(String.format("Cannot change issue status from %s to %s",
this.status, newStatus));
}
this.status = newStatus;
}
...
}
import org.axonframework.commandhandling.*
import org.axonframework.eventsourcing.*
@Aggregate(repository = "userAggregateRepository")
public class User {
@AggregateIdentifier
private UserId userId;
private String passwordHash;
@CommandHandler
public boolean handle(AuthenticateUserCommand cmd) {
boolean success = this.passwordHash.equals(hashOf(cmd.getPassword()));
if (success) {
apply(new UserAuthenticatedEvent(userId));
}
return success;
}
@EventSourcingHandler
public void on(UserCreatedEvent event) {
this.userId = event.getUserId();
this.passwordHash = event.getPassword();
}
private String hashOf(char[] password) {
return DigestUtils.sha1(String.valueOf(password));
}
}
import akka.Done
import com.lightbend.lagom.scaladsl.*
import play.api.libs.json.{Format, Json}
import com.example.auction.utils.JsonFormats._
class UserEntity extends PersistentEntity {
override def initialState = None
override def behavior: Behavior = {
case Some(user) => Actions().onReadOnlyCommand[GetUser.type, Option[User]] {
case (GetUser, ctx, state) => ctx.reply(state)
}.onReadOnlyCommand[CreateUser, Done] {
case (CreateUser(name), ctx, state) => ctx.invalidCommand("User already exists")
}
case None => Actions().onReadOnlyCommand[GetUser.type, Option[User]] {
case (GetUser, ctx, state) => ctx.reply(state)
}.onCommand[CreateUser, Done] {
case (CreateUser(name), ctx, state) => ctx.thenPersist(UserCreated(name))(_ => ctx.reply(Done))
}.onEvent {
case (UserCreated(name), state) => Some(User(name))
}
}
}
ES packaging
● github.com/aludwiko/event-sourcing-akka-persistence
import java.time.Instant
import info.ludwikowski.es.user.domain.UserCommand.*
import info.ludwikowski.es.user.domain.UserEvent.*
import scala.util.{Failure, Success, Try}
case class User (userId: UserId, name: String, email: Email, funds: Funds) {
def process(command: UserCommand): Either[List[UserEvent]] = command match {
case c: UpdateEmail => updateEmail(c)
case c: DepositFunds => deposit(c)
case c: WithdrawFunds => withdraw(c)
...
}
def apply(event: UserEvent): User = ??? //pattern matching
}
ES packaging
● snapshotting
● fail-over
● recover
● debugging
● sharding
● serialization & schema evolution
● concurrency access
● etc.
ES packaging
● domain logic
● domain validation
● 0 ES framework imports
library vs. framework
● Akka Persistence vs. Lagom
● Akka Persistence Typed
Event storage
● file
● RDBMS
● Event Store
● MongoDB
● Kafka
● Cassandra
Event storage for Akka Persistence
● file
● RDBMS
● Event Store
● MongoDB
● Kafka
● Cassandra
akka-persistence-jdbc trap
val theTag = s"%$tag%"
sql"""
SELECT "#$ordering", "#$deleted", "#$persistenceId", "#$sequenceNumber",
"#$message", "#$tags"
FROM (
SELECT * FROM #$theTableName
WHERE "#$tags" LIKE $theTag
AND "#$ordering" > $theOffset
AND "#$ordering" <= $maxOffset
ORDER BY "#$ordering"
)
WHERE rownum <= $max"""
akka-persistence-jdbc trap
SELECT * FROM events_journal
WHERE tags LIKE ‘%some_tag%’;
Cassandra perfect for ES?
● partitioning by design
● replication by design
● leaderless (no single point of failure)
● optimised for writes (2 nodes = 100 000 tx/s)
● near-linear horizontal scaling
ScyllaDB ?
● Cassandra without JVM
○ same protocol, SSTable compatibility
● C++ and Seastar lib
● up to 1,000,000 IOPS/node
● not fully supported by Akka Persistence
Event serialization
● plain text
○ JSON
○ XML
○ YAML
● binary
○ java serialization
○ Avro
○ Protocol Buffers (Protobuf)
○ Thrift
○ Kryo
Plain text Binary
human-readable deserialization required
Plain text Binary
human-readable deserialization required
precision issues (JSON IEEE 754, DoS) -
Plain text Binary
human-readable deserialization required
precision issues (JSON IEEE 754, DoS) -
storage consumption compress
Plain text Binary
human-readable deserialization required
precision issues (JSON IEEE 754, DoS) -
storage consumption compress
slow fast
Plain text Binary
human-readable deserialization required
precision issues (JSON IEEE 754, DoS) -
storage consumption compress
slow fast
poor schema evolution support full schema evolution support
Binary
● java serialization
● Avro
● Protocol Buffers (Protobuf)
● Thrift
● Kryo
Binary
● java serialization
● Avro
● Protocol Buffers (Protobuf)
● Thrift
● Kryo
Binary
● java serialization
● Avro
● Protocol Buffers (Protobuf)
● Thrift
● Kryo
Binary
● java serialization
● Avro
● Protocol Buffers (Protobuf)
● Thrift
● Kryo
Multi-language support
● Avro
○ C, C++, C#, Go, Haskell, Java, Perl, PHP, Python, Ruby, Scala
● Protocol Buffers (Protobuf)
○ even more than Avro
Speed
https://code.google.com/archive/p/thrift-protobuf-compare/wikis/Benchmarking.wiki
Size
https://code.google.com/archive/p/thrift-protobuf-compare/wikis/Benchmarking.wiki
● backward - V2 can read V1
Full compatibility
Application
Events
V1
V2
● forward - V2 can read V3
Full compatibility
Application
Events
V1, V2
V2
Application
Application
V2
V3
● forward - V2 can read V3
Full compatibility
Events
Read
model
Read
model
Read
models
Projector
V2
V3
Schema evolution - full compatibility
Protocol Buffers Avro
Add field + (optional) + (default value)
Remove field + + (default value)
Rename field + + (aliases)
https://martin.kleppmann.com/2012/12/05/schema-evolution-in-avro-protocol-buffers-thrift.html
Protobuf schema management
//user-events.proto
message UserCreatedEvent {
string user_id = 1;
string operation_id = 2;
int64 created_at = 3;
string name = 4;
string email = 5;
}
package user.application
UserCreatedEvent(
userId: String,
operationId: String,
createdAt: Long,
name: String,
email: String
)
Protobuf schema management
package user.domain
UserCreated(
userId: UserId,
operationId: OperationId,
createdAt: Instant,
name: String,
email: Email
) extends UserEvent
package user.application
UserCreatedEvent(
userId: String,
operationId: String,
createdAt: Long,
name: String,
email: String
)
Protobuf schema management
● def toDomain(event: UserCreatedEvent): UserEvent.UserCreated
● def toSerializable(event: UserEvent.UserCreated): UserCreatedEvent
Protobuf schema management
+ clean domain
- a lot of boilerplate code
Avro schema management
package user.domain
UserCreated(
userId: UserId,
operationId: OperationId,
createdAt: Instant,
name: String,
email: Email
) extends UserEvent
{
"type" : "record",
"name" : "UserCreated",
"namespace" :
"info.ludwikowski.es.user.domain",
"fields" : [ {
"name" : "userId",
"type" : "string" }, {
"name" : "operationId",
"type" : "string" }, {
"name" : "createdAt",
"type" : "long" }, {
"name" : "name",
"type" : "string" }, {
"name" : "email",
"type" : "string"
} ]
}
Avro deserialization
Bytes Deserialization Object
Reader Schema
Writer Schema
Avro writer schema source
● add schema to the payload
● custom solution
○ schema in /resources
○ schema in external storage (must be fault-tolerant)
○ Darwin project
● Schema Registry
Avro schema management
package user.domain
UserCreated(
userId: UserId,
operationId: OperationId,
createdAt: Instant,
name: String,
email: Email
) extends UserEvent
{
"type" : "record",
"name" : "UserCreated",
"namespace" :
"info.ludwikowski.es.user.domain",
"fields" : [ {
"name" : "userId",
"type" : "string" }, {
"name" : "operationId",
"type" : "string" }, {
"name" : "createdAt",
"type" : "long" }, {
"name" : "name",
"type" : "string" }, {
"name" : "email",
"type" : "string"
} ]
}
Protocol Buffers vs. Avro
{
"type" : "record",
"name" : "UserCreated",
"namespace" :
"info.ludwikowski.es.user.domain",
"fields" : [ {
"name" : "userId",
"type" : "string" }, {
"name" : "operationId",
"type" : "string" }, {
"name" : "createdAt",
"type" : "long" }, {
"name" : "name",
"type" : "string" }, {
"name" : "email",
"type" : "string"
} ]
}
message UserCreatedEvent {
string user_id = 1;
string operation_id = 2;
int64 created_at = 3;
string name = 4;
string email = 5;
}
Avro schema management
+ less boilerplate code
+/- clean domain
- reader & writer schema distribution
Avro
+ less boilerplate code
+/- clean domain
- reader & writer schema distribution
Protobuf
+ clean domain
- a lot of boilerplate code
Avro vs. Protocol Buffers
● The best serialization strategy for Event Sourcing
Event payload
● delta event
● rich event (event enrichment)
● + metadata
○ seq_num
○ created_at
○ event_id
○ command_id
○ correlation_id
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
State replay time
● snapshotting
● write-through cache
Memory consumption
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Immutable vs. mutable state?
● add/remove ImmutableList 17.496 ops/s
● add/remove TreeMap 2201.731 ops/s
Fixing state
● healing command
Updating all aggregates
User(id)
Command(user_id) Event(user_id)
Event(user_id)
Event(user_id)
Handling duplicates
Events
Read
model
Read
model
Read
models
Projector
event
bus
At-least-once delivery
https://www.seriouspuzzles.com/unicorns-in-fairy-land-500pc-jigsaw-puzzle-by-eurographics/
Handling duplicates
Events
Read
model
Read
model
Read
models
Projector
event
bus
At-least-once delivery
Events
Handling duplicates
Events
Read
model
Read
model
Read
models
Projector
event
bus
idempotent updates
Events
Event + seq_no
Event + seq_no
Handling duplicates
Events
Read
model
Read
model
Read
models
Projector
event
bus
Event + seq_no
read model update +
seq_no
Events
Broken read model
Events
ad model
ead model
Read
models
Projector
event
bus
Events
Broken read model
Events
ad model
ead model
Read
models
Projector
event
bus
read model update + offset
(manual offset management)
Events
Multi aggregate transactional update
● rethink aggregates boundaries
● compensating action
○ optimistic
○ pessimistic
Pessimistic compensation action
User account
Cinema show
Pessimistic compensation action
User account
Cinema show
charged
Pessimistic compensation action
User account
Cinema show
charged
booked
Pessimistic compensation action
User account
Cinema show
charged
booked sold out
Pessimistic compensation action
User account
Cinema show
charged
booked
booked sold out
Pessimistic compensation action
User account
Cinema show
charged
booked
booked sold out
Pessimistic compensation action
User account
Cinema show
charged
booked
booked sold out
refund
Optimistic compensation action
User account
Cinema show
charged
booked sold out
Optimistic compensation action
User account
Cinema show booked
booked sold out
overbooked
Optimistic compensation action
User account
Cinema show
charged
booked
booked sold out
overbooked
?
Saga
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Updater
event
bus
Transaction
Saga - choreography
Command Service
Domain
Events
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
Saga - orchestration
Command Service
Domain
Events
Client
Query Service
Data access
Commands Queries
Read
model
Read
model
Read
models
Projector
event
bus
Transaction
Command Service
Domain
Events
Commands
Saga
● should be persistable
● events order should be irrelevant
● time window limitation
● compensating action must be commutative
Saga
● Sagas with ES
● DDD, Saga & Event-sourcing
● Applying Saga Pattern
● Microservice Patterns
ES with RODO/GDPR
● “right to forget” with:
○ data shredding (and/or deleting)
■ events, state, views, read models
○ retention policy
■ message brokers, backups, logs
○ data before RODO migration
ES and CQRS level 3.2
Events
Client
Query Service
Data access
Commands
Queries
Read
model
Read
model
Read
models
Projector
event
bus
Command Service
Domain
Command Service
Domain
Command Service
Domain
Transaction
Sharding
Clustering
Cluster = split brain
1
5 4
3
Load balancer
2
Cluster = split brain
1
5 4
3
Load balancer
2
User(1)
Command(1)
Cluster = split brain
1
5 4
3
Load balancer
2
Cluster = split brain
1
5 4
3
Load balancer
2
User(1)
Cluster = split brain
1
5 4
3
Load balancer
2
User(1)
Command(1)
User(1)
Cluster = split brain
1
5 4
3
Load balancer
2
User(1)
Command(1)
User(1)
Command(1)
Cluster best practises
● remember about the split brain
● very good monitoring & alerting
● a lot of failover tests
● cluster also on dev/staging
● keep it as small as possible (code base, number of nodes, etc.)
Summary
● carefully choose ES lib/framework
● there is no perfect database for event sourcing
● understand event/command/state schema evolution
● eventual consistency is your friend
● scaling is complex
● database inside-out
● log-based processing mindset
Want to learn more?
● Reactive Event Sourcing with Akka (Java/Scala)
● Akka Typed Fundamentals (Java/Scala)
● Akka Cluster
● Performance tests with Gatling
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Rate me please :)
Thank you and Q&A
➔
➔ ludwikowski.info
➔ github.com/aludwiko
➔ @aludwikowski
WE
WANT
YOU
Thank you and Q&A
➔
➔ ludwikowski.info
➔ github.com/aludwiko
➔ @aludwikowski
1 of 128

Recommended

Event Sourcing - what could go wrong - Jfokus 2022 by
Event Sourcing - what could go wrong - Jfokus 2022Event Sourcing - what could go wrong - Jfokus 2022
Event Sourcing - what could go wrong - Jfokus 2022Andrzej Ludwikowski
288 views127 slides
Secrets of Performance Tuning Java on Kubernetes by
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesBruno Borges
3K views30 slides
MySQL Parallel Replication: All the 5.7 and 8.0 Details (LOGICAL_CLOCK) by
MySQL Parallel Replication: All the 5.7 and 8.0 Details (LOGICAL_CLOCK)MySQL Parallel Replication: All the 5.7 and 8.0 Details (LOGICAL_CLOCK)
MySQL Parallel Replication: All the 5.7 and 8.0 Details (LOGICAL_CLOCK)Jean-François Gagné
1.2K views55 slides
Apache Kafka Architecture & Fundamentals Explained by
Apache Kafka Architecture & Fundamentals ExplainedApache Kafka Architecture & Fundamentals Explained
Apache Kafka Architecture & Fundamentals Explainedconfluent
27.6K views33 slides
Redpanda and ClickHouse by
Redpanda and ClickHouseRedpanda and ClickHouse
Redpanda and ClickHouseAltinity Ltd
776 views14 slides
HandsOn ProxySQL Tutorial - PLSC18 by
HandsOn ProxySQL Tutorial - PLSC18HandsOn ProxySQL Tutorial - PLSC18
HandsOn ProxySQL Tutorial - PLSC18Derek Downey
752 views103 slides

More Related Content

What's hot

Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2... by
Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2...Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2...
Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2...Scalar, Inc.
5K views52 slides
Inside MongoDB: the Internals of an Open-Source Database by
Inside MongoDB: the Internals of an Open-Source DatabaseInside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source DatabaseMike Dirolf
52.5K views25 slides
Producer Performance Tuning for Apache Kafka by
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaJiangjie Qin
44.6K views79 slides
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11 by
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11Kenny Gryp
660 views55 slides
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ... by
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...confluent
12.1K views42 slides
[2018] MySQL 이중화 진화기 by
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기NHN FORWARD
10.7K views73 slides

What's hot(20)

Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2... by Scalar, Inc.
Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2...Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2...
Making Cassandra more capable, faster, and more reliable (at ApacheCon@Home 2...
Scalar, Inc.5K views
Inside MongoDB: the Internals of an Open-Source Database by Mike Dirolf
Inside MongoDB: the Internals of an Open-Source DatabaseInside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source Database
Mike Dirolf52.5K views
Producer Performance Tuning for Apache Kafka by Jiangjie Qin
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache Kafka
Jiangjie Qin44.6K views
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11 by Kenny Gryp
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11
Kenny Gryp660 views
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ... by confluent
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
confluent12.1K views
[2018] MySQL 이중화 진화기 by NHN FORWARD
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기
NHN FORWARD10.7K views
Introduction to Apache ZooKeeper by Saurav Haloi
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
Saurav Haloi128.4K views
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다. by NAVER D2
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
NAVER D225.8K views
What is new in PostgreSQL 14? by Mydbops
What is new in PostgreSQL 14?What is new in PostgreSQL 14?
What is new in PostgreSQL 14?
Mydbops652 views
MySQL/MariaDB Proxy Software Test by I Goo Lee
MySQL/MariaDB Proxy Software TestMySQL/MariaDB Proxy Software Test
MySQL/MariaDB Proxy Software Test
I Goo Lee2K views
Redis vs Infinispan | DevNation Tech Talk by Red Hat Developers
Redis vs Infinispan | DevNation Tech TalkRedis vs Infinispan | DevNation Tech Talk
Redis vs Infinispan | DevNation Tech Talk
Red Hat Developers10.5K views
How to Manage Scale-Out Environments with MariaDB MaxScale by MariaDB plc
How to Manage Scale-Out Environments with MariaDB MaxScaleHow to Manage Scale-Out Environments with MariaDB MaxScale
How to Manage Scale-Out Environments with MariaDB MaxScale
MariaDB plc1.2K views
Cassandra vs. ScyllaDB: Evolutionary Differences by ScyllaDB
Cassandra vs. ScyllaDB: Evolutionary DifferencesCassandra vs. ScyllaDB: Evolutionary Differences
Cassandra vs. ScyllaDB: Evolutionary Differences
ScyllaDB978 views
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013 by mumrah
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
mumrah61.2K views
Big Data Redis Mongodb Dynamodb Sharding by Araf Karsh Hamid
Big Data Redis Mongodb Dynamodb ShardingBig Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb Sharding
Araf Karsh Hamid207 views
Stateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes by confluent
Stateful, Stateless and Serverless - Running Apache Kafka® on KubernetesStateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
Stateful, Stateless and Serverless - Running Apache Kafka® on Kubernetes
confluent4.2K views
Thrift vs Protocol Buffers vs Avro - Biased Comparison by Igor Anishchenko
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Igor Anishchenko240.7K views
Kafka Streams for Java enthusiasts by Slim Baltagi
Kafka Streams for Java enthusiastsKafka Streams for Java enthusiasts
Kafka Streams for Java enthusiasts
Slim Baltagi5.1K views

Similar to Event sourcing - what could possibly go wrong ? Devoxx PL 2021

Event Sourcing - what could go wrong - Devoxx BE by
Event Sourcing - what could go wrong - Devoxx BEEvent Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BEAndrzej Ludwikowski
116 views122 slides
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak? by
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?SegFaultConf
290 views90 slides
Event Sourcing - what could possibly go wrong? by
Event Sourcing - what could possibly go wrong?Event Sourcing - what could possibly go wrong?
Event Sourcing - what could possibly go wrong?Andrzej Ludwikowski
317 views124 slides
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo... by
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...Codemotion
426 views121 slides
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an... by
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...Anton Kirillov
71.3K views30 slides
Docker & ECS: Secure Nearline Execution by
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionBrennan Saeta
444 views90 slides

Similar to Event sourcing - what could possibly go wrong ? Devoxx PL 2021(20)

Event Sourcing - what could go wrong - Devoxx BE by Andrzej Ludwikowski
Event Sourcing - what could go wrong - Devoxx BEEvent Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BE
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak? by SegFaultConf
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
SegFaultConf290 views
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo... by Codemotion
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
Andrzej Ludwikowski - Event Sourcing - what could possibly go wrong? - Codemo...
Codemotion426 views
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an... by Anton Kirillov
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Anton Kirillov71.3K views
Docker & ECS: Secure Nearline Execution by Brennan Saeta
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline Execution
Brennan Saeta444 views
Building a serverless company on AWS lambda and Serverless framework by Luciano Mammino
Building a serverless company on AWS lambda and Serverless frameworkBuilding a serverless company on AWS lambda and Serverless framework
Building a serverless company on AWS lambda and Serverless framework
Luciano Mammino1.5K views
Architecting Alive Apps by Jorge Ortiz
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
Jorge Ortiz537 views
Immutable Deployments with AWS CloudFormation and AWS Lambda by AOE
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS Lambda
AOE 45.5K views
FlinkForward Asia 2019 - Evolving Keystone to an Open Collaborative Real Time... by Zhenzhong Xu
FlinkForward Asia 2019 - Evolving Keystone to an Open Collaborative Real Time...FlinkForward Asia 2019 - Evolving Keystone to an Open Collaborative Real Time...
FlinkForward Asia 2019 - Evolving Keystone to an Open Collaborative Real Time...
Zhenzhong Xu218 views
Online Meetup: Why should container system / platform builders care about con... by Docker, Inc.
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...
Docker, Inc.3K views
GTS Episode 1: Reactive programming in the wild by Omer Iqbal
GTS Episode 1: Reactive programming in the wildGTS Episode 1: Reactive programming in the wild
GTS Episode 1: Reactive programming in the wild
Omer Iqbal383 views
Lightbend Lagom: Microservices Just Right by mircodotta
Lightbend Lagom: Microservices Just RightLightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just Right
mircodotta7K views
Practical AngularJS by Wei Ru
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru1.2K views
Fabric - Realtime stream processing framework by Shashank Gautam
Fabric - Realtime stream processing frameworkFabric - Realtime stream processing framework
Fabric - Realtime stream processing framework
Shashank Gautam711 views
Anatomy of an action by Gordon Chung
Anatomy of an actionAnatomy of an action
Anatomy of an action
Gordon Chung360 views

More from Andrzej Ludwikowski

Performance tests - it's a trap by
Performance tests - it's a trapPerformance tests - it's a trap
Performance tests - it's a trapAndrzej Ludwikowski
779 views88 slides
Cassandra lesson learned - extended by
Cassandra   lesson learned  - extendedCassandra   lesson learned  - extended
Cassandra lesson learned - extendedAndrzej Ludwikowski
529 views64 slides
Performance tests with Gatling (extended) by
Performance tests with Gatling (extended)Performance tests with Gatling (extended)
Performance tests with Gatling (extended)Andrzej Ludwikowski
1K views55 slides
Stress test your backend with Gatling by
Stress test your backend with GatlingStress test your backend with Gatling
Stress test your backend with GatlingAndrzej Ludwikowski
435 views54 slides
Performance tests with Gatling by
Performance tests with GatlingPerformance tests with Gatling
Performance tests with GatlingAndrzej Ludwikowski
1.1K views51 slides
Cassandra - lesson learned by
Cassandra  - lesson learnedCassandra  - lesson learned
Cassandra - lesson learnedAndrzej Ludwikowski
477 views59 slides

Recently uploaded

DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDeltares
7 views23 slides
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...Deltares
6 views28 slides
MariaDB stored procedures and why they should be improved by
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedFederico Razzoli
8 views32 slides
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t... by
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...Deltares
9 views26 slides
360 graden fabriek by
360 graden fabriek360 graden fabriek
360 graden fabriekinfo33492
36 views25 slides
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... by
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...Deltares
9 views34 slides

Recently uploaded(20)

DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by Deltares
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
Deltares7 views
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by Deltares
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
Deltares6 views
MariaDB stored procedures and why they should be improved by Federico Razzoli
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t... by Deltares
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
Deltares9 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info3349236 views
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... by Deltares
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
Deltares9 views
Software testing company in India.pptx by SakshiPatel82
Software testing company in India.pptxSoftware testing company in India.pptx
Software testing company in India.pptx
SakshiPatel827 views
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by Deltares
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
Deltares6 views
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable11 views
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge... by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...
DSD-INT 2023 Delft3D FM Suite 2024.01 2D3D - New features + Improvements - Ge...
Deltares17 views
Citi TechTalk Session 2: Kafka Deep Dive by confluent
Citi TechTalk Session 2: Kafka Deep DiveCiti TechTalk Session 2: Kafka Deep Dive
Citi TechTalk Session 2: Kafka Deep Dive
confluent17 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm13 views
SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor22 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
Tridens DevOps by Tridens
Tridens DevOpsTridens DevOps
Tridens DevOps
Tridens9 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares12 views
What Can Employee Monitoring Software Do?​ by wAnywhere
What Can Employee Monitoring Software Do?​What Can Employee Monitoring Software Do?​
What Can Employee Monitoring Software Do?​
wAnywhere21 views

Event sourcing - what could possibly go wrong ? Devoxx PL 2021

  • 1. Event Sourcing what could possibly go wrong? Andrzej Ludwikowski
  • 2. About me ➔ ➔ ludwikowski.info ➔ github.com/aludwiko ➔ @aludwikowski ➔ academy.softwaremill.com
  • 7. SoftwareMill ● Hibernate Envers ● Alpakka Kafka ● Sttp ● Scala Clippy ● Quicklens ● MacWire
  • 8. What is Event Sourcing? DB Order { items=[itemA, itemB] }
  • 9. What is Event Sourcing? DB DB Order { items=[itemA, itemB] } ItemAdded(itemA) ItemAdded(itemC) ItemRemoved(itemC) ItemAdded(itemB)
  • 10. What is Event Sourcing? DB DB Order { items=[itemA, itemB] } ItemAdded(itemA) ItemAdded(itemC) ItemRemoved(itemC) ItemAdded(itemB)
  • 11. History ● 9000 BC, Mesopotamian Clay Tablets, e.g. for market transactions
  • 12. History ● 2005, Event Sourcing “Enterprise applications that use Event Sourcing are rarer, but I have seen a few applications (or parts of applications) that use it.”
  • 13. Why Event Sourcing? ● complete log of every state change ● debugging ● performance ● scalability ● microservices integration pattern
  • 14. ES and CQRS Client Query Service Data access Queries Read model Read model Read models Command Service Domain Events Commands
  • 15. ES and CQRS level 1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Transaction Command Service Domain Events Commands
  • 16. ES and CQRS level 1 ● Entry-level, synchronous & transactional event sourcing ● Implementing event sourcing using a relational database ● slick-eventsourcing
  • 17. ES and CQRS level 1 + easy to implement + easy to reason about + 0 eventual consistency - performance - scalability
  • 18. ES and CQRS level 2 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector Transaction Command Service Domain Events Commands
  • 19. ES and CQRS level 2 +/- performance +/- scalability - eventual consistency - increased events DB load ? - lags
  • 20. ES and CQRS level 3 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector Transaction event bus Command Service Domain Events Commands
  • 21. ES and CQRS level 3.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction Command Service Domain Events Commands
  • 22. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction Command Service Domain Events Commands
  • 23. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction At-least-once delivery Command Service Domain Events Commands
  • 24. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction
  • 25. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction
  • 26. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction
  • 27. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction
  • 28. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction
  • 29. ES and CQRS level 3.1.1 Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction ?
  • 30. ES and CQRS level 3.2 Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Command Service Domain Command Service Domain Command Service Domain Transaction ` Sharded Cluster
  • 31. ES and CQRS level 3.x + performance + scalability - eventual consistency - complex implementation - locking vs Single Writer
  • 32. ES and CQRS alternatives ● Change Capture Data (CDC) logging instead of event bus? ● event bus instead of DB?
  • 33. Not covered but worth to check ● Command Sourcing ● Event Collaboration
  • 34. ES implementation? ● custom ● library ● framework
  • 35. ES from domain perspective ● commands, events, state ● 2 methods on state ○ process(command: Command): List[Event] ○ apply(event: Event): State
  • 36. ES from application perspective ● snapshotting ● fail-over ● recover ● debugging ● sharding ● serialization & schema evolution ● concurrency access ● etc.
  • 37. import javax.persistence.*; import java.util.List; @Entity public class Issue { @EmbeddedId private IssueId id; private String name; private IssueStatus status; @OneToMany(cascade = CascadeType.MERGE) private List<IssueComment> comments; ... public void changeStatusTo(IssueStatus newStatus) { if (this.status == IssueStatus.DONE && newStatus == IssueStatus.NEW || this.status == IssueStatus.NEW && newStatus == IssueStatus.DONE) { throw new RuntimeException(String.format("Cannot change issue status from %s to %s", this.status, newStatus)); } this.status = newStatus; } ... }
  • 38. import javax.persistence.*; import java.util.List; @Entity public class Issue { @EmbeddedId private IssueId id; private String name; private IssueStatus status; @OneToMany(cascade = CascadeType.MERGE) private List<IssueComment> comments; ... public void changeStatusTo(IssueStatus newStatus) { if (this.status == IssueStatus.DONE && newStatus == IssueStatus.NEW || this.status == IssueStatus.NEW && newStatus == IssueStatus.DONE) { throw new RuntimeException(String.format("Cannot change issue status from %s to %s", this.status, newStatus)); } this.status = newStatus; } ... }
  • 39. import org.axonframework.commandhandling.* import org.axonframework.eventsourcing.* @Aggregate(repository = "userAggregateRepository") public class User { @AggregateIdentifier private UserId userId; private String passwordHash; @CommandHandler public boolean handle(AuthenticateUserCommand cmd) { boolean success = this.passwordHash.equals(hashOf(cmd.getPassword())); if (success) { apply(new UserAuthenticatedEvent(userId)); } return success; } @EventSourcingHandler public void on(UserCreatedEvent event) { this.userId = event.getUserId(); this.passwordHash = event.getPassword(); } private String hashOf(char[] password) { return DigestUtils.sha1(String.valueOf(password)); } }
  • 40. import akka.Done import com.lightbend.lagom.scaladsl.* import play.api.libs.json.{Format, Json} import com.example.auction.utils.JsonFormats._ class UserEntity extends PersistentEntity { override def initialState = None override def behavior: Behavior = { case Some(user) => Actions().onReadOnlyCommand[GetUser.type, Option[User]] { case (GetUser, ctx, state) => ctx.reply(state) }.onReadOnlyCommand[CreateUser, Done] { case (CreateUser(name), ctx, state) => ctx.invalidCommand("User already exists") } case None => Actions().onReadOnlyCommand[GetUser.type, Option[User]] { case (GetUser, ctx, state) => ctx.reply(state) }.onCommand[CreateUser, Done] { case (CreateUser(name), ctx, state) => ctx.thenPersist(UserCreated(name))(_ => ctx.reply(Done)) }.onEvent { case (UserCreated(name), state) => Some(User(name)) } } }
  • 42. import java.time.Instant import info.ludwikowski.es.user.domain.UserCommand.* import info.ludwikowski.es.user.domain.UserEvent.* import scala.util.{Failure, Success, Try} case class User (userId: UserId, name: String, email: Email, funds: Funds) { def process(command: UserCommand): Either[List[UserEvent]] = command match { case c: UpdateEmail => updateEmail(c) case c: DepositFunds => deposit(c) case c: WithdrawFunds => withdraw(c) ... } def apply(event: UserEvent): User = ??? //pattern matching }
  • 43. ES packaging ● snapshotting ● fail-over ● recover ● debugging ● sharding ● serialization & schema evolution ● concurrency access ● etc.
  • 44. ES packaging ● domain logic ● domain validation ● 0 ES framework imports
  • 45. library vs. framework ● Akka Persistence vs. Lagom ● Akka Persistence Typed
  • 46. Event storage ● file ● RDBMS ● Event Store ● MongoDB ● Kafka ● Cassandra
  • 47. Event storage for Akka Persistence ● file ● RDBMS ● Event Store ● MongoDB ● Kafka ● Cassandra
  • 48. akka-persistence-jdbc trap val theTag = s"%$tag%" sql""" SELECT "#$ordering", "#$deleted", "#$persistenceId", "#$sequenceNumber", "#$message", "#$tags" FROM ( SELECT * FROM #$theTableName WHERE "#$tags" LIKE $theTag AND "#$ordering" > $theOffset AND "#$ordering" <= $maxOffset ORDER BY "#$ordering" ) WHERE rownum <= $max"""
  • 49. akka-persistence-jdbc trap SELECT * FROM events_journal WHERE tags LIKE ‘%some_tag%’;
  • 50. Cassandra perfect for ES? ● partitioning by design ● replication by design ● leaderless (no single point of failure) ● optimised for writes (2 nodes = 100 000 tx/s) ● near-linear horizontal scaling
  • 51. ScyllaDB ? ● Cassandra without JVM ○ same protocol, SSTable compatibility ● C++ and Seastar lib ● up to 1,000,000 IOPS/node ● not fully supported by Akka Persistence
  • 52. Event serialization ● plain text ○ JSON ○ XML ○ YAML ● binary ○ java serialization ○ Avro ○ Protocol Buffers (Protobuf) ○ Thrift ○ Kryo
  • 53. Plain text Binary human-readable deserialization required
  • 54. Plain text Binary human-readable deserialization required precision issues (JSON IEEE 754, DoS) -
  • 55. Plain text Binary human-readable deserialization required precision issues (JSON IEEE 754, DoS) - storage consumption compress
  • 56. Plain text Binary human-readable deserialization required precision issues (JSON IEEE 754, DoS) - storage consumption compress slow fast
  • 57. Plain text Binary human-readable deserialization required precision issues (JSON IEEE 754, DoS) - storage consumption compress slow fast poor schema evolution support full schema evolution support
  • 58. Binary ● java serialization ● Avro ● Protocol Buffers (Protobuf) ● Thrift ● Kryo
  • 59. Binary ● java serialization ● Avro ● Protocol Buffers (Protobuf) ● Thrift ● Kryo
  • 60. Binary ● java serialization ● Avro ● Protocol Buffers (Protobuf) ● Thrift ● Kryo
  • 61. Binary ● java serialization ● Avro ● Protocol Buffers (Protobuf) ● Thrift ● Kryo
  • 62. Multi-language support ● Avro ○ C, C++, C#, Go, Haskell, Java, Perl, PHP, Python, Ruby, Scala ● Protocol Buffers (Protobuf) ○ even more than Avro
  • 65. ● backward - V2 can read V1 Full compatibility Application Events V1 V2
  • 66. ● forward - V2 can read V3 Full compatibility Application Events V1, V2 V2 Application Application V2 V3
  • 67. ● forward - V2 can read V3 Full compatibility Events Read model Read model Read models Projector V2 V3
  • 68. Schema evolution - full compatibility Protocol Buffers Avro Add field + (optional) + (default value) Remove field + + (default value) Rename field + + (aliases) https://martin.kleppmann.com/2012/12/05/schema-evolution-in-avro-protocol-buffers-thrift.html
  • 69. Protobuf schema management //user-events.proto message UserCreatedEvent { string user_id = 1; string operation_id = 2; int64 created_at = 3; string name = 4; string email = 5; } package user.application UserCreatedEvent( userId: String, operationId: String, createdAt: Long, name: String, email: String )
  • 70. Protobuf schema management package user.domain UserCreated( userId: UserId, operationId: OperationId, createdAt: Instant, name: String, email: Email ) extends UserEvent package user.application UserCreatedEvent( userId: String, operationId: String, createdAt: Long, name: String, email: String )
  • 71. Protobuf schema management ● def toDomain(event: UserCreatedEvent): UserEvent.UserCreated ● def toSerializable(event: UserEvent.UserCreated): UserCreatedEvent
  • 72. Protobuf schema management + clean domain - a lot of boilerplate code
  • 73. Avro schema management package user.domain UserCreated( userId: UserId, operationId: OperationId, createdAt: Instant, name: String, email: Email ) extends UserEvent { "type" : "record", "name" : "UserCreated", "namespace" : "info.ludwikowski.es.user.domain", "fields" : [ { "name" : "userId", "type" : "string" }, { "name" : "operationId", "type" : "string" }, { "name" : "createdAt", "type" : "long" }, { "name" : "name", "type" : "string" }, { "name" : "email", "type" : "string" } ] }
  • 74. Avro deserialization Bytes Deserialization Object Reader Schema Writer Schema
  • 75. Avro writer schema source ● add schema to the payload ● custom solution ○ schema in /resources ○ schema in external storage (must be fault-tolerant) ○ Darwin project ● Schema Registry
  • 76. Avro schema management package user.domain UserCreated( userId: UserId, operationId: OperationId, createdAt: Instant, name: String, email: Email ) extends UserEvent { "type" : "record", "name" : "UserCreated", "namespace" : "info.ludwikowski.es.user.domain", "fields" : [ { "name" : "userId", "type" : "string" }, { "name" : "operationId", "type" : "string" }, { "name" : "createdAt", "type" : "long" }, { "name" : "name", "type" : "string" }, { "name" : "email", "type" : "string" } ] }
  • 77. Protocol Buffers vs. Avro { "type" : "record", "name" : "UserCreated", "namespace" : "info.ludwikowski.es.user.domain", "fields" : [ { "name" : "userId", "type" : "string" }, { "name" : "operationId", "type" : "string" }, { "name" : "createdAt", "type" : "long" }, { "name" : "name", "type" : "string" }, { "name" : "email", "type" : "string" } ] } message UserCreatedEvent { string user_id = 1; string operation_id = 2; int64 created_at = 3; string name = 4; string email = 5; }
  • 78. Avro schema management + less boilerplate code +/- clean domain - reader & writer schema distribution
  • 79. Avro + less boilerplate code +/- clean domain - reader & writer schema distribution Protobuf + clean domain - a lot of boilerplate code
  • 80. Avro vs. Protocol Buffers ● The best serialization strategy for Event Sourcing
  • 81. Event payload ● delta event ● rich event (event enrichment) ● + metadata ○ seq_num ○ created_at ○ event_id ○ command_id ○ correlation_id
  • 84. State replay time ● snapshotting ● write-through cache
  • 87. Immutable vs. mutable state? ● add/remove ImmutableList 17.496 ops/s ● add/remove TreeMap 2201.731 ops/s
  • 89. Updating all aggregates User(id) Command(user_id) Event(user_id) Event(user_id) Event(user_id)
  • 94. Event + seq_no Event + seq_no Handling duplicates Events Read model Read model Read models Projector event bus Event + seq_no read model update + seq_no Events
  • 95. Broken read model Events ad model ead model Read models Projector event bus Events
  • 96. Broken read model Events ad model ead model Read models Projector event bus read model update + offset (manual offset management) Events
  • 97. Multi aggregate transactional update ● rethink aggregates boundaries ● compensating action ○ optimistic ○ pessimistic
  • 99. Pessimistic compensation action User account Cinema show charged
  • 100. Pessimistic compensation action User account Cinema show charged booked
  • 101. Pessimistic compensation action User account Cinema show charged booked sold out
  • 102. Pessimistic compensation action User account Cinema show charged booked booked sold out
  • 103. Pessimistic compensation action User account Cinema show charged booked booked sold out
  • 104. Pessimistic compensation action User account Cinema show charged booked booked sold out refund
  • 105. Optimistic compensation action User account Cinema show charged booked sold out
  • 106. Optimistic compensation action User account Cinema show booked booked sold out overbooked
  • 107. Optimistic compensation action User account Cinema show charged booked booked sold out overbooked ?
  • 108. Saga Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Updater event bus Transaction
  • 109. Saga - choreography Command Service Domain Events Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction
  • 110. Saga - orchestration Command Service Domain Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Transaction Command Service Domain Events Commands
  • 111. Saga ● should be persistable ● events order should be irrelevant ● time window limitation ● compensating action must be commutative
  • 112. Saga ● Sagas with ES ● DDD, Saga & Event-sourcing ● Applying Saga Pattern ● Microservice Patterns
  • 113. ES with RODO/GDPR ● “right to forget” with: ○ data shredding (and/or deleting) ■ events, state, views, read models ○ retention policy ■ message brokers, backups, logs ○ data before RODO migration
  • 114. ES and CQRS level 3.2 Events Client Query Service Data access Commands Queries Read model Read model Read models Projector event bus Command Service Domain Command Service Domain Command Service Domain Transaction Sharding Clustering
  • 115. Cluster = split brain 1 5 4 3 Load balancer 2
  • 116. Cluster = split brain 1 5 4 3 Load balancer 2 User(1) Command(1)
  • 117. Cluster = split brain 1 5 4 3 Load balancer 2
  • 118. Cluster = split brain 1 5 4 3 Load balancer 2 User(1)
  • 119. Cluster = split brain 1 5 4 3 Load balancer 2 User(1) Command(1) User(1)
  • 120. Cluster = split brain 1 5 4 3 Load balancer 2 User(1) Command(1) User(1) Command(1)
  • 121. Cluster best practises ● remember about the split brain ● very good monitoring & alerting ● a lot of failover tests ● cluster also on dev/staging ● keep it as small as possible (code base, number of nodes, etc.)
  • 122. Summary ● carefully choose ES lib/framework ● there is no perfect database for event sourcing ● understand event/command/state schema evolution ● eventual consistency is your friend ● scaling is complex ● database inside-out ● log-based processing mindset
  • 123. Want to learn more? ● Reactive Event Sourcing with Akka (Java/Scala) ● Akka Typed Fundamentals (Java/Scala) ● Akka Cluster ● Performance tests with Gatling
  • 126. Thank you and Q&A ➔ ➔ ludwikowski.info ➔ github.com/aludwiko ➔ @aludwikowski
  • 128. Thank you and Q&A ➔ ➔ ludwikowski.info ➔ github.com/aludwiko ➔ @aludwikowski