SlideShare a Scribd company logo
© 2014 VMware Inc. All rights reserved. 
Scale Up Your Thinking 
Reactive Programming with Scala and Akka 
Lior Shapsa 
Yardena Meymann 
February 24, 2014
About us 
• Lior Shapsa – Leads Benchmark Development (lshapsa@vmware.com) 
• Yardena Meymann - Group Architect (ymeymann@vmware.com) 
2
The Project 
• New Generation Business Management Products 
• Manage Financial Aspects of the Cloud 
• Help CFOs to optimize the cloud cost 
• Benchmarking – Compare to Industry Best Practices 
3
What Do We Need 
• Web Scraping – naïve way isn’t good enough 
• Crowd Sourcing 
• Analyze Data 
– Build a reliable price list 
– How efficient is my virtual infra vs. industry? (cost, capacity) 
– How fast am I responding to business challenges 
• Start With Single Instance and Scale Out Fast!
Why to Scale Out 
Moore’s Law 
• The Clock Speed Has 
Reached Its Limit in 2006 
• Free Lunch Is Over
Why to Scale Out 
Amdahl’s Law 
• The New Reality 
http://en.wikipedia.org/wiki/Amdahl's_law
The Challenge 
Shared mutable state -> race conditions 
Threads are 
expensive 
Locks are hard 
(and expensive)
The Challenge 
8 Fallacies of Distributed Computing: 
– The network is reliable 
– Latency is zero 
– Bandwidth is infinite 
– The network is secure 
– Topology doesn't change 
– There is one administrator 
– Transport cost is zero 
– The network is homogeneous
Reactive Programming 
• React to Events 
– Pushing rather than pulling (No Shared State) 
• React to Load 
– Focus on scalability rather than single-user performance. 
• React to Failure 
– Resilient systems with the ability to recover quickly at all levels. 
• React to Users 
– Combine the above traits for an interactive user experience 
9
Chosen Solution: Actor Model 
• Formalized in 1973 by Carl Hewitt and refined by 
Gul Agha in mid 80s. 
– The first major adoption is done by Ericsson in mid 80s. 
• Invented Erlang and later open-sourced in 90s. 
• Built a distributed, concurrent, and fault-tolerant 
telecom system which has 99.9999999% uptime
Chosen Solution: Actor Model 
• Actor Instead of Object, Asynch Message Instead of Method Call 
• Keep Mutable State Internal, Share Nothing 
• Communicate via Immutable Message Passing 
• Messages are Kept in Mailbox and Processed Sequentially 
• Asynchronous and Non-blocking 
Actor Actor 
Mailbox 
state 
Mailbox behavior 
behavior state
Actor Example (Scala) 
• Define 
case class Greeting(who: String) //message 
class GreetingActor extends Actor { 
def receive = { 
case Greeting(who) => sender ! “Hello ” + who 
} 
} 
• Create 
val sys = ActorSystem("MySystem") 
val greeter = sys.actorOf(Props[GreetingActor], "greeter") 
• Send 
greeter ! Greeting(“Akka”);
Actor Libs For the JVM 
• Akka (Java/Scala) 
• Kilim (Java) 
• Jetlang (Java) 
• Actor’s Guild (Java) 
• Actorom (Java) 
• FunctionalJava (Java) 
• GPar (Groovy) 

Web Scraping - Example
Dispatch 
Crawling 
library 
Netty 
Web Scraping Actors Design 
Curiosity 
Site … 
Pages 
Level1 Level1 
Level2 
… 
Level2 
File 
writer 
Site 
… 
k/v
Example Site 
class Servers extends Site { 
override def start(): Unit = goto[ListPage] “…” 
} 
class ListPage extends Page { 
override def processResult(result: Response): Unit = { 
val links = listProductLinks(result.content) 
links foreach goto[ProductPage](_, pageType = Child) 
val next = getNextPage(result.content) 
next foreach goto[ListPage](_, pageType = Sibling) 
} 
} 
class ProductPage extends Page { 
override def processResult(result: Response): Unit = { 
val spec = productTitle(result.content) ++ 
generalSpec(result.content) ++ 
pricingInfo(result.content) 
writeToFile(spec) 
} 
}
Supervision 
• Let It Crash! 
– Errors are encapsulated as messages and isolated from the BL 
– The caller is not necessarily available 
• The Supervisor Reacts Upon Failure 
– Resume, keeping its accumulated internal state 
– Restart, clearing out its accumulated internal state 
– Terminate 
– Escalate
Supervision – Example (optional) 
override val supervisorStrategy = 
OneForOneStrategy(maxNrOfRetries = 10, 
withinTimeRange = 1 minute) { 
case _: ArithmeticException => Resume 
case _: NullPointerException => Restart 
case _: Exception => Escalate 
}
Akka Distributable by Design 
• Superior model for detecting and recovering from errors 
• Location transparent - scale UP and OUT for free 
• Adaptive load-balancing, cluster rebalancing & actor 
migration 
• Build extremely loosely coupled and dynamic systems 
that can change and adapt at runtime
Under the hood
Receive Method 
• Pattern match on the message 
class Site… extends Actor … { 
override def receive: Receive = { 
case Start => 
log.info(s"Starting $siteName ...") 
start() 
… 
} 
• Defined for some (but not necessarily all) messages 
• Unhandled messages are sent to a special location
Splitting Behavior Between Methods 
• Group related messages in a receive function 
• Compose receive functions with orElse operator 
private def process: Receive = { 
case res: Response => … 
case Status.Failure(e) => … 
} 
private def monitor: Receive = { 
case Create… => … 
case Terminated(actor) => … 
Curiosity 
Site … 
Crawler 
Crawling 
library 
} 
protected override def receive: Receive = process orElse monitor 
Netty 
Pages 
Page 
Page 
Page 
… 
Page 
File writer 
Site 
…
Using Traits to Compose a Behavior 
trait Percolator { myself: Actor => 
protected def percolate: Receive = … 
} 
trait Composite { myself: Actor => 
protected def monitor: Receive = … 
} 
class Page extends Actor with Percolator with Composite { 
private def process: Receive = … 
protected override def receive = 
process orElse percolate orElse monitor 
} 
Composite Percolator 
Actor 
Page 
c 
t t 
c
Web Scraping Actors Design 
Curiosity 
Dispatch 
Crawling 
library 
Netty 
Site … 
Pages 
Level1 Level1 
Level2 
… 
Level2 
File 
writer 
Site 
…
Propagate Messages 
You can forward messages without understanding them, “methodMissing” 
trait Percolator { myself: Actor => 
protected def percolate: Receive = { 
case _ => parent forward msg 
} 
class Site… extends Actor { 
protected def override receive: Receive = { 
case msg: Goto => crawler forward msg 
case msg: WriteFile => writer forward msg 
}
Futures 
• Future holds a value which may become available at some point 
– completed when the computation results in a value or an exception 
• java.util.concurrent has futures, but we can do better… 
• Scala’s futures are asynchronously compose-able 
– Callbacks: onSuccess, onFailure, onComplete 
val f: Future[List[String]] = future { session.getRecentPosts } 
f onFailure { 
case e => println("An error has occurred: " + e.getMessage) 
} 
f onSuccess { 
case posts => for (post <- posts) println(post) 
} 
• More and more API’s are non-blocking - returning futures
Tell vs Ask 
• Tell, a.k.a. ! 
– Fire & forget 
– Best concurrency and scalability 
• Ask, a.k.a. ? 
– sends and (optionally) wait for reply 
– uses delayed computation (Futures) 
– combining futures and actors – pipeTo trick 
import akka.pattern.pipe 
val page: ActorRef = … 
val f: Future[xml.NodeSeq] = Http.browse(url(…) OK as.tagsoup.NodeSeq) 
f pipeTo page 
• Why we decided to stick with “bare actors”
A Closer Look at Akka Actor 
Reference 
Instance 
Instance 
factory 
Context 
Mailbox 
Receive function 
Receive function 
Behavior
Actor State 
It’s Ok to have mutable state inside actor 
trait Composite { myself: Actor => 
private var childrenCount = 0 
override def receive: Receive = { 
case Created… => 
childrenCount = childrenCount + 1 
case Terminated… => 
childrenCount = childrenCount – 1 
if (childrenCount == 0) context stop self 
}
Lightweight State-Machine with become 
class Curiosity extends Actor { 
private def free: Receive = { 
case Start => 
crawlers foreach (_ ! Start) 
context become busy 
case Status | Stop => sender ! Free 
} 
private def busy: Receive = { 
case Stop => 
crawlers foreach (_ ! Stop) 
context become awaitingTermination 
case Status | Start => sender ! Busy 
case AllFinished => context become free 
} 
private def awaitingTermination: Receive = { 
case AllFinished => context become free 
case Status | Start | Stop => sender ! Busy 
} 
override def receive: Receive = free 
} 
Free 
Busy 
Start 
Awaiting 
Termination 
Stop 
Finished 
Finished
Actor Hierarchy DO’s and DON’Ts 
• DO give actors meaningful names if you can 
• DON’T be afraid to create lots of short-living actors 
• DON’T nest actor classes in one another 
• DO note that restart that results from failure is not the same as a 
graceful stop 
• DON’T define public methods on Actors 
• DO choose supervision strategy wisely, build your hierarchy according 
to the strategy 
• DON’T confuse actor.Status.Failure with util.Failure 
• DO make sure messages are immutable 
• DON’T rely on using generics in messages, as they will be erased in 
bytecode (unless you reify with ClassTag/TypeTag)
Stopping Actors 
• Watching another actor – Death Watch 
– Not same as supervision 
– Use context.watch(actorReference) 
– Terminated(actorReference) events 
• Stop vs. PoisonPill and how we used both 
– context.stop – terminate after current message 
– context.kill – terminate now 
– PoisonPill message – terminate after processing all messages
Web Scraping - Termination 
Curiosity 
Dispatch 
Crawling 
library 
Netty 
Site … 
Pages 
Page Page 
Page 
… 
Page 
File 
writer 
Site 
… 
k/v k/v k/v
ETL – Decrypt Translate & Load (optional) 
34 
Decrypt Load Router Router 
Load Manager 
Decrypt 
Worker 
Translate 
Worker 
Archiver 
Mongo 
Loader 
Decrypt Manager 
Translate 
WTorarknesrlate 
Worker 
Decrypt 
WDorekcerrypt 
Worker 
Directory 
Watcher 
Decrypt 
WDorekcerrypt 
Worker 
Directory 
Watcher
Exposing Actors with Spray 
• Spray – lightweight HTTP server, non-blocking, 100% Akka 
• Making your actors respond to HTTP requests 
import akka.io.IO 
import spray.can.Http 
import spray.routing.HttpService 
val Handler = new Actor with HttpService { 
def actorRefFactory = context 
def receive = runRoute { 
path("start") { … { crawlers ! Start ; …}} ~ 
path("stop") { … { crawlers ! Stop ; …}} ~ 
… 
} 
} 
IO(Http)(system) ! Http.Bind(handler, interface = … , port = …)
Testing Akka 
• ScalaTest – BDD (Given-When-Then) 
• ScalaMock & Mockito 
• Measuring Scala code coverage with sbt (scct + cobertura + some 
tricks) 
• Using Akka TestKit + Spray 
• ScalaCheck
Testing Akka - Example 
import org.scalatest._ 
import akka.testkit.{ImplicitSender , TestActorRef, TestKit} 
class CuriosityTest extends TestKit(new ActorSystem(“…”) … { 
val myTestedActor = TestActorRef[Curiosity] 
“Curiosity" must { 
"display free status when not working" in { 
myTestedActor ! Status 
expectMsg(Free) 
} 
} 
… 
}
Testing Akka – Running Tests
Debugging Akka 
• Typesafe console 
• Logs, watching for DeadLetter 
• Using Scala clone of Yammer Metrics
Typesafe Console
Q&A
Our Amazing Team 
If you want to join, find us at http://vmware.jobs/
Thank You!

More Related Content

What's hot

Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Scala Intro
Scala IntroScala Intro
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Adrian Spender
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
Meetu Maltiar
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
Sunghyouk Bae
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
Francesco Usai
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
Sunghyouk Bae
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Sunghyouk Bae
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
suraj_atreya
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 

What's hot (20)

scala
scalascala
scala
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala
ScalaScala
Scala
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 

Similar to Scale up your thinking

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
Peter Lawrey
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
Manuel Bernhardt
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
Harinath Krishnamoorthy
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
Yung-Lin Ho
 
Akka Microservices Architecture And Design
Akka Microservices Architecture And DesignAkka Microservices Architecture And Design
Akka Microservices Architecture And Design
Yaroslav Tkachenko
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with AkkaMaciej Matyjas
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
Skills Matter
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
AD_
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayYardena Meymann
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017
Agustin Ramos
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camelkrasserm
 
Building large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor frameworkBuilding large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor framework
Vignesh Sukumar
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OT
getch123
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
Alex Miller
 

Similar to Scale up your thinking (20)

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Akka Microservices Architecture And Design
Akka Microservices Architecture And DesignAkka Microservices Architecture And Design
Akka Microservices Architecture And Design
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
Akka (1)
Akka (1)Akka (1)
Akka (1)
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Building large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor frameworkBuilding large scale, job processing systems with Scala Akka Actor framework
Building large scale, job processing systems with Scala Akka Actor framework
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OT
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 

Recently uploaded

Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 

Recently uploaded (20)

Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 

Scale up your thinking

  • 1. © 2014 VMware Inc. All rights reserved. Scale Up Your Thinking Reactive Programming with Scala and Akka Lior Shapsa Yardena Meymann February 24, 2014
  • 2. About us • Lior Shapsa – Leads Benchmark Development (lshapsa@vmware.com) • Yardena Meymann - Group Architect (ymeymann@vmware.com) 2
  • 3. The Project • New Generation Business Management Products • Manage Financial Aspects of the Cloud • Help CFOs to optimize the cloud cost • Benchmarking – Compare to Industry Best Practices 3
  • 4. What Do We Need • Web Scraping – naïve way isn’t good enough • Crowd Sourcing • Analyze Data – Build a reliable price list – How efficient is my virtual infra vs. industry? (cost, capacity) – How fast am I responding to business challenges • Start With Single Instance and Scale Out Fast!
  • 5. Why to Scale Out Moore’s Law • The Clock Speed Has Reached Its Limit in 2006 • Free Lunch Is Over
  • 6. Why to Scale Out Amdahl’s Law • The New Reality http://en.wikipedia.org/wiki/Amdahl's_law
  • 7. The Challenge Shared mutable state -> race conditions Threads are expensive Locks are hard (and expensive)
  • 8. The Challenge 8 Fallacies of Distributed Computing: – The network is reliable – Latency is zero – Bandwidth is infinite – The network is secure – Topology doesn't change – There is one administrator – Transport cost is zero – The network is homogeneous
  • 9. Reactive Programming • React to Events – Pushing rather than pulling (No Shared State) • React to Load – Focus on scalability rather than single-user performance. • React to Failure – Resilient systems with the ability to recover quickly at all levels. • React to Users – Combine the above traits for an interactive user experience 9
  • 10. Chosen Solution: Actor Model • Formalized in 1973 by Carl Hewitt and refined by Gul Agha in mid 80s. – The first major adoption is done by Ericsson in mid 80s. • Invented Erlang and later open-sourced in 90s. • Built a distributed, concurrent, and fault-tolerant telecom system which has 99.9999999% uptime
  • 11. Chosen Solution: Actor Model • Actor Instead of Object, Asynch Message Instead of Method Call • Keep Mutable State Internal, Share Nothing • Communicate via Immutable Message Passing • Messages are Kept in Mailbox and Processed Sequentially • Asynchronous and Non-blocking Actor Actor Mailbox state Mailbox behavior behavior state
  • 12. Actor Example (Scala) • Define case class Greeting(who: String) //message class GreetingActor extends Actor { def receive = { case Greeting(who) => sender ! “Hello ” + who } } • Create val sys = ActorSystem("MySystem") val greeter = sys.actorOf(Props[GreetingActor], "greeter") • Send greeter ! Greeting(“Akka”);
  • 13. Actor Libs For the JVM • Akka (Java/Scala) • Kilim (Java) • Jetlang (Java) • Actor’s Guild (Java) • Actorom (Java) • FunctionalJava (Java) • GPar (Groovy) 
  • 14. Web Scraping - Example
  • 15. Dispatch Crawling library Netty Web Scraping Actors Design Curiosity Site … Pages Level1 Level1 Level2 … Level2 File writer Site … k/v
  • 16. Example Site class Servers extends Site { override def start(): Unit = goto[ListPage] “…” } class ListPage extends Page { override def processResult(result: Response): Unit = { val links = listProductLinks(result.content) links foreach goto[ProductPage](_, pageType = Child) val next = getNextPage(result.content) next foreach goto[ListPage](_, pageType = Sibling) } } class ProductPage extends Page { override def processResult(result: Response): Unit = { val spec = productTitle(result.content) ++ generalSpec(result.content) ++ pricingInfo(result.content) writeToFile(spec) } }
  • 17. Supervision • Let It Crash! – Errors are encapsulated as messages and isolated from the BL – The caller is not necessarily available • The Supervisor Reacts Upon Failure – Resume, keeping its accumulated internal state – Restart, clearing out its accumulated internal state – Terminate – Escalate
  • 18. Supervision – Example (optional) override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate }
  • 19. Akka Distributable by Design • Superior model for detecting and recovering from errors • Location transparent - scale UP and OUT for free • Adaptive load-balancing, cluster rebalancing & actor migration • Build extremely loosely coupled and dynamic systems that can change and adapt at runtime
  • 21. Receive Method • Pattern match on the message class Site… extends Actor … { override def receive: Receive = { case Start => log.info(s"Starting $siteName ...") start() … } • Defined for some (but not necessarily all) messages • Unhandled messages are sent to a special location
  • 22. Splitting Behavior Between Methods • Group related messages in a receive function • Compose receive functions with orElse operator private def process: Receive = { case res: Response => … case Status.Failure(e) => … } private def monitor: Receive = { case Create… => … case Terminated(actor) => … Curiosity Site … Crawler Crawling library } protected override def receive: Receive = process orElse monitor Netty Pages Page Page Page … Page File writer Site …
  • 23. Using Traits to Compose a Behavior trait Percolator { myself: Actor => protected def percolate: Receive = … } trait Composite { myself: Actor => protected def monitor: Receive = … } class Page extends Actor with Percolator with Composite { private def process: Receive = … protected override def receive = process orElse percolate orElse monitor } Composite Percolator Actor Page c t t c
  • 24. Web Scraping Actors Design Curiosity Dispatch Crawling library Netty Site … Pages Level1 Level1 Level2 … Level2 File writer Site …
  • 25. Propagate Messages You can forward messages without understanding them, “methodMissing” trait Percolator { myself: Actor => protected def percolate: Receive = { case _ => parent forward msg } class Site… extends Actor { protected def override receive: Receive = { case msg: Goto => crawler forward msg case msg: WriteFile => writer forward msg }
  • 26. Futures • Future holds a value which may become available at some point – completed when the computation results in a value or an exception • java.util.concurrent has futures, but we can do better… • Scala’s futures are asynchronously compose-able – Callbacks: onSuccess, onFailure, onComplete val f: Future[List[String]] = future { session.getRecentPosts } f onFailure { case e => println("An error has occurred: " + e.getMessage) } f onSuccess { case posts => for (post <- posts) println(post) } • More and more API’s are non-blocking - returning futures
  • 27. Tell vs Ask • Tell, a.k.a. ! – Fire & forget – Best concurrency and scalability • Ask, a.k.a. ? – sends and (optionally) wait for reply – uses delayed computation (Futures) – combining futures and actors – pipeTo trick import akka.pattern.pipe val page: ActorRef = … val f: Future[xml.NodeSeq] = Http.browse(url(…) OK as.tagsoup.NodeSeq) f pipeTo page • Why we decided to stick with “bare actors”
  • 28. A Closer Look at Akka Actor Reference Instance Instance factory Context Mailbox Receive function Receive function Behavior
  • 29. Actor State It’s Ok to have mutable state inside actor trait Composite { myself: Actor => private var childrenCount = 0 override def receive: Receive = { case Created… => childrenCount = childrenCount + 1 case Terminated… => childrenCount = childrenCount – 1 if (childrenCount == 0) context stop self }
  • 30. Lightweight State-Machine with become class Curiosity extends Actor { private def free: Receive = { case Start => crawlers foreach (_ ! Start) context become busy case Status | Stop => sender ! Free } private def busy: Receive = { case Stop => crawlers foreach (_ ! Stop) context become awaitingTermination case Status | Start => sender ! Busy case AllFinished => context become free } private def awaitingTermination: Receive = { case AllFinished => context become free case Status | Start | Stop => sender ! Busy } override def receive: Receive = free } Free Busy Start Awaiting Termination Stop Finished Finished
  • 31. Actor Hierarchy DO’s and DON’Ts • DO give actors meaningful names if you can • DON’T be afraid to create lots of short-living actors • DON’T nest actor classes in one another • DO note that restart that results from failure is not the same as a graceful stop • DON’T define public methods on Actors • DO choose supervision strategy wisely, build your hierarchy according to the strategy • DON’T confuse actor.Status.Failure with util.Failure • DO make sure messages are immutable • DON’T rely on using generics in messages, as they will be erased in bytecode (unless you reify with ClassTag/TypeTag)
  • 32. Stopping Actors • Watching another actor – Death Watch – Not same as supervision – Use context.watch(actorReference) – Terminated(actorReference) events • Stop vs. PoisonPill and how we used both – context.stop – terminate after current message – context.kill – terminate now – PoisonPill message – terminate after processing all messages
  • 33. Web Scraping - Termination Curiosity Dispatch Crawling library Netty Site … Pages Page Page Page … Page File writer Site … k/v k/v k/v
  • 34. ETL – Decrypt Translate & Load (optional) 34 Decrypt Load Router Router Load Manager Decrypt Worker Translate Worker Archiver Mongo Loader Decrypt Manager Translate WTorarknesrlate Worker Decrypt WDorekcerrypt Worker Directory Watcher Decrypt WDorekcerrypt Worker Directory Watcher
  • 35. Exposing Actors with Spray • Spray – lightweight HTTP server, non-blocking, 100% Akka • Making your actors respond to HTTP requests import akka.io.IO import spray.can.Http import spray.routing.HttpService val Handler = new Actor with HttpService { def actorRefFactory = context def receive = runRoute { path("start") { … { crawlers ! Start ; …}} ~ path("stop") { … { crawlers ! Stop ; …}} ~ … } } IO(Http)(system) ! Http.Bind(handler, interface = … , port = …)
  • 36. Testing Akka • ScalaTest – BDD (Given-When-Then) • ScalaMock & Mockito • Measuring Scala code coverage with sbt (scct + cobertura + some tricks) • Using Akka TestKit + Spray • ScalaCheck
  • 37. Testing Akka - Example import org.scalatest._ import akka.testkit.{ImplicitSender , TestActorRef, TestKit} class CuriosityTest extends TestKit(new ActorSystem(“…”) … { val myTestedActor = TestActorRef[Curiosity] “Curiosity" must { "display free status when not working" in { myTestedActor ! Status expectMsg(Free) } } … }
  • 38. Testing Akka – Running Tests
  • 39. Debugging Akka • Typesafe console • Logs, watching for DeadLetter • Using Scala clone of Yammer Metrics
  • 41. Q&A
  • 42. Our Amazing Team If you want to join, find us at http://vmware.jobs/

Editor's Notes

  1. Benchmark cloud cost, efficiency and capacity Benchmarking module is written 100% in Scala 2.10. Backend is based on Typesafe stack (SBT, AKKA, Spray, Play), HDFS, Spark, MongoDB, Lucene, etc… Frontend is based on HTML 5 and AngularJS
  2. Web Scraping Collect updated inventory and costs of Servers, OSs, CPUs, Labor, Storage, etc… Use reliable techniques to extract cost and specifications out of the web pages Crowd Sourcing Collect users inventory and costs to build better costing functions Validation, masking, filtering, encryption, compression Analyze Build a reliable price list How efficient is my virtual infra vs. industry? (cost, capacity) How fast am I responding to business challenges
  3. http://www.reactivemanifesto.org/#event-driven
  4. Free - high CPU utilization, low latency, high throughput and scalability
  5. sends a message asynchronously and returns a Future representing a possible reply
  6. More neat tricks: stashing messages, full-blown state-machines
  7. More neat tricks: stashing messages, full-blown state-machines