2. Actor model in .NET - Akka.NetVoltcode
Agenda
● Actor model - history and definition
● What to expect from an actor framework? Why is it useful?
● Akka.NET showcase with examples
● Akka.NET current state and the future
3. Actor model in .NET - Akka.NetVoltcode
1973 - Concept formulated by Carl Hewitt et al.:
“A universal modular ACTOR formalism for artificial intelligence”
1986 - Gul Agha, doctoral dissertation
"Actors: A Model of Concurrent Computation in Distributed Systems"
1986 - Joe Armstrong and others in Ericsson - Erlang programming language and
VM. Current version of Erlang/OTP is 19.1 (2016.09)
2009 - initial release of Akka framework (JVM, Scala) by Typesafe (currently
Lightbend)
2014.02 - initial release of Akka.NET - Aaron Stannard, Roger Alsing
Actor model - 40+ year old!
4. Actor model in .NET - Akka.NetVoltcode
Actors communicate by exchanging messages
asynchronously
Actors have internal state that is invisible from the
outside, no shared mutable state
Actors can decide to change their state upon reception
of a message - behavior specification
Each actor processes immutable messages sequentially
- one message at a time*
Actor model - “concurrent object-oriented programming”
Actor
State
Behavior
Messages
5. Actor model in .NET - Akka.NetVoltcode
Actor model - “concurrent object-oriented programming”
Actors can create child actors
Actors are identified by addresses
Actors have mailboxes, where messages arrive
By default, messages are processed in the order
in which they arrived
/Anakin
Come to
the dark
side!
/Anakin/Luke /Anakin/Leia
6. Actor model in .NET - Akka.NetVoltcode
Actor model - benefits
No deadlocks!
No shared state!
No global mutable state!
Fault isolation - “let it crash”!
Encapsulation!
7. Actor model in .NET - Akka.NetVoltcode
Actor frameworks - features
● “Green” threads
● Supervision tree
● Remote deployment
● Routing
● Clustering
● Distributed Pub-sub
● Conflict-free Replicated Data Types (CRDTs)
● Hot code reloading
8. Actor model in .NET - Akka.NetVoltcode
Akka.NET - modules
(as of version 1.1.2)
● Akka
● Akka.Remote
● Akka.Cluster
○ Akka.Cluster.Sharding
○ Akka.Cluster.PubSub
○ Akka.Cluster.Singleton
○ Akka.Cluster.DData (in progress)
● Akka.Persistence
● Akka.Streams
● Akka.TestKit
○ MultiNodeTestKit
9. Voltcode Actor model in .NET - Akka.NetVoltcode
Hello actor
We need an ActorSystem in our application
Create a class and inherit from UntypedActor, ReceiveActor or TypedActor
Add/register message handling to the actor.
Deploy actors using actor system (or indirectly via router)
Tell, don't ask. Ask only if you really must. You may also forward or set
ReceiveTimeout.
10. Voltcode Actor model in .NET - Akka.NetVoltcode
State machines
Actors can choose to modify their behavior as a result of message
Akka provides several methods that facilitate switching handlers’ registrations:
Become(Action newBehaviorDefinition)
BecomeStacked(Action newBehaviorDefinition)
UnbecomeStacked()
Second option in Akka is a more advanced state machine implementation: FSM
More options at a cost of readability
Stashing provides a mechanism to withhold messages until Actor is able to process them (often used with
Become):
Inherit from IWithUnboundedStash and provide :
IStash Stash { get; set; }
Stash.Stash()
Stash.Prepend(IEnumerable<Envelope> envelopes )
Stash.Unstash()
Stash.UnstashAll() (with conditional overload)
Stash.ClearStash()
Code sample!
SampleLocal
11. Voltcode Actor model in .NET - Akka.NetVoltcode
Error handling, supervision and monitoring
Be clear about failures, do not hide them under the carpet aka “Let it crash” philosophy.
Exception inside an actor does not propagate automatically to parent. Instead of killing the actor permanently, it causes its
restart.
Actor can die for real in several other ways (PoisonPill, Kill, Stop() GracefulStop(timeToWait)).
Two types of supervision for such cases are available OOTB:
● Parental supervision (implicit)
○ Parent reacts to children failures
● Unrelated actors supervision (explicit watching)
○ Register via Watch
○ Terminated message on death
○ DeathPactException
/parent
/child1
/doctor /patient
Watch
Code sample!
SampleSupervision
12. Voltcode Actor model in .NET - Akka.NetVoltcode
Routing
A router is a special kind of actor that does not interpret messages, only passes them between
sender and routees.
Router can be instantiated in code and via HOCON configuration
Router can process more than 1 message at once (!)
Built-in routers:
● Broadcast
● Random
● Round-robin
● Consistent hashing
● TailChopping
● ScatterGatherFirstCompleted
● SmallestMailbox
Pools can be resized dynamically using resizer & providing upper and lower bound of number of routees
Code sample!
SampleRouting
13. Voltcode Actor model in .NET - Akka.NetVoltcode
Remote actors - Akka.Remote
All tools work with remote actors!
● Addressing - addressing scheme supports remote actors,
IActorRefs work the same
● Supervision - you can watch a remote actor!
● Routing - you can routeto remote actors!
● Deployment - you can deploy actors to remote processes!
Remote actor address must be extended with extra information -
hostname, port, remote actor system
Watch on remote actors reacts to graceful stopping and to network
failures (disassociation of remote nodes)
Code sample!
SampleRemote
14. Voltcode Actor model in .NET - Akka.NetVoltcode
Cluster is
● Mesh network
● Fault-tolerant
● Elastic
● Decentralized
● P2P
● Without a single point of failure
● Without a single point of bottleneck
Clustering
n1
n2
n3
n4
n5
15. Voltcode Actor model in .NET - Akka.NetVoltcode
Clustering
Aimed towards high availability and partition
tolerance (AP in CAP)
● There are ways to provide more consistency!
Two types of nodes - seed and non-seed
● Seed nodes - well-known starting nodes
● Non seed
Nodes create and maintain the cluster using gossip
protocol (P2P)
● New nodes discovery
● Dead nodes removal
● Detecting changes in nodes availability
Seed Non-s1
Non-s2
Code sample!
SampleCluster
1
2
2
3
17. Voltcode Actor model in .NET - Akka.NetVoltcode
Clustering - distributed pub-sub
Special “mediator” actors
Subscribe with:
Publish with:
var mediator = DistributedPubSub.Get(Context.System).Mediator;
mediator.Tell(new Subscribe("topic", Self));
Receive<SubscribeAck>(_ => Become(Subscribed));
var mediator = DistributedPubSub.Get(Context.System).Mediator;
mediator.Tell(new Publish("topic", new MyMessage()));
Alternatively: use Send,
SendToAll or groups within
topics
Subscribe/SubscribeAck is
mirrored by
Unsubscribe/UnsubscribeAck.
Alternatively : use Put/Remove
API to register using actor path
instead of topic name
18. Voltcode Actor model in .NET - Akka.NetVoltcode
Clustering - additional tools
Sharding
(requires Akka.Persistence)
Singleton
Cluster.Client
Distributed Data (CRDTs)
19. Voltcode Actor model in .NET - Akka.NetVoltcode
Testing
Akka utilities for testing:
TestKit - basic actor messaging testing.
MultiNodeTestKit - extension of the above to create multi-node tests
Plugins for popular unit test frameworks are available (XUnit, NUnit, VSUnit, etc.)
Code sample!
SampleTest
20. Voltcode Actor model in .NET - Akka.NetVoltcode
Akka.Persistence
Enable state persistence for stateful actors
● By default - persist changes to state in an incremental way, without mutations - ES
● Optional - persist state snapshots
Actor state recovery is done using:
● Message replay
● Snapshots restore
Storage backend is pluggable (MySql, PostgreSQL, MS SQL, MongoDB, … ), in-memory option is also available.
Additional features:
● At-least-once delivery using AtLeastOnceDelivery mixin for PersistentActor
● Event adapters - schema versioning support (“upcasting”), domain and data model separation
21. Voltcode Actor model in .NET - Akka.NetVoltcode
Akka.Streams
Manipulate data streams in a reactive fashion with back-pressure support
(slowing down producers to avoid OOMs). Akka.Streams doesn’t use actors explicitly , but uses Akka internals
One way to look at it is an ETL framework for asynchronous data processing with strategies to cope with overload.
At the moment it does not automatically distribute stream processing through network-connected nodes, however such
composition can be achieved with manual effort. Gearpump (JVM) is an example of a framework built on top of Akka for real-time
big data engine.
Core Concepts (from Akka.NET docs):
● Stream - An active process that involves moving and transforming data
● Materializer - makes stream run
● Graph - A description of a stream processing topology, defining the pathways through which elements shall flow when the
stream is running.
● Processing Stage - The common name for all building blocks that build up a Graph
○ Source - producer with 1 output, emits data elements whenever downstream is ready to receive
○ Sink - consumer with 1 input, requests and accepts data, may slow down upstream producers
○ Flow - processor with 1 output, 1 input, connects up- and downstream by transforming elements flowing through it
○ RunnableGraph - A Flow that has both ends "attached" to a Source and Sink respectively, and is ready to be run().
Code sample!
SampleStream
22. Actor model in .NET - Akka.NetVoltcode
Akka.NET - performance, scalability
Local perf
2m+ msg/sec per core (95m / 48 core) - Opteron 2.3 GHz in 2015 Akka.NET
using ping pong test
4.5m+ msg/sec per core in ReceiveActorThroughputSpec test (recent
Akka.NET on build machine)
Remote perf
~50k msg/sec per single connection (with Akka 1.1)
Mostly driven by underlying TCP transport (Helios), to be rewritten for Akka 1.5
(100k+/sec).
Largest .NET cluster in prod - “hundreds” of nodes (in JVM ~2600 nodes)
23. Actor model in .NET - Akka.NetVoltcode
Akka.NET - future
Move libraries out of beta:
Akka.Cluster.Tools
Akka.Persistence
Akka.Streams
New libraries:
Distributed Data
.NET Core support (1.5)
Wire as the default serializer (1.5)
TLS networking
24. Actor model in .NET - Akka.NetVoltcode
Resources
Code samples available under:
https://github.com/voltcode/AkkaNetSamples
Find out more about Akka.NET and the Actor Model:
http://getakka.net
https://github.com/akkadotnet/akka.net/
https://gitter.im/akkadotnet/akka.net
https://petabridge.com/bootcamp/
http://petabridge.com/blog
http://bartoszsypytkowski.com/
Many resources available for Akka (Lightbend documentation)
actor model, clusters in general (Erlang, Riak - basho)
Book(Scala) : Reactive Messaging Patterns with the Actor Model
25. Actor model in .NET - Akka.NetVoltcode
Questions?
Feel free to contact me under @voltcode