SlideShare a Scribd company logo
1 of 19
Download to read offline
Event-Driven
Architectures
Version 1
Event Driven Architectures
BENEFITS
● Async communication between microservices based on events
● Decoupled microservices, enables teams to act more independently, increases velocity
● Using Kafka as the event backbone, increases resilience, applications can restart, recover events or replay
them
● Data store of immutable append-only logs
DRAWBACKS
● Need for handling of duplicate events
● Lack of clear workflow order
● Complex error handling
● Requires a comprehensive set of monitoring tools
Version 1: Events for async communication
between services:
Deployment Overview
● The project is deployed on AWS EKS using Terraform
● AWS RDS - Postgres is used for the database
● Fully Managed Apache Kafka - MSK
● Infrastructure as Code with Terraform
● Bastion service to provide an API for configuring Postgres and Kafka using Golang
Microservices Overview
● OrderService: Responsible for the order creation. Creates the initial event to the Orders Topic
● UserService: Handles user information, user addresses etc
● PaymentService: Contacts the payment provider and handles payment failures
● WarehouseService: Validates the orders based on the available items stock. Handles the
shipment of the order
● EmailService: Informs the user about the final status of the order by sending an email using an
external email provider
Single Writer Principle
● Responsibility for propagating events of a specific type to a single service
● Improves consistency and validation
● Team that manages a services has ownership of the schema and versioning of the events
● E.g. OrderServices controls every state change made to an Orders
Topics
● Orders: OrderRequested, OrderValidated, OrderPaid, OrderShipped
● OrderValidations: OrderValidationValidated, OrderValidationOutOfStock
● Payments: PaymentSucceeded, PaymentFailed
● Shipments: ShipmentShipped, ShipmentFailed, ShipmentDelivered
Event flow
Event structure
● Generic Message interface with payload and
messageId
● messageId should be a message specific id,
not the same as the unique id of a Domain
Object
● Record the Key-Value Pair send as an Event
to Kafka
● Key of the Record should be the unique id of
the Domain Object ( e.g. orderId)
interface Message <T> {
val payload: T
val messageId: UUID
}
data class OrderMessage(
override val payload: Order,
override val messageId: UUID
) : Message<Order>
fun Order.toOrderMessageRecord():
Record<String, OrderMessage> =
Record.of(
id.toString(),
OrderMessage(
payload = this,
messageId = UUID.randomUUID()
)
)
Event ordering
● Kafka topics are partitioned and spread over a
number of partitions
● Events with the same key are always written to
same the partition
● Orders Events with the same order id are always
written to the same partition
● This guarantees that events for the same order
with specific order status are put in one partition
with a particular order
enum class OrderStatus {
REQUESTED,
VALIDATED,
OUT_OF_STOCK,
PAID,
SHIPPED,
COMPLETED,
PAYMENT_FAILED,
CANCELLED,
REFUNDED,
SHIPMENT_FAILED
}
Record.of(
order.id,
OrderMessage(
payload = order,
messageId = UUID.randomUUID()
)
)
Avoiding duplicate Events
● Ideally Kafka would send every event once, but failures could lead to a Consumer receiving the same
event multiple times
● An offset (increasing integer value) is used to track which messages are already consumed
● Each message in a specific partition has a unique offset
● enable.auto.commit has to be set to false
● Idempotent event handlers can be used which behave like a Http PUT operation.
● Unfortunately not every operation is idempotent
Avoiding duplicate Events 2
● Tracking received events with the support of an
ACID database can help us guarantee exactly once
delivery
● When receiving an event we create a
ProcessedEvent object with eventId set to the
messageId included in the received event
● We wrap then any DB update in a transaction
with an record insert into the ProcessedEventEntity
table
● If an event is already processed the DB insert will
fail and the transaction will be rolled back
● Commit back the event as successfully processed
on Kafka, even in case of a received duplicate, so
that we don’t receive it again
data class ProcessedEvent(
val eventId: UUID,
val processedAt: Instant
)
@Entity
@Table(name = "processed_events")
class ProcessedEventEntity(
@Column(nullable = false, name =
"event_id")
@Id
var eventId: UUID,
@Column(nullable = false, name =
"processed_at")
var processedAt: Instant,
@CreationTimestamp
@Column(name = "created_at")
var createdAt: Instant? = null,
@UpdateTimestamp
@Column(name = "updated_at")
var updatedAt: Instant? = null
)
Kafka specific settings
● kafka.acks = all, number of acknowledgments the producer requires the leader to have received before considering a
request complete
○ Events written to the partition leader are not immediately readable by consumers
○ Only when all in-sync replicas have acknowledged the write the message is considered committed
○ This ensures that messages cannot be lost by a broker failure
● kafka.enable.idempotence = true
○ Producer will ensure that exactly one copy of each message is written in the stream
● kafka.enable.auto.commit = false
○ Controls if the consumer will commit offsets automatically. Using auto commit gives us “at least once”
delivery, as Kafka guarantees that no messages will be missed, but duplicates are possible.
Error handling strategies
● Dead Letter Queue (Topic)
● Retry Topic, before sending to the DLQ
Drawbacks and alternatives
DRAWBACKS
● No atomicity between Kafka and Database
● Complex to write and manage custom distributed transactions
● Undetermined state when some type of failures happen
○ No guarantee that the DB transaction will commit, if sending the Event in the middle of the transaction
○ If sending the Event after the DB transaction, no guarantee that it won’t crash when sending the Event
○ E.g. after creating a new Order in the DB when the OrderRequested Event to Kafka fails: Undetermined state
ALTERNATIVES
● CDC (Debezium) and Outbox Pattern
● Kafka Streams
Let’s see some code snippets!
https://github.com/arconsis/Eshop-EDA
References
● Kafka The Definitive Guide by Neha Narkhede, Gwen Shapira, Todd Palino:
https://www.amazon.com/Kafka-Definitive-Real-Time-Stream-Processing/dp/1491936169
● Designing event driven systems by Ben Stopford (https://www.confluent.io/designing-event-driven-
systems/)
Contact Info
● arconsis:
○ Website: https://www.arconsis.com
○ Github: https://github.com/arconsis
● Dimos Botsaris:
○ Website: https://www.eldimious.com/
○ Github: https://github.com/eldimious
○ Email: botsaris.d@gmail.com
● Alexandros Koufatzis:
○ Github: https://github.com/akoufa
○ Email: akoufa@gmail.com
 Event Driven Architectures

More Related Content

Similar to Event Driven Architectures

Similar to Event Driven Architectures (20)

Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture  Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture
 
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...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
 
Introduction to kubernetes
Introduction to kubernetesIntroduction to kubernetes
Introduction to kubernetes
 
Serverless London 2019 FaaS composition using Kafka and CloudEvents
Serverless London 2019   FaaS composition using Kafka and CloudEventsServerless London 2019   FaaS composition using Kafka and CloudEvents
Serverless London 2019 FaaS composition using Kafka and CloudEvents
 
Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Logisland "Event Mining at scale"
Logisland "Event Mining at scale"
 
Siddhi - cloud-native stream processor
Siddhi - cloud-native stream processorSiddhi - cloud-native stream processor
Siddhi - cloud-native stream processor
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flink
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 
A day in the life of a log message
A day in the life of a log messageA day in the life of a log message
A day in the life of a log message
 
How Netflix Uses Amazon Kinesis Streams to Monitor and Optimize Large-scale N...
How Netflix Uses Amazon Kinesis Streams to Monitor and Optimize Large-scale N...How Netflix Uses Amazon Kinesis Streams to Monitor and Optimize Large-scale N...
How Netflix Uses Amazon Kinesis Streams to Monitor and Optimize Large-scale N...
 
How Docker Accelerates Continuous Development at ironSource: Containers #101 ...
How Docker Accelerates Continuous Development at ironSource: Containers #101 ...How Docker Accelerates Continuous Development at ironSource: Containers #101 ...
How Docker Accelerates Continuous Development at ironSource: Containers #101 ...
 
A Tour of Apache Kafka
A Tour of Apache KafkaA Tour of Apache Kafka
A Tour of Apache Kafka
 
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
Como creamos QuestDB Cloud, un SaaS basado en Kubernetes alrededor de QuestDB...
 
Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...
Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...
Creating Connector to Bridge the Worlds of Kafka and gRPC at Wework (Anoop Di...
 
Avoiding the Pit of Despair - Event Sourcing with Akka and Cassandra
Avoiding the Pit of Despair - Event Sourcing with Akka and CassandraAvoiding the Pit of Despair - Event Sourcing with Akka and Cassandra
Avoiding the Pit of Despair - Event Sourcing with Akka and Cassandra
 
Kubernetes #1 intro
Kubernetes #1   introKubernetes #1   intro
Kubernetes #1 intro
 
Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020
 
Using MongoDB with Kafka - Use Cases and Best Practices
Using MongoDB with Kafka -  Use Cases and Best PracticesUsing MongoDB with Kafka -  Use Cases and Best Practices
Using MongoDB with Kafka - Use Cases and Best Practices
 
Event Sourcing and beyond with Akka.NET Persistence
Event Sourcing and beyond with Akka.NET PersistenceEvent Sourcing and beyond with Akka.NET Persistence
Event Sourcing and beyond with Akka.NET Persistence
 
Apache Kafka Streams
Apache Kafka StreamsApache Kafka Streams
Apache Kafka Streams
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

Event Driven Architectures

  • 2. Event Driven Architectures BENEFITS ● Async communication between microservices based on events ● Decoupled microservices, enables teams to act more independently, increases velocity ● Using Kafka as the event backbone, increases resilience, applications can restart, recover events or replay them ● Data store of immutable append-only logs DRAWBACKS ● Need for handling of duplicate events ● Lack of clear workflow order ● Complex error handling ● Requires a comprehensive set of monitoring tools
  • 3. Version 1: Events for async communication between services:
  • 4. Deployment Overview ● The project is deployed on AWS EKS using Terraform ● AWS RDS - Postgres is used for the database ● Fully Managed Apache Kafka - MSK ● Infrastructure as Code with Terraform ● Bastion service to provide an API for configuring Postgres and Kafka using Golang
  • 5. Microservices Overview ● OrderService: Responsible for the order creation. Creates the initial event to the Orders Topic ● UserService: Handles user information, user addresses etc ● PaymentService: Contacts the payment provider and handles payment failures ● WarehouseService: Validates the orders based on the available items stock. Handles the shipment of the order ● EmailService: Informs the user about the final status of the order by sending an email using an external email provider
  • 6. Single Writer Principle ● Responsibility for propagating events of a specific type to a single service ● Improves consistency and validation ● Team that manages a services has ownership of the schema and versioning of the events ● E.g. OrderServices controls every state change made to an Orders
  • 7. Topics ● Orders: OrderRequested, OrderValidated, OrderPaid, OrderShipped ● OrderValidations: OrderValidationValidated, OrderValidationOutOfStock ● Payments: PaymentSucceeded, PaymentFailed ● Shipments: ShipmentShipped, ShipmentFailed, ShipmentDelivered
  • 9. Event structure ● Generic Message interface with payload and messageId ● messageId should be a message specific id, not the same as the unique id of a Domain Object ● Record the Key-Value Pair send as an Event to Kafka ● Key of the Record should be the unique id of the Domain Object ( e.g. orderId) interface Message <T> { val payload: T val messageId: UUID } data class OrderMessage( override val payload: Order, override val messageId: UUID ) : Message<Order> fun Order.toOrderMessageRecord(): Record<String, OrderMessage> = Record.of( id.toString(), OrderMessage( payload = this, messageId = UUID.randomUUID() ) )
  • 10. Event ordering ● Kafka topics are partitioned and spread over a number of partitions ● Events with the same key are always written to same the partition ● Orders Events with the same order id are always written to the same partition ● This guarantees that events for the same order with specific order status are put in one partition with a particular order enum class OrderStatus { REQUESTED, VALIDATED, OUT_OF_STOCK, PAID, SHIPPED, COMPLETED, PAYMENT_FAILED, CANCELLED, REFUNDED, SHIPMENT_FAILED } Record.of( order.id, OrderMessage( payload = order, messageId = UUID.randomUUID() ) )
  • 11. Avoiding duplicate Events ● Ideally Kafka would send every event once, but failures could lead to a Consumer receiving the same event multiple times ● An offset (increasing integer value) is used to track which messages are already consumed ● Each message in a specific partition has a unique offset ● enable.auto.commit has to be set to false ● Idempotent event handlers can be used which behave like a Http PUT operation. ● Unfortunately not every operation is idempotent
  • 12. Avoiding duplicate Events 2 ● Tracking received events with the support of an ACID database can help us guarantee exactly once delivery ● When receiving an event we create a ProcessedEvent object with eventId set to the messageId included in the received event ● We wrap then any DB update in a transaction with an record insert into the ProcessedEventEntity table ● If an event is already processed the DB insert will fail and the transaction will be rolled back ● Commit back the event as successfully processed on Kafka, even in case of a received duplicate, so that we don’t receive it again data class ProcessedEvent( val eventId: UUID, val processedAt: Instant ) @Entity @Table(name = "processed_events") class ProcessedEventEntity( @Column(nullable = false, name = "event_id") @Id var eventId: UUID, @Column(nullable = false, name = "processed_at") var processedAt: Instant, @CreationTimestamp @Column(name = "created_at") var createdAt: Instant? = null, @UpdateTimestamp @Column(name = "updated_at") var updatedAt: Instant? = null )
  • 13. Kafka specific settings ● kafka.acks = all, number of acknowledgments the producer requires the leader to have received before considering a request complete ○ Events written to the partition leader are not immediately readable by consumers ○ Only when all in-sync replicas have acknowledged the write the message is considered committed ○ This ensures that messages cannot be lost by a broker failure ● kafka.enable.idempotence = true ○ Producer will ensure that exactly one copy of each message is written in the stream ● kafka.enable.auto.commit = false ○ Controls if the consumer will commit offsets automatically. Using auto commit gives us “at least once” delivery, as Kafka guarantees that no messages will be missed, but duplicates are possible.
  • 14. Error handling strategies ● Dead Letter Queue (Topic) ● Retry Topic, before sending to the DLQ
  • 15. Drawbacks and alternatives DRAWBACKS ● No atomicity between Kafka and Database ● Complex to write and manage custom distributed transactions ● Undetermined state when some type of failures happen ○ No guarantee that the DB transaction will commit, if sending the Event in the middle of the transaction ○ If sending the Event after the DB transaction, no guarantee that it won’t crash when sending the Event ○ E.g. after creating a new Order in the DB when the OrderRequested Event to Kafka fails: Undetermined state ALTERNATIVES ● CDC (Debezium) and Outbox Pattern ● Kafka Streams
  • 16. Let’s see some code snippets! https://github.com/arconsis/Eshop-EDA
  • 17. References ● Kafka The Definitive Guide by Neha Narkhede, Gwen Shapira, Todd Palino: https://www.amazon.com/Kafka-Definitive-Real-Time-Stream-Processing/dp/1491936169 ● Designing event driven systems by Ben Stopford (https://www.confluent.io/designing-event-driven- systems/)
  • 18. Contact Info ● arconsis: ○ Website: https://www.arconsis.com ○ Github: https://github.com/arconsis ● Dimos Botsaris: ○ Website: https://www.eldimious.com/ ○ Github: https://github.com/eldimious ○ Email: botsaris.d@gmail.com ● Alexandros Koufatzis: ○ Github: https://github.com/akoufa ○ Email: akoufa@gmail.com