SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

試験にでるSpring
試験にでるSpring試験にでるSpring
試験にでるSpring
土岐 孝平
 
[IMQA] performance consulting
[IMQA] performance consulting[IMQA] performance consulting
[IMQA] performance consulting
IMQA
 
Kubernetes環境で実現するWebアプリケーションセキュリティ
Kubernetes環境で実現するWebアプリケーションセキュリティKubernetes環境で実現するWebアプリケーションセキュリティ
Kubernetes環境で実現するWebアプリケーションセキュリティ
NGINX, Inc.
 
Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話
Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話
Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話
LINE Corporation
 

Mais procurados (20)

Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 SeoulElastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
 
試験にでるSpring
試験にでるSpring試験にでるSpring
試験にでるSpring
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
 
AWS 6월 웨비나 | AWS에서 MS SQL 서버 운영하기 (김민성 솔루션즈아키텍트)
AWS 6월 웨비나 | AWS에서 MS SQL 서버 운영하기 (김민성 솔루션즈아키텍트)AWS 6월 웨비나 | AWS에서 MS SQL 서버 운영하기 (김민성 솔루션즈아키텍트)
AWS 6월 웨비나 | AWS에서 MS SQL 서버 운영하기 (김민성 솔루션즈아키텍트)
 
Celery의 빛과 그림자
Celery의 빛과 그림자Celery의 빛과 그림자
Celery의 빛과 그림자
 
Kubernetes on Premise Practical Guide
Kubernetes on Premise Practical GuideKubernetes on Premise Practical Guide
Kubernetes on Premise Practical Guide
 
비동기 어플리케이션 모니터링과 밀당하기
비동기 어플리케이션 모니터링과 밀당하기비동기 어플리케이션 모니터링과 밀당하기
비동기 어플리케이션 모니터링과 밀당하기
 
[IMQA] performance consulting
[IMQA] performance consulting[IMQA] performance consulting
[IMQA] performance consulting
 
Kubernetes環境で実現するWebアプリケーションセキュリティ
Kubernetes環境で実現するWebアプリケーションセキュリティKubernetes環境で実現するWebアプリケーションセキュリティ
Kubernetes環境で実現するWebアプリケーションセキュリティ
 
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
 
게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
 
Deep dive into flink interval join
Deep dive into flink interval joinDeep dive into flink interval join
Deep dive into flink interval join
 
Streaming with Spring Cloud Stream and Apache Kafka - Soby Chacko
Streaming with Spring Cloud Stream and Apache Kafka - Soby ChackoStreaming with Spring Cloud Stream and Apache Kafka - Soby Chacko
Streaming with Spring Cloud Stream and Apache Kafka - Soby Chacko
 
Spanner移行について本気出して考えてみた
Spanner移行について本気出して考えてみたSpanner移行について本気出して考えてみた
Spanner移行について本気出して考えてみた
 
Adopting Java for the Serverless world at Serverless Meetup New York and Boston
Adopting Java for the Serverless world at Serverless Meetup New York and BostonAdopting Java for the Serverless world at Serverless Meetup New York and Boston
Adopting Java for the Serverless world at Serverless Meetup New York and Boston
 
Amazon ECS/ECR을 활용하여 마이크로서비스 구성하기 - 김기완 (AWS 솔루션즈아키텍트)
Amazon ECS/ECR을 활용하여 마이크로서비스 구성하기 - 김기완 (AWS 솔루션즈아키텍트)Amazon ECS/ECR을 활용하여 마이크로서비스 구성하기 - 김기완 (AWS 솔루션즈아키텍트)
Amazon ECS/ECR을 활용하여 마이크로서비스 구성하기 - 김기완 (AWS 솔루션즈아키텍트)
 
Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話
Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話
Akka ActorとAMQPでLINEのメッセージングパイプラインをリプレースした話
 
with NATS with Kubernetesの世界へ
with NATS with Kubernetesの世界へwith NATS with Kubernetesの世界へ
with NATS with Kubernetesの世界へ
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 
Быстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложенийБыстрая и безболезненная разработка клиентской части веб-приложений
Быстрая и безболезненная разработка клиентской части веб-приложений
 

Último

+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
 
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
 

Último (20)

+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...
 
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 🔝✔️✔️
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
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
 
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
 
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
 
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
 
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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.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 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
 
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
 
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...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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
 
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 ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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
 
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
 

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

Notas do Editor

  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