SlideShare a Scribd company logo
akka.net
soeren.stelzer@clear-it.de
Reactive Manifest und Akka.Net
Wie kommen wir da hin? Reactive Manifesto
event Handling data flow graph processing
System Architecure
zuverlässige skalierbare
elastic
message-driven
resilient
responsive
http://www.reactivemanifesto.org/de
Elastic
react to load
Message-Driven
Services / Components Interaction
Resilient
react to failures
Responsive
react to users
Reactive System
goal
methods
concepts
resilient elastic
Reactive Programming in .Net - actorbased computing with Akka.Net
Up Out
Down In
Reactive Programming in .Net - actorbased computing with Akka.Net
at first, dry theory…
Reactive Programming in .Net - actorbased computing with Akka.Net
Carl Hewitt (1973),
Actor Model of Computation:
Scalable Robust Information Systems
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
…jetzt.
• Typesafe: Actor-Framework
• Scala (JVM) => Java
• ausgereiftes, erprobtes Framework
• Akka.Net
• Portierung von Akka (2013)
• Aaron Stannard Roger Johansson
• http://getakka.net
akka.net
Concurreny
 Scalability
 Fault-tolerance
Simpler
 Programming Model
 Managed Runtime
 Open Source Distribution
…with a single unified
Scale UP
Scale OUT
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
http://doc.akka.io/docs/akka/current/intro/use-cases.html
PM> Install-Package Akka
nuget
using Akka.Actor;
using (var actorSystem = ActorSystem.Create("MyActorSystem"))
{
// universe
}
nur innerhalb dieses Blocks
„leben“ Aktoren
var actorSystem = ActorSystem.Create("MyActorSystem"));
// universe
actorSystem.WhenTerminated.Wait(); // wait for termination-task
actorSystem.AwaitTermination(); // deprecated
oder
// universe
IActorRef myActor = actorSystem.ActorOf(
Props.Create(() => new MyActor())
);
using (var actorSystem = ActorSystem.Create("MyActorSystem"))
{
}
// talk to the actor
myActor.Tell(new SomeMessage("rise up slave..."));
erzeuge AktorSystem
fordere spezifischen
Aktor an
sprich mit dem erhaltenen
Aktor
public class SomeMessage
{
public SomeMessage(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public class MyActor : ReceiveActor
{
public MyActor()
{
Receive<string>(message => {
Sender.Tell(message);
});
Receive<SomeMessage>(message => {
// react to message
});
}
}
alle Nachrichten sind
immutable
Nachrichten werden
prinzipiell nach ihrem
Typ unterschieden *
* es geht fein-granularer
und abstrakter
Receive<string>(s => Console.WriteLine("Received string: " + s)); //1
Receive<int>(i => Console.WriteLine("Received integer: " + i)); //2
IActorRef sender = Sender;
//Receive using Funcs
Receive<string>(s =>
{
if (s.Length > 5) {
Console.WriteLine("1: " + s);
return true;
}
return false;
});
Receive<string>(s => Console.WriteLine("2: " + s));
//predicates
Receive<string>(s => s.Length > 5, s => Console.WriteLine("1: " + s)); //1
Receive<string>(s => s.Length > 2, s => Console.WriteLine("2: " + s)); //2
Receive<string>(s => Console.WriteLine("3: " + s));
//handler priority
Receive<string>(s => s.Length > 5, s => Console.WriteLine("1: " + s)); //1
Receive<string>(s => s.Length > 2, s => Console.WriteLine("2: " + s)); //2
Receive<string>(s => Console.WriteLine("3: " + s)); //3
Reactive Programming in .Net - actorbased computing with Akka.Net
public class MyActor : ActorBase
{
public MyActor()
{
//nothing todo
}
protected override bool Receive(object _message)
{
//handle different messages
var message = _message as SomeMessage;
if(message != null)
{
return false;
}
return false;
}
}
Nachrichten werden
prinzipiell nach ihrem
Typ unterschieden *
* es geht fein-granularer
und abstrakter
using Akka.Actor;
public class MyUntypedActor : UntypedActor
{
protected override void OnReceive(object message)
{
var msg = message as Messages.InputError;
if (msg != null)
{
// cool, its for me
}
else
{
Unhandled(message); //from ActorBase
}
}
}
• anders als beim ReceiveActor müssen nicht behandelte
Nachrichten selbst als solche markiert werden
IActorRef friend = Context.ActorOf(Props.Create(() => new MyReceiveActor()));
sender.Tell(new SomeMessage("Re: " + message.Name));
IActorRef friend = ...
friend.Tell(new SomeMessage("Forward: " + message.Name), sender);
IActorRef friend = ...
friend.Forward(new SomeMessage("Forward: " + message.Name)); forward
tell + explicit sender
tell
Nicht die da, andere….
event-driven thread
Actor
Behavior
Mailbox
State
Childs
Supervisor-Strategy
ActorRef 1 2 34
Transport [Akka]
IActorRef myActor = ...
myActor.Tell(new Message("four"));
• IActorRef: handle oder reference auf einen Actor
• Nachrichten werden niemals direkt an einen
Actor gesendet
• ActorSystem fügt Metadaten (Sender, Empfänger) hinzu
• ActorSystem garantiert Ankunft jeder Nachricht *
IActorRef
• Actor Namen sind optional
• best practise: named actors
Create
Look up
IActorRef myActor = actorSystem.ActorOf(
Props.Create(() => new MyActor()),
"myactor1"
);
• adressierbar über ActorPath
• Actoren bilden eine Hierarchy
Parent
Children
Sender
ActorSelection randomActor =
actorSystem.ActorSelection("akka://ActorSys/user/myactor1");
Props props1 = Props.Create(typeof(MyActor));
Props props2 = Props.Create(() => new MyActor());
Props props3 = Props.Create<MyActor>();
typeof Syntax
lambda Syntax
generic Syntax
• einzigerWeg um Parameter
zu übergeben
• unsicher
Context.ActorOf(props2);
actorSystem.ActorOf(props2);
aus einem Actor heraus:
direkt im ActorSystem:
-> erzeugt HierarchieVerwendung
Reactive Programming in .Net - actorbased computing with Akka.Net
akka.tcp://MySystem@localhost:9001/user/actorName1
Protocol
ActorSystem
Akka
Path
Akka Remote
Address
/syst
em
Guardians
/a1 /a2
top level
actor
/b1
/c1 /cx
/b2
/c2 /cx
akka://ActorSystem/user
akka://ActorSystem/user/a1
akka://ActorSystem/user/a1/b2
akka://ActorSystem/user/a1/*/cx
/user
/
Reactive Programming in .Net - actorbased computing with Akka.Net
parent
parent
Failure
SupervisionStrategy
• Restart, Stop, Resume, Escalate
• 2 Default-Strategien: One-For-One und All-For-One
• erklärtes Ziel ist es Fehler einzugrenzen:
• localizing the failure: fehleranfälligen Code
The critical thing to know here is that *whatever action is
taken on a parent propagates to its children*. If a parent is
halted, all its children halt. If it is restarted, all its children
restart.
protected override SupervisorStrategy SupervisorStrategy() {
// immer die gleiche Entscheidung
return new OneForOneStrategy(
maxNrOfRetries: 10,
withinTimeRange: TimeSpan.FromSeconds(30),
localOnlyDecider: exception =>
{
Console.WriteLine("*** Supervision: Restart");
return Directive.Restart;
}
);
}
Clients
[SignalR]
Clients
[SignalR]
Clients
[SignalR]
GameHub
[SignalR]
Bridge-
Actor
[Akka]
GameCtrl-
Actor
[Akka]
Player-
Actor
[Akka]
internet
join
attack attack
refreshState
sendState
changeHealth
join
attack
Clients
[SignalR]
Clients
[SignalR]
Clients
[SignalR]
GameHub
[SignalR]
internet
join
attack
ActorSystem
[Akka]
public class MvcApplication : HttpApplication {
protected void Application_Start()
{
//ASP.Net Stuff: Filters, Routes, ...
//Akka init
GameActorSystem.Create();
}
void Application_End()
{
GameActorSystem.Shutdown();
}
}
public static class GameActorSystem
{
private static ActorSystem ActorSystem;
private static IGameEventsPusher _gameEventsPusher;
public static void Create()
{
_gameEventsPusher = new SignalRGameEventPusher();
ActorSystem = Akka.Actor.ActorSystem.Create("GameSystem");
ActorReferences.GameController = ActorSystem.ActorOf<GameControllerActor>();
ActorReferences.SignalRBridge = ActorSystem.ActorOf(
Props.Create(() =>
new SignalRBridgeActor(_gameEventsPusher, ActorReferences.GameController)),
"SignalRBridge„
);
}
public static void Shutdown()
{
ActorSystem.Shutdown();
ActorSystem.AwaitTermination(TimeSpan.FromSeconds(1));
}
public static class ActorReferences ...
}
class SignalRGameEventPusher : IGameEventsPusher {
private static readonly IHubContext _gameHubContext;
static SignalRGameEventPusher() //static CTOR
{
_gameHubContext = GlobalHost.ConnectionManager.GetHubContext<GameHub>();
}
public void PlayerJoined(string playerName, int playerHealth)
{
_gameHubContext.Clients.All.playerJoined(playerName, playerHealth);
}
public void UpdatePlayerHealth(string playerName, int playerHealth)
{
_gameHubContext.Clients.All.updatePlayerHealth(playerName, playerHealth);
}
}
GameHub
[SignalR]
ActorSystem
[Akka]
playerJoined
updatePlayerHealth
Clients
Clients
Clients
public class GameHub : Hub
{
public void JoinGame(string playerName)
{
GameActorSystem
.ActorReferences
.SignalRBridge
.Tell(new JoinGameMessage(playerName));
}
public void Attack(string playerName)
{
GameActorSystem
.ActorReferences
.SignalRBridge
.Tell(new AttackPlayerMessage(playerName));
}
}
GameHub
[SignalR]
join
attack
ActorSystem
[Akka]
Reactive Programming in .Net - actorbased computing with Akka.Net
Closed
Open
Deleted
open close
delete

More Related Content

What's hot (20)

PPTX
Serverless lessons learned #2 dead letter queues
Maik Wiesmüller
 
PPTX
Greenfield Development with CQRS
David Hoerster
 
PPTX
Serverless lessons learned #3 reserved concurrency
Maik Wiesmüller
 
PPTX
Serverless lessons learned #5 retries
Maik Wiesmüller
 
KEY
Anatomy of a high-volume, cloud-based WordPress architecture
Gabriel Koen
 
PPTX
Serverless lessons learned #1 custom sdk timeouts
Maik Wiesmüller
 
PDF
Local development using telepresence
Irvi Aini
 
PPSX
How Postman adopted Docker
Shamasis Bhattacharya
 
PDF
Continuous Delivery in Java
XPeppers
 
PPTX
Serverless lessons learned #8 backoff
Maik Wiesmüller
 
PPTX
Serverless lessons learned #4 circuit breaker
Maik Wiesmüller
 
PDF
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Benjamin Tan
 
PDF
Akka - A Brief Intro
Thomas Lockney
 
PPTX
Akka.net versus microsoft orleans
Bill Tulloch
 
PDF
How Elixir helped us scale our Video User Profile Service for the Olympics
Emerson Macedo
 
PDF
Actor model in F# and Akka.NET
Riccardo Terrell
 
PDF
Empower every Azure Function to achieve more!!
Massimo Bonanni
 
PDF
AWS Lambda from the trenches
Yan Cui
 
PPTX
Serverless lessons learned #7 rate limiting
Maik Wiesmüller
 
PPTX
Vera: How I WiFi Enabled My Coffee Pot
Tyler Petresky
 
Serverless lessons learned #2 dead letter queues
Maik Wiesmüller
 
Greenfield Development with CQRS
David Hoerster
 
Serverless lessons learned #3 reserved concurrency
Maik Wiesmüller
 
Serverless lessons learned #5 retries
Maik Wiesmüller
 
Anatomy of a high-volume, cloud-based WordPress architecture
Gabriel Koen
 
Serverless lessons learned #1 custom sdk timeouts
Maik Wiesmüller
 
Local development using telepresence
Irvi Aini
 
How Postman adopted Docker
Shamasis Bhattacharya
 
Continuous Delivery in Java
XPeppers
 
Serverless lessons learned #8 backoff
Maik Wiesmüller
 
Serverless lessons learned #4 circuit breaker
Maik Wiesmüller
 
Elixir – Peeking into Elixir's Processes, OTP and Supervisors
Benjamin Tan
 
Akka - A Brief Intro
Thomas Lockney
 
Akka.net versus microsoft orleans
Bill Tulloch
 
How Elixir helped us scale our Video User Profile Service for the Olympics
Emerson Macedo
 
Actor model in F# and Akka.NET
Riccardo Terrell
 
Empower every Azure Function to achieve more!!
Massimo Bonanni
 
AWS Lambda from the trenches
Yan Cui
 
Serverless lessons learned #7 rate limiting
Maik Wiesmüller
 
Vera: How I WiFi Enabled My Coffee Pot
Tyler Petresky
 

Viewers also liked (9)

PPTX
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
Tamir Dresher
 
PPTX
Drm and the web
Anthony Brown
 
PPTX
Intro to RX
Scott Weinstein
 
PDF
Distributed Transactions in Akka.NET
petabridge
 
PPTX
From Zero to the Actor Model (With Akka.Net) - CodeMash2017 - Tamir Dresher
Tamir Dresher
 
PPTX
Reactive Development: Commands, Actors and Events. Oh My!!
David Hoerster
 
PPTX
CQRS Evolved - CQRS + Akka.NET
David Hoerster
 
PDF
Online game server on Akka.NET (NDC2016)
Esun Kim
 
PPTX
CQRS and Event Sourcing, An Alternative Architecture for DDD
Dennis Doomen
 
Building responsive applications with Rx - CodeMash2017 - Tamir Dresher
Tamir Dresher
 
Drm and the web
Anthony Brown
 
Intro to RX
Scott Weinstein
 
Distributed Transactions in Akka.NET
petabridge
 
From Zero to the Actor Model (With Akka.Net) - CodeMash2017 - Tamir Dresher
Tamir Dresher
 
Reactive Development: Commands, Actors and Events. Oh My!!
David Hoerster
 
CQRS Evolved - CQRS + Akka.NET
David Hoerster
 
Online game server on Akka.NET (NDC2016)
Esun Kim
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
Dennis Doomen
 
Ad

Similar to Reactive Programming in .Net - actorbased computing with Akka.Net (20)

PDF
Akka Actors: an Introduction
Roberto Casadei
 
PDF
Scaling Web Apps with Akka
Maciej Matyjas
 
PDF
Akka lsug skills matter
Skills Matter
 
KEY
Akka london scala_user_group
Skills Matter
 
PDF
Activator and Reactive at Play NYC meetup
Henrik Engström
 
PDF
First glance at Akka 2.0
Vasil Remeniuk
 
PDF
Building Stateful Microservices With Akka
Yaroslav Tkachenko
 
PDF
Introduction to Actor Model and Akka
Yung-Lin Ho
 
PDF
Akka Remoting and Clustering: an Introduction
Roberto Casadei
 
PPTX
Akka Microservices Architecture And Design
Yaroslav Tkachenko
 
PDF
Networks and types - the future of Akka
Johan Andrén
 
PPTX
Introduction to Akka - Atlanta Java Users Group
Roy Russo
 
PPTX
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
PPTX
Introduction to Apache Mesos
Joe Stein
 
PDF
Building Massively Scalable application with Akka 2.0
Knoldus Inc.
 
PDF
What`s new in Java 7
Georgian Micsa
 
PDF
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
PDF
Akka and futures
Knoldus Inc.
 
PPT
JS everywhere 2011
Oleg Podsechin
 
PDF
Akka (BeJUG)
Sander Mak (@Sander_Mak)
 
Akka Actors: an Introduction
Roberto Casadei
 
Scaling Web Apps with Akka
Maciej Matyjas
 
Akka lsug skills matter
Skills Matter
 
Akka london scala_user_group
Skills Matter
 
Activator and Reactive at Play NYC meetup
Henrik Engström
 
First glance at Akka 2.0
Vasil Remeniuk
 
Building Stateful Microservices With Akka
Yaroslav Tkachenko
 
Introduction to Actor Model and Akka
Yung-Lin Ho
 
Akka Remoting and Clustering: an Introduction
Roberto Casadei
 
Akka Microservices Architecture And Design
Yaroslav Tkachenko
 
Networks and types - the future of Akka
Johan Andrén
 
Introduction to Akka - Atlanta Java Users Group
Roy Russo
 
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
Introduction to Apache Mesos
Joe Stein
 
Building Massively Scalable application with Akka 2.0
Knoldus Inc.
 
What`s new in Java 7
Georgian Micsa
 
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
Akka and futures
Knoldus Inc.
 
JS everywhere 2011
Oleg Podsechin
 
Ad

Recently uploaded (20)

PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 

Reactive Programming in .Net - actorbased computing with Akka.Net

  • 4. Wie kommen wir da hin? Reactive Manifesto
  • 5. event Handling data flow graph processing System Architecure zuverlässige skalierbare elastic message-driven resilient responsive http://www.reactivemanifesto.org/de
  • 6. Elastic react to load Message-Driven Services / Components Interaction Resilient react to failures Responsive react to users Reactive System goal methods concepts
  • 11. at first, dry theory…
  • 13. Carl Hewitt (1973), Actor Model of Computation: Scalable Robust Information Systems
  • 18. • Typesafe: Actor-Framework • Scala (JVM) => Java • ausgereiftes, erprobtes Framework • Akka.Net • Portierung von Akka (2013) • Aaron Stannard Roger Johansson • http://getakka.net akka.net
  • 19. Concurreny  Scalability  Fault-tolerance Simpler  Programming Model  Managed Runtime  Open Source Distribution …with a single unified
  • 25. PM> Install-Package Akka nuget using Akka.Actor; using (var actorSystem = ActorSystem.Create("MyActorSystem")) { // universe } nur innerhalb dieses Blocks „leben“ Aktoren var actorSystem = ActorSystem.Create("MyActorSystem")); // universe actorSystem.WhenTerminated.Wait(); // wait for termination-task actorSystem.AwaitTermination(); // deprecated oder
  • 26. // universe IActorRef myActor = actorSystem.ActorOf( Props.Create(() => new MyActor()) ); using (var actorSystem = ActorSystem.Create("MyActorSystem")) { } // talk to the actor myActor.Tell(new SomeMessage("rise up slave...")); erzeuge AktorSystem fordere spezifischen Aktor an sprich mit dem erhaltenen Aktor
  • 27. public class SomeMessage { public SomeMessage(string name) { Name = name; } public string Name { get; private set; } } public class MyActor : ReceiveActor { public MyActor() { Receive<string>(message => { Sender.Tell(message); }); Receive<SomeMessage>(message => { // react to message }); } } alle Nachrichten sind immutable Nachrichten werden prinzipiell nach ihrem Typ unterschieden * * es geht fein-granularer und abstrakter
  • 28. Receive<string>(s => Console.WriteLine("Received string: " + s)); //1 Receive<int>(i => Console.WriteLine("Received integer: " + i)); //2 IActorRef sender = Sender;
  • 29. //Receive using Funcs Receive<string>(s => { if (s.Length > 5) { Console.WriteLine("1: " + s); return true; } return false; }); Receive<string>(s => Console.WriteLine("2: " + s)); //predicates Receive<string>(s => s.Length > 5, s => Console.WriteLine("1: " + s)); //1 Receive<string>(s => s.Length > 2, s => Console.WriteLine("2: " + s)); //2 Receive<string>(s => Console.WriteLine("3: " + s)); //handler priority Receive<string>(s => s.Length > 5, s => Console.WriteLine("1: " + s)); //1 Receive<string>(s => s.Length > 2, s => Console.WriteLine("2: " + s)); //2 Receive<string>(s => Console.WriteLine("3: " + s)); //3
  • 31. public class MyActor : ActorBase { public MyActor() { //nothing todo } protected override bool Receive(object _message) { //handle different messages var message = _message as SomeMessage; if(message != null) { return false; } return false; } } Nachrichten werden prinzipiell nach ihrem Typ unterschieden * * es geht fein-granularer und abstrakter
  • 32. using Akka.Actor; public class MyUntypedActor : UntypedActor { protected override void OnReceive(object message) { var msg = message as Messages.InputError; if (msg != null) { // cool, its for me } else { Unhandled(message); //from ActorBase } } } • anders als beim ReceiveActor müssen nicht behandelte Nachrichten selbst als solche markiert werden
  • 33. IActorRef friend = Context.ActorOf(Props.Create(() => new MyReceiveActor())); sender.Tell(new SomeMessage("Re: " + message.Name)); IActorRef friend = ... friend.Tell(new SomeMessage("Forward: " + message.Name), sender); IActorRef friend = ... friend.Forward(new SomeMessage("Forward: " + message.Name)); forward tell + explicit sender tell
  • 34. Nicht die da, andere….
  • 35. event-driven thread Actor Behavior Mailbox State Childs Supervisor-Strategy ActorRef 1 2 34 Transport [Akka] IActorRef myActor = ... myActor.Tell(new Message("four")); • IActorRef: handle oder reference auf einen Actor • Nachrichten werden niemals direkt an einen Actor gesendet • ActorSystem fügt Metadaten (Sender, Empfänger) hinzu • ActorSystem garantiert Ankunft jeder Nachricht *
  • 36. IActorRef • Actor Namen sind optional • best practise: named actors Create Look up IActorRef myActor = actorSystem.ActorOf( Props.Create(() => new MyActor()), "myactor1" ); • adressierbar über ActorPath • Actoren bilden eine Hierarchy Parent Children Sender ActorSelection randomActor = actorSystem.ActorSelection("akka://ActorSys/user/myactor1");
  • 37. Props props1 = Props.Create(typeof(MyActor)); Props props2 = Props.Create(() => new MyActor()); Props props3 = Props.Create<MyActor>(); typeof Syntax lambda Syntax generic Syntax • einzigerWeg um Parameter zu übergeben • unsicher Context.ActorOf(props2); actorSystem.ActorOf(props2); aus einem Actor heraus: direkt im ActorSystem: -> erzeugt HierarchieVerwendung
  • 40. /syst em Guardians /a1 /a2 top level actor /b1 /c1 /cx /b2 /c2 /cx akka://ActorSystem/user akka://ActorSystem/user/a1 akka://ActorSystem/user/a1/b2 akka://ActorSystem/user/a1/*/cx /user /
  • 42. parent parent Failure SupervisionStrategy • Restart, Stop, Resume, Escalate • 2 Default-Strategien: One-For-One und All-For-One
  • 43. • erklärtes Ziel ist es Fehler einzugrenzen: • localizing the failure: fehleranfälligen Code The critical thing to know here is that *whatever action is taken on a parent propagates to its children*. If a parent is halted, all its children halt. If it is restarted, all its children restart.
  • 44. protected override SupervisorStrategy SupervisorStrategy() { // immer die gleiche Entscheidung return new OneForOneStrategy( maxNrOfRetries: 10, withinTimeRange: TimeSpan.FromSeconds(30), localOnlyDecider: exception => { Console.WriteLine("*** Supervision: Restart"); return Directive.Restart; } ); }
  • 47. public class MvcApplication : HttpApplication { protected void Application_Start() { //ASP.Net Stuff: Filters, Routes, ... //Akka init GameActorSystem.Create(); } void Application_End() { GameActorSystem.Shutdown(); } }
  • 48. public static class GameActorSystem { private static ActorSystem ActorSystem; private static IGameEventsPusher _gameEventsPusher; public static void Create() { _gameEventsPusher = new SignalRGameEventPusher(); ActorSystem = Akka.Actor.ActorSystem.Create("GameSystem"); ActorReferences.GameController = ActorSystem.ActorOf<GameControllerActor>(); ActorReferences.SignalRBridge = ActorSystem.ActorOf( Props.Create(() => new SignalRBridgeActor(_gameEventsPusher, ActorReferences.GameController)), "SignalRBridge„ ); } public static void Shutdown() { ActorSystem.Shutdown(); ActorSystem.AwaitTermination(TimeSpan.FromSeconds(1)); } public static class ActorReferences ... }
  • 49. class SignalRGameEventPusher : IGameEventsPusher { private static readonly IHubContext _gameHubContext; static SignalRGameEventPusher() //static CTOR { _gameHubContext = GlobalHost.ConnectionManager.GetHubContext<GameHub>(); } public void PlayerJoined(string playerName, int playerHealth) { _gameHubContext.Clients.All.playerJoined(playerName, playerHealth); } public void UpdatePlayerHealth(string playerName, int playerHealth) { _gameHubContext.Clients.All.updatePlayerHealth(playerName, playerHealth); } } GameHub [SignalR] ActorSystem [Akka] playerJoined updatePlayerHealth Clients Clients Clients
  • 50. public class GameHub : Hub { public void JoinGame(string playerName) { GameActorSystem .ActorReferences .SignalRBridge .Tell(new JoinGameMessage(playerName)); } public void Attack(string playerName) { GameActorSystem .ActorReferences .SignalRBridge .Tell(new AttackPlayerMessage(playerName)); } } GameHub [SignalR] join attack ActorSystem [Akka]

Editor's Notes

  • #5: shared nothing, almost maximum isolation between services no shared state (including persistence) no shared domain model or logic easy scale out & easy failover share non-functional infrastructure code network access, serialization, failover, …  ---- These changes are happening because application requirements have changed dramatically in recent years. Only a few years ago a large application had tens of servers, seconds of response time, hours of offline maintenance and gigabytes of data. Today applications are deployed on everything from mobile devices to cloud-based clusters running thousands of multi-core processors. Users expect millisecond response times and 100% uptime. Data is measured in Petabytes. Today's demands are simply not met by yesterday’s software architectures.
  • #6: http://www.reactivemanifesto.org/ Elastizität (im Unterschied zu Skalierbarkeit) Englisch: elasticity (in contrast to scalability) Elastizität bedeutet, dass der Durchsatz eines Systems automatisch erhöht oder vermindert werden kann, um sich an sich verändernde Lastbedingungen anzupassen. Voraussetzung hierfür ist die Skalierbarkeit des Systems, damit der Durchsatz von vermehrten Ressourcen profitieren kann. Elastizität erweitert also den Begriff der Skalierbarkeit um automatisches Ressourcenmanagement.
  • #7: Responsiveness = React to users / clients in timely manner (lags, „the system is down“) Avoid slow responses often means: tied up resources in calling and called system Disk IO, Out of Memory, … slow systems aren‘t usable a responsive System depends on Resilient and Elastic one
  • #8: Responsiveness = React to users / clients in timely manner (lags, „the system is down“) Avoid slow responses often means: tied up resources in calling and called system Disk IO, Out of Memory, … slow systems aren‘t usable a responsive System depends on Resilient and Elastic one
  • #9: Resilient = A resilient system react to failures it keeps processing transactions, even when there are: transient impulses persistent stresses or component failures disrupting normal processing often meant by people that say stability --- in realworld: redundancy supervisor bulk head delegation low coupled components ---  Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.  Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.
  • #10: Elastic = A elastic system can allocate / deallocate resources for every indivdual component (service) dynamically to match demands --- Elasticity is about resources (resources are constraint) [CPUs, Memory, VMs, …] good Idea: share N resources between M applications --- They achieve elasticity in a cost-effective way on commodity hardware and software platforms. --- Vertikale Skalierung (scale up) -> become bigger Horizontale Skalierung (scale out) -> become more --- Scalability Haiku Avoid all shared resources if you can‘t avoid it: try to batch and never block Abstraction Thread vs. Task Locking vs. Hiding & Proxying Isolation and Abstraction over Resources and State with Message-Driven Architecture
  • #11: Resilient = A resilient system react to failures it keeps processing transactions, even when there are: transient impulses persistent stresses or component failures disrupting normal processing often meant by people that say stability --- in realworld: redundancy supervisor bulk head delegation low coupled components ---  Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.  Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.
  • #13: Following Hewitt, Bishop, and Steiger's 1973 publication, Irene Greif developed an operational semantics for the Actor model as part of her doctoral research.[4] Two years later, Henry Baker and Hewitt published a set of axiomatic laws for Actor systems.[5][6] Other major milestones include William Clinger's 1981 dissertation introducing a denotational semantics based on power domains[3] and Gul Agha's 1985 dissertation which further developed a transition-based semantic model complementary to Clinger's.[7] This resulted in the full development of actor model theory. CSP: Communicating Sequential Processes / Theoretical Communicating Sequential Processes (TCSP) „Calculus of Communicating Systems“ „Algebra of Communicating Processes“ Pi-Kalkül
  • #14: Following Hewitt, Bishop, and Steiger's 1973 publication, Irene Greif developed an operational semantics for the Actor model as part of her doctoral research.[4] Two years later, Henry Baker and Hewitt published a set of axiomatic laws for Actor systems.[5][6] Other major milestones include William Clinger's 1981 dissertation introducing a denotational semantics based on power domains[3] and Gul Agha's 1985 dissertation which further developed a transition-based semantic model complementary to Clinger's.[7] This resulted in the full development of actor model theory. CSP: Communicating Sequential Processes / Theoretical Communicating Sequential Processes (TCSP) „Calculus of Communicating Systems“ „Algebra of Communicating Processes“ Pi-Kalkül
  • #15: Following Hewitt, Bishop, and Steiger's 1973 publication, Irene Greif developed an operational semantics for the Actor model as part of her doctoral research.[4] Two years later, Henry Baker and Hewitt published a set of axiomatic laws for Actor systems.[5][6] Other major milestones include William Clinger's 1981 dissertation introducing a denotational semantics based on power domains[3] and Gul Agha's 1985 dissertation which further developed a transition-based semantic model complementary to Clinger's.[7] This resulted in the full development of actor model theory. CSP: Communicating Sequential Processes / Theoretical Communicating Sequential Processes (TCSP) „Calculus of Communicating Systems“ „Algebra of Communicating Processes“ Pi-Kalkül
  • #16: An actor is a computational entity that, in response to a message it receives, can concurrently: send a finite number of messages to other actors; create a finite number of new actors; designate the behavior to be used for the next message it receives. There is no assumed sequence to the above actions and they could be carried out in parallel. Decoupling the sender from communications sent was a fundamental advance of the Actor model enablingasynchronous communication and control structures as patterns of passing messages.[9] Recipients of messages are identified by address, sometimes called "mailing address". Thus an actor can only communicate with actors whose addresses it has. It can obtain those from a message it receives, or if the address is for an actor it has itself created. The Actor model is characterized by inherent concurrency of computation within and among actors, dynamic creation of actors, inclusion of actor addresses in messages, and interaction only through direct asynchronousmessage passing with no restriction on message arrival order. -------- functions, coroutines, processes, numbers, lists, databases, and devices should be represented as actors
  • #17: An actor is a computational entity that, in response to a message it receives, can concurrently: send a finite number of messages to other actors; create a finite number of new actors; designate the behavior to be used for the next message it receives. There is no assumed sequence to the above actions and they could be carried out in parallel. Decoupling the sender from communications sent was a fundamental advance of the Actor model enablingasynchronous communication and control structures as patterns of passing messages.[9] Recipients of messages are identified by address, sometimes called "mailing address". Thus an actor can only communicate with actors whose addresses it has. It can obtain those from a message it receives, or if the address is for an actor it has itself created. The Actor model is characterized by inherent concurrency of computation within and among actors, dynamic creation of actors, inclusion of actor addresses in messages, and interaction only through direct asynchronousmessage passing with no restriction on message arrival order. -------- The actor theory requires that everything in the system, functions, coroutines, processes, numbers, lists, databases, and devices should be represented as actors, and be capable of receiving messages. This may seem at first a little dogmatic, but there are important practical benefits that arise from having a totally actor-oriented system.
  • #22: Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc. Low level concurrency plumbing BECOMES SIMPLE WORKFLOW - you only think about how messages flow in the system You get high CPU utilization, low latency, high throughput and scalability - FOR FREE as part of the model Proven and superior model for detecting and recovering from errors ------ Actors are location transparent & distributable by design Scale UP and OUT for free as part of the model You get the PERFECT FABRIC for the CLOUD elastic & dynamic fault-tolerant & self-healing adaptive load-balancing, cluster rebalancing & actor migration build extremely loosely coupled and dynamic systems that can change and adapt at runtime
  • #23: Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc. Low level concurrency plumbing BECOMES SIMPLE WORKFLOW - you only think about how messages flow in the system You get high CPU utilization, low latency, high throughput and scalability - FOR FREE as part of the model Proven and superior model for detecting and recovering from errors ------ Actors are location transparent & distributable by design Scale UP and OUT for free as part of the model You get the PERFECT FABRIC for the CLOUD elastic & dynamic fault-tolerant & self-healing adaptive load-balancing, cluster rebalancing & actor migration build extremely loosely coupled and dynamic systems that can change and adapt at runtime
  • #24: Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc. Low level concurrency plumbing BECOMES SIMPLE WORKFLOW - you only think about how messages flow in the system You get high CPU utilization, low latency, high throughput and scalability - FOR FREE as part of the model Proven and superior model for detecting and recovering from errors ------ Actors are location transparent & distributable by design Scale UP and OUT for free as part of the model You get the PERFECT FABRIC for the CLOUD elastic & dynamic fault-tolerant & self-healing adaptive load-balancing, cluster rebalancing & actor migration build extremely loosely coupled and dynamic systems that can change and adapt at runtime
  • #26: Transaction processing (Online Gaming, Finance/Banking, Trading, Statistics, Betting, Social Media, Telecom) Scale up, scale out, fault-tolerance / HA Service backend (any industry, any app) Service REST, SOAP, Cometd, WebSockets etc Act as message hub / integration layer Scale up, scale out, fault-tolerance / HA Concurrency/parallelism (any app) Correct Simple to work with and understand Just add the jars to your existing JVM project (use Scala, Java, Groovy or JRuby) Simulation Master/Worker, Compute Grid, MapReduce etc. Batch processing (any industry) Camel integration to hook up with batch data sources Actors divide and conquer the batch workloads Communications Hub (Telecom, Web media, Mobile media) Scale up, scale out, fault-tolerance / HA Gaming and Betting (MOM, online gaming, betting) Scale up, scale out, fault-tolerance / HA Business Intelligence/Data Mining/general purpose crunching Scale up, scale out, fault-tolerance / HA Complex Event Stream Processing Scale up, scale out, fault-tolerance / HA
  • #28: NOTE: When creating Props, ActorSystem, or ActorRef you will very rarely see the new keyword. These objects must be created through the factory methods built into Akka.NET. If you're using new you might be making a mistake.
  • #29: NOTE: When creating Props, ActorSystem, or ActorRef you will very rarely see the new keyword. These objects must be created through the factory methods built into Akka.NET. If you're using new you might be making a mistake.
  • #33: NOTE: When creating Props, ActorSystem, or ActorRef you will very rarely see the new keyword. These objects must be created through the factory methods built into Akka.NET. If you're using new you might be making a mistake.
  • #34: With an UntypedActor, unhandled messages are not logged as unhandled unless you manually mark them as such, like so: However, in a ReceiveActor—which we cover in Unit 2—unhandled messages are automatically sent to Unhandled so the logging is done for you.
  • #35: Anmerkung: Messages SIND immutable ------ Messages Are Immutable Time for a fun developer buzzword that will make you sound really smart:immutability! So what’s an “immutable” object? An immutable object is an object who’s state (i.e. the contents of its memory) cannot be modified once it’s been created. If you’re a .NET developer, you’ve used the string class. Did you know that in .NETstring is an immutable object? Let me give you an example: var myStr = "Hi!".ToLowerInvariant().Replace("!", "?"); In this example, the following occurs in this order: .NET allocates a const string with the content Hi!” and then ToLowerInvariant() is called, which copies the original “Hi!” string and modifies the copy to become all lowercase and returns the modified copy (which now reads as “hi!”) Then .Replace(string,string) is called, which copies the “hi!” string returned byToLowerInvariant and modifies the copy to substitute ! with ? and returns the modified copy, with the final result reading as “hi?” Since the original string is immutable, all of these operations had to make a copy of the string before they could make their changes. Immutable messages are inherently thread-safe. No thread can modify the content of an immutable message, so a second thread receiving the original message doesn’t have to worry about a previous thread altering the state in an unpredictable way.
  • #37: You do talk to them, just not directly :) You have to talk to them via the intermediary of the ActorSystem. It gives you better information to work with and messaging semantics. The ActorSystem wraps all messages in anEnvelope that contains metadata about the message. This metadata is automatically unpacked and made available in the context of your actor. It allows "location transparency": this is a fancy way of saying that you don't have to worry about which process or machine your actor lives in. Keeping track of all this is the system's job. This is essential for allowing remote actors, which is how you can scale an actor system up to handle massive amounts of data (e.g. have it work on multiple machines in a cluster). More on this later.
  • #38: *CAUTION*: Do NOT call new MyActorClass() outside of Props and the ActorSystem to make an actor.
  • #40: There are two key reasons actors exist in a hierarchy: To atomize work and turn massive amounts of data into manageable chunks To contain errors and make the system resilient Since parents supervise their children, this means that every actor has a supervisor, and every actor can also BE a supervisor.
  • #42: / - The Root Guardian /user – Root Actor Actor path == actor position in hierarchy
  • #44: Here's the sequence of events when an error occurs: Unhandled exception occurs in child actor (c1), which is supervised by its parent (b1). c1 suspends operations. The system sends a Failure message from c1 to b1, with the Exception that was raised. b1 issues a directive to c1 telling it what to do. Life goes on, and the affected part of the system heals itself without burning down the whole house. The critical thing to know here is that *whatever action is taken on a parent propagates to its children*. If a parent is halted, all its children halt. If it is restarted, all its children restart.Kittens and unicorns, handing out free ice cream and coffee to be enjoyed while relaxing on a pillowy rainbow. Yay! ---- Restart the child (default): this is the common case, and the default. Stop the child: this permanently terminates the child actor. Escalate the error (and stop itself): this is the parent saying "I don't know what to do! I'm gonna stop everything and ask MY parent!" Resume processing (ignores the error): you generally won't use this. Ignore it for now.
  • #45: Here's the sequence of events when an error occurs: Unhandled exception occurs in child actor (c1), which is supervised by its parent (b1). c1 suspends operations. The system sends a Failure message from c1 to b1, with the Exception that was raised. b1 issues a directive to c1 telling it what to do. Life goes on, and the affected part of the system heals itself without burning down the whole house. The critical thing to know here is that *whatever action is taken on a parent propagates to its children*. If a parent is halted, all its children halt. If it is restarted, all its children restart.Kittens and unicorns, handing out free ice cream and coffee to be enjoyed while relaxing on a pillowy rainbow. Yay! ---- Restart the child (default): this is the common case, and the default. Stop the child: this permanently terminates the child actor. Escalate the error (and stop itself): this is the parent saying "I don't know what to do! I'm gonna stop everything and ask MY parent!" Resume processing (ignores the error): you generally won't use this. Ignore it for now.