SlideShare a Scribd company logo
Scala, Akka, Play
The why and how of reactive web-applications on the JVM
Lambda Days 2015
Manuel Bernhardt - @elmanu
Agenda
1. The Why
2. The How
Who is speaking?
• freelance software consultant based
in Vienna
• Vienna Scala User Group
• web, web, web
Who is speaking?
• freelance software consultant based
in Vienna
• Vienna Scala User Group
• web, web, web
• writing a book on reactive web-
applications
http://www.manning.com/
bernhardt
The Why
The Why
The Whys
1st
Why: it's 2015, the
year of...
2015!
Flying cars?
Hoverboards?
Self-lacing shoes?
2015: many-core
CPUs
• End of the single-core multi-core era
• Many players in the space
• Tilera, Cavium
• Adapteva Parallela
• Xeon PHI
• It's happening!
Too many cores?
• 1981 "640 kb ought to be enough
for anybody" ~ Bill Gates
Too many cores?
• 1981 "640 kb ought to be enough
for anybody" ~ Bill Gates
• 2014 "4 cores ought to be enough
for anybody" ~ Linus Torvalds1
1
http://highscalability.com/blog/2014/12/31/linus-the-whole-parallel-
computing-is-the-future-is-a-bunch.html
2nd
Why: distribution
is the norm, not the
exception
It's all in the cloud
• divide & conquer: specialized
services that do one thing well
• storage: S3
• emails: MailChimp
• monitoring: New Relic, Plumbr
• etc. etc. etc.
Reactive Web-Applications @ LambdaDays
This is not the
cloud
That's more like the
cloud
• scaling out to handle large loads
• scaling out / replication to handle
node failure
Yes! That's the
cloud!
• networks, networks, networks
• they fail all the time
• Jepsen series3
3
http://aphyr.com
The cloud is hard
• CAP theorem
• 8 fallacies of distributed computing
• hard problem, no easy solution
• PAXOS, CQRS, CRDTs
3rd
Why: Winter is
coming
Reactive Web-Applications @ LambdaDays
Side note: Internet of Lost Things
Prediction: "By 2020, everyone will have a bunch of online
things lost in their appartment"
4th
Why: Houston, we
have a problem
Our traditional programming
tools don't work in this setting
We have been
brainwashed to
use:
1. imperative programming with
mutable state
2. locks, locks, locks
The problem with mutable state
car.setPosition(0);
car.setPosition(10);
The problem with mutable state
The problem with
locks
• solution workaround for a broken
conceptual model
• hard to reason about
• performance hit
The problem with
object-orientation
in Java
• there is no notion of time, only an
illusion thereof
• changes to a mutable model only
make sense locally if nobody is
watching
• the larger the scope, the harder it
gets to prevent inconsistencies
The Whys
1. many-core CPUs are here
2. everything is distributed
3. IoT around the corner with 26 billions devices
4. our traditional approach does not work here
The How
The How
The Hows
In theory
• Functional Programming
• The Actor Model
• Evented Server Model
• Stateless architecture
• Event Sourcing
• Reactive Streams
In practice
• Functional Programming Scala
• The Actor Model Akka
• Evented Server Model Play
• Stateless architecture Play
• Event Sourcing Akka Persistence
• Reactive Streams Akka Streams
1st
How: Functional
Programming Scala
Short Scala history
• Martin Odersky, EPFL
• first release in 2003
• Typesafe Inc.
Design goals
• Full interoperability with Java
• Cut down boilerplate
• Pure object orientation & functional programming
• Move away from null
• Many-core programming
Core concepts of Functional
Programming
• immutability
• functions
• transforming data with functions
Immutability
case class Car(brand: String, position: Int)
val car = Car(brand = "DeLorean", position = 0)
val movedCar = car.copy(position = 10)
val movedCarLaterOn = car.copy(position = 30)
Immutability
case class Car(brand: String, position: Int)
val car = Car(brand = "DeLorean", position = 0)
val movedCar = car.copy(position = 10)
val movedCarLaterOn = car.copy(position = 30)
Work with snapshots of
state
Higher-order
functions
val (minors, majors) =
users.partition(_.age < 18)
Higher-order
functions
val isMinor =
(age: Int) => age < 18
val (minors, majors) =
users.partition(isMinor)
Higher-order
functions
val isMinor =
(age: Int) => age < 18
val (minors, majors) =
users.partition(isMinor)
Moving behaviour around instead
of moving data around
Transforming data
val addresses = users.filter(_.age > 18)
.map(_.address)
.sortBy(_.city)
Goal: To build increasingly complex behaviour through
a series of transformations / by composing functions
Composition
def fetchUser(id: Long): Option[User] = ...
def fetchCar(id: Long): Option[Car] = ...
val insuranceCost: Option[BigDecimal] = for {
user <- fetchUser(42)
car <- fetchCar(23)
} yield {
car.price / 10 - user.age
}
Composition
def fetchUser(id: Long): Future[User] = ...
def fetchCar(id: Long): Future[Car] = ...
val insuranceCost: Future[BigDecimal] = for {
user <- fetchUser(42)
car <- fetchCar(23)
} yield {
car.price / 10 - user.age
}
Composition
def fetchUser(id: Long): Try[User] = ...
def fetchCar(id: Long): Try[Car] = ...
val insuranceCost: Try[BigDecimal] = for {
user <- fetchUser(42)
car <- fetchCar(23)
} yield {
car.price / 10 - user.age
}
Composition
def fetchUser(id: Long): [User] = ...
def fetchCar(id: Long): [Car] = ...
val insuranceCost: [BigDecimal] = for {
user <- (42)
car <- (23)
} yield {
car.price / 10 - user.age
}
Composition!
Option
Future
Try
...
Functional
composition
• Option, Future, Try all implement
monadic operations
• set of data structures following the
same laws
• know one, know them all
• keeping things DRY
• also, it's not that scary
2nd
how: Actor model
Akka
History
• 1973 "A Universal Modular Actor
Formalism for Artificial Intelligence",
Carl Hewitt, Peter Bishop and
Richard Steiger
• based on physics (quantum
physics and relativistic physics)
• 1986 First release of Erlang (Joe
Armstrong)
• 1998 Ericsson reports that the
AXD301 switch achieves an
availability of 99.9999999%
History
• 2010 First release of Akka (Jonas
Bonér)
• inspired by Erlang and the Actor
Model
• message-based asynchronous
concurrency toolkit
• object-oriented programming
done right
History
• 2010 First release of Akka (Jonas
Bonér)
• inspired by Erlang and the Actor
Model
• message-based asynchronous
concurrency toolkit
• object-oriented programming
done right
• Akka is also a mountain in Sweden
Actors
• lightweight objects
• send and receive messages (mailbox)
• can have children (supervision)
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
Sending and receiving messages
case object RevelationOfFathership
class Luke extends Actor {
def receive = {
case RevelationOfFathership =>
System.err.println("Noooooooooo")
}
}
Sending and receiving messages
case object RevelationOfFathership
class Luke extends Actor {
def receive = {
case RevelationOfFathership =>
System.err.println("Noooooooooo")
}
}
val luke = ActorSystem.actorOf(Props[Luke])
luke ! RevelationOfFathership
Supervision
class Vader extends Actor {
val troopers: ActorRef = context
.actorOf[StromTrooper]
.withRouter(
RoundRobinRouter(nrOfInstances = 8)
)
}
Supervision
class Vader extends Actor {
val troopers: ActorRef = context
.actorOf[StromTrooper]
.withRouter(
RoundRobinRouter(nrOfInstances = 8)
)
}
Supervision
class Vader extends Actor {
val troopers: ActorRef = context
.actorOf[StromTrooper]
.withRouter(
RoundRobinRouter(nrOfInstances = 8)
)
override def supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 3) {
case t: Throwable =>
log.error("StormTrooper down!",
t)
Restart
}
}
3rd
How: Evented
servers & statless
architecture Play
Play history
• MVC framework, inspired by RoR,
Django, Symfony
• Zenexity
• first version released in 2009
• version 2.0 released in 2012, core
rewritten in Scala
Design Principles
• everything is compiled
• non-blocking I/O
• controller actions are functions (request => response)
• "share nothing" => horizontal scalability
Threaded servers
• like a train station with multiple
tracks
• station chief decides which trains go
on which platform
• if there are more trains than
platforms, trains queue up
• if too many trains are queuing up,
huge delays occur and passengers
go home
Evented servers
• like a waiter in a restaurant
• runs back and forth between tables
and the kitchen
• does only small tasks that do not
take much time
• one server can each serve many
tables at once
Advantages of the evented
approach
• less threads means less memory
• better CPU utilization (reduced context switching)
• (much) higher throughputs than threaded servers
The Hows
1. functional programming (immutability, functions,
composition)
2. actor model
3. evented servers & stateless architecture
4. event-sourcing & reactive streams
Summary
• many-core & distributed systems
around the corner and there to stay
• get ready and adopt some of the
"new" tools
Thank you
http://www.manning.com/bernhardt
code ctwlambdad 41% discount
@elmanu / manuel@bernhardt.io
Questions?

More Related Content

PDF
3 things you must know to think reactive - Geecon Kraków 2015
PDF
The dark side of Akka and the remedy
PDF
Back to the futures, actors and pipes: using Akka for large-scale data migration
PDF
System Integration with Akka and Apache Camel
PDF
State of Akka 2017 - The best is yet to come
PDF
Actor Model Akka Framework
PDF
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
PPTX
Concurrency in Scala - the Akka way
3 things you must know to think reactive - Geecon Kraków 2015
The dark side of Akka and the remedy
Back to the futures, actors and pipes: using Akka for large-scale data migration
System Integration with Akka and Apache Camel
State of Akka 2017 - The best is yet to come
Actor Model Akka Framework
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Concurrency in Scala - the Akka way

What's hot (20)

PDF
Advanced akka features
PPTX
Introduction to Akka - Atlanta Java Users Group
PDF
Akka Futures and Akka Remoting
PPTX
Akka Actor presentation
ZIP
Above the clouds: introducing Akka
PDF
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
PPTX
The dark side of Akka and the remedy - bp.scala meetup
PDF
The things we don't see – stories of Software, Scala and Akka
PDF
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
PPTX
Akka.net versus microsoft orleans
PDF
Not Only Streams for Akademia JLabs
PPTX
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
PDF
The Cloud-natives are RESTless @ JavaOne
PDF
Introduction to Asynchronous scala
PDF
Reactive integrations with Akka Streams
PDF
The internet of (lego) trains
PDF
Akka-chan's Survival Guide for the Streaming World
PDF
Actor Clustering with Docker Containers and Akka.Net in F#
PDF
Akka Cluster in Java - JCConf 2015
PDF
Building reactive distributed systems with Akka
Advanced akka features
Introduction to Akka - Atlanta Java Users Group
Akka Futures and Akka Remoting
Akka Actor presentation
Above the clouds: introducing Akka
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
The dark side of Akka and the remedy - bp.scala meetup
The things we don't see – stories of Software, Scala and Akka
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Akka.net versus microsoft orleans
Not Only Streams for Akademia JLabs
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
The Cloud-natives are RESTless @ JavaOne
Introduction to Asynchronous scala
Reactive integrations with Akka Streams
The internet of (lego) trains
Akka-chan's Survival Guide for the Streaming World
Actor Clustering with Docker Containers and Akka.Net in F#
Akka Cluster in Java - JCConf 2015
Building reactive distributed systems with Akka
Ad

Viewers also liked (20)

PDF
Reactive Web Applications
ODP
Node.js architecture (EN)
PDF
Intro to Reactive Programming
PPTX
Secure Coding for NodeJS
PDF
Passport Nodejs Lightening Talk
PDF
OO Design
PDF
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
PDF
[Start] Playing
PDF
Playing with Scala
ODP
Play Template Engine Based On Scala
PDF
Designing Reactive Systems with Akka
PDF
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
PDF
Your First Scala Web Application using Play 2.1
PPTX
Load balancing theory and practice
PDF
Play framework And Google Cloud Platform GCP.
PDF
Refactoring the Tennis Kata v2 (2016)
PDF
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
PPTX
Введение в Akka
PPTX
Akka-http
PDF
Lagom in Practice
Reactive Web Applications
Node.js architecture (EN)
Intro to Reactive Programming
Secure Coding for NodeJS
Passport Nodejs Lightening Talk
OO Design
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
[Start] Playing
Playing with Scala
Play Template Engine Based On Scala
Designing Reactive Systems with Akka
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
Your First Scala Web Application using Play 2.1
Load balancing theory and practice
Play framework And Google Cloud Platform GCP.
Refactoring the Tennis Kata v2 (2016)
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Введение в Akka
Akka-http
Lagom in Practice
Ad

Similar to Reactive Web-Applications @ LambdaDays (20)

PDF
Reactive Software Systems
PDF
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
PPTX
Scale up your thinking
PPT
Reactive programming with examples
PPTX
Concurrency Constructs Overview
KEY
Akka london scala_user_group
ODP
Reactive programming with scala and akka
PDF
Reactive applications and Akka intro used in the Madrid Scala Meetup
PDF
Building Stateful Microservices With Akka
PDF
Reactive applications using Akka
PPTX
Building Reactive Applications With Akka And Java
PDF
Reactive meetup 0 copy
PPTX
Reactive web applications
PDF
Take a Look at Akka+Java (English version)
PDF
Beyond fault tolerance with actor programming - Fabio Tiriticco - Codemotion ...
PDF
Beyond Fault Tolerance with Actor Programming
PPTX
Indic threads pune12-typesafe stack software development on the jvm
PDF
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
PDF
Building Reactive Applications with Akka & Java 8 - Bonèr
PDF
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Reactive Software Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Scale up your thinking
Reactive programming with examples
Concurrency Constructs Overview
Akka london scala_user_group
Reactive programming with scala and akka
Reactive applications and Akka intro used in the Madrid Scala Meetup
Building Stateful Microservices With Akka
Reactive applications using Akka
Building Reactive Applications With Akka And Java
Reactive meetup 0 copy
Reactive web applications
Take a Look at Akka+Java (English version)
Beyond fault tolerance with actor programming - Fabio Tiriticco - Codemotion ...
Beyond Fault Tolerance with Actor Programming
Indic threads pune12-typesafe stack software development on the jvm
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
Building Reactive Applications with Akka & Java 8 - Bonèr
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of

More from Manuel Bernhardt (15)

PDF
Is there anybody out there? Reactive Systems Hamburg
PDF
Is there anybody out there? Scala Days Berlin 2018
PDF
Is there anybody out there?
PDF
Is there anybody out there?
PDF
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
PDF
8 Akka anti-patterns you'd better be aware of
PDF
Beyond the buzzword: a reactive web-appliction in practice
PDF
Beyond the Buzzword - a reactive application in practice
PDF
Six years of Scala and counting
PDF
Writing a technical book
PDF
Project Phoenix - From PHP to the Play Framework in 3 months
PDF
Scala - Java2Days Sofia
PDF
Tips and tricks for setting up a Play 2 project
PDF
Introduction to Scala
PDF
Scala pitfalls
Is there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there?
Is there anybody out there?
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 Akka anti-patterns you'd better be aware of
Beyond the buzzword: a reactive web-appliction in practice
Beyond the Buzzword - a reactive application in practice
Six years of Scala and counting
Writing a technical book
Project Phoenix - From PHP to the Play Framework in 3 months
Scala - Java2Days Sofia
Tips and tricks for setting up a Play 2 project
Introduction to Scala
Scala pitfalls

Recently uploaded (20)

PPTX
web development for engineering and engineering
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
additive manufacturing of ss316l using mig welding
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Artificial Intelligence
PPT
Mechanical Engineering MATERIALS Selection
PPTX
UNIT 4 Total Quality Management .pptx
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
737-MAX_SRG.pdf student reference guides
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
web development for engineering and engineering
bas. eng. economics group 4 presentation 1.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Safety Seminar civil to be ensured for safe working.
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
additive manufacturing of ss316l using mig welding
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Artificial Intelligence
Mechanical Engineering MATERIALS Selection
UNIT 4 Total Quality Management .pptx
III.4.1.2_The_Space_Environment.p pdffdf
CYBER-CRIMES AND SECURITY A guide to understanding
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Fundamentals of safety and accident prevention -final (1).pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
737-MAX_SRG.pdf student reference guides
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026

Reactive Web-Applications @ LambdaDays

  • 1. Scala, Akka, Play The why and how of reactive web-applications on the JVM Lambda Days 2015 Manuel Bernhardt - @elmanu
  • 3. Who is speaking? • freelance software consultant based in Vienna • Vienna Scala User Group • web, web, web
  • 4. Who is speaking? • freelance software consultant based in Vienna • Vienna Scala User Group • web, web, web • writing a book on reactive web- applications http://www.manning.com/ bernhardt
  • 7. 1st Why: it's 2015, the year of...
  • 9. 2015: many-core CPUs • End of the single-core multi-core era • Many players in the space • Tilera, Cavium • Adapteva Parallela • Xeon PHI • It's happening!
  • 10. Too many cores? • 1981 "640 kb ought to be enough for anybody" ~ Bill Gates
  • 11. Too many cores? • 1981 "640 kb ought to be enough for anybody" ~ Bill Gates • 2014 "4 cores ought to be enough for anybody" ~ Linus Torvalds1 1 http://highscalability.com/blog/2014/12/31/linus-the-whole-parallel- computing-is-the-future-is-a-bunch.html
  • 12. 2nd Why: distribution is the norm, not the exception
  • 13. It's all in the cloud • divide & conquer: specialized services that do one thing well • storage: S3 • emails: MailChimp • monitoring: New Relic, Plumbr • etc. etc. etc.
  • 15. This is not the cloud
  • 16. That's more like the cloud • scaling out to handle large loads • scaling out / replication to handle node failure
  • 17. Yes! That's the cloud! • networks, networks, networks • they fail all the time • Jepsen series3 3 http://aphyr.com
  • 18. The cloud is hard • CAP theorem • 8 fallacies of distributed computing • hard problem, no easy solution • PAXOS, CQRS, CRDTs
  • 21. Side note: Internet of Lost Things Prediction: "By 2020, everyone will have a bunch of online things lost in their appartment"
  • 23. Our traditional programming tools don't work in this setting
  • 24. We have been brainwashed to use: 1. imperative programming with mutable state 2. locks, locks, locks
  • 25. The problem with mutable state car.setPosition(0); car.setPosition(10);
  • 26. The problem with mutable state
  • 27. The problem with locks • solution workaround for a broken conceptual model • hard to reason about • performance hit
  • 28. The problem with object-orientation in Java • there is no notion of time, only an illusion thereof • changes to a mutable model only make sense locally if nobody is watching • the larger the scope, the harder it gets to prevent inconsistencies
  • 29. The Whys 1. many-core CPUs are here 2. everything is distributed 3. IoT around the corner with 26 billions devices 4. our traditional approach does not work here
  • 32. In theory • Functional Programming • The Actor Model • Evented Server Model • Stateless architecture • Event Sourcing • Reactive Streams
  • 33. In practice • Functional Programming Scala • The Actor Model Akka • Evented Server Model Play • Stateless architecture Play • Event Sourcing Akka Persistence • Reactive Streams Akka Streams
  • 35. Short Scala history • Martin Odersky, EPFL • first release in 2003 • Typesafe Inc.
  • 36. Design goals • Full interoperability with Java • Cut down boilerplate • Pure object orientation & functional programming • Move away from null • Many-core programming
  • 37. Core concepts of Functional Programming • immutability • functions • transforming data with functions
  • 38. Immutability case class Car(brand: String, position: Int) val car = Car(brand = "DeLorean", position = 0) val movedCar = car.copy(position = 10) val movedCarLaterOn = car.copy(position = 30)
  • 39. Immutability case class Car(brand: String, position: Int) val car = Car(brand = "DeLorean", position = 0) val movedCar = car.copy(position = 10) val movedCarLaterOn = car.copy(position = 30) Work with snapshots of state
  • 40. Higher-order functions val (minors, majors) = users.partition(_.age < 18)
  • 41. Higher-order functions val isMinor = (age: Int) => age < 18 val (minors, majors) = users.partition(isMinor)
  • 42. Higher-order functions val isMinor = (age: Int) => age < 18 val (minors, majors) = users.partition(isMinor) Moving behaviour around instead of moving data around
  • 43. Transforming data val addresses = users.filter(_.age > 18) .map(_.address) .sortBy(_.city) Goal: To build increasingly complex behaviour through a series of transformations / by composing functions
  • 44. Composition def fetchUser(id: Long): Option[User] = ... def fetchCar(id: Long): Option[Car] = ... val insuranceCost: Option[BigDecimal] = for { user <- fetchUser(42) car <- fetchCar(23) } yield { car.price / 10 - user.age }
  • 45. Composition def fetchUser(id: Long): Future[User] = ... def fetchCar(id: Long): Future[Car] = ... val insuranceCost: Future[BigDecimal] = for { user <- fetchUser(42) car <- fetchCar(23) } yield { car.price / 10 - user.age }
  • 46. Composition def fetchUser(id: Long): Try[User] = ... def fetchCar(id: Long): Try[Car] = ... val insuranceCost: Try[BigDecimal] = for { user <- fetchUser(42) car <- fetchCar(23) } yield { car.price / 10 - user.age }
  • 47. Composition def fetchUser(id: Long): [User] = ... def fetchCar(id: Long): [Car] = ... val insuranceCost: [BigDecimal] = for { user <- (42) car <- (23) } yield { car.price / 10 - user.age }
  • 49. Functional composition • Option, Future, Try all implement monadic operations • set of data structures following the same laws • know one, know them all • keeping things DRY • also, it's not that scary
  • 51. History • 1973 "A Universal Modular Actor Formalism for Artificial Intelligence", Carl Hewitt, Peter Bishop and Richard Steiger • based on physics (quantum physics and relativistic physics) • 1986 First release of Erlang (Joe Armstrong) • 1998 Ericsson reports that the AXD301 switch achieves an availability of 99.9999999%
  • 52. History • 2010 First release of Akka (Jonas Bonér) • inspired by Erlang and the Actor Model • message-based asynchronous concurrency toolkit • object-oriented programming done right
  • 53. History • 2010 First release of Akka (Jonas Bonér) • inspired by Erlang and the Actor Model • message-based asynchronous concurrency toolkit • object-oriented programming done right • Akka is also a mountain in Sweden
  • 54. Actors • lightweight objects • send and receive messages (mailbox) • can have children (supervision)
  • 58. Sending and receiving messages case object RevelationOfFathership class Luke extends Actor { def receive = { case RevelationOfFathership => System.err.println("Noooooooooo") } }
  • 59. Sending and receiving messages case object RevelationOfFathership class Luke extends Actor { def receive = { case RevelationOfFathership => System.err.println("Noooooooooo") } } val luke = ActorSystem.actorOf(Props[Luke]) luke ! RevelationOfFathership
  • 60. Supervision class Vader extends Actor { val troopers: ActorRef = context .actorOf[StromTrooper] .withRouter( RoundRobinRouter(nrOfInstances = 8) ) }
  • 61. Supervision class Vader extends Actor { val troopers: ActorRef = context .actorOf[StromTrooper] .withRouter( RoundRobinRouter(nrOfInstances = 8) ) }
  • 62. Supervision class Vader extends Actor { val troopers: ActorRef = context .actorOf[StromTrooper] .withRouter( RoundRobinRouter(nrOfInstances = 8) ) override def supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3) { case t: Throwable => log.error("StormTrooper down!", t) Restart } }
  • 63. 3rd How: Evented servers & statless architecture Play
  • 64. Play history • MVC framework, inspired by RoR, Django, Symfony • Zenexity • first version released in 2009 • version 2.0 released in 2012, core rewritten in Scala
  • 65. Design Principles • everything is compiled • non-blocking I/O • controller actions are functions (request => response) • "share nothing" => horizontal scalability
  • 66. Threaded servers • like a train station with multiple tracks • station chief decides which trains go on which platform • if there are more trains than platforms, trains queue up • if too many trains are queuing up, huge delays occur and passengers go home
  • 67. Evented servers • like a waiter in a restaurant • runs back and forth between tables and the kitchen • does only small tasks that do not take much time • one server can each serve many tables at once
  • 68. Advantages of the evented approach • less threads means less memory • better CPU utilization (reduced context switching) • (much) higher throughputs than threaded servers
  • 69. The Hows 1. functional programming (immutability, functions, composition) 2. actor model 3. evented servers & stateless architecture 4. event-sourcing & reactive streams
  • 70. Summary • many-core & distributed systems around the corner and there to stay • get ready and adopt some of the "new" tools