SlideShare ist ein Scribd-Unternehmen logo
1 von 19
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

Weitere ähnliche Inhalte

Ähnlich wie Event Driven Architectures

Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture  Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture Yaroslav Tkachenko
 
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...Anton Kirillov
 
Introduction to kubernetes
Introduction to kubernetesIntroduction to kubernetes
Introduction to kubernetesRishabh Indoria
 
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 CloudEventsNeil Avery
 
Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Thomas Bailet
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flinkRenato Guimaraes
 
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 messageJosef Karásek
 
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...Amazon Web Services
 
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 ...Brittany Ingram
 
A Tour of Apache Kafka
A Tour of Apache KafkaA Tour of Apache Kafka
A Tour of Apache Kafkaconfluent
 
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...javier ramirez
 
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...confluent
 
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 CassandraLuke Tillman
 
Kubernetes #1 intro
Kubernetes #1   introKubernetes #1   intro
Kubernetes #1 introTerry Cho
 
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 2020Andrea Scuderi
 
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 PracticesAntonios Giannopoulos
 
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 PersistenceKonrad Dusza
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
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 Modelsaagamshah0812
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
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 GoalsJhone kinadey
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 

Kürzlich hochgeladen (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
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
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

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

Hinweis der Redaktion

  1. The difference between Key and MessageId will be handled later when we talk about duplication
  2. The difference between Key and MessageId will be handled later when we talk about duplication
  3. The difference between Key and MessageId will be handled later when we talk about duplication
  4. The difference between Key and MessageId will be handled later when we talk about duplication
  5. The difference between Key and MessageId will be handled later when we talk about duplication
  6. The difference between Key and MessageId will be handled later when we talk about duplication
  7. TODO: Add some diagrams similar to the ones found here: https://betterprogramming.pub/how-to-handle-duplicate-messages-and-message-ordering-in-kafka-82e2fef82025
  8. CDC = Change Data Capture