SlideShare a Scribd company logo
1 of 43
Akka: Arquitetura
Orientada a Atores
Fabiano Guizellini Modos
Arquiteto de Software - HBSIS
@fmodos
ACTOR Model = Modelo de Atores
Agenda
 Conceito de Atores
 Non Blocking / Blocking
 Comunicação Assíncrona
 Supervisor
 Router
 Cluster
“If you can’t explain it simply, you don’t understand it well enough“
Albert Einstein
Quem Usa Akka?
“1. Scalable, both horizontally to hundreds of nodes and vertically to very
many processors, handling billions of requests per day
2. Low latency, controllable at a very fine grain
3. Resilient to failure
4. Flexibility in adjusting the service boundaries
5. A programming model AND culture encouraging scalability and simplicity,
including clean failure and error handling”
"How PayPal Scaled To Billions Of Transactions Daily Using Just 8VMs"
http://highscalability.com/blog/2016/8/15/how-paypal-scaled-to-billions-of-
transactions-daily-using-ju.html
"A New, Reactive Way for PayPal to Build Applications"
https://www.paypal-engineering.com/2016/05/11/squbs-a-new-reactive-way-for-
paypal-to-build-applications/
Quem Usa Akka?
"How does one display them in real time for roughly 500 million members on
a social network like LinkedIn?"
"Now You See Me, Now You Don’t: LinkedIn’s Real-Time Presence Platform"
https://engineering.linkedin.com/blog/2018/01/now-you-see-me--now-you-dont--
linkedins-real-time-presence-platf
Ano 1973 - A Universal Modular ACTOR
Formalism for Artificial Intelligence
“Current developments in hardware technology are
making it economically attractive to run many physical
processors in parallel.... The actor formalism provides a
coherent method for organizing and controlling all
these processors.” by Carl Hewitt
Ano 1986 – ERLANG
A Ericsson desenvolveu essa linguagem baseada no conceito de atores com o
objetivo de melhorar o desenvolvimento de aplicações de telefonia.
"when you build a system in Erlang, you can see
the system as a serious of very small programs"
Greg Young
https://vimeo.com/108441214
QUEM USA?
Ano 2009 – Akka
Jonas Bonér é um Java Champion. Ele criou o Akka em Java inspirado no
conceito de ACTOR e da linguagem Erlang.
Ano 2015 – Quando eu conheci Akka
Utilizado no produto Unidocs da HBSIS
✘ Responsável pela emissão de documentos de transporte
✘ ~30 milhões de documentos
✘ ~1000 atores dividos em 8 microservices
✘ Processa ~80k eventos por hora
https://www.youtube.com/watch?v=7erJ1DV_Tlo
ACTOR é um agente com as
seguinte responsabilidades:
 Processing
 Storage
 Communication
ACTOR by Carl Hewitt
Hands On
Otimizar as filas do Subway
Projeto Subway
✘ FIFO – Fila
✘ Exception - Cliente Desmaiou
✘ Load – Garçom Sobrecarregado
✘ Pergunta do Milhão
FIFO – First In First Out
Problema: Um Cliente Lento Afeta Toda a Fila
Waiter waiter = new Waiter();
int delayToChoose = 10000;
waiter.receiveOrder(new NewSandwich("Slow Client", delayToChoose));
waiter.receiveOrder(new NewSandwich("Fast Client", 0));
BLOCKING
Fila Blocking
Varias Filas Blocking
FIFO – Blocking
FOFO – Faster Order Faster Out
Non Blocking
Comunicação
Waiter Customer
nextOrder()
Waiter
Actor
“NextOrder”
Customer
Actor
Waiter
Actor
“MyOrder”
Customer
Actor
Blocking Non Blocking
“MyOrder”
Comunicação
Blocking Non Blocking
FOFO – Faster Order Faster Out
“MyOrder”
Customer
Actor
Waiter
Actor
“NextOrder”
Customer
Actor
“FINISH”
Customer
Actor
Concorrência com ACTOR
Actor
Ref
Waiter
Actor
MailBox
Actor
Ref
Customer
Actor
MailBox
Acesso a
atores somente
via REF
ThreadSafe:
{activeCustomer++}
MailBox envia
uma Mensagem
por vez para o
Actor
ACTOR toma decisão a partir do “Estado”
Waiter
Actor
“NextOrder”
Customer
Actor
Waiter
Actor
“MyOrder”
Customer
Actor
Waiter
Actor
“NextOrder”
Customer
Actor
Waiter
Actor
“FINISH”
Customer
Actor
totalOrder: 2
{totalOrder++}
totalOrder: 3
{if(totalOrder==3) “FINISH”}
ActorSystem system= ActorSystem.create("SubwaySystem");
ActorRef waiter =
system.actorOf(Props.create(WaiterActor.class), "waiter");
int delayToChoose = 10000;
waiter.tell(new NewSandwich("Slow Client", delayToChoose),
ActorRef.noSender());
waiter.tell(new NewSandwich("Fast Client", 0), ActorRef.noSender());
HANDS ON - ActorSystem
HANDS ON - Comunicação entre Atores
public class CustomerActor extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder().//
matchEquals(EnumOrder.NEXT_ORDER, order -> {
doOrder();
}).build();
}
public class WaiterActor extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()//
.match(Order.class, order -> {
totalOrders++;
log("Processando pedido "+order.getSalad());
getSender().tell(EnumOrder.NEXT_ORDER, getSelf());
Projeto Subway
✘ FIFO – Fila Blocking
✘ Exception - Cliente Desmaiou
✘ Load – Garçom Sobrecarregado
✘ Pergunta do Milhão
Catch Exception de outra Thread?
Try {
New Thread(new Runnable(){
Public void run(){
Throw new RuntimeException(“HEY”);
}
}).start();
}catch(Exception e){
System.out.println(“HEY EXCEPTION?”)
}
Actor cria e supervisiona outros Actor
Waiter
Actor
newActor()
Actor
Context
“NewCustomer”
watch(actor)
“NextOrder”
Customer
Actor
Error
Exception
if (totalOrders == 1 && sandwich.isFaint()) {
throw new RuntimeException("Problem here");
}
@Override
public SupervisorStrategy supervisorStrategy() {
return new OneForOneStrategy(10, Duration.create("1 minute"),
DeciderBuilder.match(RuntimeException.class, e -> restart())//
.matchAny(o -> escalate()).build());
}
WaiterActor:
CustomerActor:
HANDS ON - SupervisorStrategy
Projeto Subway
✘ FIFO – Fila Blocking
✘ Exception - Cliente Desmaiou
✘ Load – Garçom Sobrecarregado
✘ Pergunta do Milhão
Router
Hosts
Actor
“NewSandwich”
Waiter
Router
Waiter
Actor
Waiter
Actor
Implementações Router
o RoundRobinPool
o RandomPool
o SmallestMailBoxPool
o ConsistentHashingPool
HostessActor:
private ActorRef waiters = getContext().actorOf(
new RoundRobinPool(2).props(Props.create(WaiterActor.class))
, "waiter");
@Override
public Receive createReceive() {
return receiveBuilder()
.match(NewSandwich.class, s -> {
waiters.tell(s, getSelf());
}).build();
}
HANDS ON - Router
Projeto Subway
✘ FIFO – Fila Blocking
✘ Exception - Cliente Desmaiou
✘ Load – Garçom Sobrecarregado
✘ Pergunta do Milhão
Perguntas hipsters na TI
2004 - aplicação Web ou Desktop?
2008 - você usa Ajax?
2012 - você desenvolve Mobile?
2016 – tem quantos Microservices?
2017 – usa NoSQL?
2018 - como você escala a Aplicação?
Scaling
Hosts
Actor
Waiter
Actor
Waiter
Actor
MQ
MQ
Clustering
Hosts
Actor
“NewSandwich”
Waiter
Router
Waiter
Actor
Waiter
Actor
Customer
Actor
Customer
Actor
JVM Hosts
JVM Waiter
JVM Waiter
int totalInstances = 2;
int maxInstancesPerNode = 1;
boolean allowLocalRoutees = false;
Set<String> useRoles = new HashSet<>(Arrays.asList("compute"));
ActorRef waiters = getContext()
.actorOf(
new ClusterRouterPool(new RoundRobinPool(2), new
ClusterRouterPoolSettings(totalInstances,
maxInstancesPerNode, allowLocalRoutees,
useRoles)).props(Props.create(WaiterActor.class)),
"waiterRouter");
HANDS ON - Cluster
Projeto Subway
✘ FIFO – Fila Blocking
✘ Exception - Cliente Desmaiou
✘ Load – Garçom Sobrecarregado
✘ Pergunta do Milhão
Recapitulando
✘ Comunicação -> Non Blocking e Thread Safe
✘ Supervisor -> Tratativa de exception em threads diferentes
✘ Router -> Load Balancing do lado do cliente
✘ Cluster -> Todos os ítens acima de forma transparente em um
ambiente distribuído
Actors são baseados em comportamento
Carga
ActorCarga
ActorCarga
Actor
CTeActor/Cnpj1
CTeActor/CnpjX
NFeActor/Cnpj1
Carga
ActorCarga
ActorEmail
Actor
Cte + Cnpj1
Cte + CnpjX
Nfe + Cnpj1
Request
Email
Email
Email
Cte + Cnpj1
Email
“A good architecture will allow a system to be born as
a monolith, deployed in a single file, but then to grow
into a set of independently… microservices”
by Uncle Bob – Clean Architecture
Agradecimento
Obrigado Akka por me ensinar a arquitetar sistemas baseado em
comportamento.
Muito Obrigado!
@fmodos

More Related Content

Similar to Akka: Arquitetura Orientada a Atores

Manage your APIs and Microservices with an API Gateway
Manage your APIs and Microservices with an API GatewayManage your APIs and Microservices with an API Gateway
Manage your APIs and Microservices with an API GatewayThibault Charbonnier
 
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Codemotion
 
The 'Serverless' Paradigm, OpenWhisk and FIWARE
The 'Serverless' Paradigm, OpenWhisk and FIWAREThe 'Serverless' Paradigm, OpenWhisk and FIWARE
The 'Serverless' Paradigm, OpenWhisk and FIWAREFIWARE
 
The Serverless Paradigm, OpenWhisk and FIWARE
The Serverless Paradigm, OpenWhisk and FIWAREThe Serverless Paradigm, OpenWhisk and FIWARE
The Serverless Paradigm, OpenWhisk and FIWAREAlex Glikson
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 
How to measure everything - a million metrics per second with minimal develop...
How to measure everything - a million metrics per second with minimal develop...How to measure everything - a million metrics per second with minimal develop...
How to measure everything - a million metrics per second with minimal develop...Jos Boumans
 
Building a Bank with Go
Building a Bank with GoBuilding a Bank with Go
Building a Bank with GoC4Media
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Capacity Planning for Linux Systems
Capacity Planning for Linux SystemsCapacity Planning for Linux Systems
Capacity Planning for Linux SystemsRodrigo Campos
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaMatt Stine
 
Ajax Push For Revolutionary Enterprise Applications
Ajax Push For Revolutionary Enterprise ApplicationsAjax Push For Revolutionary Enterprise Applications
Ajax Push For Revolutionary Enterprise Applicationselliando dias
 
Pros and Cons of a MicroServices Architecture talk at AWS ReInvent
Pros and Cons of a MicroServices Architecture talk at AWS ReInventPros and Cons of a MicroServices Architecture talk at AWS ReInvent
Pros and Cons of a MicroServices Architecture talk at AWS ReInventSudhir Tonse
 
Nagios Conference 2014 - David Josephsen - Alert on What You Draw
Nagios Conference 2014 - David Josephsen - Alert on What You DrawNagios Conference 2014 - David Josephsen - Alert on What You Draw
Nagios Conference 2014 - David Josephsen - Alert on What You DrawNagios
 
Liferay Devcon presentation on Workflow & Dynamic Forms
Liferay Devcon presentation on Workflow & Dynamic FormsLiferay Devcon presentation on Workflow & Dynamic Forms
Liferay Devcon presentation on Workflow & Dynamic FormsWillem Vermeer
 
Liferay Devcon Presentation on Dynamic Forms with Liferay Workflow
Liferay Devcon Presentation on Dynamic Forms with Liferay WorkflowLiferay Devcon Presentation on Dynamic Forms with Liferay Workflow
Liferay Devcon Presentation on Dynamic Forms with Liferay WorkflowWillem Vermeer
 
HTML Hypermedia APIs and Adaptive Web Design - jDays 2013
HTML Hypermedia APIs and Adaptive Web Design - jDays 2013HTML Hypermedia APIs and Adaptive Web Design - jDays 2013
HTML Hypermedia APIs and Adaptive Web Design - jDays 2013Gustaf Nilsson Kotte
 

Similar to Akka: Arquitetura Orientada a Atores (20)

Manage your APIs and Microservices with an API Gateway
Manage your APIs and Microservices with an API GatewayManage your APIs and Microservices with an API Gateway
Manage your APIs and Microservices with an API Gateway
 
Micro service architecture
Micro service architectureMicro service architecture
Micro service architecture
 
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...
 
The 'Serverless' Paradigm, OpenWhisk and FIWARE
The 'Serverless' Paradigm, OpenWhisk and FIWAREThe 'Serverless' Paradigm, OpenWhisk and FIWARE
The 'Serverless' Paradigm, OpenWhisk and FIWARE
 
The Serverless Paradigm, OpenWhisk and FIWARE
The Serverless Paradigm, OpenWhisk and FIWAREThe Serverless Paradigm, OpenWhisk and FIWARE
The Serverless Paradigm, OpenWhisk and FIWARE
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
How to measure everything - a million metrics per second with minimal develop...
How to measure everything - a million metrics per second with minimal develop...How to measure everything - a million metrics per second with minimal develop...
How to measure everything - a million metrics per second with minimal develop...
 
DevOps and Cloud Native
DevOps and Cloud NativeDevOps and Cloud Native
DevOps and Cloud Native
 
Building a Bank with Go
Building a Bank with GoBuilding a Bank with Go
Building a Bank with Go
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Hello istio
Hello istioHello istio
Hello istio
 
Capacity Planning for Linux Systems
Capacity Planning for Linux SystemsCapacity Planning for Linux Systems
Capacity Planning for Linux Systems
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
 
Ajax Push For Revolutionary Enterprise Applications
Ajax Push For Revolutionary Enterprise ApplicationsAjax Push For Revolutionary Enterprise Applications
Ajax Push For Revolutionary Enterprise Applications
 
Pros and Cons of a MicroServices Architecture talk at AWS ReInvent
Pros and Cons of a MicroServices Architecture talk at AWS ReInventPros and Cons of a MicroServices Architecture talk at AWS ReInvent
Pros and Cons of a MicroServices Architecture talk at AWS ReInvent
 
Nagios Conference 2014 - David Josephsen - Alert on What You Draw
Nagios Conference 2014 - David Josephsen - Alert on What You DrawNagios Conference 2014 - David Josephsen - Alert on What You Draw
Nagios Conference 2014 - David Josephsen - Alert on What You Draw
 
Liferay Devcon presentation on Workflow & Dynamic Forms
Liferay Devcon presentation on Workflow & Dynamic FormsLiferay Devcon presentation on Workflow & Dynamic Forms
Liferay Devcon presentation on Workflow & Dynamic Forms
 
Liferay Devcon Presentation on Dynamic Forms with Liferay Workflow
Liferay Devcon Presentation on Dynamic Forms with Liferay WorkflowLiferay Devcon Presentation on Dynamic Forms with Liferay Workflow
Liferay Devcon Presentation on Dynamic Forms with Liferay Workflow
 
HTML Hypermedia APIs and Adaptive Web Design - jDays 2013
HTML Hypermedia APIs and Adaptive Web Design - jDays 2013HTML Hypermedia APIs and Adaptive Web Design - jDays 2013
HTML Hypermedia APIs and Adaptive Web Design - jDays 2013
 

More from Fabiano Modos

Architecting For Resilience
Architecting For ResilienceArchitecting For Resilience
Architecting For ResilienceFabiano Modos
 
Arquitetando com buzzwords
Arquitetando com buzzwordsArquitetando com buzzwords
Arquitetando com buzzwordsFabiano Modos
 
Arquiteturaentregacontinuav2 160513025436
Arquiteturaentregacontinuav2 160513025436Arquiteturaentregacontinuav2 160513025436
Arquiteturaentregacontinuav2 160513025436Fabiano Modos
 
Real time com java e Node.Js
Real time com java e Node.JsReal time com java e Node.Js
Real time com java e Node.JsFabiano Modos
 
Introdução no sql mongodb java
Introdução no sql mongodb javaIntrodução no sql mongodb java
Introdução no sql mongodb javaFabiano Modos
 
Lições Aprendidas MongoDB
Lições Aprendidas MongoDBLições Aprendidas MongoDB
Lições Aprendidas MongoDBFabiano Modos
 
Spring Data com MongoDB
Spring Data com MongoDBSpring Data com MongoDB
Spring Data com MongoDBFabiano Modos
 

More from Fabiano Modos (8)

Architecting For Resilience
Architecting For ResilienceArchitecting For Resilience
Architecting For Resilience
 
Arquitetando com buzzwords
Arquitetando com buzzwordsArquitetando com buzzwords
Arquitetando com buzzwords
 
Arquiteturaentregacontinuav2 160513025436
Arquiteturaentregacontinuav2 160513025436Arquiteturaentregacontinuav2 160513025436
Arquiteturaentregacontinuav2 160513025436
 
Real time com java e Node.Js
Real time com java e Node.JsReal time com java e Node.Js
Real time com java e Node.Js
 
Introdução no sql mongodb java
Introdução no sql mongodb javaIntrodução no sql mongodb java
Introdução no sql mongodb java
 
Lições Aprendidas MongoDB
Lições Aprendidas MongoDBLições Aprendidas MongoDB
Lições Aprendidas MongoDB
 
Spring Data com MongoDB
Spring Data com MongoDBSpring Data com MongoDB
Spring Data com MongoDB
 
Arquitetura Reativa
Arquitetura ReativaArquitetura Reativa
Arquitetura Reativa
 

Recently uploaded

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

Akka: Arquitetura Orientada a Atores

  • 1. Akka: Arquitetura Orientada a Atores Fabiano Guizellini Modos Arquiteto de Software - HBSIS @fmodos
  • 2. ACTOR Model = Modelo de Atores
  • 3. Agenda  Conceito de Atores  Non Blocking / Blocking  Comunicação Assíncrona  Supervisor  Router  Cluster “If you can’t explain it simply, you don’t understand it well enough“ Albert Einstein
  • 4. Quem Usa Akka? “1. Scalable, both horizontally to hundreds of nodes and vertically to very many processors, handling billions of requests per day 2. Low latency, controllable at a very fine grain 3. Resilient to failure 4. Flexibility in adjusting the service boundaries 5. A programming model AND culture encouraging scalability and simplicity, including clean failure and error handling” "How PayPal Scaled To Billions Of Transactions Daily Using Just 8VMs" http://highscalability.com/blog/2016/8/15/how-paypal-scaled-to-billions-of- transactions-daily-using-ju.html "A New, Reactive Way for PayPal to Build Applications" https://www.paypal-engineering.com/2016/05/11/squbs-a-new-reactive-way-for- paypal-to-build-applications/
  • 5. Quem Usa Akka? "How does one display them in real time for roughly 500 million members on a social network like LinkedIn?" "Now You See Me, Now You Don’t: LinkedIn’s Real-Time Presence Platform" https://engineering.linkedin.com/blog/2018/01/now-you-see-me--now-you-dont-- linkedins-real-time-presence-platf
  • 6. Ano 1973 - A Universal Modular ACTOR Formalism for Artificial Intelligence “Current developments in hardware technology are making it economically attractive to run many physical processors in parallel.... The actor formalism provides a coherent method for organizing and controlling all these processors.” by Carl Hewitt
  • 7. Ano 1986 – ERLANG A Ericsson desenvolveu essa linguagem baseada no conceito de atores com o objetivo de melhorar o desenvolvimento de aplicações de telefonia. "when you build a system in Erlang, you can see the system as a serious of very small programs" Greg Young https://vimeo.com/108441214 QUEM USA?
  • 8. Ano 2009 – Akka Jonas Bonér é um Java Champion. Ele criou o Akka em Java inspirado no conceito de ACTOR e da linguagem Erlang.
  • 9. Ano 2015 – Quando eu conheci Akka Utilizado no produto Unidocs da HBSIS ✘ Responsável pela emissão de documentos de transporte ✘ ~30 milhões de documentos ✘ ~1000 atores dividos em 8 microservices ✘ Processa ~80k eventos por hora
  • 10. https://www.youtube.com/watch?v=7erJ1DV_Tlo ACTOR é um agente com as seguinte responsabilidades:  Processing  Storage  Communication ACTOR by Carl Hewitt
  • 11. Hands On Otimizar as filas do Subway
  • 12. Projeto Subway ✘ FIFO – Fila ✘ Exception - Cliente Desmaiou ✘ Load – Garçom Sobrecarregado ✘ Pergunta do Milhão
  • 13. FIFO – First In First Out Problema: Um Cliente Lento Afeta Toda a Fila Waiter waiter = new Waiter(); int delayToChoose = 10000; waiter.receiveOrder(new NewSandwich("Slow Client", delayToChoose)); waiter.receiveOrder(new NewSandwich("Fast Client", 0)); BLOCKING
  • 16. FIFO – Blocking FOFO – Faster Order Faster Out Non Blocking
  • 19. FOFO – Faster Order Faster Out “MyOrder” Customer Actor Waiter Actor “NextOrder” Customer Actor “FINISH” Customer Actor
  • 20.
  • 21. Concorrência com ACTOR Actor Ref Waiter Actor MailBox Actor Ref Customer Actor MailBox Acesso a atores somente via REF ThreadSafe: {activeCustomer++} MailBox envia uma Mensagem por vez para o Actor
  • 22. ACTOR toma decisão a partir do “Estado” Waiter Actor “NextOrder” Customer Actor Waiter Actor “MyOrder” Customer Actor Waiter Actor “NextOrder” Customer Actor Waiter Actor “FINISH” Customer Actor totalOrder: 2 {totalOrder++} totalOrder: 3 {if(totalOrder==3) “FINISH”}
  • 23. ActorSystem system= ActorSystem.create("SubwaySystem"); ActorRef waiter = system.actorOf(Props.create(WaiterActor.class), "waiter"); int delayToChoose = 10000; waiter.tell(new NewSandwich("Slow Client", delayToChoose), ActorRef.noSender()); waiter.tell(new NewSandwich("Fast Client", 0), ActorRef.noSender()); HANDS ON - ActorSystem
  • 24. HANDS ON - Comunicação entre Atores public class CustomerActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder().// matchEquals(EnumOrder.NEXT_ORDER, order -> { doOrder(); }).build(); } public class WaiterActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder()// .match(Order.class, order -> { totalOrders++; log("Processando pedido "+order.getSalad()); getSender().tell(EnumOrder.NEXT_ORDER, getSelf());
  • 25. Projeto Subway ✘ FIFO – Fila Blocking ✘ Exception - Cliente Desmaiou ✘ Load – Garçom Sobrecarregado ✘ Pergunta do Milhão
  • 26. Catch Exception de outra Thread? Try { New Thread(new Runnable(){ Public void run(){ Throw new RuntimeException(“HEY”); } }).start(); }catch(Exception e){ System.out.println(“HEY EXCEPTION?”) }
  • 27. Actor cria e supervisiona outros Actor Waiter Actor newActor() Actor Context “NewCustomer” watch(actor) “NextOrder” Customer Actor Error Exception
  • 28. if (totalOrders == 1 && sandwich.isFaint()) { throw new RuntimeException("Problem here"); } @Override public SupervisorStrategy supervisorStrategy() { return new OneForOneStrategy(10, Duration.create("1 minute"), DeciderBuilder.match(RuntimeException.class, e -> restart())// .matchAny(o -> escalate()).build()); } WaiterActor: CustomerActor: HANDS ON - SupervisorStrategy
  • 29. Projeto Subway ✘ FIFO – Fila Blocking ✘ Exception - Cliente Desmaiou ✘ Load – Garçom Sobrecarregado ✘ Pergunta do Milhão
  • 31. Implementações Router o RoundRobinPool o RandomPool o SmallestMailBoxPool o ConsistentHashingPool
  • 32. HostessActor: private ActorRef waiters = getContext().actorOf( new RoundRobinPool(2).props(Props.create(WaiterActor.class)) , "waiter"); @Override public Receive createReceive() { return receiveBuilder() .match(NewSandwich.class, s -> { waiters.tell(s, getSelf()); }).build(); } HANDS ON - Router
  • 33. Projeto Subway ✘ FIFO – Fila Blocking ✘ Exception - Cliente Desmaiou ✘ Load – Garçom Sobrecarregado ✘ Pergunta do Milhão
  • 34. Perguntas hipsters na TI 2004 - aplicação Web ou Desktop? 2008 - você usa Ajax? 2012 - você desenvolve Mobile? 2016 – tem quantos Microservices? 2017 – usa NoSQL? 2018 - como você escala a Aplicação?
  • 37. int totalInstances = 2; int maxInstancesPerNode = 1; boolean allowLocalRoutees = false; Set<String> useRoles = new HashSet<>(Arrays.asList("compute")); ActorRef waiters = getContext() .actorOf( new ClusterRouterPool(new RoundRobinPool(2), new ClusterRouterPoolSettings(totalInstances, maxInstancesPerNode, allowLocalRoutees, useRoles)).props(Props.create(WaiterActor.class)), "waiterRouter"); HANDS ON - Cluster
  • 38. Projeto Subway ✘ FIFO – Fila Blocking ✘ Exception - Cliente Desmaiou ✘ Load – Garçom Sobrecarregado ✘ Pergunta do Milhão
  • 39. Recapitulando ✘ Comunicação -> Non Blocking e Thread Safe ✘ Supervisor -> Tratativa de exception em threads diferentes ✘ Router -> Load Balancing do lado do cliente ✘ Cluster -> Todos os ítens acima de forma transparente em um ambiente distribuído
  • 40. Actors são baseados em comportamento Carga ActorCarga ActorCarga Actor CTeActor/Cnpj1 CTeActor/CnpjX NFeActor/Cnpj1 Carga ActorCarga ActorEmail Actor Cte + Cnpj1 Cte + CnpjX Nfe + Cnpj1 Request Email Email Email Cte + Cnpj1 Email
  • 41. “A good architecture will allow a system to be born as a monolith, deployed in a single file, but then to grow into a set of independently… microservices” by Uncle Bob – Clean Architecture
  • 42. Agradecimento Obrigado Akka por me ensinar a arquitetar sistemas baseado em comportamento.