Building Reactive Systems with Akka (in Java 8 or Scala)

Jonas Bonér
Jonas BonérFounder & CTO at Lightbend
Building 
Reactive Systems 
with Akka 
Jonas Bonér 
Typesafe 
CTO & co-founder 
Twitter: @jboner
The rules of the game 
have changed
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks 
Few concurrent users
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks 
Few concurrent users Lots of concurrent users
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks 
Few concurrent users Lots of concurrent users 
Small data sets
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks 
Few concurrent users Lots of concurrent users 
Small data sets Large data sets
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks 
Few concurrent users Lots of concurrent users 
Small data sets Large data sets 
Latency in seconds
3 
Apps in the 60s-90s 
were written for 
Apps today 
are written for 
Single machines Clusters of machines 
Single core processors Multicore processors 
Expensive RAM Cheap RAM 
Expensive disk Cheap disk 
Slow networks Fast networks 
Few concurrent users Lots of concurrent users 
Small data sets Large data sets 
Latency in seconds Latency in milliseconds
Building Reactive Systems with Akka (in Java 8 or Scala)
Cost Gravity is at Work 
X
Cost Gravity is at Work 
X
Reactive applications share four traits 
Reactive 
Applications 
5
Reactive applications enrich the user 
experience with low latency response.
Responsive 
• Real-time, engaging, rich and collaborative 
• Create an open and ongoing dialog with users 
• More efficient workflow; inspires a feeling of connectedness 
• Fully Reactive enabling push instead of pull 
7 
“The move to these technologies is already paying off. 
Response times are down for processor intensive code–such as image 
and PDF generation–by around 75%.” 
Brian Pugh, VP of Engineering, Lucid Software
Reactive applications react to 
changes in the world around them.
Message-Driven 
• Loosely coupled architecture, easier to extend, maintain, evolve 
• Asynchronous and non-blocking 
• Concurrent by design, immutable state 
• Lower latency and higher throughput 
9 
“Clearly, the goal is to do these operations concurrently and 
non-blocking, so that entire blocks of seats or sections are not locked. 
We’re able to find and allocate seats under load in less than 20ms 
without trying very hard to achieve it.” 
Andrew Headrick, Platform Architect, Ticketfly
Introducing the Actor Model
11 
The Actor Model
11 
The Actor Model 
A computational model that embodies:
11 
The Actor Model 
A computational model that embodies: 
✓ Processing
11 
The Actor Model 
A computational model that embodies: 
✓ Processing 
✓ Storage
11 
The Actor Model 
A computational model that embodies: 
✓ Processing 
✓ Storage 
✓ Communication
A computational model that embodies: 
✓ Processing 
✓ Storage 
✓ Communication 
Supports 3 axioms—when an Actor receives a message it can: 
11 
The Actor Model
A computational model that embodies: 
✓ Processing 
✓ Storage 
✓ Communication 
Supports 3 axioms—when an Actor receives a message it can: 
1. Create new Actors 
11 
The Actor Model
A computational model that embodies: 
✓ Processing 
✓ Storage 
✓ Communication 
Supports 3 axioms—when an Actor receives a message it can: 
1. Create new Actors 
2. Send messages to Actors it knows 
11 
The Actor Model
A computational model that embodies: 
✓ Processing 
✓ Storage 
✓ Communication 
Supports 3 axioms—when an Actor receives a message it can: 
1. Create new Actors 
2. Send messages to Actors it knows 
3. Designate how it should handle the next message it receives 
11 
The Actor Model
The essence of an actor 
from Akka’s perspective 
0. DEFINE 
1. CREATE 
2. SEND 
3. BECOME 
4. SUPERVISE 
12
public class Greeting implements Serializable { 
public final String who; 
public Greeting(String who) { this.who = who; } 
} 
! 
public class Greeter extends AbstractActor {{ 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchAny(unknown -> { 
println(“Unknown message " + unknown); 
}).build()); 
}} 
0. DEFINE 
X
public class Greeting implements Serializable { 
public final String who; 
public Greeting(String who) { this.who = who; } 
} 
! 
public class Greeter extends AbstractActor {{ 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchAny(unknown -> { 
println(“Unknown message " + unknown); 
}).build()); 
}} 
0. DEFINE 
X 
Define the message(s) the Actor 
should be able to respond to
public class Greeting implements Serializable { 
public final String who; 
public Greeting(String who) { this.who = who; } 
} 
! 
public class Greeter extends AbstractActor {{ 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchAny(unknown -> { 
println(“Unknown message " + unknown); 
}).build()); 
}} 
0. DEFINE 
X 
Define the message(s) the Actor 
should be able to respond to 
Define the Actor class
public class Greeting implements Serializable { 
public final String who; 
public Greeting(String who) { this.who = who; } 
} 
! 
public class Greeter extends AbstractActor {{ 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchAny(unknown -> { 
println(“Unknown message " + unknown); 
}).build()); 
}} 
0. DEFINE 
X 
Define the message(s) the Actor 
should be able to respond to 
Define the Actor class 
Define the Actor’s behavior
1. CREATE 
ActorSystem system = ActorSystem.create("MySystem"); 
! 
ActorRef greeter = 
system.actorOf(Props.create(Greeter.class), “greeter");
1. CREATE 
Create an Actor system 
ActorSystem system = ActorSystem.create("MySystem"); 
! 
ActorRef greeter = 
system.actorOf(Props.create(Greeter.class), “greeter");
1. CREATE 
Create an Actor system 
Actor configuration 
ActorSystem system = ActorSystem.create("MySystem"); 
! 
ActorRef greeter = 
system.actorOf(Props.create(Greeter.class), “greeter");
1. CREATE 
Create an Actor system 
Actor configuration 
ActorSystem system = ActorSystem.create("MySystem"); 
! 
ActorRef greeter = 
system.actorOf(Props.create(Greeter.class), “greeter"); 
Give it a name
1. CREATE 
Create an Actor system 
ActorSystem system = ActorSystem.create("MySystem"); 
! 
ActorRef greeter = 
system.actorOf(Props.create(Greeter.class), “greeter"); 
Give it a name 
Create the Actor 
Actor configuration
1. CREATE 
Create an Actor system 
ActorSystem system = ActorSystem.create("MySystem"); 
! 
ActorRef greeter = 
system.actorOf(Props.create(Greeter.class), “greeter"); 
Give it a name 
You get an ActorRef back 
Create the Actor 
Actor configuration
0. DEFINE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
13 
case Greeting(who) => log.info(s"Hello ${who}") 
} 
}
0. DEFINE 
13 
Define the message(s) the Actor 
should be able to respond to 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info(s"Hello ${who}") 
} 
}
0. DEFINE 
13 
Define the message(s) the Actor 
should be able to respond to 
Define the Actor class 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info(s"Hello ${who}") 
} 
}
0. DEFINE 
13 
Define the message(s) the Actor 
should be able to respond to 
Define the Actor class 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info(s"Hello ${who}") 
} 
} 
Define the Actor’s behavior
1. CREATE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info("Hello " + who) 
} 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
1. CREATE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
Create an Actor system 
case Greeting(who) => log.info("Hello " + who) 
} 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
1. CREATE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
Create an Actor system 
case Greeting(who) => log.info("Hello " } 
Actor configuration 
+ who) 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
1. CREATE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info("Hello " + who) 
} 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter") 
Give it a name 
Create an Actor system 
Actor configuration
1. CREATE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
Create an Actor system 
case Greeting(who) => log.info("Hello " } 
Actor configuration 
+ who) 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter") 
Give it a name 
Create the Actor
1. CREATE 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
Create an Actor system 
case Greeting(who) => log.info("Hello " } 
Actor configuration 
+ who) 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter") 
Give it a name 
You get an ActorRef bCarcekate the Actor
Actors can form hierarchies 
Guardian System Actor
Actors can form hierarchies 
Guardian System Actor 
system.actorOf(Props.create(Foo.class), “Foo”);
Actors can form hierarchies 
Foo 
Guardian System Actor 
system.actorOf(Props.create(Foo.class), “Foo”);
Actors can form hierarchies 
Foo 
Guardian System Actor 
context().actorOf(Props.create(A.class), “A”);
Actors can form hierarchies 
A 
Foo 
Guardian System Actor 
context().actorOf(Props.create(A.class), “A”);
Actors can form hierarchies 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
Guardian System Actor
Actors can form hierarchies 
Guardian System Actor
Actors can form hierarchies 
Guardian System Actor 
system.actorOf(Props[Foo], “Foo”)
Actors can form hierarchies 
Foo 
Guardian System Actor 
system.actorOf(Props[Foo], “Foo”)
Actors can form hierarchies 
Foo 
Guardian System Actor 
context.actorOf(Props[A], “A”)
Actors can form hierarchies 
A 
Foo 
Guardian System Actor 
context.actorOf(Props[A], “A”)
Actors can form hierarchies 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
Guardian System Actor
Name resolution—like a file-system 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
Guardian System Actor
Name resolution—like a file-system 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
/Foo 
Guardian System Actor
Name resolution—like a file-system 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
/Foo 
/Foo/A 
Guardian System Actor
Name resolution—like a file-system 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
/Foo 
/Foo/A 
/Foo/A/B 
Guardian System Actor
Name resolution—like a file-system 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
/Foo 
/Foo/A 
/Foo/A/B 
/Foo/A/D 
Guardian System Actor
2. SEND 
X 
greeter.tell(new Greeting("Charlie Parker”), sender);
2. SEND 
X 
greeter.tell(new Greeting("Charlie Parker”), sender); 
Send the message asynchronously
2. SEND 
X 
Pass in the sender ActorRef 
greeter.tell(new Greeting("Charlie Parker”), sender); 
Send the message asynchronously
Bring it together 
X 
public class Greeting implements Serializable { 
public final String who; 
public Greeting(String who) { this.who = who; } 
} 
public class Greeter extends AbstractActor {{ 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchAny(unknown -> { 
println(“Unknown message " + unknown); 
}).build()); 
} 
}} 
! 
ActorSystem system = ActorSystem.create("MySystem"); 
ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter"); 
greeter.tell(new Greeting(“Charlie Parker”));
2. SEND 
17 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info(s”Hello ${who}") 
} 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter") 
greeter ! Greeting("Charlie Parker")
2. SEND 
17 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info(s”Hello ${who}") 
} 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter") 
greeter ! Greeting("Charlie Parker") 
Send the message asynchronously
Bring it together 
18 
case class Greeting(who: String) 
! 
class GreetingActor extends Actor with ActorLogging { 
def receive = { 
case Greeting(who) => log.info(s”Hello ${who}") 
} 
} 
! 
val system = ActorSystem("MySystem") 
val greeter = system.actorOf(Props[GreetingActor], name = "greeter") 
greeter ! Greeting("Charlie Parker")
DEMO TIME A simple game of ping pong
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
}
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
} 
context().become(ReceiveBuilder.
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
} 
Change the behavior 
context().become(ReceiveBuilder.
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
} 
Change the behavior 
context().become(ReceiveBuilder. 
match(Greeting.class, m -> {
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
} 
Change the behavior 
context().become(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Go Away!”);
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
} 
Change the behavior 
context().become(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Go Away!”); 
}).build());
3. BECOME 
X 
public class Greeter extends AbstractActor { 
public Greeter { 
receive(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Hello " + m.who); 
}). 
matchEquals(“stop" -> { 
!!!! }).build(); 
} 
} 
Change the behavior 
context().become(ReceiveBuilder. 
match(Greeting.class, m -> { 
println(“Go Away!”); 
}).build());
3. BECOME 
19 
class GreetingActor extends Actor with ActorLogging { 
def receive = happy 
! 
val happy: Receive = { 
case Greeting(who) => log.info(s”Hello ${who}") 
case Angry => context become angry 
} 
! 
val angry: Receive = { 
case Greeting(_) => log.info("Go away!") 
case Happy => context become happy 
} 
}
3. BECOME 
19 
class GreetingActor extends Actor with ActorLogging { 
def receive = happy 
! 
val happy: Receive = { 
case Greeting(who) => log.info(s”Hello ${who}") 
case Angry => context become angry 
} 
! 
val angry: Receive = { 
case Greeting(_) => log.info("Go away!") 
case Happy => context become happy 
} 
} 
Redefine the behavior
Reactive applications are architected 
to handle failure at all levels.
Resilient 
• Failure is embraced as a natural state in the app lifecycle 
• Resilience is a first-class construct 
• Failure is detected, isolated, and managed 
• Applications self heal 
21 
“The Typesafe Reactive Platform helps us maintain a very 
aggressive development and deployment cycle, all in a fail-forward manner. 
It’s now the default choice for developing all new services.” 
Peter Hausel, VP Engineering, Gawker Media
Think Vending Machine
Think Vending Machine 
Coffee 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Add more coins 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Add more coins 
Programmer Machine 
Gets coffee
Think Vending Machine 
Coffee 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Out of coffee beans error 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
OutW of corfofeen begans error 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Programmer Machine
Think Vending Machine 
Coffee 
Inserts coins 
Out of 
coffee beans 
error 
Programmer Machine
Think Vending Machine 
Service 
Guy 
Coffee 
Inserts coins 
Out of 
coffee beans 
error 
Programmer Machine
Think Vending Machine 
Service 
Guy 
Coffee 
Inserts coins 
Out of 
coffee beans 
error 
Programmer Machine 
Adds 
more 
beans
Think Vending Machine 
Service 
Guy 
Coffee 
Inserts coins 
Programmer Machine 
Gets coffee 
Out of 
coffee beans 
error 
Adds 
more 
beans
The Right Way 
Client Service
The Right Way 
Request 
Client Service
The Right Way 
Request 
Client Service 
Response
The Right Way 
Request 
Validation Error 
Client Service 
Response
The Right Way 
Request 
Validation Error 
Client Service 
Response 
Application 
Error
The Right Way 
Supervisor 
Request 
Validation Error 
Client Service 
Response 
Application 
Error
The Right Way 
Supervisor 
Request 
Validation Error 
Client Service 
Response 
Application 
Error 
Manages 
Failure
Building Reactive Systems with Akka (in Java 8 or Scala)
Use Bulkheads 
• Isolate the failure 
• Compartmentalize 
• Manage failure locally 
• Avoid cascading failures
Use Bulkheads 
• Isolate the failure 
• Compartmentalize 
• Manage failure locally 
• Avoid cascading failures
Enter Supervision
Enter Supervision
Supervisor hierarchies 
A 
Foo Bar 
B 
C 
B 
E 
A 
D 
C 
Automatic and mandatory supervision
4. SUPERVISE 
X 
Every single actor has a default supervisor strategy. 
Which is usually sufficient. 
But it can be overridden. 
class Supervisor extends UntypedActor { 
private SupervisorStrategy strategy = new OneForOneStrategy( 
10, Duration.create(1, TimeUnit.MINUTES), 
DeciderBuilder. 
match(ArithmeticException.class, e -> resume()). 
match(NullPointerException.class, e -> restart()). 
matchAny( e -> escalate()). 
build()); 
! 
@Override public SupervisorStrategy supervisorStrategy() { 
return strategy; 
}
4. SUPERVISE 
X 
class Supervisor extends UntypedActor { 
private SupervisorStrategy strategy = new OneForOneStrategy( 
10, Duration.create(1, TimeUnit.MINUTES), 
DeciderBuilder. 
match(ArithmeticException.class, e -> resume()). 
match(NullPointerException.class, e -> restart()). 
matchAny( e -> escalate()). 
build()); 
! 
@Override public SupervisorStrategy supervisorStrategy() { 
return strategy; 
} 
ActorRef worker = context.actorOf( 
Props.create(Worker.class), "worker"); 
public void onReceive(Object i) throws Exception { 
… 
} 
}
Monitor through Death Watch 
X 
public class WatchActor extends AbstractActor { 
final ActorRef child = context().actorOf(Props.empty(), "child"); 
! 
public WatchActor() { 
context().watch(child); 
receive(ReceiveBuilder. 
match(Terminated.class, 
t -> t.actor().equals(child), 
t -> { 
… // handle termination 
}).build() 
); 
} 
}
Monitor through Death Watch 
X 
public class WatchActor extends AbstractActor { 
final ActorRef child = context().actorOf(Props.empty(), "child"); 
! 
public WatchActor() { 
context().watch(child); 
receive(ReceiveBuilder. 
match(Terminated.class, 
t -> t.actor().equals(child), 
t -> { 
… // handle termination 
}).build() 
); 
} 
} 
Create a child actor
Monitor through Death Watch 
X 
public class WatchActor extends AbstractActor { 
final ActorRef child = context().actorOf(Props.empty(), "child"); 
! 
public WatchActor() { 
context().watch(child); 
receive(ReceiveBuilder. 
match(Terminated.class, 
t -> t.actor().equals(child), 
t -> { 
… // handle termination 
}).build() 
); 
} 
} 
Create a child actor 
Watch it
Monitor through Death Watch 
X 
public class WatchActor extends AbstractActor { 
final ActorRef child = context().actorOf(Props.empty(), "child"); 
! 
public WatchActor() { 
context().watch(child); 
receive(ReceiveBuilder. 
match(Terminated.class, 
t -> t.actor().equals(child), 
t -> { 
… // handle termination 
}).build() 
); 
} 
} 
Create a child actor 
Watch it 
Handle termination message
4. SUPERVISE 
29 
Every single actor has a default 
supervisor strategy. 
Which is usually sufficient. 
But it can be overridden.
4. SUPERVISE 
29 
Every single actor has a default 
supervisor strategy. 
Which is usually sufficient. 
But it can be overridden. 
class Supervisor extends Actor { 
override val supervisorStrategy = 
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { 
case _: ArithmeticException => Resume 
case _: NullPointerException => Restart 
case _: Exception => Escalate 
} 
! 
val worker = context.actorOf(Props[Worker], name = "worker") 
! 
def receive = {
4. SUPERVISE 
29 
class Supervisor extends Actor { 
override val supervisorStrategy = 
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { 
case _: ArithmeticException => Resume 
case _: NullPointerException => Restart 
case _: Exception => Escalate 
} 
! 
val worker = context.actorOf(Props[Worker], name = "worker") 
! 
def receive = { 
case n: Int => worker forward n 
} 
} 
!
Cleanup & (Re)initialization 
30 
class Worker extends Actor { 
... 
override def preRestart( 
reason: Throwable, message: Option[Any]) { 
... // clean up before restart 
} 
override def postRestart(reason: Throwable) { 
... // init after restart 
} 
}
Monitor through Death Watch 
31 
class Watcher extends Actor { 
val child = context.actorOf(Props.empty, "child") 
context.watch(child) 
! 
def receive = { 
case Terminated(`child`) => … // handle child termination 
} 
}
Monitor through Death Watch 
31 
Create a child actor 
class Watcher extends Actor { 
val child = context.actorOf(Props.empty, "child") 
context.watch(child) 
! 
def receive = { 
case Terminated(`child`) => … // handle child termination 
} 
}
Monitor through Death Watch 
31 
Create a child actor 
Watch it 
class Watcher extends Actor { 
val child = context.actorOf(Props.empty, "child") 
context.watch(child) 
! 
def receive = { 
case Terminated(`child`) => … // handle child termination 
} 
}
Monitor through Death Watch 
31 
Create a child actor 
Watch it 
class Watcher extends Actor { 
val child = context.actorOf(Props.empty, "child") 
context.watch(child) 
Handle termination message 
! 
def receive = { 
case Terminated(`child`) => … // handle child termination 
} 
}
Reactive applications scale up 
and down to meet demand.
Elastic 
• Elasticity and Scalability to embrace the Cloud 
• Adaptive Scale on Demand 
• Clustered servers support joining and leaving of nodes 
• More cost-efficient utilization of hardware 
33 
“Our traffic can increase by as much as 100x for 15 minutes each day. 
Until a couple of years ago, noon was a stressful time. 
Nowadays, it’s usually a non-event.” 
Eric Bowman, VP Architecture, Gilt Groupe
34 
Scale UP 
Scale OUT
34 
Essentially the same thing
35 
We need to 
1. Minimize Contention 
2. Maximize Locality of Reference
36 
Share 
NOTHING 
Design
Fully event-driven apps are a necessity 
X 
Amdahl’s Law will hunt you down
Define a router 
ActorRef router = context().actorOf( 
new RoundRobinPool(5).props(Props.create(Worker.class)), 
“router”) 
X
Define a router 
37 
val router = context.actorOf( 
RoundRobinPool(5).props(Props[Worker])), “router”)
…or from config 
38 
akka.actor.deployment { 
/service/router { 
router = round-robin-pool 
resizer { 
lower-bound = 12 
upper-bound = 15 
} 
} 
}
Turn on clustering 
39 
akka { 
actor { 
provider = "akka.cluster.ClusterActorRefProvider" 
... 
} 
cluster { 
seed-nodes = [ 
“akka.tcp://ClusterSystem@127.0.0.1:2551", 
“akka.tcp://ClusterSystem@127.0.0.1:2552" 
] 
auto-down = off 
} 
}
Use clustered routers 
40 
akka.actor.deployment 
{ 
/service/master 
{ 
router 
= 
consistent-­‐hashing-­‐pool 
nr-­‐of-­‐instances 
= 
100 
! 
cluster 
{ 
enabled 
= 
on 
max-nr-of-instances-per-node = 3 
allow-­‐local-­‐routees 
= 
on 
use-­‐role 
= 
compute 
} 
} 
}
Use clustered routers 
40 
Or perhaps use an 
AdaptiveLoadBalancingPool 
akka.actor.deployment 
{ 
/service/master 
{ 
router 
= 
consistent-­‐hashing-­‐pool 
nr-­‐of-­‐instances 
= 
100 
! 
cluster 
{ 
enabled 
= 
on 
max-nr-of-instances-per-node = 3 
allow-­‐local-­‐routees 
= 
on 
use-­‐role 
= 
compute 
} 
} 
}
Use clustered pub-sub 
41
Use clustered pub-sub 
41 
class Subscriber extends Actor { 
val mediator = 
DistributedPubSubExtension(context.system).mediator 
mediator ! Subscribe(“content”, self) 
def receive = { … } 
}
Use clustered pub-sub 
41 
class Publisher extends Actor { 
val mediator = 
DistributedPubSubExtension(context.system).mediator 
def receive = { 
case in: String => 
mediator ! Publish("content", in.toUpperCase) 
} 
}
• Cluster Membership 
• Cluster Pub/Sub 
• Cluster Leader 
• Clustered Singleton 
• Cluster Roles 
• Cluster Sharding 
42 
Other Akka Cluster features
• Supports two different models: 
• Command Sourcing 
• Event Sourcing 
• Great for implementing 
• durable actors 
• replication 
• CQRS etc. 
• Messages persisted to Journal and replayed on restart 
43 
Use Akka Persistence
X 
Command Sourcing Event Sourcing
X 
Command Sourcing Event Sourcing 
write-ahead-log
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery 
persisted before validation
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery 
persisted before validation events cannot fail
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery 
persisted before validation events cannot fail 
allows retroactive changes to 
the business logic
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery 
persisted before validation events cannot fail 
allows retroactive changes to 
the business logic 
fixing the business logic will not 
affect persisted events
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery 
persisted before validation events cannot fail 
allows retroactive changes to 
the business logic 
fixing the business logic will not 
affect persisted events 
naming: represent intent, 
imperative
X 
Command Sourcing Event Sourcing 
write-ahead-log derive events from a command 
same behavior during recovery 
as normal operation 
only state-changing behavior 
during recovery 
persisted before validation events cannot fail 
allows retroactive changes to 
the business logic 
fixing the business logic will not 
affect persisted events 
naming: represent intent, 
imperative 
naming: things that have 
completed, verbs in past tense
Domain Events 
• Things that have completed, facts 
• Immutable 
• Verbs in past tense 
Akka 
Persistence 
Webinar 
• CustomerRelocated 
• CargoShipped 
• InvoiceSent 
“State transitions are an important part of our problem 
space and should be modeled within our domain.” 
Greg Young, 2008
Life beyond Distributed Transactions: 
an Apostate’s Opinion 
Position Paper by Pat Helland 
http://www-­‐db.cs.wisc.edu/cidr/cidr2007/papers/cidr07p15.pdf 
“In general, application developers simply do not implement 
large scalable applications assuming distributed transactions.” 
Pat Helland 
Akka 
Persistence 
Webinar
Consistency boundary 
• An Actor is can define an Aggregate Root 
• Each containing one or more Entities 
• Aggregate Root is the Transactional Boundary 
• Strong consistency within an Aggregate 
• Eventual consistency between Aggregates 
• No limit to scalability 
Akka 
Persistence 
Webinar
DEMO TIME Persist a game of ping pong
Building Reactive Systems with Akka (in Java 8 or Scala)
http://reactivemanifesto.org
Typesafe Activator 
http://typesafe.com/platform/getstarted
• Purely asynchronous and non-blocking 
web frameworks 
• No container required, no inherent 
bottlenecks in session management 
48 
Typesafe Reactive Platform 
• Actors are asynchronous and 
communicate via message passing 
• Supervision and clustering in support of 
fault tolerance 
• Asynchronous and immutable 
programming constructs 
• Composable abstractions enabling 
simpler concurrency and parallelism
Reactive is being adopted across 
a wide range of industries.
50 
Finance Internet/Social Media Mfg/Hardware Government Retail
Questions?
©Typesafe 2014 – All Rights Reserved
1 of 176

Recommended

Achieving mass scale with Quasar Fibers by
Achieving mass scale with Quasar FibersAchieving mass scale with Quasar Fibers
Achieving mass scale with Quasar FibersIdan Sheinberg
807 views41 slides
Introducing Akka by
Introducing AkkaIntroducing Akka
Introducing AkkaJonas Bonér
24.2K views180 slides
State of Akka 2017 - The best is yet to come by
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeKonrad Malawski
5.5K views192 slides
Building reactive distributed systems with Akka by
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Johan Andrén
4.1K views54 slides
Actor Model Akka Framework by
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka FrameworkHarinath Krishnamoorthy
362 views30 slides
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC by
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYCBuilding a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYCKonrad Malawski
1.1K views112 slides

More Related Content

What's hot

Reactive Web-Applications @ LambdaDays by
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysManuel Bernhardt
6K views71 slides
CQRS Evolved - CQRS + Akka.NET by
CQRS Evolved - CQRS + Akka.NETCQRS Evolved - CQRS + Akka.NET
CQRS Evolved - CQRS + Akka.NETDavid Hoerster
6.3K views57 slides
Akka.net versus microsoft orleans by
Akka.net versus microsoft orleansAkka.net versus microsoft orleans
Akka.net versus microsoft orleansBill Tulloch
8.6K views44 slides
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't by
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tKonrad Malawski
1.5K views136 slides
The Need for Async @ ScalaWorld by
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldKonrad Malawski
4.5K views170 slides
The things we don't see – stories of Software, Scala and Akka by
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
4K views119 slides

What's hot(20)

CQRS Evolved - CQRS + Akka.NET by David Hoerster
CQRS Evolved - CQRS + Akka.NETCQRS Evolved - CQRS + Akka.NET
CQRS Evolved - CQRS + Akka.NET
David Hoerster6.3K views
Akka.net versus microsoft orleans by Bill Tulloch
Akka.net versus microsoft orleansAkka.net versus microsoft orleans
Akka.net versus microsoft orleans
Bill Tulloch8.6K views
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't by Konrad Malawski
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
Konrad Malawski1.5K views
The Need for Async @ ScalaWorld by Konrad Malawski
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorld
Konrad Malawski4.5K views
The things we don't see – stories of Software, Scala and Akka by Konrad Malawski
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
Konrad Malawski4K views
Actor model in .NET - Akka.NET by Konrad Dusza
Actor model in .NET - Akka.NETActor model in .NET - Akka.NET
Actor model in .NET - Akka.NET
Konrad Dusza991 views
The Cloud-natives are RESTless @ JavaOne by Konrad Malawski
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne
Konrad Malawski1K views
A gentle introduction into AKKA and the actor model by Mykhailo Kotsur
A gentle introduction into AKKA and the actor modelA gentle introduction into AKKA and the actor model
A gentle introduction into AKKA and the actor model
Mykhailo Kotsur737 views
Developing distributed applications with Akka and Akka Cluster by Konstantin Tsykulenko
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
Composable and streamable Play apps by Yevgeniy Brikman
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
Yevgeniy Brikman122.3K views
Reactive Streams, j.u.concurrent & Beyond! by Konrad Malawski
Reactive Streams, j.u.concurrent & Beyond!Reactive Streams, j.u.concurrent & Beyond!
Reactive Streams, j.u.concurrent & Beyond!
Konrad Malawski1.9K views
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems by Jonas Bonér
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsGo Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Jonas Bonér8.6K views
Node.js vs Play Framework (with Japanese subtitles) by Yevgeniy Brikman
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
Yevgeniy Brikman42.5K views
Play Framework + Docker + CircleCI + AWS + EC2 Container Service by Josh Padnick
Play Framework + Docker + CircleCI + AWS + EC2 Container ServicePlay Framework + Docker + CircleCI + AWS + EC2 Container Service
Play Framework + Docker + CircleCI + AWS + EC2 Container Service
Josh Padnick13.1K views
Introduction to akka actors with java 8 by Johan Andrén
Introduction to akka actors with java 8Introduction to akka actors with java 8
Introduction to akka actors with java 8
Johan Andrén11.8K views
Akka Streams in Action @ ScalaDays Berlin 2016 by Konrad Malawski
Akka Streams in Action @ ScalaDays Berlin 2016Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016
Konrad Malawski2.6K views
Akka in Practice: Designing Actor-based Applications by NLJUG
Akka in Practice: Designing Actor-based ApplicationsAkka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based Applications
NLJUG28.7K views

Viewers also liked

Reactive Supply To Changing Demand by
Reactive Supply To Changing DemandReactive Supply To Changing Demand
Reactive Supply To Changing DemandJonas Bonér
4.8K views101 slides
Enterprise Search Summit - Speeding Up Search by
Enterprise Search Summit - Speeding Up SearchEnterprise Search Summit - Speeding Up Search
Enterprise Search Summit - Speeding Up SearchAzul Systems Inc.
936 views47 slides
Pragmatic Real-World Scala (short version) by
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
72.8K views108 slides
From Microliths To Microsystems by
From Microliths To MicrosystemsFrom Microliths To Microsystems
From Microliths To MicrosystemsJonas Bonér
6.4K views84 slides
Reactive Microsystems: The Evolution of Microservices at Scale by
Reactive Microsystems: The Evolution of Microservices at ScaleReactive Microsystems: The Evolution of Microservices at Scale
Reactive Microsystems: The Evolution of Microservices at ScaleJonas Bonér
3K views75 slides
How Events Are Reshaping Modern Systems by
How Events Are Reshaping Modern SystemsHow Events Are Reshaping Modern Systems
How Events Are Reshaping Modern SystemsJonas Bonér
1.8K views165 slides

Viewers also liked(17)

Reactive Supply To Changing Demand by Jonas Bonér
Reactive Supply To Changing DemandReactive Supply To Changing Demand
Reactive Supply To Changing Demand
Jonas Bonér4.8K views
Enterprise Search Summit - Speeding Up Search by Azul Systems Inc.
Enterprise Search Summit - Speeding Up SearchEnterprise Search Summit - Speeding Up Search
Enterprise Search Summit - Speeding Up Search
Azul Systems Inc.936 views
Pragmatic Real-World Scala (short version) by Jonas Bonér
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér72.8K views
From Microliths To Microsystems by Jonas Bonér
From Microliths To MicrosystemsFrom Microliths To Microsystems
From Microliths To Microsystems
Jonas Bonér6.4K views
Reactive Microsystems: The Evolution of Microservices at Scale by Jonas Bonér
Reactive Microsystems: The Evolution of Microservices at ScaleReactive Microsystems: The Evolution of Microservices at Scale
Reactive Microsystems: The Evolution of Microservices at Scale
Jonas Bonér3K views
How Events Are Reshaping Modern Systems by Jonas Bonér
How Events Are Reshaping Modern SystemsHow Events Are Reshaping Modern Systems
How Events Are Reshaping Modern Systems
Jonas Bonér1.8K views
Akka cluster overview at 010dev by Roland Kuhn
Akka cluster overview at 010devAkka cluster overview at 010dev
Akka cluster overview at 010dev
Roland Kuhn6.8K views
Slides - Intro to Akka.Cluster by petabridge
Slides - Intro to Akka.ClusterSlides - Intro to Akka.Cluster
Slides - Intro to Akka.Cluster
petabridge22.4K views
Building Scalable, Highly Concurrent & Fault Tolerant Systems - Lessons Learned by Jonas Bonér
Building Scalable, Highly Concurrent & Fault Tolerant Systems -  Lessons LearnedBuilding Scalable, Highly Concurrent & Fault Tolerant Systems -  Lessons Learned
Building Scalable, Highly Concurrent & Fault Tolerant Systems - Lessons Learned
Jonas Bonér41.8K views
Introduction to Actor Model and Akka by Yung-Lin Ho
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
Yung-Lin Ho15.2K views
"Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo... by Lucidworks
"Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo..."Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo...
"Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo...
Lucidworks11K views
Spark shuffle introduction by colorant
Spark shuffle introductionSpark shuffle introduction
Spark shuffle introduction
colorant50.6K views
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac... by Jonas Bonér
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Jonas Bonér54.3K views
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri by Kazuki Negoro
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
Kazuki Negoro24K views

Similar to Building Reactive Systems with Akka (in Java 8 or Scala)

Building Reactive Applications with Akka & Java 8 - Bonèr by
Building Reactive Applications with Akka & Java 8 - BonèrBuilding Reactive Applications with Akka & Java 8 - Bonèr
Building Reactive Applications with Akka & Java 8 - BonèrCodemotion
1.4K views132 slides
Clear AppSec Visibility with AppSpider and ThreadFix by
 Clear AppSec Visibility with AppSpider and ThreadFix Clear AppSec Visibility with AppSpider and ThreadFix
Clear AppSec Visibility with AppSpider and ThreadFixDenim Group
644 views56 slides
Node.js meetup 17.05.2017 ember.js - escape the javascript fatigue by
Node.js meetup 17.05.2017   ember.js - escape the javascript fatigueNode.js meetup 17.05.2017   ember.js - escape the javascript fatigue
Node.js meetup 17.05.2017 ember.js - escape the javascript fatigueTobias Braner
195 views61 slides
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM by
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMManuel Bernhardt
1.4K views67 slides
Modern Release Engineering in a Nutshell - Why Researchers should Care! by
Modern Release Engineering in a Nutshell - Why Researchers should Care!Modern Release Engineering in a Nutshell - Why Researchers should Care!
Modern Release Engineering in a Nutshell - Why Researchers should Care!Bram Adams
751 views140 slides
Develop & Deploy cloud-native apps as resilient Microservices Architectures by
Develop & Deploy cloud-native apps as resilient Microservices ArchitecturesDevelop & Deploy cloud-native apps as resilient Microservices Architectures
Develop & Deploy cloud-native apps as resilient Microservices ArchitecturesRed Hat Developers
787 views47 slides

Similar to Building Reactive Systems with Akka (in Java 8 or Scala)(20)

Building Reactive Applications with Akka & Java 8 - Bonèr by Codemotion
Building Reactive Applications with Akka & Java 8 - BonèrBuilding Reactive Applications with Akka & Java 8 - Bonèr
Building Reactive Applications with Akka & Java 8 - Bonèr
Codemotion1.4K views
Clear AppSec Visibility with AppSpider and ThreadFix by Denim Group
 Clear AppSec Visibility with AppSpider and ThreadFix Clear AppSec Visibility with AppSpider and ThreadFix
Clear AppSec Visibility with AppSpider and ThreadFix
Denim Group644 views
Node.js meetup 17.05.2017 ember.js - escape the javascript fatigue by Tobias Braner
Node.js meetup 17.05.2017   ember.js - escape the javascript fatigueNode.js meetup 17.05.2017   ember.js - escape the javascript fatigue
Node.js meetup 17.05.2017 ember.js - escape the javascript fatigue
Tobias Braner195 views
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM by Manuel Bernhardt
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Manuel Bernhardt1.4K views
Modern Release Engineering in a Nutshell - Why Researchers should Care! by Bram Adams
Modern Release Engineering in a Nutshell - Why Researchers should Care!Modern Release Engineering in a Nutshell - Why Researchers should Care!
Modern Release Engineering in a Nutshell - Why Researchers should Care!
Bram Adams751 views
Develop & Deploy cloud-native apps as resilient Microservices Architectures by Red Hat Developers
Develop & Deploy cloud-native apps as resilient Microservices ArchitecturesDevelop & Deploy cloud-native apps as resilient Microservices Architectures
Develop & Deploy cloud-native apps as resilient Microservices Architectures
Red Hat Developers787 views
Cassandra & puppet, scaling data at $15 per month by daveconnors
Cassandra & puppet, scaling data at $15 per monthCassandra & puppet, scaling data at $15 per month
Cassandra & puppet, scaling data at $15 per month
daveconnors37.3K views
Intro to @viewport & other new Responsive Web Design CSS features by Andreas Bovens
Intro to @viewport & other new Responsive Web Design CSS featuresIntro to @viewport & other new Responsive Web Design CSS features
Intro to @viewport & other new Responsive Web Design CSS features
Andreas Bovens20.6K views
David Bilík: Anko – modern way to build your layouts? by mdevtalk
David Bilík: Anko – modern way to build your layouts?David Bilík: Anko – modern way to build your layouts?
David Bilík: Anko – modern way to build your layouts?
mdevtalk1.9K views
3 Tips to Deliver Fast Performance Across Mobile Web by Dynatrace
3 Tips to Deliver Fast Performance Across Mobile Web3 Tips to Deliver Fast Performance Across Mobile Web
3 Tips to Deliver Fast Performance Across Mobile Web
Dynatrace468 views
Proxy Deep Dive Voxxed Belgrad 2015 by Sven Ruppert
Proxy Deep Dive Voxxed Belgrad 2015Proxy Deep Dive Voxxed Belgrad 2015
Proxy Deep Dive Voxxed Belgrad 2015
Sven Ruppert252 views
EricEvans_StrategicDesign.ppt by Nisha819927
EricEvans_StrategicDesign.pptEricEvans_StrategicDesign.ppt
EricEvans_StrategicDesign.ppt
Nisha8199275 views
The Ember.js Framework - Everything You Need To Know by All Things Open
The Ember.js Framework - Everything You Need To KnowThe Ember.js Framework - Everything You Need To Know
The Ember.js Framework - Everything You Need To Know
All Things Open1.6K views
Use Web Skills To Build Mobile Apps by Nathan Smith
Use Web Skills To Build Mobile AppsUse Web Skills To Build Mobile Apps
Use Web Skills To Build Mobile Apps
Nathan Smith8.7K views
Building High Performance Apps with In-memory Data by Amazon Web Services
Building High Performance Apps with In-memory DataBuilding High Performance Apps with In-memory Data
Building High Performance Apps with In-memory Data
5 Key Components of Genrocket by GenRocket
5 Key Components of Genrocket5 Key Components of Genrocket
5 Key Components of Genrocket
GenRocket273 views

More from Jonas Bonér

The Reactive Principles: Design Principles For Cloud Native Applications by
The Reactive Principles: Design Principles For Cloud Native ApplicationsThe Reactive Principles: Design Principles For Cloud Native Applications
The Reactive Principles: Design Principles For Cloud Native ApplicationsJonas Bonér
1.3K views104 slides
Cloudstate—Towards Stateful Serverless by
Cloudstate—Towards Stateful ServerlessCloudstate—Towards Stateful Serverless
Cloudstate—Towards Stateful ServerlessJonas Bonér
667 views173 slides
Designing Events-first Microservices by
Designing Events-first MicroservicesDesigning Events-first Microservices
Designing Events-first MicroservicesJonas Bonér
1.6K views156 slides
Without Resilience, Nothing Else Matters by
Without Resilience, Nothing Else MattersWithout Resilience, Nothing Else Matters
Without Resilience, Nothing Else MattersJonas Bonér
16.2K views115 slides
Life Beyond the Illusion of Present by
Life Beyond the Illusion of PresentLife Beyond the Illusion of Present
Life Beyond the Illusion of PresentJonas Bonér
81.7K views89 slides
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems by
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsGo Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsJonas Bonér
30.9K views115 slides

More from Jonas Bonér(9)

The Reactive Principles: Design Principles For Cloud Native Applications by Jonas Bonér
The Reactive Principles: Design Principles For Cloud Native ApplicationsThe Reactive Principles: Design Principles For Cloud Native Applications
The Reactive Principles: Design Principles For Cloud Native Applications
Jonas Bonér1.3K views
Cloudstate—Towards Stateful Serverless by Jonas Bonér
Cloudstate—Towards Stateful ServerlessCloudstate—Towards Stateful Serverless
Cloudstate—Towards Stateful Serverless
Jonas Bonér667 views
Designing Events-first Microservices by Jonas Bonér
Designing Events-first MicroservicesDesigning Events-first Microservices
Designing Events-first Microservices
Jonas Bonér1.6K views
Without Resilience, Nothing Else Matters by Jonas Bonér
Without Resilience, Nothing Else MattersWithout Resilience, Nothing Else Matters
Without Resilience, Nothing Else Matters
Jonas Bonér16.2K views
Life Beyond the Illusion of Present by Jonas Bonér
Life Beyond the Illusion of PresentLife Beyond the Illusion of Present
Life Beyond the Illusion of Present
Jonas Bonér81.7K views
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems by Jonas Bonér
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsGo Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Jonas Bonér30.9K views
Event Driven-Architecture from a Scalability perspective by Jonas Bonér
Event Driven-Architecture from a Scalability perspectiveEvent Driven-Architecture from a Scalability perspective
Event Driven-Architecture from a Scalability perspective
Jonas Bonér11.8K views
Scalability, Availability & Stability Patterns by Jonas Bonér
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability Patterns
Jonas Bonér516.3K views
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM by Jonas Bonér
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVMState: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
Jonas Bonér11.9K views

Recently uploaded

Ansari: Practical experiences with an LLM-based Islamic Assistant by
Ansari: Practical experiences with an LLM-based Islamic AssistantAnsari: Practical experiences with an LLM-based Islamic Assistant
Ansari: Practical experiences with an LLM-based Islamic AssistantM Waleed Kadous
7 views29 slides
MK__Cert.pdf by
MK__Cert.pdfMK__Cert.pdf
MK__Cert.pdfHassan Khan
16 views1 slide
Update 42 models(Diode/General ) in SPICE PARK(DEC2023) by
Update 42 models(Diode/General ) in SPICE PARK(DEC2023)Update 42 models(Diode/General ) in SPICE PARK(DEC2023)
Update 42 models(Diode/General ) in SPICE PARK(DEC2023)Tsuyoshi Horigome
39 views16 slides
START Newsletter 3 by
START Newsletter 3START Newsletter 3
START Newsletter 3Start Project
6 views25 slides
Design of machine elements-UNIT 3.pptx by
Design of machine elements-UNIT 3.pptxDesign of machine elements-UNIT 3.pptx
Design of machine elements-UNIT 3.pptxgopinathcreddy
34 views31 slides
Proposal Presentation.pptx by
Proposal Presentation.pptxProposal Presentation.pptx
Proposal Presentation.pptxkeytonallamon
63 views36 slides

Recently uploaded(20)

Ansari: Practical experiences with an LLM-based Islamic Assistant by M Waleed Kadous
Ansari: Practical experiences with an LLM-based Islamic AssistantAnsari: Practical experiences with an LLM-based Islamic Assistant
Ansari: Practical experiences with an LLM-based Islamic Assistant
M Waleed Kadous7 views
Update 42 models(Diode/General ) in SPICE PARK(DEC2023) by Tsuyoshi Horigome
Update 42 models(Diode/General ) in SPICE PARK(DEC2023)Update 42 models(Diode/General ) in SPICE PARK(DEC2023)
Update 42 models(Diode/General ) in SPICE PARK(DEC2023)
Design of machine elements-UNIT 3.pptx by gopinathcreddy
Design of machine elements-UNIT 3.pptxDesign of machine elements-UNIT 3.pptx
Design of machine elements-UNIT 3.pptx
gopinathcreddy34 views
Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc... by csegroupvn
Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc...Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc...
Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc...
csegroupvn6 views
SUMIT SQL PROJECT SUPERSTORE 1.pptx by Sumit Jadhav
SUMIT SQL PROJECT SUPERSTORE 1.pptxSUMIT SQL PROJECT SUPERSTORE 1.pptx
SUMIT SQL PROJECT SUPERSTORE 1.pptx
Sumit Jadhav 22 views
GDSC Mikroskil Members Onboarding 2023.pdf by gdscmikroskil
GDSC Mikroskil Members Onboarding 2023.pdfGDSC Mikroskil Members Onboarding 2023.pdf
GDSC Mikroskil Members Onboarding 2023.pdf
gdscmikroskil59 views
Design_Discover_Develop_Campaign.pptx by ShivanshSeth6
Design_Discover_Develop_Campaign.pptxDesign_Discover_Develop_Campaign.pptx
Design_Discover_Develop_Campaign.pptx
ShivanshSeth645 views
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx by lwang78
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
lwang78165 views
ASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdf by AlhamduKure
ASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdfASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdf
ASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdf
AlhamduKure6 views
MongoDB.pdf by ArthyR3
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
ArthyR349 views
REACTJS.pdf by ArthyR3
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
ArthyR335 views

Building Reactive Systems with Akka (in Java 8 or Scala)

  • 1. Building Reactive Systems with Akka Jonas Bonér Typesafe CTO & co-founder Twitter: @jboner
  • 2. The rules of the game have changed
  • 3. 3 Apps in the 60s-90s were written for Apps today are written for
  • 4. 3 Apps in the 60s-90s were written for Apps today are written for Single machines
  • 5. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines
  • 6. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors
  • 7. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors
  • 8. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM
  • 9. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM
  • 10. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk
  • 11. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk
  • 12. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks
  • 13. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks
  • 14. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks Few concurrent users
  • 15. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks Few concurrent users Lots of concurrent users
  • 16. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks Few concurrent users Lots of concurrent users Small data sets
  • 17. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks Few concurrent users Lots of concurrent users Small data sets Large data sets
  • 18. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks Few concurrent users Lots of concurrent users Small data sets Large data sets Latency in seconds
  • 19. 3 Apps in the 60s-90s were written for Apps today are written for Single machines Clusters of machines Single core processors Multicore processors Expensive RAM Cheap RAM Expensive disk Cheap disk Slow networks Fast networks Few concurrent users Lots of concurrent users Small data sets Large data sets Latency in seconds Latency in milliseconds
  • 21. Cost Gravity is at Work X
  • 22. Cost Gravity is at Work X
  • 23. Reactive applications share four traits Reactive Applications 5
  • 24. Reactive applications enrich the user experience with low latency response.
  • 25. Responsive • Real-time, engaging, rich and collaborative • Create an open and ongoing dialog with users • More efficient workflow; inspires a feeling of connectedness • Fully Reactive enabling push instead of pull 7 “The move to these technologies is already paying off. Response times are down for processor intensive code–such as image and PDF generation–by around 75%.” Brian Pugh, VP of Engineering, Lucid Software
  • 26. Reactive applications react to changes in the world around them.
  • 27. Message-Driven • Loosely coupled architecture, easier to extend, maintain, evolve • Asynchronous and non-blocking • Concurrent by design, immutable state • Lower latency and higher throughput 9 “Clearly, the goal is to do these operations concurrently and non-blocking, so that entire blocks of seats or sections are not locked. We’re able to find and allocate seats under load in less than 20ms without trying very hard to achieve it.” Andrew Headrick, Platform Architect, Ticketfly
  • 29. 11 The Actor Model
  • 30. 11 The Actor Model A computational model that embodies:
  • 31. 11 The Actor Model A computational model that embodies: ✓ Processing
  • 32. 11 The Actor Model A computational model that embodies: ✓ Processing ✓ Storage
  • 33. 11 The Actor Model A computational model that embodies: ✓ Processing ✓ Storage ✓ Communication
  • 34. A computational model that embodies: ✓ Processing ✓ Storage ✓ Communication Supports 3 axioms—when an Actor receives a message it can: 11 The Actor Model
  • 35. A computational model that embodies: ✓ Processing ✓ Storage ✓ Communication Supports 3 axioms—when an Actor receives a message it can: 1. Create new Actors 11 The Actor Model
  • 36. A computational model that embodies: ✓ Processing ✓ Storage ✓ Communication Supports 3 axioms—when an Actor receives a message it can: 1. Create new Actors 2. Send messages to Actors it knows 11 The Actor Model
  • 37. A computational model that embodies: ✓ Processing ✓ Storage ✓ Communication Supports 3 axioms—when an Actor receives a message it can: 1. Create new Actors 2. Send messages to Actors it knows 3. Designate how it should handle the next message it receives 11 The Actor Model
  • 38. The essence of an actor from Akka’s perspective 0. DEFINE 1. CREATE 2. SEND 3. BECOME 4. SUPERVISE 12
  • 39. public class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; } } ! public class Greeter extends AbstractActor {{ receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchAny(unknown -> { println(“Unknown message " + unknown); }).build()); }} 0. DEFINE X
  • 40. public class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; } } ! public class Greeter extends AbstractActor {{ receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchAny(unknown -> { println(“Unknown message " + unknown); }).build()); }} 0. DEFINE X Define the message(s) the Actor should be able to respond to
  • 41. public class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; } } ! public class Greeter extends AbstractActor {{ receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchAny(unknown -> { println(“Unknown message " + unknown); }).build()); }} 0. DEFINE X Define the message(s) the Actor should be able to respond to Define the Actor class
  • 42. public class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; } } ! public class Greeter extends AbstractActor {{ receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchAny(unknown -> { println(“Unknown message " + unknown); }).build()); }} 0. DEFINE X Define the message(s) the Actor should be able to respond to Define the Actor class Define the Actor’s behavior
  • 43. 1. CREATE ActorSystem system = ActorSystem.create("MySystem"); ! ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter");
  • 44. 1. CREATE Create an Actor system ActorSystem system = ActorSystem.create("MySystem"); ! ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter");
  • 45. 1. CREATE Create an Actor system Actor configuration ActorSystem system = ActorSystem.create("MySystem"); ! ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter");
  • 46. 1. CREATE Create an Actor system Actor configuration ActorSystem system = ActorSystem.create("MySystem"); ! ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter"); Give it a name
  • 47. 1. CREATE Create an Actor system ActorSystem system = ActorSystem.create("MySystem"); ! ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter"); Give it a name Create the Actor Actor configuration
  • 48. 1. CREATE Create an Actor system ActorSystem system = ActorSystem.create("MySystem"); ! ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter"); Give it a name You get an ActorRef back Create the Actor Actor configuration
  • 49. 0. DEFINE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { 13 case Greeting(who) => log.info(s"Hello ${who}") } }
  • 50. 0. DEFINE 13 Define the message(s) the Actor should be able to respond to case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info(s"Hello ${who}") } }
  • 51. 0. DEFINE 13 Define the message(s) the Actor should be able to respond to Define the Actor class case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info(s"Hello ${who}") } }
  • 52. 0. DEFINE 13 Define the message(s) the Actor should be able to respond to Define the Actor class case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info(s"Hello ${who}") } } Define the Actor’s behavior
  • 53. 1. CREATE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info("Hello " + who) } } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
  • 54. 1. CREATE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { Create an Actor system case Greeting(who) => log.info("Hello " + who) } } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
  • 55. 1. CREATE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { Create an Actor system case Greeting(who) => log.info("Hello " } Actor configuration + who) } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
  • 56. 1. CREATE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info("Hello " + who) } } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") Give it a name Create an Actor system Actor configuration
  • 57. 1. CREATE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { Create an Actor system case Greeting(who) => log.info("Hello " } Actor configuration + who) } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") Give it a name Create the Actor
  • 58. 1. CREATE case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { Create an Actor system case Greeting(who) => log.info("Hello " } Actor configuration + who) } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") Give it a name You get an ActorRef bCarcekate the Actor
  • 59. Actors can form hierarchies Guardian System Actor
  • 60. Actors can form hierarchies Guardian System Actor system.actorOf(Props.create(Foo.class), “Foo”);
  • 61. Actors can form hierarchies Foo Guardian System Actor system.actorOf(Props.create(Foo.class), “Foo”);
  • 62. Actors can form hierarchies Foo Guardian System Actor context().actorOf(Props.create(A.class), “A”);
  • 63. Actors can form hierarchies A Foo Guardian System Actor context().actorOf(Props.create(A.class), “A”);
  • 64. Actors can form hierarchies A Foo Bar B C B E A D C Guardian System Actor
  • 65. Actors can form hierarchies Guardian System Actor
  • 66. Actors can form hierarchies Guardian System Actor system.actorOf(Props[Foo], “Foo”)
  • 67. Actors can form hierarchies Foo Guardian System Actor system.actorOf(Props[Foo], “Foo”)
  • 68. Actors can form hierarchies Foo Guardian System Actor context.actorOf(Props[A], “A”)
  • 69. Actors can form hierarchies A Foo Guardian System Actor context.actorOf(Props[A], “A”)
  • 70. Actors can form hierarchies A Foo Bar B C B E A D C Guardian System Actor
  • 71. Name resolution—like a file-system A Foo Bar B C B E A D C Guardian System Actor
  • 72. Name resolution—like a file-system A Foo Bar B C B E A D C /Foo Guardian System Actor
  • 73. Name resolution—like a file-system A Foo Bar B C B E A D C /Foo /Foo/A Guardian System Actor
  • 74. Name resolution—like a file-system A Foo Bar B C B E A D C /Foo /Foo/A /Foo/A/B Guardian System Actor
  • 75. Name resolution—like a file-system A Foo Bar B C B E A D C /Foo /Foo/A /Foo/A/B /Foo/A/D Guardian System Actor
  • 76. 2. SEND X greeter.tell(new Greeting("Charlie Parker”), sender);
  • 77. 2. SEND X greeter.tell(new Greeting("Charlie Parker”), sender); Send the message asynchronously
  • 78. 2. SEND X Pass in the sender ActorRef greeter.tell(new Greeting("Charlie Parker”), sender); Send the message asynchronously
  • 79. Bring it together X public class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; } } public class Greeter extends AbstractActor {{ receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchAny(unknown -> { println(“Unknown message " + unknown); }).build()); } }} ! ActorSystem system = ActorSystem.create("MySystem"); ActorRef greeter = system.actorOf(Props.create(Greeter.class), “greeter"); greeter.tell(new Greeting(“Charlie Parker”));
  • 80. 2. SEND 17 case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info(s”Hello ${who}") } } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") greeter ! Greeting("Charlie Parker")
  • 81. 2. SEND 17 case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info(s”Hello ${who}") } } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") greeter ! Greeting("Charlie Parker") Send the message asynchronously
  • 82. Bring it together 18 case class Greeting(who: String) ! class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info(s”Hello ${who}") } } ! val system = ActorSystem("MySystem") val greeter = system.actorOf(Props[GreetingActor], name = "greeter") greeter ! Greeting("Charlie Parker")
  • 83. DEMO TIME A simple game of ping pong
  • 84. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } }
  • 85. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } } context().become(ReceiveBuilder.
  • 86. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } } Change the behavior context().become(ReceiveBuilder.
  • 87. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } } Change the behavior context().become(ReceiveBuilder. match(Greeting.class, m -> {
  • 88. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } } Change the behavior context().become(ReceiveBuilder. match(Greeting.class, m -> { println(“Go Away!”);
  • 89. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } } Change the behavior context().become(ReceiveBuilder. match(Greeting.class, m -> { println(“Go Away!”); }).build());
  • 90. 3. BECOME X public class Greeter extends AbstractActor { public Greeter { receive(ReceiveBuilder. match(Greeting.class, m -> { println(“Hello " + m.who); }). matchEquals(“stop" -> { !!!! }).build(); } } Change the behavior context().become(ReceiveBuilder. match(Greeting.class, m -> { println(“Go Away!”); }).build());
  • 91. 3. BECOME 19 class GreetingActor extends Actor with ActorLogging { def receive = happy ! val happy: Receive = { case Greeting(who) => log.info(s”Hello ${who}") case Angry => context become angry } ! val angry: Receive = { case Greeting(_) => log.info("Go away!") case Happy => context become happy } }
  • 92. 3. BECOME 19 class GreetingActor extends Actor with ActorLogging { def receive = happy ! val happy: Receive = { case Greeting(who) => log.info(s”Hello ${who}") case Angry => context become angry } ! val angry: Receive = { case Greeting(_) => log.info("Go away!") case Happy => context become happy } } Redefine the behavior
  • 93. Reactive applications are architected to handle failure at all levels.
  • 94. Resilient • Failure is embraced as a natural state in the app lifecycle • Resilience is a first-class construct • Failure is detected, isolated, and managed • Applications self heal 21 “The Typesafe Reactive Platform helps us maintain a very aggressive development and deployment cycle, all in a fail-forward manner. It’s now the default choice for developing all new services.” Peter Hausel, VP Engineering, Gawker Media
  • 96. Think Vending Machine Coffee Programmer Machine
  • 97. Think Vending Machine Coffee Inserts coins Programmer Machine
  • 98. Think Vending Machine Coffee Inserts coins Add more coins Programmer Machine
  • 99. Think Vending Machine Coffee Inserts coins Add more coins Programmer Machine Gets coffee
  • 100. Think Vending Machine Coffee Programmer Machine
  • 101. Think Vending Machine Coffee Inserts coins Programmer Machine
  • 102. Think Vending Machine Coffee Inserts coins Out of coffee beans error Programmer Machine
  • 103. Think Vending Machine Coffee Inserts coins OutW of corfofeen begans error Programmer Machine
  • 104. Think Vending Machine Coffee Inserts coins Programmer Machine
  • 105. Think Vending Machine Coffee Inserts coins Out of coffee beans error Programmer Machine
  • 106. Think Vending Machine Service Guy Coffee Inserts coins Out of coffee beans error Programmer Machine
  • 107. Think Vending Machine Service Guy Coffee Inserts coins Out of coffee beans error Programmer Machine Adds more beans
  • 108. Think Vending Machine Service Guy Coffee Inserts coins Programmer Machine Gets coffee Out of coffee beans error Adds more beans
  • 109. The Right Way Client Service
  • 110. The Right Way Request Client Service
  • 111. The Right Way Request Client Service Response
  • 112. The Right Way Request Validation Error Client Service Response
  • 113. The Right Way Request Validation Error Client Service Response Application Error
  • 114. The Right Way Supervisor Request Validation Error Client Service Response Application Error
  • 115. The Right Way Supervisor Request Validation Error Client Service Response Application Error Manages Failure
  • 117. Use Bulkheads • Isolate the failure • Compartmentalize • Manage failure locally • Avoid cascading failures
  • 118. Use Bulkheads • Isolate the failure • Compartmentalize • Manage failure locally • Avoid cascading failures
  • 121. Supervisor hierarchies A Foo Bar B C B E A D C Automatic and mandatory supervision
  • 122. 4. SUPERVISE X Every single actor has a default supervisor strategy. Which is usually sufficient. But it can be overridden. class Supervisor extends UntypedActor { private SupervisorStrategy strategy = new OneForOneStrategy( 10, Duration.create(1, TimeUnit.MINUTES), DeciderBuilder. match(ArithmeticException.class, e -> resume()). match(NullPointerException.class, e -> restart()). matchAny( e -> escalate()). build()); ! @Override public SupervisorStrategy supervisorStrategy() { return strategy; }
  • 123. 4. SUPERVISE X class Supervisor extends UntypedActor { private SupervisorStrategy strategy = new OneForOneStrategy( 10, Duration.create(1, TimeUnit.MINUTES), DeciderBuilder. match(ArithmeticException.class, e -> resume()). match(NullPointerException.class, e -> restart()). matchAny( e -> escalate()). build()); ! @Override public SupervisorStrategy supervisorStrategy() { return strategy; } ActorRef worker = context.actorOf( Props.create(Worker.class), "worker"); public void onReceive(Object i) throws Exception { … } }
  • 124. Monitor through Death Watch X public class WatchActor extends AbstractActor { final ActorRef child = context().actorOf(Props.empty(), "child"); ! public WatchActor() { context().watch(child); receive(ReceiveBuilder. match(Terminated.class, t -> t.actor().equals(child), t -> { … // handle termination }).build() ); } }
  • 125. Monitor through Death Watch X public class WatchActor extends AbstractActor { final ActorRef child = context().actorOf(Props.empty(), "child"); ! public WatchActor() { context().watch(child); receive(ReceiveBuilder. match(Terminated.class, t -> t.actor().equals(child), t -> { … // handle termination }).build() ); } } Create a child actor
  • 126. Monitor through Death Watch X public class WatchActor extends AbstractActor { final ActorRef child = context().actorOf(Props.empty(), "child"); ! public WatchActor() { context().watch(child); receive(ReceiveBuilder. match(Terminated.class, t -> t.actor().equals(child), t -> { … // handle termination }).build() ); } } Create a child actor Watch it
  • 127. Monitor through Death Watch X public class WatchActor extends AbstractActor { final ActorRef child = context().actorOf(Props.empty(), "child"); ! public WatchActor() { context().watch(child); receive(ReceiveBuilder. match(Terminated.class, t -> t.actor().equals(child), t -> { … // handle termination }).build() ); } } Create a child actor Watch it Handle termination message
  • 128. 4. SUPERVISE 29 Every single actor has a default supervisor strategy. Which is usually sufficient. But it can be overridden.
  • 129. 4. SUPERVISE 29 Every single actor has a default supervisor strategy. Which is usually sufficient. But it can be overridden. class Supervisor extends Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate } ! val worker = context.actorOf(Props[Worker], name = "worker") ! def receive = {
  • 130. 4. SUPERVISE 29 class Supervisor extends Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate } ! val worker = context.actorOf(Props[Worker], name = "worker") ! def receive = { case n: Int => worker forward n } } !
  • 131. Cleanup & (Re)initialization 30 class Worker extends Actor { ... override def preRestart( reason: Throwable, message: Option[Any]) { ... // clean up before restart } override def postRestart(reason: Throwable) { ... // init after restart } }
  • 132. Monitor through Death Watch 31 class Watcher extends Actor { val child = context.actorOf(Props.empty, "child") context.watch(child) ! def receive = { case Terminated(`child`) => … // handle child termination } }
  • 133. Monitor through Death Watch 31 Create a child actor class Watcher extends Actor { val child = context.actorOf(Props.empty, "child") context.watch(child) ! def receive = { case Terminated(`child`) => … // handle child termination } }
  • 134. Monitor through Death Watch 31 Create a child actor Watch it class Watcher extends Actor { val child = context.actorOf(Props.empty, "child") context.watch(child) ! def receive = { case Terminated(`child`) => … // handle child termination } }
  • 135. Monitor through Death Watch 31 Create a child actor Watch it class Watcher extends Actor { val child = context.actorOf(Props.empty, "child") context.watch(child) Handle termination message ! def receive = { case Terminated(`child`) => … // handle child termination } }
  • 136. Reactive applications scale up and down to meet demand.
  • 137. Elastic • Elasticity and Scalability to embrace the Cloud • Adaptive Scale on Demand • Clustered servers support joining and leaving of nodes • More cost-efficient utilization of hardware 33 “Our traffic can increase by as much as 100x for 15 minutes each day. Until a couple of years ago, noon was a stressful time. Nowadays, it’s usually a non-event.” Eric Bowman, VP Architecture, Gilt Groupe
  • 138. 34 Scale UP Scale OUT
  • 139. 34 Essentially the same thing
  • 140. 35 We need to 1. Minimize Contention 2. Maximize Locality of Reference
  • 141. 36 Share NOTHING Design
  • 142. Fully event-driven apps are a necessity X Amdahl’s Law will hunt you down
  • 143. Define a router ActorRef router = context().actorOf( new RoundRobinPool(5).props(Props.create(Worker.class)), “router”) X
  • 144. Define a router 37 val router = context.actorOf( RoundRobinPool(5).props(Props[Worker])), “router”)
  • 145. …or from config 38 akka.actor.deployment { /service/router { router = round-robin-pool resizer { lower-bound = 12 upper-bound = 15 } } }
  • 146. Turn on clustering 39 akka { actor { provider = "akka.cluster.ClusterActorRefProvider" ... } cluster { seed-nodes = [ “akka.tcp://ClusterSystem@127.0.0.1:2551", “akka.tcp://ClusterSystem@127.0.0.1:2552" ] auto-down = off } }
  • 147. Use clustered routers 40 akka.actor.deployment { /service/master { router = consistent-­‐hashing-­‐pool nr-­‐of-­‐instances = 100 ! cluster { enabled = on max-nr-of-instances-per-node = 3 allow-­‐local-­‐routees = on use-­‐role = compute } } }
  • 148. Use clustered routers 40 Or perhaps use an AdaptiveLoadBalancingPool akka.actor.deployment { /service/master { router = consistent-­‐hashing-­‐pool nr-­‐of-­‐instances = 100 ! cluster { enabled = on max-nr-of-instances-per-node = 3 allow-­‐local-­‐routees = on use-­‐role = compute } } }
  • 150. Use clustered pub-sub 41 class Subscriber extends Actor { val mediator = DistributedPubSubExtension(context.system).mediator mediator ! Subscribe(“content”, self) def receive = { … } }
  • 151. Use clustered pub-sub 41 class Publisher extends Actor { val mediator = DistributedPubSubExtension(context.system).mediator def receive = { case in: String => mediator ! Publish("content", in.toUpperCase) } }
  • 152. • Cluster Membership • Cluster Pub/Sub • Cluster Leader • Clustered Singleton • Cluster Roles • Cluster Sharding 42 Other Akka Cluster features
  • 153. • Supports two different models: • Command Sourcing • Event Sourcing • Great for implementing • durable actors • replication • CQRS etc. • Messages persisted to Journal and replayed on restart 43 Use Akka Persistence
  • 154. X Command Sourcing Event Sourcing
  • 155. X Command Sourcing Event Sourcing write-ahead-log
  • 156. X Command Sourcing Event Sourcing write-ahead-log derive events from a command
  • 157. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation
  • 158. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery
  • 159. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery persisted before validation
  • 160. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery persisted before validation events cannot fail
  • 161. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery persisted before validation events cannot fail allows retroactive changes to the business logic
  • 162. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery persisted before validation events cannot fail allows retroactive changes to the business logic fixing the business logic will not affect persisted events
  • 163. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery persisted before validation events cannot fail allows retroactive changes to the business logic fixing the business logic will not affect persisted events naming: represent intent, imperative
  • 164. X Command Sourcing Event Sourcing write-ahead-log derive events from a command same behavior during recovery as normal operation only state-changing behavior during recovery persisted before validation events cannot fail allows retroactive changes to the business logic fixing the business logic will not affect persisted events naming: represent intent, imperative naming: things that have completed, verbs in past tense
  • 165. Domain Events • Things that have completed, facts • Immutable • Verbs in past tense Akka Persistence Webinar • CustomerRelocated • CargoShipped • InvoiceSent “State transitions are an important part of our problem space and should be modeled within our domain.” Greg Young, 2008
  • 166. Life beyond Distributed Transactions: an Apostate’s Opinion Position Paper by Pat Helland http://www-­‐db.cs.wisc.edu/cidr/cidr2007/papers/cidr07p15.pdf “In general, application developers simply do not implement large scalable applications assuming distributed transactions.” Pat Helland Akka Persistence Webinar
  • 167. Consistency boundary • An Actor is can define an Aggregate Root • Each containing one or more Entities • Aggregate Root is the Transactional Boundary • Strong consistency within an Aggregate • Eventual consistency between Aggregates • No limit to scalability Akka Persistence Webinar
  • 168. DEMO TIME Persist a game of ping pong
  • 172. • Purely asynchronous and non-blocking web frameworks • No container required, no inherent bottlenecks in session management 48 Typesafe Reactive Platform • Actors are asynchronous and communicate via message passing • Supervision and clustering in support of fault tolerance • Asynchronous and immutable programming constructs • Composable abstractions enabling simpler concurrency and parallelism
  • 173. Reactive is being adopted across a wide range of industries.
  • 174. 50 Finance Internet/Social Media Mfg/Hardware Government Retail
  • 176. ©Typesafe 2014 – All Rights Reserved