SlideShare a Scribd company logo
1 of 36
Akka
Patterns and anti-patterns
Roman Timushev
2014
About me
• Work at Qubell Inc.
• Scala since 2011
• Akka since 1.x
• Now: Scala, Akka, Play, MongoDB, RabbitMQ
Agenda
• Anti-patterns
• Ask is so cool
• Dependency injection for the win
• I like to block it, block it
• No mutable state is so functional
• Patterns
• Actor initialization
• Safe closures
• Flow control
Ask is so cool
Tell, don’t ask:
classic code
class FineService {
def getFine(v: Double) = {
v * greedinessService.getGreediness()
}
}
class GreedinessService {
def getGreediness(): Double = {
db.query("select ...")
}
}
class DbService {
def query(s: String): Double = ???
}
Tell, don’t ask:
classic actor code
class FineService extends Actor {
def receive = {
case GetFine(v) =>
(greedinessService ? GetGreediness)
.mapTo[Double].map(_ * v).pipeTo(sender())
}
}
class GreedinessService extends Actor {
def receive = {
case GetGreediness =>
(db ? Query("select ..."))
.mapTo[Double].pipeTo(sender())
}
}
Timeout
Timeout
Tell, don’t ask
• Works perfect until loaded
• Timeouts everywhere
• equal — you don’t get the exact cause
• different — unmanageable hell
• Use thoughtful!
Tell, don’t ask:
invert control flow
class FineService extends Actor {
var greediness: Double = 0
def receive = {
case GetFine(v) => sender() ! greediness
case SetGreediness(g) => greediness = g
}
}
class GreedinessService extends Actor {
def receive = {
case ReloadGreediness =>
(db ? Query("select ..."))
.mapTo[Double].map(SetGreediness).pipeTo(fineService)
}
}
Dependency injection
for the win
Dependency injection:
actor references
trait AkkaComponent {
def actorSystem: ActorSystem
}
trait DividerComponent {
def divider: ActorRef
}
trait CalculatorComponent {
def calculator: ActorRef
}
Dependency injection:
actor references
trait CalculatorComponentImpl extends CalculatorComponent {
this: AkkaComponent with DividerComponent =>
lazy val calculator = actorSystem.actorOf(Props(new Calculator))
class Calculator extends Actor {
override val supervisorStrategy = ???
def receive = {
case m: Divide => divider forward m
}
}
}
Dependency injection:
actor props
trait AkkaComponent {
def actorSystem: ActorSystem
}
trait DividerComponent {
def divider: Props
}
trait CalculatorComponent {
def calculator: ActorRef
}
I like to
block it, block it
Blocking
class Blocker extends Actor {
import context._
def receive = {
case GetThreadCount =>
sender() ! Await.result(sleep(), 10 seconds)
// or
sender() ! spinAwait(sleep(), 10 seconds)
}
def sleep() =
after(10 millis, system.scheduler)(Future.successful())
}
Blocking
• Run 1000 actors
• Send 1 request to every actor
• Default executor (fork-join, parallelism-max = 64)
Spin Await
Threads 28 ~ 1000
Success rate 60% 100%
Total time 410s 0.5s
No mutable state
is so functional
Stateless actor
class StatelessActor extends Actor {
def receive = {
case Divide(a, b) => sender() ! (a / b)
}
}
class Calculator extends Actor {
def receive = {
case Calculate =>
context.actorOf(Props[StatelessActor]) ! Divide(84, 2)
case result: Int =>
println(s"The answer is $result")
}
}
Just future
class Calculator extends Actor {
def receive = {
case Calculate =>
Future { 84 / 2 } pipeTo self
case result: Int =>
println(s"The answer is $result")
}
}
Actor initialization
Actor initialization
• Actor parameters:
• Actor constructor
• Initializing message
• Initialize yourself
• Long initialization:
• Blocking
• Switching actor behavior with dropping
• Switching actor behavior with stashing
Actor initialization:
initializing message
class FineCalculator extends Actor {
var greediness = none[Double]
def receive = {
case SetGreediness(g) =>
greediness = some(g)
case GetFine(v) =>
sender() ! (v * greediness.get)
}
}
Actor initialization:
parameterized receive
class FineCalculator extends Actor {
def receive = uninitialized
def uninitialized: Receive = {
case SetGreediness(m) => context.become(initialized(m))
}
def initialized(greediness: Double): Receive = {
case GetFine(x) => sender() ! (x * greediness)
}
}
Scala.Rx
val a = Var(1)
val b = Var(2)
val c = Rx{ a() + b() }
val cObs = Obs(c) { println(c()) }
// prints 3
assert(c() == 3)
a() = 4
// prints 6
assert(c() == 6)
Actor initialization:
reactive receive
class FineCalculator extends Actor {
val greediness = Var(none[Double])
val actorReceive =
Rx { greediness().fold(uninitialized)(initialized) }
val actorReceiveObs =
Obs(actorReceive) { context.become(actorReceive()) }
def receive = uninitialized
def uninitialized: Receive = {
case SetGreediness(g) => greediness() = some(g)
}
def initialized(g: Double): Receive = uninitialized orElse {
case GetFine(v) => sender() ! (v * g)
}
}
Actor initialization:
initialize yourself
class FineCalculatorCallback extends Actor {
(context.actorSelection("..") ? GetGreediness)
.mapTo[Double].map(SetGreediness).pipeTo(self)
def receive = uninitialized
def uninitialized: Receive = {
case SetGreediness(m) => context.become(initialized(m))
}
def initialized(greediness: Double): Receive = {
case GetFine(x) => sender() ! (x * greediness)
}
}
Safe closures
Closing over actor state
When you use
• Future.apply
• future methods (map,
flatMap etc.)
• scheduler
And access
• this
• vars
• context
• sender()
you are asking for trouble
Unsafe closures
class Computer extends Actor {
var counter = 0
override def receive: Receive = {
case Inc =>
val requester = sender()
Future {
counter += 1 // unsafe!
requester ! counter
}
}
}
Local executor
trait LocalExecutor {
this: Actor =>
implicit val executor = new ExecutionContext {
override def execute(runnable: Runnable): Unit =
self ! runnable
override def reportFailure(t: Throwable): Unit =
self ! t
}
def receive: Receive = {
case r: Runnable => r.run()
case t: Throwable => throw t
}
}
Safe closures
class Computer extends Actor with LocalExecutor {
var counter = 0
override def receive: Receive = super.receive orElse {
case Inc =>
val requester = sender()
Future {
counter += 1 // safe
requester ! counter
}
}
}
Flow control
Flow control:
push
• The simplest option, use by default
Flow control:
throttle
• You should know maximum message rate in
advance
• TimerBasedThrottler (akka-contrib)
Flow control:
push with ack / pull
• Acknowledge individual messages or batches
• Difference: who is first
Questions?
References

More Related Content

What's hot

Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScriptFITC
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
Flying Futures at the same sky can make the sun rise at midnight
Flying Futures at the same sky can make the sun rise at midnightFlying Futures at the same sky can make the sun rise at midnight
Flying Futures at the same sky can make the sun rise at midnightWiem Zine Elabidine
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio Martín
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesKonrad Malawski
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projectsIgnacio Martín
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Ignacio Martín
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)A K M Zahiduzzaman
 
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...Tim Chaplin
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
DDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceDDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceKonrad Malawski
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsGlobalLogic Ukraine
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)BoneyGawande
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 

What's hot (20)

Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
Flying Futures at the same sky can make the sun rise at midnight
Flying Futures at the same sky can make the sun rise at midnightFlying Futures at the same sky can make the sun rise at midnight
Flying Futures at the same sky can make the sun rise at midnight
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutes
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Pure Future
Pure FuturePure Future
Pure Future
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)
 
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
DDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceDDDing Tools = Akka Persistence
DDDing Tools = Akka Persistence
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Fiber supervision in ZIO
Fiber supervision in ZIOFiber supervision in ZIO
Fiber supervision in ZIO
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 

Similar to Akka patterns

Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn De Goes
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedykrivachy
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsAndrii Lashchenko
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveJeff Smith
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
Project Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesProject Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesRoland Kuhn
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka featuresGrzegorz Duda
 
8 things I wish I knew when I started with Akka
8 things I wish I knew when I started with Akka8 things I wish I knew when I started with Akka
8 things I wish I knew when I started with AkkaMarkus Jura
 

Similar to Akka patterns (20)

Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedy
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applications
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Project Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesProject Gålbma – Actors vs Types
Project Gålbma – Actors vs Types
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
8 things I wish I knew when I started with Akka
8 things I wish I knew when I started with Akka8 things I wish I knew when I started with Akka
8 things I wish I knew when I started with Akka
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 

Recently uploaded

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
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 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Recently uploaded (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
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 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 

Akka patterns

  • 2. About me • Work at Qubell Inc. • Scala since 2011 • Akka since 1.x • Now: Scala, Akka, Play, MongoDB, RabbitMQ
  • 3. Agenda • Anti-patterns • Ask is so cool • Dependency injection for the win • I like to block it, block it • No mutable state is so functional • Patterns • Actor initialization • Safe closures • Flow control
  • 4. Ask is so cool
  • 5. Tell, don’t ask: classic code class FineService { def getFine(v: Double) = { v * greedinessService.getGreediness() } } class GreedinessService { def getGreediness(): Double = { db.query("select ...") } } class DbService { def query(s: String): Double = ??? }
  • 6. Tell, don’t ask: classic actor code class FineService extends Actor { def receive = { case GetFine(v) => (greedinessService ? GetGreediness) .mapTo[Double].map(_ * v).pipeTo(sender()) } } class GreedinessService extends Actor { def receive = { case GetGreediness => (db ? Query("select ...")) .mapTo[Double].pipeTo(sender()) } } Timeout Timeout
  • 7. Tell, don’t ask • Works perfect until loaded • Timeouts everywhere • equal — you don’t get the exact cause • different — unmanageable hell • Use thoughtful!
  • 8. Tell, don’t ask: invert control flow class FineService extends Actor { var greediness: Double = 0 def receive = { case GetFine(v) => sender() ! greediness case SetGreediness(g) => greediness = g } } class GreedinessService extends Actor { def receive = { case ReloadGreediness => (db ? Query("select ...")) .mapTo[Double].map(SetGreediness).pipeTo(fineService) } }
  • 10. Dependency injection: actor references trait AkkaComponent { def actorSystem: ActorSystem } trait DividerComponent { def divider: ActorRef } trait CalculatorComponent { def calculator: ActorRef }
  • 11. Dependency injection: actor references trait CalculatorComponentImpl extends CalculatorComponent { this: AkkaComponent with DividerComponent => lazy val calculator = actorSystem.actorOf(Props(new Calculator)) class Calculator extends Actor { override val supervisorStrategy = ??? def receive = { case m: Divide => divider forward m } } }
  • 12. Dependency injection: actor props trait AkkaComponent { def actorSystem: ActorSystem } trait DividerComponent { def divider: Props } trait CalculatorComponent { def calculator: ActorRef }
  • 13. I like to block it, block it
  • 14. Blocking class Blocker extends Actor { import context._ def receive = { case GetThreadCount => sender() ! Await.result(sleep(), 10 seconds) // or sender() ! spinAwait(sleep(), 10 seconds) } def sleep() = after(10 millis, system.scheduler)(Future.successful()) }
  • 15. Blocking • Run 1000 actors • Send 1 request to every actor • Default executor (fork-join, parallelism-max = 64) Spin Await Threads 28 ~ 1000 Success rate 60% 100% Total time 410s 0.5s
  • 16. No mutable state is so functional
  • 17. Stateless actor class StatelessActor extends Actor { def receive = { case Divide(a, b) => sender() ! (a / b) } } class Calculator extends Actor { def receive = { case Calculate => context.actorOf(Props[StatelessActor]) ! Divide(84, 2) case result: Int => println(s"The answer is $result") } }
  • 18. Just future class Calculator extends Actor { def receive = { case Calculate => Future { 84 / 2 } pipeTo self case result: Int => println(s"The answer is $result") } }
  • 20. Actor initialization • Actor parameters: • Actor constructor • Initializing message • Initialize yourself • Long initialization: • Blocking • Switching actor behavior with dropping • Switching actor behavior with stashing
  • 21. Actor initialization: initializing message class FineCalculator extends Actor { var greediness = none[Double] def receive = { case SetGreediness(g) => greediness = some(g) case GetFine(v) => sender() ! (v * greediness.get) } }
  • 22. Actor initialization: parameterized receive class FineCalculator extends Actor { def receive = uninitialized def uninitialized: Receive = { case SetGreediness(m) => context.become(initialized(m)) } def initialized(greediness: Double): Receive = { case GetFine(x) => sender() ! (x * greediness) } }
  • 23. Scala.Rx val a = Var(1) val b = Var(2) val c = Rx{ a() + b() } val cObs = Obs(c) { println(c()) } // prints 3 assert(c() == 3) a() = 4 // prints 6 assert(c() == 6)
  • 24. Actor initialization: reactive receive class FineCalculator extends Actor { val greediness = Var(none[Double]) val actorReceive = Rx { greediness().fold(uninitialized)(initialized) } val actorReceiveObs = Obs(actorReceive) { context.become(actorReceive()) } def receive = uninitialized def uninitialized: Receive = { case SetGreediness(g) => greediness() = some(g) } def initialized(g: Double): Receive = uninitialized orElse { case GetFine(v) => sender() ! (v * g) } }
  • 25. Actor initialization: initialize yourself class FineCalculatorCallback extends Actor { (context.actorSelection("..") ? GetGreediness) .mapTo[Double].map(SetGreediness).pipeTo(self) def receive = uninitialized def uninitialized: Receive = { case SetGreediness(m) => context.become(initialized(m)) } def initialized(greediness: Double): Receive = { case GetFine(x) => sender() ! (x * greediness) } }
  • 27. Closing over actor state When you use • Future.apply • future methods (map, flatMap etc.) • scheduler And access • this • vars • context • sender() you are asking for trouble
  • 28. Unsafe closures class Computer extends Actor { var counter = 0 override def receive: Receive = { case Inc => val requester = sender() Future { counter += 1 // unsafe! requester ! counter } } }
  • 29. Local executor trait LocalExecutor { this: Actor => implicit val executor = new ExecutionContext { override def execute(runnable: Runnable): Unit = self ! runnable override def reportFailure(t: Throwable): Unit = self ! t } def receive: Receive = { case r: Runnable => r.run() case t: Throwable => throw t } }
  • 30. Safe closures class Computer extends Actor with LocalExecutor { var counter = 0 override def receive: Receive = super.receive orElse { case Inc => val requester = sender() Future { counter += 1 // safe requester ! counter } } }
  • 32. Flow control: push • The simplest option, use by default
  • 33. Flow control: throttle • You should know maximum message rate in advance • TimerBasedThrottler (akka-contrib)
  • 34. Flow control: push with ack / pull • Acknowledge individual messages or batches • Difference: who is first