SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Akka Microservices Architecture And
Design
Yaroslav Tkachenko
Senior Software Engineer at Demonware (Activision)
@sap1ens
✋
Actors
● Communicate with asynchronous messages
instead of method invocations
● Manage their own state
● When responding to a message, can:
○ Create other (child) actors
○ Send messages to other actors
○ Stop (child) actors or themselves
📬 📬
📬
object MyActor {
case class Greeting(from: String)
case object Goodbye
}
class MyActor extends Actor with ActorLogging {
import MyActor._
def receive = {
case Greeting(greeter) => log.info(s"I was greeted by $greeter.")
case Goodbye => log.info("Someone said goodbye to me.")
}
}
val system = ActorSystem("mySystem")
val myActor = system.actorOf(Props[MyActor], "myactor")
myActor ! Greeting("another actor")
Actor != Class
loop() ->
receive
{From, Msg} ->
io:format("received ~p~n", [Msg]),
From ! "got it";
end.
Erlang
object HelloWorld {
final case class Greet(whom: String, replyTo: ActorRef[Greeted])
final case class Greeted(whom: String)
val greeter = Actor.immutable[Greet] { (_, msg) ⇒
println(s"Hello ${msg.whom}!")
msg.replyTo ! Greeted(msg.whom)
Actor.same
}
}
Akka Typed
Actor Systems
??? What the ...
● I know MVC!
● How do I do DI?
● What about that pattern X?
● Does it follow SOA?
● Microservices?
Domain-Driven Design
● Focus on core domain and business logic
● Base complex designs on the domain model
● Collaborate with domain experts (ubiquitous language)
● Strategic and tactical patterns
Tactical Patterns
Entity (Case Class)
● Account
● User
● Transaction
Value object (Trait)
● Checking | Savings | Credit Card
● Active | Inactive
● Debit | Credit
Entities contain business logic only involving their own state.
We can also call this logic pure.
● Account.addBalance
● User.isDisabled
● Transaction.hasLedger
Event (Actor Message - Case Class) is simply a fact that
something happened.
● AccountDeactivated(account)
● UserCreated(user)
● TransactionUpdated(transaction, transaction)
Command (Actor Message - Case Class) is a direct
instruction for data manipulation, retrieval or a side-effect.
● DeactivateAccount(account)
● CreateUser(user)
● UpdateTransaction(transaction)
Repository (Actor OR Object/Class) is a way to access or
modify domain data and produce a set of entities.
● accountRepository ! FindAccountById(id)
● userRepository ! UpdateUserName(id, name)
● transactionRepository !
FindAllTransactionsBetween(date, date)
Domain Services (Actors) manage multiple entities and/or
communicate with other services and repositories to
implement complex logic.
They’re usually stateless.
● accountService ! DeactivateAccount(account)
● userService ! RegisterUser(name, email, type)
● transactionService ! MergeTransactions(transaction,
transaction)
How about Aggregate Roots?
We defined an Application Core, containing our Domain
model and business logic. We haven’t yet discussed:
● APIs
● Integrations
● Security
● etc.
Application Services implement Adapter pattern and they’re
explicitly located outside of the Application Core. Usually
represented as Actors. They can be responsible for:
● Communication via HTTP, RPC APIs, messaging queues
● Integrations with 3rd-party systems
● Security, caching, etc.
Strategical Patterns
How (assuming we should) do we split our Domain Model
into multiple [micro]services?
Domain
Bounded Context Bounded Context
Subdomain
Subdomain
Subdomain
Subdomain
Subdomain
Subdomain
Sweet spots for service boundaries!
Online education service
User Management Courses
User profiles
Achievements
Billing
Catalog
Content
management
Reviews
So, our [micro]services are:
- Completely isolated
- Deployed separately
- Have different actor systems
- Have clear boundaries from DDD perspective
Now we have multiple [micro]services running multiple actor
systems. How do they communicate?
- Synchronously, over HTTP/RPC
- Asynchronously, over messaging
It is unfortunate that synchronous HTTP is
widely considered as the go-to Microservice
communication protocol. Its synchronous
nature introduces strong coupling
between services which makes it a very bad
default protocol for inter-service
communication.
Instead, communication between
Microservices needs to be based on
Asynchronous Message-Passing. Having
an asynchronous boundary between services
is necessary in order to decouple them, and
their communication flow:
• in time: for concurrency, and
• in space: for distribution and mobility
Bla bla microservices bla bla
Jonas Bonér
CTO of Lightbend
Messaging with actors
UserService
UserCreated
EmailSender
Service
SendEmail
Routing
QueueProducer
Adapter
QueueConsumer
Adapter
Core Core
Adapters Adapters
Message routing is very specific to your domain:
- Use ActiveMQ/RabbitMQ by default and see if you can
survive with static topics/queues
- Add custom middleware layer for routing (consumer and
producer at the same time)
- Use Kafka with Kafka Streams / Akka Streams
EIP was published in 2003 and it contains 65 patterns.
Apache Camel:
- Integration framework based on EIP
- akka-camel is an official Akka library
- Can be used with any JVM language
- “The most unknown coolest library out there” (©) JM
class CustomerService extends Actor with ActorLogging with Consumer {
val camel = CamelExtension(system)
camel.context.addComponent("activemq", ActiveMQComponent.activeMQComponent(
"tcp://localhost:61616"
))
def endpointUri = "activemq:topic:events"
def receive = {
case e: CamelMessage => {
sender() ! "SomeMessage"
}
}
}
Apache Camel
Alpakka - Enterprise Integration Done Right ©
- Built in top of Akka Streams
- Back-pressure all the way
- Still in active development
Stateful services
Stateful application service keeps all data inside the
application instead of an external storage (like database
or cache)
Why discuss stateful services?
Example, service requirements:
- Need to be really fast (low latency)
- Should have “strong” consistency (at least within one
entity), no stale data
- Should be highly available (HA)
- Lots of data
- [Maybe] very complex queries
Which means:
- Might be very challenging to use a database
- Can’t use caching
- Solution: stateful service. Keeping data and application
logic together
Naive approach:
- Just keeping data in memory. Ok…
- Need to make service HA, running at least 2 nodes. Ok…
- Now we have duplicated data. How do we route
requests? Sticky LB? Some partitioning?
- Or what if our data volume is too big for one node?
- We need to shard it. How?
- Akka Cluster Sharding + Akka Persistence FTW!
Akka Clustering is a cluster membership service:
- Gossip-based
- No SPOF
- Eventually consistent
- Failure detection built-in
Powerful collection of patterns for building distributed
applications:
- Cluster Routing
- Cluster Pub/Sub
- Cluster Singleton
- Cluster Sharding
Akka Persistence allows actors to persist internal state to an
external storage and recover after restarts and crashes:
- Event sourcing applied to an internal actor state
- RDBMS, NoSQL, caches and and queues as storage
- Snapshotting for fast recovery
Akka Cluster Sharding + Akka Persistence = ❤️
StatsService
1 3 5
StatsService
2 4 6
statsServiceRegion ! GetStats(userId)
Stateful services with Akka:
- Routing, sharding and recovery built-in
- You still just deal with actors!
- Akka Distributed Data can be used instead of external
storage
It’s important to remember that Akka Clustering application
is still restricted by the bounded context (or subdomain) and
it should be used within the microservice boundary.
Summary
- Akka is great!
- Use Domain-Driven Design for modelling your application
core and understanding service boundaries
- Use Enterprise Integration Patterns for developing your
asynchronous messaging design
- Look at Akka Clustering and Persistence for complex
problems with distributed services
Questions?
@sap1ens
sap1ens.com

Weitere ähnliche Inhalte

Was ist angesagt?

Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
SANG WON PARK
 
Real-Time Dynamic Data Export Using the Kafka Ecosystem
Real-Time Dynamic Data Export Using the Kafka EcosystemReal-Time Dynamic Data Export Using the Kafka Ecosystem
Real-Time Dynamic Data Export Using the Kafka Ecosystem
confluent
 
AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。
AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。
AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。
Takehiro Suemitsu
 

Was ist angesagt? (20)

EC2上のWordPressをShifterに移行してみた!
 EC2上のWordPressをShifterに移行してみた! EC2上のWordPressをShifterに移行してみた!
EC2上のWordPressをShifterに移行してみた!
 
20180509 AWS Black Belt Online Seminar Amazon GuardDuty
20180509 AWS Black Belt Online Seminar Amazon GuardDuty20180509 AWS Black Belt Online Seminar Amazon GuardDuty
20180509 AWS Black Belt Online Seminar Amazon GuardDuty
 
Redshift Spectrumを使ってみた話
Redshift Spectrumを使ってみた話Redshift Spectrumを使ってみた話
Redshift Spectrumを使ってみた話
 
20180522 AWS Black Belt Online Seminar 失敗例を成功に変えるアンチパターン
20180522 AWS Black Belt Online Seminar 失敗例を成功に変えるアンチパターン20180522 AWS Black Belt Online Seminar 失敗例を成功に変えるアンチパターン
20180522 AWS Black Belt Online Seminar 失敗例を成功に変えるアンチパターン
 
Amazon Kinesis Familyを活用したストリームデータ処理
Amazon Kinesis Familyを活用したストリームデータ処理Amazon Kinesis Familyを活用したストリームデータ処理
Amazon Kinesis Familyを活用したストリームデータ処理
 
ksqlDB로 실시간 데이터 변환 및 스트림 처리
ksqlDB로 실시간 데이터 변환 및 스트림 처리ksqlDB로 실시간 데이터 변환 및 스트림 처리
ksqlDB로 실시간 데이터 변환 및 스트림 처리
 
Kubernetes Forum Seoul 2019: Re-architecting Data Platform with Kubernetes
Kubernetes Forum Seoul 2019: Re-architecting Data Platform with KubernetesKubernetes Forum Seoul 2019: Re-architecting Data Platform with Kubernetes
Kubernetes Forum Seoul 2019: Re-architecting Data Platform with Kubernetes
 
Deep Dive on AWS Lambda
Deep Dive on AWS LambdaDeep Dive on AWS Lambda
Deep Dive on AWS Lambda
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
[REPEAT 1] Elastic Load Balancing: Deep Dive and Best Practices (NET404-R1) -...
 
Real-Time Dynamic Data Export Using the Kafka Ecosystem
Real-Time Dynamic Data Export Using the Kafka EcosystemReal-Time Dynamic Data Export Using the Kafka Ecosystem
Real-Time Dynamic Data Export Using the Kafka Ecosystem
 
AWS Black Belt Techシリーズ AWS Key Management Service
AWS Black Belt Techシリーズ AWS Key Management ServiceAWS Black Belt Techシリーズ AWS Key Management Service
AWS Black Belt Techシリーズ AWS Key Management Service
 
はじめてのAWS CLI
はじめてのAWS CLIはじめてのAWS CLI
はじめてのAWS CLI
 
[Main Session] 카프카, 데이터 플랫폼의 최강자
[Main Session] 카프카, 데이터 플랫폼의 최강자[Main Session] 카프카, 데이터 플랫폼의 최강자
[Main Session] 카프카, 데이터 플랫폼의 최강자
 
Securing Kafka
Securing Kafka Securing Kafka
Securing Kafka
 
AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。
AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。
AWSでAPI Gatewayから非同期でLambdaを起動してS3にファイルアップロードしようとしたらハマった話。
 
Apache kafka 관리와 모니터링
Apache kafka 관리와 모니터링Apache kafka 관리와 모니터링
Apache kafka 관리와 모니터링
 
[AWS Builders] Effective AWS Glue
[AWS Builders] Effective AWS Glue[AWS Builders] Effective AWS Glue
[AWS Builders] Effective AWS Glue
 
Kafka Tutorial Advanced Kafka Consumers
Kafka Tutorial Advanced Kafka ConsumersKafka Tutorial Advanced Kafka Consumers
Kafka Tutorial Advanced Kafka Consumers
 
AWS Black Belt Online Seminar 2017 AWS WAF
AWS Black Belt Online Seminar 2017 AWS WAFAWS Black Belt Online Seminar 2017 AWS WAF
AWS Black Belt Online Seminar 2017 AWS WAF
 

Ähnlich wie Akka Microservices Architecture And Design

Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
Salesforce Developers
 
ReactiveSummeriserAkka-ScalaByBay2016
ReactiveSummeriserAkka-ScalaByBay2016ReactiveSummeriserAkka-ScalaByBay2016
ReactiveSummeriserAkka-ScalaByBay2016
Ho Tien VU
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 

Ähnlich wie Akka Microservices Architecture And Design (20)

Actor model in .NET - Akka.NET
Actor model in .NET - Akka.NETActor model in .NET - Akka.NET
Actor model in .NET - Akka.NET
 
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
 
Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
 
Akka (1)
Akka (1)Akka (1)
Akka (1)
 
ReactiveSummeriserAkka-ScalaByBay2016
ReactiveSummeriserAkka-ScalaByBay2016ReactiveSummeriserAkka-ScalaByBay2016
ReactiveSummeriserAkka-ScalaByBay2016
 
[ScalaByTheBay2016] Implement a scalable statistical aggregation system using...
[ScalaByTheBay2016] Implement a scalable statistical aggregation system using...[ScalaByTheBay2016] Implement a scalable statistical aggregation system using...
[ScalaByTheBay2016] Implement a scalable statistical aggregation system using...
 
DotNext 2020 - When and How to Use the Actor Model and Akka.NET
DotNext 2020 - When and How to Use the Actor Model and Akka.NETDotNext 2020 - When and How to Use the Actor Model and Akka.NET
DotNext 2020 - When and How to Use the Actor Model and Akka.NET
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Building Stateful Microservices With Akka
Building Stateful Microservices With AkkaBuilding Stateful Microservices With Akka
Building Stateful Microservices With Akka
 
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYCBuilding a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den Hoek
 
Case Study: Elasticsearch Ingest Using StreamSets at Cisco Intercloud
Case Study: Elasticsearch Ingest Using StreamSets at Cisco IntercloudCase Study: Elasticsearch Ingest Using StreamSets at Cisco Intercloud
Case Study: Elasticsearch Ingest Using StreamSets at Cisco Intercloud
 
Case Study: Elasticsearch Ingest Using StreamSets @ Cisco Intercloud
Case Study: Elasticsearch Ingest Using StreamSets @ Cisco IntercloudCase Study: Elasticsearch Ingest Using StreamSets @ Cisco Intercloud
Case Study: Elasticsearch Ingest Using StreamSets @ Cisco Intercloud
 
Software architecture for data applications
Software architecture for data applicationsSoftware architecture for data applications
Software architecture for data applications
 
CQRS Evolved - CQRS + Akka.NET
CQRS Evolved - CQRS + Akka.NETCQRS Evolved - CQRS + Akka.NET
CQRS Evolved - CQRS + Akka.NET
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
MeteorJS Introduction
MeteorJS IntroductionMeteorJS Introduction
MeteorJS Introduction
 
Reactive app using actor model & apache spark
Reactive app using actor model & apache sparkReactive app using actor model & apache spark
Reactive app using actor model & apache spark
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 

Mehr von Yaroslav Tkachenko

Dynamic Change Data Capture with Flink CDC and Consistent Hashing
Dynamic Change Data Capture with Flink CDC and Consistent HashingDynamic Change Data Capture with Flink CDC and Consistent Hashing
Dynamic Change Data Capture with Flink CDC and Consistent Hashing
Yaroslav Tkachenko
 
Быстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложенийБыстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложений
Yaroslav Tkachenko
 

Mehr von Yaroslav Tkachenko (17)

Dynamic Change Data Capture with Flink CDC and Consistent Hashing
Dynamic Change Data Capture with Flink CDC and Consistent HashingDynamic Change Data Capture with Flink CDC and Consistent Hashing
Dynamic Change Data Capture with Flink CDC and Consistent Hashing
 
Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?
 
Apache Flink Adoption at Shopify
Apache Flink Adoption at ShopifyApache Flink Adoption at Shopify
Apache Flink Adoption at Shopify
 
Storing State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your AnalyticsStoring State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your Analytics
 
It's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda ArchitectureIt's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda Architecture
 
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to StreamingBravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming
Bravo Six, Going Realtime. Transitioning Activision Data Pipeline to Streaming
 
Apache Kafka: New Features That You Might Not Know About
Apache Kafka: New Features That You Might Not Know AboutApache Kafka: New Features That You Might Not Know About
Apache Kafka: New Features That You Might Not Know About
 
Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...
Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...
Building Scalable and Extendable Data Pipeline for Call of Duty Games: Lesson...
 
Designing Scalable and Extendable Data Pipeline for Call Of Duty Games
Designing Scalable and Extendable Data Pipeline for Call Of Duty GamesDesigning Scalable and Extendable Data Pipeline for Call Of Duty Games
Designing Scalable and Extendable Data Pipeline for Call Of Duty Games
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
 
Actors or Not: Async Event Architectures
Actors or Not: Async Event ArchitecturesActors or Not: Async Event Architectures
Actors or Not: Async Event Architectures
 
Kafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processingKafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processing
 
Querying Data Pipeline with AWS Athena
Querying Data Pipeline with AWS AthenaQuerying Data Pipeline with AWS Athena
Querying Data Pipeline with AWS Athena
 
Why Actor-Based Systems Are The Best For Microservices
Why Actor-Based Systems Are The Best For MicroservicesWhy Actor-Based Systems Are The Best For Microservices
Why Actor-Based Systems Are The Best For Microservices
 
Why actor-based systems are the best for microservices
Why actor-based systems are the best for microservicesWhy actor-based systems are the best for microservices
Why actor-based systems are the best for microservices
 
Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture  Building Eventing Systems for Microservice Architecture
Building Eventing Systems for Microservice Architecture
 
Быстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложенийБыстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложений
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
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
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
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
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
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...
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
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
 

Akka Microservices Architecture And Design

  • 1. Akka Microservices Architecture And Design Yaroslav Tkachenko Senior Software Engineer at Demonware (Activision) @sap1ens
  • 2.
  • 4. ● Communicate with asynchronous messages instead of method invocations ● Manage their own state ● When responding to a message, can: ○ Create other (child) actors ○ Send messages to other actors ○ Stop (child) actors or themselves
  • 6. object MyActor { case class Greeting(from: String) case object Goodbye } class MyActor extends Actor with ActorLogging { import MyActor._ def receive = { case Greeting(greeter) => log.info(s"I was greeted by $greeter.") case Goodbye => log.info("Someone said goodbye to me.") } } val system = ActorSystem("mySystem") val myActor = system.actorOf(Props[MyActor], "myactor") myActor ! Greeting("another actor")
  • 8. loop() -> receive {From, Msg} -> io:format("received ~p~n", [Msg]), From ! "got it"; end. Erlang
  • 9. object HelloWorld { final case class Greet(whom: String, replyTo: ActorRef[Greeted]) final case class Greeted(whom: String) val greeter = Actor.immutable[Greet] { (_, msg) ⇒ println(s"Hello ${msg.whom}!") msg.replyTo ! Greeted(msg.whom) Actor.same } } Akka Typed
  • 12.
  • 13. ● I know MVC! ● How do I do DI? ● What about that pattern X? ● Does it follow SOA? ● Microservices?
  • 15. ● Focus on core domain and business logic ● Base complex designs on the domain model ● Collaborate with domain experts (ubiquitous language) ● Strategic and tactical patterns
  • 17. Entity (Case Class) ● Account ● User ● Transaction Value object (Trait) ● Checking | Savings | Credit Card ● Active | Inactive ● Debit | Credit
  • 18. Entities contain business logic only involving their own state. We can also call this logic pure. ● Account.addBalance ● User.isDisabled ● Transaction.hasLedger
  • 19. Event (Actor Message - Case Class) is simply a fact that something happened. ● AccountDeactivated(account) ● UserCreated(user) ● TransactionUpdated(transaction, transaction)
  • 20. Command (Actor Message - Case Class) is a direct instruction for data manipulation, retrieval or a side-effect. ● DeactivateAccount(account) ● CreateUser(user) ● UpdateTransaction(transaction)
  • 21. Repository (Actor OR Object/Class) is a way to access or modify domain data and produce a set of entities. ● accountRepository ! FindAccountById(id) ● userRepository ! UpdateUserName(id, name) ● transactionRepository ! FindAllTransactionsBetween(date, date)
  • 22. Domain Services (Actors) manage multiple entities and/or communicate with other services and repositories to implement complex logic. They’re usually stateless. ● accountService ! DeactivateAccount(account) ● userService ! RegisterUser(name, email, type) ● transactionService ! MergeTransactions(transaction, transaction)
  • 24.
  • 25. We defined an Application Core, containing our Domain model and business logic. We haven’t yet discussed: ● APIs ● Integrations ● Security ● etc.
  • 26.
  • 27. Application Services implement Adapter pattern and they’re explicitly located outside of the Application Core. Usually represented as Actors. They can be responsible for: ● Communication via HTTP, RPC APIs, messaging queues ● Integrations with 3rd-party systems ● Security, caching, etc.
  • 29. How (assuming we should) do we split our Domain Model into multiple [micro]services?
  • 30. Domain Bounded Context Bounded Context Subdomain Subdomain Subdomain Subdomain Subdomain Subdomain Sweet spots for service boundaries!
  • 31. Online education service User Management Courses User profiles Achievements Billing Catalog Content management Reviews
  • 32. So, our [micro]services are: - Completely isolated - Deployed separately - Have different actor systems - Have clear boundaries from DDD perspective
  • 33. Now we have multiple [micro]services running multiple actor systems. How do they communicate? - Synchronously, over HTTP/RPC - Asynchronously, over messaging
  • 34. It is unfortunate that synchronous HTTP is widely considered as the go-to Microservice communication protocol. Its synchronous nature introduces strong coupling between services which makes it a very bad default protocol for inter-service communication. Instead, communication between Microservices needs to be based on Asynchronous Message-Passing. Having an asynchronous boundary between services is necessary in order to decouple them, and their communication flow: • in time: for concurrency, and • in space: for distribution and mobility Bla bla microservices bla bla Jonas Bonér CTO of Lightbend
  • 36.
  • 37.
  • 39. Message routing is very specific to your domain: - Use ActiveMQ/RabbitMQ by default and see if you can survive with static topics/queues - Add custom middleware layer for routing (consumer and producer at the same time) - Use Kafka with Kafka Streams / Akka Streams
  • 40. EIP was published in 2003 and it contains 65 patterns.
  • 41.
  • 42. Apache Camel: - Integration framework based on EIP - akka-camel is an official Akka library - Can be used with any JVM language - “The most unknown coolest library out there” (©) JM
  • 43. class CustomerService extends Actor with ActorLogging with Consumer { val camel = CamelExtension(system) camel.context.addComponent("activemq", ActiveMQComponent.activeMQComponent( "tcp://localhost:61616" )) def endpointUri = "activemq:topic:events" def receive = { case e: CamelMessage => { sender() ! "SomeMessage" } } }
  • 44. Apache Camel Alpakka - Enterprise Integration Done Right © - Built in top of Akka Streams - Back-pressure all the way - Still in active development
  • 46. Stateful application service keeps all data inside the application instead of an external storage (like database or cache) Why discuss stateful services?
  • 47. Example, service requirements: - Need to be really fast (low latency) - Should have “strong” consistency (at least within one entity), no stale data - Should be highly available (HA) - Lots of data - [Maybe] very complex queries
  • 48. Which means: - Might be very challenging to use a database - Can’t use caching - Solution: stateful service. Keeping data and application logic together
  • 49. Naive approach: - Just keeping data in memory. Ok… - Need to make service HA, running at least 2 nodes. Ok… - Now we have duplicated data. How do we route requests? Sticky LB? Some partitioning? - Or what if our data volume is too big for one node? - We need to shard it. How? - Akka Cluster Sharding + Akka Persistence FTW!
  • 50. Akka Clustering is a cluster membership service: - Gossip-based - No SPOF - Eventually consistent - Failure detection built-in
  • 51. Powerful collection of patterns for building distributed applications: - Cluster Routing - Cluster Pub/Sub - Cluster Singleton - Cluster Sharding
  • 52. Akka Persistence allows actors to persist internal state to an external storage and recover after restarts and crashes: - Event sourcing applied to an internal actor state - RDBMS, NoSQL, caches and and queues as storage - Snapshotting for fast recovery
  • 53. Akka Cluster Sharding + Akka Persistence = ❤️
  • 54. StatsService 1 3 5 StatsService 2 4 6 statsServiceRegion ! GetStats(userId)
  • 55. Stateful services with Akka: - Routing, sharding and recovery built-in - You still just deal with actors! - Akka Distributed Data can be used instead of external storage
  • 56. It’s important to remember that Akka Clustering application is still restricted by the bounded context (or subdomain) and it should be used within the microservice boundary.
  • 58. - Akka is great! - Use Domain-Driven Design for modelling your application core and understanding service boundaries - Use Enterprise Integration Patterns for developing your asynchronous messaging design - Look at Akka Clustering and Persistence for complex problems with distributed services

Hinweis der Redaktion

  1. Survey: Raise your hand if you heard something about Akka and actors Keep your hand raised if you played with Akka, built some pet projects Keep your hand raised if you used Akka in production
  2. Akka Documentation is not very helpful for actually designing complex applications
  3. SPOF - single point of failure