SlideShare a Scribd company logo
1 of 138
Download to read offline
Networks & Types
Konrad `ktoso` Malawski, Akka Team
Scala Days New York, June 2018
Art by mastermind31, also “a sneaky reference”, extra points if you “get it”.
The Future[T] of Akka (Actors)
Konrad `ktoso` Malawski
Akka Team
Java Champion
Reactive Streams TCK
Scala Library Improvement Process Committee Member
GeeCON Teamakka.io
typesafe.com
geecon.org
Java.pl / KrakowScala.pl
sckrk.com / meetup.com/Paper-Cup @ London
GDGKrakow.pl
lambdakrk.pl @ Tokyo, Japan
Bear with me today,
long intro this time,
but likely most content-heavy talk in quite a while.
Build powerful reactive, concurrent,
and distributed applications more easily
Akka
- Distributed programming made simple
- High performance messaging (up to 1 million msgs/s on Artery)
- Asynchronous and Reactive by default
- Initiator of Reactive Streams initiative, now part of JDK9
- Productive development, with tuned type-safe tools
What does Akka solve?
https://www.lightbend.com/akka-five-year-anniversary
Types
Last years of Akka have all been about types
Akka hates Types, dude. Trust me.
Mmmm, cereal…
Last years of Akka have all been about types
Focus and large projects since 2013/2014:
Spray => Akka HTTP, 2013 (!)
incredibly typed HTTP APIs / DSL
Last years of Akka have all been about types
Focus and large projects since 2013/2014:
Spray => Akka HTTP, 2013 (!)
incredibly typed HTTP APIs / DSL
Reactive Streams, 2014(Mathias and Johannes did first-first-first impl!)
Akka Streams – completely Typed, part of JDK9+
Alpakka, 2016
Modern take on “Camel”-like integrations, but streaming
Last years of Akka have all been about types
Focus and large projects since 2013/2014:
Spray => Akka HTTP, 2013 (!)
incredibly typed HTTP APIs / DSL
Reactive Streams, 2014(Mathias and Johannes did first-first-first impl!)
Akka Streams – completely Typed, part of JDK9+
Alpakka, 2016
Modern take on “Camel”-like integrations, but streaming
Akka Typed (and Cluster, Persistence, …), 2014-ish~
Experiments since 2014, active “finalizing” since 2016
Right now: full team effort and going to ship prod-ready this year.
Spray => Akka HTTP, 2013 (!)
incredibly typed HTTP APIs / DSL
Reactive Streams, 2014(Mathias and Johannes did first-first-first impl!)
Akka Streams – completely Typed, part of JDK9+
Alpakka, 2016
Modern take on “Camel”-like integrations, but streaming
Akka Typed (and Cluster, Persistence, …), 2014-ish~
Experiments since 2014, active “finalizing” since 2016
Right now: full team effort and going to ship prod-ready this year.
Last years of Akka have all been about types
Focus and large projects since 2014:
Typed
Typed
Typed
Typed
Distributed
Distributed extensions via StreamRefs,
(yes, we’re aware of RSocket :-))
Fully Streaming HTTP server,
incl. WIP HTTP/2
- More compile time type-safety, results in less runtime debugging.
- Runtime debugging is much harder than compile time
- Resulting in a more productive programming team.
Types help build more reliable systems in production.
Not something Akka was arguing against,
however with long Erlang inspiration,
we did not help much with Type-safety in Actors…
The need for strong/strict typing
- Inherently at odds with concurrent and especially distributed computing
- Not trivial problem, unless simplified: 

Annual topic of multiple research papers to bring type-safety to the Actor model

- “TAkka” 2014, Phillip Wadler et al, University of Edinburgh
- “Reactors, Channels and Event Streams …” 2015, 

Aleksandar Prokopec, Martin Odersky, EPFL
- Typed Actors [RIP],


Not direct implementation of these papers, however certainly inspired by them.
The need for strong/strict typing
Actors
Issues with untyped Actors
1. can send “wrong message” to an actor
• because ActorRef.tell(AnyRef)
• hard to navigate / understand code with ActorRefs being passed around
2. interop with Futures / mutable “sender()” / accidental closing over m. state
3. “actors don’t compose!” (the same way as functional concepts do)
“classic”Valid complaints about / issues with actors:
Issues with untyped Actors
1. can send “wrong message” to an actor
• because ActorRef.tell(AnyRef)
• hard to navigate / understand code with ActorRefs being passed around
2. interop with Futures / mutable “sender()” / accidental closing over m. state
3. “actors don’t compose!” (the same way as functional concepts do)
“classic”Valid complaints about / issues with actors:
1. flow-control not built-into Actor messaging
2. supervision too often misunderstood / abused / backoff limitations
3. actorSelection feature often abused (String => ActorRef)
Akka Team’s extras:
Issues with untyped Actors
1. “entirely pure”, however we love pure domain models *within* Actors (!)

2. “super mega high performance”, but “high-performance-ish enough”

You *can* build a kernel-bypass high performance super tunes blog…

but why would you (except that it’s “hardcore” (and fun :-)))
4. “build only for the local case”. 

The moment you go concurrent / multi-core / multi-socket…

you have all the complexities of distributed systems already, 

not hiding it yields understandable systems.
And, “no.”
It was never and will never be the main goal of Actors to:
Untyped Actors
• “sender()” propagated automatically
• any message type can be sent to any Actor
• actor’s def receive = { … } don’t return values
Untyped actors => Akka Typed
Untyped Actors
• “sender()” propagated automatically
• any message type can be sent to any Actor
• actor’s def receive = { … } don’t return values
Akka Actor Typed
• “sender” is part of the protocol
• only the right type of messages can be sent: 

ActorRef[MessageProtocol]
• behaviors always return new behaviors

(state machines for the win)
Untyped Actors => Akka Typed
class MyActor extends Actor {
def receive: Any => Unit = {
case Msg(a) =>
sender() ! “Hi there!”
// …
}
}
Reminder of Akka “Classic” Actors
“classic”
Actors & Types
Akka Actor Typed
Actors & Types
=
Since almost ready for prime-time,
let’s settle the naming dance as well.
Is it really all about
ActorRef[T]?
No!
ActorRef[T] — the “big deal”
http://omaketheater.com
ActorRef[T] — the “big deal”
http://omaketheater.com
ActorRef[T] — the “big deal”
In this talk, I will argue that:
While ActorRef[T] is a great change,
the potential and compositional power of Behavior[T]
by far outshines it, by unlocking new ways to compose behaviors/actors.
ActorRef[T]
Solves complaint “1”:
— can not “send wrong message”
— “hard to navigate code” if I only see “ActorRef”
Our first Typed Actor
Exciting :O
Akka Actor Typed basics (getting our first ActorRef)
Akka Typed top level behavior and spawning #25223
import akka.NotUsed
import akka.actor.typed._
import akka.actor.typed.scaladsl._
val sys =
ActorSystem(Behaviors.setup { context
context.spawn(schedulingMaster, "schedulingMaster")
context.spawn(otherSubsystem, "subsystemMaster")
Behavior.ignore
}, name = “ScalaDaysSystem")
May SLIGHTLY Change, some simplifications here…
Akka Actor Typed basics (getting our first ActorRef)
Akka Typed top level behavior and spawning #25223
import akka.NotUsed
import akka.actor.typed._
import akka.actor.typed.scaladsl._
val sys: ActorSystem[NotUsed] =
ActorSystem(Behaviors.setup { context
context.spawn(SchedulingMaster, "schedulingMaster")
context.spawn(OtherSubsystem, "subsystemMaster")
Behavior.ignore
}, name = "ScalaDaysSystem")
// ActorSystem[T] extends ActorRef[T]
sys ! NotUsed
May SLIGHTLY Change, some simplifications here…
Akka Actor Typed basics (getting our first ActorRef)
val sys: ActorRef[NotUsed] = ???
sys ! NotUsed
sys ! “LOL!”
There’s much more to it than it looks like though…
[error] /Users/ktoso/code/akka/akka-actor-typed/src/main/scala/akka/Example.scala:17:11: type mismatch;
[error] found : String(“LOL!”)
[error] required: akka.NotUsed
[error] ref ! "LOL"
[error] ^
[error] one error found
TENS OF YEARS OF RESEARCH AND DEVELOPMENT!!!
A M A Z I N G.
Akka Actor Typed basics (getting our first ActorRef)
object SchedulingMaster {
sealed trait Protocol
final case class Register(name: String) extends Protocol
def apply: Behavior[Protocol] =
behavior(Set.empty)
private def behavior(registered: Set[String]): Behavior[Protocol] =
Behaviors.receiveMessage[Protocol] {
case Register(name)
behavior(registered + name)
}
}
val ref: ActorRef[SchedulingMaster.Protocol] =
context.spawn(SchedulingMaster, "schedulingMaster")
Behaviors.receive*
akka.actor.typed.scaladsl.Behaviors._
Behaviors._
akka.actor.typed.scaladsl.Behaviors._
ActorSystem[T] — currently using an “emulation layer”
Co-existence
- tell between typed/untyped, spawn on untyped etc.
- https://akka.io/blog/2017/05/06/typed-coexistence
ActorSystem[T] — currently using an “emulation layer”
Co-existence
& Low-risk migration
- Currently running on thin “emulation layer”
- More and more things implemented “natively” (e.g. Persistence)
- tell between typed/untyped, spawn on untyped etc.
- https://akka.io/blog/2017/05/06/typed-coexistence
Behavior[T]
Solves complaint “3”:
— behaviors do compose!
ActorRef[T]
Behaviors
with capabilities
Decorating behaviors to get more capabilities
def behavior =
Behaviors.receiveMessage { m
println("Received: " + m)
Behaviors.same
}
“Oh, but I need logging…”
“Oh, but I need to spawn actors…”
Decorating behaviors to get more capabilities
def behavior =
Behaviors.receiveMessage { m
println("Received: " + m)
Behaviors.same
}
def behavior =
Behaviors.setup[Message] { context
Behaviors.receiveMessage { m
context.log.info("Received: " + m)
Behaviors.same
}
}
Decorating behaviors to get more capabilities
def behavior =
Behaviors.receiveMessage { m
println("Received: " + m)
Behaviors.same
}
import scala.concurrent.duration._
trait Message
object Timeout extends Message
def behavior: Behavior[Message] =
Behaviors.withTimers[Message] { timers
timers.startSingleTimer("timerKey", Timeout, 10.seconds)
Behaviors.receiveMessage {
case Timeout
Behaviors.stopped
case m
Behaviors.ignore
}
}
“Oh, but I need timers…”
Re-using / Combining
Behaviors
Behavior.orElse
def ping(counters: Map[String, Int]): Behavior[Ping] = {
val ping1: Behavior[Ping] = Behaviors.receiveMessagePartial {
case Ping1(replyTo: ActorRef[Pong])
val newCounters = counters.updated("ping1", counters.getOrElse("ping1", 0) + 1)
replyTo ! Pong(newCounters("ping1"))
ping(newCounters)
}
val ping2: Behavior[Ping] = Behaviors.receiveMessage {
case Ping2(replyTo: ActorRef[Pong])
val newCounters = counters.updated("ping2", counters.getOrElse("ping2", 0) + 1)
replyTo ! Pong(newCounters("ping2"))
ping(newCounters)
case _ Behaviors.unhandled
}
ping1.orElse(ping2)
}
}
sealed trait Ping
case class Ping1(replyTo: ActorRef[Pong]) extends Ping
case class Ping2(replyTo: ActorRef[Pong]) extends Ping
case class Pong(counter: Int)
ActorRef[T]
def ping(counters: Map[String, Int]): Behavior[Ping] = {
val ping1: Behavior[Ping] = Behaviors.receiveMessagePartial {
case Ping1(replyTo: ActorRef[Pong])
val newCounters = counters.updated("ping1", counters.getOrElse("ping1", 0) + 1)
replyTo ! Pong(newCounters("ping1"))
ping(newCounters)
}
val ping2: Behavior[Ping] = Behaviors.receiveMessage {
case Ping2(replyTo: ActorRef[Pong])
val newCounters = counters.updated("ping2", counters.getOrElse("ping2", 0) + 1)
replyTo ! Pong(newCounters("ping2"))
ping(newCounters)
case _ Behaviors.unhandled
}
ping1.orElse(ping2)
}
}
sealed trait Ping
case class Ping1(replyTo: ActorRef[Pong]) extends Ping
case class Ping2(replyTo: ActorRef[Pong]) extends Ping
case class Pong(counter: Int)
This WOULD be possible on Scala 3…!
val b: Behavior[A | B] = canA.orElse(canB)
THIS DOES NOT WORK ON SCALA 2.x
This is a “wild speculations” slide.
Do not quote me on these…
This WOULD be possible on Scala 3…!
val b: Behavior[A | B] = canA.orElse(canB)
Scala 2.x: Nein! Was ist denn ein “A | B”?
Das verstehe ich doch überhaupt nicht!
THIS DOES NOT WORK ON SCALA 2.x
This is a “wild speculations” slide.
Do not quote me on these…
This WOULD be possible on Scala 3…!
val b: Behavior[A | B] = canA.orElse(canB)
We don’t have Union Types…
THIS DOES NOT WORK ON SCALA 2.x
This is a “wild speculations” slide.
Do not quote me on these…
Scala 2.x: Nein! Was ist denn ein “A | B”?
Das verstehe ich doch überhaupt nicht!
This WOULD be possible on Scala 3…!
val b: Behavior[A | B] = canA.orElse(canB)
But wait…! Scala 3 will have union types!
https://dotty.epfl.ch/docs/reference/union-types.html
THIS DOES NOT WORK ON SCALA 2.x
This is a “wild speculations” slide.
Do not quote me on these…
What can we do until then though? narrow/widen
/**
* Narrow the type of this Behavior, which is always a safe operation.
*/
final def narrow[U <: T]: Behavior[U] = this.asInstanceOf[Behavior[U]]
What can we do until then though? narrow/widen
/**
* Narrow the type of this Behavior, which is always a safe operation.
*/
final def narrow[U <: T]: Behavior[U] = this.asInstanceOf[Behavior[U]]
import akka.actor.typed.scaladsl.Behaviors
trait Animal
trait Cat extends Animal
trait Dog extends Animal
trait Capybara extends Animal
val doc: Behaviors.Receive[Animal] = Behaviors.receiveMessage[Animal] { msg
Behaviors.same
}
val capyDoc: Behavior[Capybara] = doc.narrow[Capybara]
case class InternalProtocol(name: String, replyTo: ActorRef[InternalReply])
case class InternalReply(id: Int)
val doc: Behavior[Animal] =
Behaviors.receive[AnyRef] { // The “cop out” method
case (context, msg: Animal)
val registration: ActorRef[InternalProtocol] =
context.spawnAnonymous(
Behaviors.receiveMessage[InternalProtocol] {
case InternalProtocol(name, replyTo)
replyTo ! InternalReply(1337)
Behaviors.stopped
})
registration ! InternalProtocol(msg.getClass.getName, context.self)
Behaviors.same
case (context, confirmed: InternalReply) // handle “internal”
println("Confirmed: " + confirmed.id)
Behaviors.same
}.narrow[Animal] // exposing still “safely”
What can we do until then though? narrow/widen
Use narrow to narrow down what
types you allow others to send to you.
// this doc can only handle Capybaras:
val capyDoctor: Behaviors.Receive[Capybara] =
Behaviors.receiveMessage[Capybara] {
kapi Behaviors.same
}
val adapting: Behavior[Animal] =
capyDoctor.widen[Animal] {
case dog: Dog
// it's kind of like a capybara...
new Capybara { val actually = dog }
} // all others => Unhandled
We can also “widen”
/**
* Widen the wrapped Behavior by placing a funnel in front of it: the supplied
* PartialFunction decides which message to pull in (those that it is defined
* at) and may transform the incoming message to place them into the wrapped
* Behavior’s type hierarchy. Signals are not transformed.
*
* Example:
* {{{
* receive[String] { (ctx, msg) => println(msg); same }.widen[Number] {
* case b: BigDecimal => s"BigDecimal(&dollar;b)"
* case i: BigInteger => s"BigInteger(&dollar;i)"
* // drop all other kinds of Number
* }
* }}}
*/
def widen[U](matcher: PartialFunction[U, T]): Behavior[U] =
BehaviorImpl.widened(behavior, matcher)
Use widen to “widen” the set of types you can handle,
by adapting them or leaving them unhandled.
Behaviors.receive[Internal] {
case (context, _)
val adapterRef: ActorRef[ExternalProtocol] =
context.messageAdapter[ExternalProtocol] {
case other if other.isSomething new InternalSomething(other)
case other new InternalWrappedOther(other)
}
// …
}
Message adapters; “reply to me, and I’ll adapt to my T”
Use messageAdapter to create
“mini ActorRef” that translates
someone’s protocol => your own protocol.
def ask[U](message: ActorRef[U] A)
(implicit timeout: Timeout, scheduler: Scheduler): Future[U] = ???
def ask[Req, Res](otherActor: ActorRef[Req])
(createRequest: ActorRef[Res] Req)
(mapResponse: Try[Res] T)
(implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit = ???
Various `ask` patterns
Ask received a number of versions, that cut more and more clutter
depending on how much context it has available.
Behavior[A | B]
What can we do until then though?
NOT AT ALL PROVEN CRAZY IDEA
DON’T TRUST ME ON THIS (YET)
// can't do this nowadays:
// val all: Behavior[???] = canA orElse canB // nope
val all: Behavior[Union2[A, B]] = anyOf(canA, canB) // special behavior impl
val allRef: ActorRef[Union2[A, B]] = context.spawn(all, "fake-union")
val a: A = ???
val b: B = ???
allRef ! a // implicitly packed as Union2[A, B]
allRef ! b // implicitly packed as Union2[A, B]
Crazy experiments,
could we emulate…
https://github.com/akka/akka/issues/25251
But…
How can an ActorRef[T],
receive lifecycle messages…?
Messages and Signals
val canA: Behaviors.Receive[A] =
Behaviors.receiveMessage[A] { msg
???
}
canA.receiveSignal {
case (context, PostStop)
println("I'm dead now...")
Behaviors.same
}
Behaviors.Receive[T] extends Behavior[T]
Actors
ACTORS HANDLE MESSAGES
“classic”
Abuse of [system|context].actorSelection considered an anti-pattern.
Why is that so?
(See also “Zen of Akka” talk for more discussion about it)
Please don’t overuse actorSelection :-)
“classic”
Reminder: Sending messages to
a “dead” actor results in dead letters.
“classic” Note the difference between
messages which are unhandled.
The actor exists, but did not handle the msg.
“classic” actorSelection with “wrong” name
also results in dead letters.
We don’t even know if this actor ever lived!
“classic”
Note also that String => ActorRef[T] could never yield the “right T”.
We need something:
Less error prone and more type-safe.
And even more useful…
String => ActorRef[T] can’t ever possibly give the right T
actorSelection is dead.
The Receptionist(think: Grand Budapest Hotel, love that movie…)
Receptionist
Receptionist
Receptionist
Receptionist
actorSystem.receptionist: ActorRef[Receptionist.Command] ! (command)
abstract class Receptionist extends Extension {
def ref: ActorRef[Receptionist.Command]
}
final case class Register[T] private[akka] (key: ServiceKey[T],
serviceInstance: ActorRef[T],
replyTo: Option[ActorRef[Receptionist.Registered]]
) extends Command
final case class Find[T] private[akka] (key: ServiceKey[T],
replyTo: ActorRef[Receptionist.Listing]
) extends Command
final case class Subscribe[T] private[akka] (key: ServiceKey[T],
subscriber: ActorRef[Receptionist.Listing]
) extends Command
final case class Listing[T] private[akka] (key: ServiceKey[T],
serviceInstances: Set[ActorRef[T]]
) extends Receptionist.Listing
Cluster
Receptionist
Typed
Showing both the distributed part and the Subscribe feature here.
They are independent though, you could sub locally.
Mutable Behavior[T]
Your fast-path to type-safety
from classic.
Moving from Classic to Typed, *EASILY*
class ChatRoomBehavior extends Actor {
private var sessions: List[ActorRef[SessionCommand]] =
List.empty
override def receive = {
case GetSession(screenName, client)
. . .
case PublishSessionMessage(screenName, message)
. . .
}
}
}
Moving from Classic to Typed, *EASILY*
class ChatRoomBehavior(ctx: ActorContext[RoomCommand])
extends MutableBehavior[RoomCommand] {
private var sessions: List[ActorRef[SessionCommand]] = List.empty
override def onMessage(msg: RoomCommand): Behavior[RoomCommand] = {
msg match {
case GetSession(screenName, client)
. . .
Behaviors.same
case PublishSessionMessage(screenName, message)
. . .
this
}
}
}
class ChatRoomBehavior extends Actor {
private var sessions: List[ActorRef[SessionCommand]] =
List.empty
override def receive {
case GetSession(screenName, client)
. . .
case PublishSessionMessage(screenName, message)
. . .
}
}
}
“classic”
Yes, you can mix-and-match all “styles” of Behaviors.
Yes, you can also mix JavaDSL/ScalaDSL — they share the Behavior type.
String => ActorRef[T] can’t ever possibly give the right T
Changes in Supervision
Meant to:
- handle “failures”, not “errors”.
- be always-on, hierarchical
Is often abused to:
- replace try/catch,Try,Either,Validation etc.
Not able to express “backoff”:
- is implemented as separate BackoffSupervisor
“Classic supervision”: always on, in parent actor
“classic”Supervision in
Declarative, composable supervision
val ref = Behaviors.supervise(targetBehavior)
.onFailure[SomeException](SupervisorStrategy.restart)
Mini DSL for building supervision, which is also “just” a Behavior[T]
Declarative, composable supervision
val ref = Behaviors.supervise(targetBehavior)
.onFailure[SomeException](SupervisorStrategy.restart)
supervise(
supervise(
targetBehavior
).onFailure[Exc2](SupervisorStrategy.resume)
).onFailure[Exc3](SupervisorStrategy.restart)
Mini DSL for building supervision, which is also “just” a Behavior[T]
Supports nesting , for sharing logic for “common handler” etc
New supervision strategies
More advanced supervision strategies!
SupervisorStrategy
.restartWithBackoff(minBackoff, maxBackoff, randomFactor = 0.2)
.withResetBackoffAfter(10.seconds)
SupervisorStrategy
.restartWithLimit(
maxNrOfRetries = 3,
withinTimeRange = 1.second
)
Downsides!
Downsides!
Yeah, well…
Types?
Downsides of typedness…
Not so suprisingly, more types may mean more “dancing around”,
getting the types “right”.
You will thank yourself in the future though,
once you have to go back and maintain a piece of code :-)
Don’t fear dropping to MutableBehavior[T] if it feels right!
Flow Control
Wouldn’t it be nice if we spent years of work on a flow-control protocol…
… and could actually apply it to many areas of Akka…?
Extra:
“Origins of back-pressure”
https://twitter.com/impurepics/status/1000466142866149377
“Origins of back-pressure”
https://twitter.com/impurepics/status/1000466142866149377
https://twitter.com/impurepics/status/1000466142866149377
Akka Streams
…which implement Reactive Streams
Typed by default
Akka Streams
…which implement Reactive Streams
Typed by default
…which is the async-flow-control standard
…which is now also part of JDK9+ (j.u.c.Flow)
Fast Publisher will send at-most 3 elements.
This is pull-based-backpressure.
Reactive Streams: “dynamic push/pull”
Akka Streams
over Network
Typed by default
Extra:
StreamRefs — new feature in Akka 2.5.10
“Reactive Streams semantics,
over network boundaries.”
StreamRefs — new feature in Akka 2.5.10
“Reactive Streams semantics,
over network boundaries.”
“Like ActorRef[T], but for Akka Streams”
Very lightweight, and simple.
StreamRefs — new feature in Akka 2.5.10
By design NOT a“distributed automatic stream
processing deployment and management framework”.
(e.g. how Spark, Flink or Beam could be described).
Ideal for
combining Alpakka Enterprise Integration,
Data Processing or Ingestion Pipelines,
or back-pressured / flow-controlled messaging between systems.
See also, Nitesh Kant, Netflix @ Reactive Summit
https://www.youtube.com/watch?v=5FE6xnH5Lak
Life without StreamRefs
HTTP/1.1 503 Service Unavailable
HTTP/1.1 503 Service Unavailable
And then:
Throttling as represented by 503 responses…
Applying circuit breakers…
Introducing manual flow control…
Life without StreamRefs
Life with StreamRefs
JVM 2
ActorSystem
JVM 1
ActorSystem
(special)
SinkSource Flow
Flow Sink
SourceRef
StreamRefs — new feature since Akka 2.5.10
JVM 2
ActorSystem
JVM 1
ActorSystem
(special)
SinkSource Flow
Flow SinkSourceRef
This end controls
the pace through
backpressure
StreamRefs — new feature since Akka 2.5.10
“origin” side “remote” side
.runWith(StreamRefs.sourceRef)
run Source and,
materialize SourceRef
SourceRef
Source
Arbitrarily complex
Source graph
.source.runWith(any Sink)
Establishes link and demands for elements to be sent to remote side
SourceRef
send to remote recipient
(e.g. via actor messaging)
SourceRef — high-level overview
SourceRef usage example (prepare)
Scala
SourceRef usage example (use)
Can we apply this to
Actor messaging?
Somewhat.
Better flow control mechanisms in Typed Actors
Could we combine StreamRef semantics + re-delivery…
with pre-packaged Behaviors / “companions”…?
Experiment here: https://github.com/akka/akka/pull/25099
In other news…
In other news…
Artery (UDP, Aeron) transport – soon to become stable
Artery TCP+TLS transport – new, soon to become stable
Akka Cluster Multi-DC – dc awareness fully supported
Akka Multi-DC Persistence* – fully supported multi-dc persistence
Typed Persistence – Akka Persistence, but fully typed, soon ready
Alpakka (Akka Streams connectors to various tech) 

Remoting feature matrix
Remoting
“classic”
Artery Remoting
Artery TCP
Remoting
Protocol
TCP
TLS+TCP
UDP
(Aeron)
TCP
TLS+TCP
Large messages Troublesome Dedicated lanes
Dedicated
connection
Heartbeat and
System
Messages
Prioritised Dedicated lanes
Dedicated
connection
Benchmarked*
throughput
70k msg/s
700k+ msg/s
(up to 1m msg/s)
600k+ msg/s
How to use Artery?
single option,
no new artifacts
Artery: ActorRef Compression
Compression triggered for “heavy hitters”,
so “most chatty” Actors to maximise benefit.
Triggers automatically & transparently.
Artery: ActorRef / Manifest Compression
Artery: ActorRef / Manifest Compression
In this case ActorRef compression reduced the size of a small envelope size by 74%
- from 162 to 42 bytes (sic!).
Tracing
& Monitoring
Monitoring Akka
developer.lightbend.com/docs/monitoring/latest/home.html
+
DataDog || StatsD || Graphite || …anything!
Monitoring & Tracing Akka Streams
MDC, Context, Metrics, Tracing…
for Akka Streams (!!!)
SOON…
Tracing Akka with Jaeger or Zipkin
Uber Jaeger
Zipkin
Tracing Akka with Jaeger or Zipkin
Lightbend Monitoring
https://developer.lightbend.com/docs/cinnamon/latest/extensions/opentracing.html
Tracing across nodes
https://developer.lightbend.com/docs/cinnamon/latest/extensions/opentracing.html
Tracing transparently across:
- Akka Actor messaging

- Scala Futures

- Akka HTTP client / server
- Akka Streams (!)
More Cloud Native-ness / aware-ness
Out now:
- Multi-Datacenter awareness (OSS)
- Multi-Datacenter Replication for Akka Persistence (Commercial)
Active new development:
- “right and proper” integrations with k8s (Lightbend Orchestration,Akka Management)
Read
& Watch
discuss.akka.io
blog.akka.io
Docs:
https://doc.akka.io/docs/akka/2.5/typed/index.html
https://doc.akka.io/docs/akka/2.5/stream/stream-refs.html
More resources:
https://developer.lightbend.com
https://www.lightbend.com/resources
Graphics used in presentation:
Title slide: https://mastermind31.deviantart.com/art/Minimal-Enomoto-Takane-510564143
All other drawings and pictures — myself (CC 3.0, BY-NC)
Further reading…
“Zen of Akka”, ScalaDays NYC 2016
Underlying principles, best-practices, some anti-patterns
https://www.youtube.com/watch?v=vgFoKOxrTzg
Recommended viewing (selfish plug)
“The best is yet to come”, Scala Days CPH 2017
How we got here, how one thing inter-ops with another, and roadmap
https://www.youtube.com/watch?v=CGyIPVGB2-4 (~200 slides, 50 mins)
All slides on https://www.slideshare.net/ktoso
(Please give it a day for this slide deck to appear there)
”Why Reactive?”, free ebook, not “sponsored” content :-)
Show it off to people new to reactive systems, to get “the idea” behind it.
bit.ly/why-reactive
Recommended reading (selfish plug)
New free Coursera / edx course about
Akka Typed & Akka Streams soon!
Pre annoucement :-)
Happy typed hakking!
Konrad `ktoso` Malawski, ktoso@lightbend.com
http://kto.so / http://konrad.malaw.ski / @ktosopl
Akka docs: akka.io/docs
Lake Ashi, Hakone, Japan

More Related Content

What's hot

Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka StreamsKonrad Malawski
 
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
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
 
Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016Konrad Malawski
 
The things we don't see – stories of Software, Scala and Akka
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
 
End to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketEnd to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketKonrad Malawski
 
How Reactive Streams & Akka Streams change the JVM Ecosystem
How Reactive Streams & Akka Streams change the JVM EcosystemHow Reactive Streams & Akka Streams change the JVM Ecosystem
How Reactive Streams & Akka Streams change the JVM EcosystemKonrad Malawski
 
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...Konrad Malawski
 
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneKonrad Malawski
 
VJUG24 - Reactive Integrations with Akka Streams
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka StreamsJohan Andrén
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysManuel Bernhardt
 
Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Johan Andrén
 
Reactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsKonrad Malawski
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camelkrasserm
 
Distributed Consensus A.K.A. "What do we eat for lunch?"
Distributed Consensus A.K.A. "What do we eat for lunch?"Distributed Consensus A.K.A. "What do we eat for lunch?"
Distributed Consensus A.K.A. "What do we eat for lunch?"Konrad Malawski
 
Streaming all the things with akka streams
Streaming all the things with akka streams   Streaming all the things with akka streams
Streaming all the things with akka streams Johan Andrén
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedykrivachy
 
Apache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the boxApache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the boxClaus Ibsen
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentationGene Chang
 
Scala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streamsScala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streamsJohan Andrén
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayRoland Kuhn
 

What's hot (20)

Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
 
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
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
 
Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016
 
The things we don't see – stories of Software, Scala and Akka
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
 
End to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketEnd to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to Socket
 
How Reactive Streams & Akka Streams change the JVM Ecosystem
How Reactive Streams & Akka Streams change the JVM EcosystemHow Reactive Streams & Akka Streams change the JVM Ecosystem
How Reactive Streams & Akka Streams change the JVM Ecosystem
 
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
 
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne
 
VJUG24 - Reactive Integrations with Akka Streams
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka Streams
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka
 
Reactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka StreamsReactive Stream Processing with Akka Streams
Reactive Stream Processing with Akka Streams
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
 
Distributed Consensus A.K.A. "What do we eat for lunch?"
Distributed Consensus A.K.A. "What do we eat for lunch?"Distributed Consensus A.K.A. "What do we eat for lunch?"
Distributed Consensus A.K.A. "What do we eat for lunch?"
 
Streaming all the things with akka streams
Streaming all the things with akka streams   Streaming all the things with akka streams
Streaming all the things with akka streams
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedy
 
Apache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the boxApache Camel Introduction & What's in the box
Apache Camel Introduction & What's in the box
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Scala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streamsScala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streams
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive Way
 

Similar to Networks and Types - the Future of Akka @ ScalaDays NYC 2018

Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesLightbend
 
The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupkrivachy
 
Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)Esun Kim
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Evan Chan
 
Model with actors and implement with Akka
Model with actors and implement with AkkaModel with actors and implement with Akka
Model with actors and implement with AkkaNgoc Dao
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Konrad Malawski
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)Konrad Malawski
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Anatomy of a Reactive Application
Anatomy of a Reactive ApplicationAnatomy of a Reactive Application
Anatomy of a Reactive ApplicationMark Wilson
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den HoekRubiX BV
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with AkkaMaciej Matyjas
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...Lightbend
 

Similar to Networks and Types - the Future of Akka @ ScalaDays NYC 2018 (20)

Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
 
The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetup
 
Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015
 
Model with actors and implement with Akka
Model with actors and implement with AkkaModel with actors and implement with Akka
Model with actors and implement with Akka
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Anatomy of a Reactive Application
Anatomy of a Reactive ApplicationAnatomy of a Reactive Application
Anatomy of a Reactive Application
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den Hoek
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
Akka A to Z: A Guide To The Industry’s Best Toolkit for Fast Data and Microse...
 

More from Konrad Malawski

Akka Typed (quick talk) - JFokus 2018
Akka Typed (quick talk) - JFokus 2018Akka Typed (quick talk) - JFokus 2018
Akka Typed (quick talk) - JFokus 2018Konrad Malawski
 
Krakow communities @ 2016
Krakow communities @ 2016Krakow communities @ 2016
Krakow communities @ 2016Konrad Malawski
 
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRKKonrad Malawski
 
2014 akka-streams-tokyo-japanese
2014 akka-streams-tokyo-japanese2014 akka-streams-tokyo-japanese
2014 akka-streams-tokyo-japaneseKonrad Malawski
 
Open soucerers - jak zacząć swoją przygodę z open source
Open soucerers - jak zacząć swoją przygodę z open sourceOpen soucerers - jak zacząć swoją przygodę z open source
Open soucerers - jak zacząć swoją przygodę z open sourceKonrad Malawski
 
HBase RowKey design for Akka Persistence
HBase RowKey design for Akka PersistenceHBase RowKey design for Akka Persistence
HBase RowKey design for Akka PersistenceKonrad Malawski
 
Scalding - the not-so-basics @ ScalaDays 2014
Scalding - the not-so-basics @ ScalaDays 2014Scalding - the not-so-basics @ ScalaDays 2014
Scalding - the not-so-basics @ ScalaDays 2014Konrad Malawski
 
DDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceDDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceKonrad Malawski
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesKonrad Malawski
 

More from Konrad Malawski (10)

Akka Typed (quick talk) - JFokus 2018
Akka Typed (quick talk) - JFokus 2018Akka Typed (quick talk) - JFokus 2018
Akka Typed (quick talk) - JFokus 2018
 
Krakow communities @ 2016
Krakow communities @ 2016Krakow communities @ 2016
Krakow communities @ 2016
 
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
 
Zen of Akka
Zen of AkkaZen of Akka
Zen of Akka
 
2014 akka-streams-tokyo-japanese
2014 akka-streams-tokyo-japanese2014 akka-streams-tokyo-japanese
2014 akka-streams-tokyo-japanese
 
Open soucerers - jak zacząć swoją przygodę z open source
Open soucerers - jak zacząć swoją przygodę z open sourceOpen soucerers - jak zacząć swoją przygodę z open source
Open soucerers - jak zacząć swoją przygodę z open source
 
HBase RowKey design for Akka Persistence
HBase RowKey design for Akka PersistenceHBase RowKey design for Akka Persistence
HBase RowKey design for Akka Persistence
 
Scalding - the not-so-basics @ ScalaDays 2014
Scalding - the not-so-basics @ ScalaDays 2014Scalding - the not-so-basics @ ScalaDays 2014
Scalding - the not-so-basics @ ScalaDays 2014
 
DDDing Tools = Akka Persistence
DDDing Tools = Akka PersistenceDDDing Tools = Akka Persistence
DDDing Tools = Akka Persistence
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutes
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Networks and Types - the Future of Akka @ ScalaDays NYC 2018

  • 1. Networks & Types Konrad `ktoso` Malawski, Akka Team Scala Days New York, June 2018 Art by mastermind31, also “a sneaky reference”, extra points if you “get it”. The Future[T] of Akka (Actors)
  • 2. Konrad `ktoso` Malawski Akka Team Java Champion Reactive Streams TCK Scala Library Improvement Process Committee Member GeeCON Teamakka.io typesafe.com geecon.org Java.pl / KrakowScala.pl sckrk.com / meetup.com/Paper-Cup @ London GDGKrakow.pl lambdakrk.pl @ Tokyo, Japan
  • 3. Bear with me today, long intro this time, but likely most content-heavy talk in quite a while.
  • 4. Build powerful reactive, concurrent, and distributed applications more easily Akka
  • 5. - Distributed programming made simple - High performance messaging (up to 1 million msgs/s on Artery) - Asynchronous and Reactive by default - Initiator of Reactive Streams initiative, now part of JDK9 - Productive development, with tuned type-safe tools What does Akka solve?
  • 6.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20. Types
  • 21. Last years of Akka have all been about types Akka hates Types, dude. Trust me. Mmmm, cereal…
  • 22. Last years of Akka have all been about types Focus and large projects since 2013/2014: Spray => Akka HTTP, 2013 (!) incredibly typed HTTP APIs / DSL
  • 23. Last years of Akka have all been about types Focus and large projects since 2013/2014: Spray => Akka HTTP, 2013 (!) incredibly typed HTTP APIs / DSL Reactive Streams, 2014(Mathias and Johannes did first-first-first impl!) Akka Streams – completely Typed, part of JDK9+ Alpakka, 2016 Modern take on “Camel”-like integrations, but streaming
  • 24. Last years of Akka have all been about types Focus and large projects since 2013/2014: Spray => Akka HTTP, 2013 (!) incredibly typed HTTP APIs / DSL Reactive Streams, 2014(Mathias and Johannes did first-first-first impl!) Akka Streams – completely Typed, part of JDK9+ Alpakka, 2016 Modern take on “Camel”-like integrations, but streaming Akka Typed (and Cluster, Persistence, …), 2014-ish~ Experiments since 2014, active “finalizing” since 2016 Right now: full team effort and going to ship prod-ready this year.
  • 25. Spray => Akka HTTP, 2013 (!) incredibly typed HTTP APIs / DSL Reactive Streams, 2014(Mathias and Johannes did first-first-first impl!) Akka Streams – completely Typed, part of JDK9+ Alpakka, 2016 Modern take on “Camel”-like integrations, but streaming Akka Typed (and Cluster, Persistence, …), 2014-ish~ Experiments since 2014, active “finalizing” since 2016 Right now: full team effort and going to ship prod-ready this year. Last years of Akka have all been about types Focus and large projects since 2014: Typed Typed Typed Typed Distributed Distributed extensions via StreamRefs, (yes, we’re aware of RSocket :-)) Fully Streaming HTTP server, incl. WIP HTTP/2
  • 26. - More compile time type-safety, results in less runtime debugging. - Runtime debugging is much harder than compile time - Resulting in a more productive programming team. Types help build more reliable systems in production. Not something Akka was arguing against, however with long Erlang inspiration, we did not help much with Type-safety in Actors… The need for strong/strict typing
  • 27. - Inherently at odds with concurrent and especially distributed computing - Not trivial problem, unless simplified: 
 Annual topic of multiple research papers to bring type-safety to the Actor model
 - “TAkka” 2014, Phillip Wadler et al, University of Edinburgh - “Reactors, Channels and Event Streams …” 2015, 
 Aleksandar Prokopec, Martin Odersky, EPFL - Typed Actors [RIP], 
 Not direct implementation of these papers, however certainly inspired by them. The need for strong/strict typing
  • 29. Issues with untyped Actors 1. can send “wrong message” to an actor • because ActorRef.tell(AnyRef) • hard to navigate / understand code with ActorRefs being passed around 2. interop with Futures / mutable “sender()” / accidental closing over m. state 3. “actors don’t compose!” (the same way as functional concepts do) “classic”Valid complaints about / issues with actors:
  • 30. Issues with untyped Actors 1. can send “wrong message” to an actor • because ActorRef.tell(AnyRef) • hard to navigate / understand code with ActorRefs being passed around 2. interop with Futures / mutable “sender()” / accidental closing over m. state 3. “actors don’t compose!” (the same way as functional concepts do) “classic”Valid complaints about / issues with actors: 1. flow-control not built-into Actor messaging 2. supervision too often misunderstood / abused / backoff limitations 3. actorSelection feature often abused (String => ActorRef) Akka Team’s extras:
  • 31. Issues with untyped Actors 1. “entirely pure”, however we love pure domain models *within* Actors (!)
 2. “super mega high performance”, but “high-performance-ish enough”
 You *can* build a kernel-bypass high performance super tunes blog…
 but why would you (except that it’s “hardcore” (and fun :-))) 4. “build only for the local case”. 
 The moment you go concurrent / multi-core / multi-socket…
 you have all the complexities of distributed systems already, 
 not hiding it yields understandable systems. And, “no.” It was never and will never be the main goal of Actors to:
  • 32. Untyped Actors • “sender()” propagated automatically • any message type can be sent to any Actor • actor’s def receive = { … } don’t return values Untyped actors => Akka Typed
  • 33. Untyped Actors • “sender()” propagated automatically • any message type can be sent to any Actor • actor’s def receive = { … } don’t return values Akka Actor Typed • “sender” is part of the protocol • only the right type of messages can be sent: 
 ActorRef[MessageProtocol] • behaviors always return new behaviors
 (state machines for the win) Untyped Actors => Akka Typed
  • 34. class MyActor extends Actor { def receive: Any => Unit = { case Msg(a) => sender() ! “Hi there!” // … } } Reminder of Akka “Classic” Actors “classic”
  • 36. Akka Actor Typed Actors & Types = Since almost ready for prime-time, let’s settle the naming dance as well.
  • 37. Is it really all about ActorRef[T]? No!
  • 38. ActorRef[T] — the “big deal” http://omaketheater.com
  • 39. ActorRef[T] — the “big deal” http://omaketheater.com
  • 40. ActorRef[T] — the “big deal” In this talk, I will argue that: While ActorRef[T] is a great change, the potential and compositional power of Behavior[T] by far outshines it, by unlocking new ways to compose behaviors/actors.
  • 41. ActorRef[T] Solves complaint “1”: — can not “send wrong message” — “hard to navigate code” if I only see “ActorRef”
  • 42. Our first Typed Actor Exciting :O
  • 43. Akka Actor Typed basics (getting our first ActorRef) Akka Typed top level behavior and spawning #25223 import akka.NotUsed import akka.actor.typed._ import akka.actor.typed.scaladsl._ val sys = ActorSystem(Behaviors.setup { context context.spawn(schedulingMaster, "schedulingMaster") context.spawn(otherSubsystem, "subsystemMaster") Behavior.ignore }, name = “ScalaDaysSystem") May SLIGHTLY Change, some simplifications here…
  • 44. Akka Actor Typed basics (getting our first ActorRef) Akka Typed top level behavior and spawning #25223 import akka.NotUsed import akka.actor.typed._ import akka.actor.typed.scaladsl._ val sys: ActorSystem[NotUsed] = ActorSystem(Behaviors.setup { context context.spawn(SchedulingMaster, "schedulingMaster") context.spawn(OtherSubsystem, "subsystemMaster") Behavior.ignore }, name = "ScalaDaysSystem") // ActorSystem[T] extends ActorRef[T] sys ! NotUsed May SLIGHTLY Change, some simplifications here…
  • 45. Akka Actor Typed basics (getting our first ActorRef) val sys: ActorRef[NotUsed] = ??? sys ! NotUsed sys ! “LOL!” There’s much more to it than it looks like though… [error] /Users/ktoso/code/akka/akka-actor-typed/src/main/scala/akka/Example.scala:17:11: type mismatch; [error] found : String(“LOL!”) [error] required: akka.NotUsed [error] ref ! "LOL" [error] ^ [error] one error found TENS OF YEARS OF RESEARCH AND DEVELOPMENT!!! A M A Z I N G.
  • 46. Akka Actor Typed basics (getting our first ActorRef) object SchedulingMaster { sealed trait Protocol final case class Register(name: String) extends Protocol def apply: Behavior[Protocol] = behavior(Set.empty) private def behavior(registered: Set[String]): Behavior[Protocol] = Behaviors.receiveMessage[Protocol] { case Register(name) behavior(registered + name) } } val ref: ActorRef[SchedulingMaster.Protocol] = context.spawn(SchedulingMaster, "schedulingMaster")
  • 49. ActorSystem[T] — currently using an “emulation layer” Co-existence - tell between typed/untyped, spawn on untyped etc. - https://akka.io/blog/2017/05/06/typed-coexistence
  • 50. ActorSystem[T] — currently using an “emulation layer” Co-existence & Low-risk migration - Currently running on thin “emulation layer” - More and more things implemented “natively” (e.g. Persistence) - tell between typed/untyped, spawn on untyped etc. - https://akka.io/blog/2017/05/06/typed-coexistence
  • 52. Solves complaint “3”: — behaviors do compose! ActorRef[T]
  • 54. Decorating behaviors to get more capabilities def behavior = Behaviors.receiveMessage { m println("Received: " + m) Behaviors.same } “Oh, but I need logging…” “Oh, but I need to spawn actors…”
  • 55. Decorating behaviors to get more capabilities def behavior = Behaviors.receiveMessage { m println("Received: " + m) Behaviors.same } def behavior = Behaviors.setup[Message] { context Behaviors.receiveMessage { m context.log.info("Received: " + m) Behaviors.same } }
  • 56. Decorating behaviors to get more capabilities def behavior = Behaviors.receiveMessage { m println("Received: " + m) Behaviors.same } import scala.concurrent.duration._ trait Message object Timeout extends Message def behavior: Behavior[Message] = Behaviors.withTimers[Message] { timers timers.startSingleTimer("timerKey", Timeout, 10.seconds) Behaviors.receiveMessage { case Timeout Behaviors.stopped case m Behaviors.ignore } } “Oh, but I need timers…”
  • 58. Behavior.orElse def ping(counters: Map[String, Int]): Behavior[Ping] = { val ping1: Behavior[Ping] = Behaviors.receiveMessagePartial { case Ping1(replyTo: ActorRef[Pong]) val newCounters = counters.updated("ping1", counters.getOrElse("ping1", 0) + 1) replyTo ! Pong(newCounters("ping1")) ping(newCounters) } val ping2: Behavior[Ping] = Behaviors.receiveMessage { case Ping2(replyTo: ActorRef[Pong]) val newCounters = counters.updated("ping2", counters.getOrElse("ping2", 0) + 1) replyTo ! Pong(newCounters("ping2")) ping(newCounters) case _ Behaviors.unhandled } ping1.orElse(ping2) } } sealed trait Ping case class Ping1(replyTo: ActorRef[Pong]) extends Ping case class Ping2(replyTo: ActorRef[Pong]) extends Ping case class Pong(counter: Int)
  • 59. ActorRef[T] def ping(counters: Map[String, Int]): Behavior[Ping] = { val ping1: Behavior[Ping] = Behaviors.receiveMessagePartial { case Ping1(replyTo: ActorRef[Pong]) val newCounters = counters.updated("ping1", counters.getOrElse("ping1", 0) + 1) replyTo ! Pong(newCounters("ping1")) ping(newCounters) } val ping2: Behavior[Ping] = Behaviors.receiveMessage { case Ping2(replyTo: ActorRef[Pong]) val newCounters = counters.updated("ping2", counters.getOrElse("ping2", 0) + 1) replyTo ! Pong(newCounters("ping2")) ping(newCounters) case _ Behaviors.unhandled } ping1.orElse(ping2) } } sealed trait Ping case class Ping1(replyTo: ActorRef[Pong]) extends Ping case class Ping2(replyTo: ActorRef[Pong]) extends Ping case class Pong(counter: Int)
  • 60. This WOULD be possible on Scala 3…! val b: Behavior[A | B] = canA.orElse(canB) THIS DOES NOT WORK ON SCALA 2.x This is a “wild speculations” slide. Do not quote me on these…
  • 61. This WOULD be possible on Scala 3…! val b: Behavior[A | B] = canA.orElse(canB) Scala 2.x: Nein! Was ist denn ein “A | B”? Das verstehe ich doch überhaupt nicht! THIS DOES NOT WORK ON SCALA 2.x This is a “wild speculations” slide. Do not quote me on these…
  • 62. This WOULD be possible on Scala 3…! val b: Behavior[A | B] = canA.orElse(canB) We don’t have Union Types… THIS DOES NOT WORK ON SCALA 2.x This is a “wild speculations” slide. Do not quote me on these… Scala 2.x: Nein! Was ist denn ein “A | B”? Das verstehe ich doch überhaupt nicht!
  • 63. This WOULD be possible on Scala 3…! val b: Behavior[A | B] = canA.orElse(canB) But wait…! Scala 3 will have union types! https://dotty.epfl.ch/docs/reference/union-types.html THIS DOES NOT WORK ON SCALA 2.x This is a “wild speculations” slide. Do not quote me on these…
  • 64. What can we do until then though? narrow/widen /** * Narrow the type of this Behavior, which is always a safe operation. */ final def narrow[U <: T]: Behavior[U] = this.asInstanceOf[Behavior[U]]
  • 65. What can we do until then though? narrow/widen /** * Narrow the type of this Behavior, which is always a safe operation. */ final def narrow[U <: T]: Behavior[U] = this.asInstanceOf[Behavior[U]] import akka.actor.typed.scaladsl.Behaviors trait Animal trait Cat extends Animal trait Dog extends Animal trait Capybara extends Animal val doc: Behaviors.Receive[Animal] = Behaviors.receiveMessage[Animal] { msg Behaviors.same } val capyDoc: Behavior[Capybara] = doc.narrow[Capybara]
  • 66. case class InternalProtocol(name: String, replyTo: ActorRef[InternalReply]) case class InternalReply(id: Int) val doc: Behavior[Animal] = Behaviors.receive[AnyRef] { // The “cop out” method case (context, msg: Animal) val registration: ActorRef[InternalProtocol] = context.spawnAnonymous( Behaviors.receiveMessage[InternalProtocol] { case InternalProtocol(name, replyTo) replyTo ! InternalReply(1337) Behaviors.stopped }) registration ! InternalProtocol(msg.getClass.getName, context.self) Behaviors.same case (context, confirmed: InternalReply) // handle “internal” println("Confirmed: " + confirmed.id) Behaviors.same }.narrow[Animal] // exposing still “safely” What can we do until then though? narrow/widen Use narrow to narrow down what types you allow others to send to you.
  • 67. // this doc can only handle Capybaras: val capyDoctor: Behaviors.Receive[Capybara] = Behaviors.receiveMessage[Capybara] { kapi Behaviors.same } val adapting: Behavior[Animal] = capyDoctor.widen[Animal] { case dog: Dog // it's kind of like a capybara... new Capybara { val actually = dog } } // all others => Unhandled We can also “widen” /** * Widen the wrapped Behavior by placing a funnel in front of it: the supplied * PartialFunction decides which message to pull in (those that it is defined * at) and may transform the incoming message to place them into the wrapped * Behavior’s type hierarchy. Signals are not transformed. * * Example: * {{{ * receive[String] { (ctx, msg) => println(msg); same }.widen[Number] { * case b: BigDecimal => s"BigDecimal(&dollar;b)" * case i: BigInteger => s"BigInteger(&dollar;i)" * // drop all other kinds of Number * } * }}} */ def widen[U](matcher: PartialFunction[U, T]): Behavior[U] = BehaviorImpl.widened(behavior, matcher) Use widen to “widen” the set of types you can handle, by adapting them or leaving them unhandled.
  • 68. Behaviors.receive[Internal] { case (context, _) val adapterRef: ActorRef[ExternalProtocol] = context.messageAdapter[ExternalProtocol] { case other if other.isSomething new InternalSomething(other) case other new InternalWrappedOther(other) } // … } Message adapters; “reply to me, and I’ll adapt to my T” Use messageAdapter to create “mini ActorRef” that translates someone’s protocol => your own protocol.
  • 69. def ask[U](message: ActorRef[U] A) (implicit timeout: Timeout, scheduler: Scheduler): Future[U] = ??? def ask[Req, Res](otherActor: ActorRef[Req]) (createRequest: ActorRef[Res] Req) (mapResponse: Try[Res] T) (implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit = ??? Various `ask` patterns Ask received a number of versions, that cut more and more clutter depending on how much context it has available.
  • 70. Behavior[A | B] What can we do until then though? NOT AT ALL PROVEN CRAZY IDEA DON’T TRUST ME ON THIS (YET) // can't do this nowadays: // val all: Behavior[???] = canA orElse canB // nope val all: Behavior[Union2[A, B]] = anyOf(canA, canB) // special behavior impl val allRef: ActorRef[Union2[A, B]] = context.spawn(all, "fake-union") val a: A = ??? val b: B = ??? allRef ! a // implicitly packed as Union2[A, B] allRef ! b // implicitly packed as Union2[A, B] Crazy experiments, could we emulate… https://github.com/akka/akka/issues/25251
  • 71. But… How can an ActorRef[T], receive lifecycle messages…?
  • 72. Messages and Signals val canA: Behaviors.Receive[A] = Behaviors.receiveMessage[A] { msg ??? } canA.receiveSignal { case (context, PostStop) println("I'm dead now...") Behaviors.same } Behaviors.Receive[T] extends Behavior[T]
  • 74. “classic” Abuse of [system|context].actorSelection considered an anti-pattern. Why is that so? (See also “Zen of Akka” talk for more discussion about it) Please don’t overuse actorSelection :-)
  • 75. “classic” Reminder: Sending messages to a “dead” actor results in dead letters.
  • 76. “classic” Note the difference between messages which are unhandled. The actor exists, but did not handle the msg.
  • 77. “classic” actorSelection with “wrong” name also results in dead letters. We don’t even know if this actor ever lived!
  • 78. “classic” Note also that String => ActorRef[T] could never yield the “right T”. We need something: Less error prone and more type-safe. And even more useful… String => ActorRef[T] can’t ever possibly give the right T
  • 80. The Receptionist(think: Grand Budapest Hotel, love that movie…)
  • 84. Receptionist actorSystem.receptionist: ActorRef[Receptionist.Command] ! (command) abstract class Receptionist extends Extension { def ref: ActorRef[Receptionist.Command] } final case class Register[T] private[akka] (key: ServiceKey[T], serviceInstance: ActorRef[T], replyTo: Option[ActorRef[Receptionist.Registered]] ) extends Command final case class Find[T] private[akka] (key: ServiceKey[T], replyTo: ActorRef[Receptionist.Listing] ) extends Command final case class Subscribe[T] private[akka] (key: ServiceKey[T], subscriber: ActorRef[Receptionist.Listing] ) extends Command final case class Listing[T] private[akka] (key: ServiceKey[T], serviceInstances: Set[ActorRef[T]] ) extends Receptionist.Listing
  • 86. Typed Showing both the distributed part and the Subscribe feature here. They are independent though, you could sub locally.
  • 87. Mutable Behavior[T] Your fast-path to type-safety from classic.
  • 88. Moving from Classic to Typed, *EASILY* class ChatRoomBehavior extends Actor { private var sessions: List[ActorRef[SessionCommand]] = List.empty override def receive = { case GetSession(screenName, client) . . . case PublishSessionMessage(screenName, message) . . . } } }
  • 89. Moving from Classic to Typed, *EASILY* class ChatRoomBehavior(ctx: ActorContext[RoomCommand]) extends MutableBehavior[RoomCommand] { private var sessions: List[ActorRef[SessionCommand]] = List.empty override def onMessage(msg: RoomCommand): Behavior[RoomCommand] = { msg match { case GetSession(screenName, client) . . . Behaviors.same case PublishSessionMessage(screenName, message) . . . this } } } class ChatRoomBehavior extends Actor { private var sessions: List[ActorRef[SessionCommand]] = List.empty override def receive { case GetSession(screenName, client) . . . case PublishSessionMessage(screenName, message) . . . } } }
  • 90. “classic” Yes, you can mix-and-match all “styles” of Behaviors. Yes, you can also mix JavaDSL/ScalaDSL — they share the Behavior type. String => ActorRef[T] can’t ever possibly give the right T
  • 92. Meant to: - handle “failures”, not “errors”. - be always-on, hierarchical Is often abused to: - replace try/catch,Try,Either,Validation etc. Not able to express “backoff”: - is implemented as separate BackoffSupervisor “Classic supervision”: always on, in parent actor “classic”Supervision in
  • 93. Declarative, composable supervision val ref = Behaviors.supervise(targetBehavior) .onFailure[SomeException](SupervisorStrategy.restart) Mini DSL for building supervision, which is also “just” a Behavior[T]
  • 94. Declarative, composable supervision val ref = Behaviors.supervise(targetBehavior) .onFailure[SomeException](SupervisorStrategy.restart) supervise( supervise( targetBehavior ).onFailure[Exc2](SupervisorStrategy.resume) ).onFailure[Exc3](SupervisorStrategy.restart) Mini DSL for building supervision, which is also “just” a Behavior[T] Supports nesting , for sharing logic for “common handler” etc
  • 95. New supervision strategies More advanced supervision strategies! SupervisorStrategy .restartWithBackoff(minBackoff, maxBackoff, randomFactor = 0.2) .withResetBackoffAfter(10.seconds) SupervisorStrategy .restartWithLimit( maxNrOfRetries = 3, withinTimeRange = 1.second )
  • 98. Downsides of typedness… Not so suprisingly, more types may mean more “dancing around”, getting the types “right”. You will thank yourself in the future though, once you have to go back and maintain a piece of code :-) Don’t fear dropping to MutableBehavior[T] if it feels right!
  • 99. Flow Control Wouldn’t it be nice if we spent years of work on a flow-control protocol… … and could actually apply it to many areas of Akka…? Extra:
  • 102. Akka Streams …which implement Reactive Streams Typed by default
  • 103. Akka Streams …which implement Reactive Streams Typed by default …which is the async-flow-control standard …which is now also part of JDK9+ (j.u.c.Flow)
  • 104. Fast Publisher will send at-most 3 elements. This is pull-based-backpressure. Reactive Streams: “dynamic push/pull”
  • 105. Akka Streams over Network Typed by default Extra:
  • 106. StreamRefs — new feature in Akka 2.5.10 “Reactive Streams semantics, over network boundaries.”
  • 107. StreamRefs — new feature in Akka 2.5.10 “Reactive Streams semantics, over network boundaries.” “Like ActorRef[T], but for Akka Streams” Very lightweight, and simple.
  • 108. StreamRefs — new feature in Akka 2.5.10 By design NOT a“distributed automatic stream processing deployment and management framework”. (e.g. how Spark, Flink or Beam could be described). Ideal for combining Alpakka Enterprise Integration, Data Processing or Ingestion Pipelines, or back-pressured / flow-controlled messaging between systems.
  • 109. See also, Nitesh Kant, Netflix @ Reactive Summit https://www.youtube.com/watch?v=5FE6xnH5Lak Life without StreamRefs
  • 110. HTTP/1.1 503 Service Unavailable HTTP/1.1 503 Service Unavailable And then: Throttling as represented by 503 responses… Applying circuit breakers… Introducing manual flow control… Life without StreamRefs
  • 112. JVM 2 ActorSystem JVM 1 ActorSystem (special) SinkSource Flow Flow Sink SourceRef StreamRefs — new feature since Akka 2.5.10
  • 113. JVM 2 ActorSystem JVM 1 ActorSystem (special) SinkSource Flow Flow SinkSourceRef This end controls the pace through backpressure StreamRefs — new feature since Akka 2.5.10
  • 114. “origin” side “remote” side .runWith(StreamRefs.sourceRef) run Source and, materialize SourceRef SourceRef Source Arbitrarily complex Source graph .source.runWith(any Sink) Establishes link and demands for elements to be sent to remote side SourceRef send to remote recipient (e.g. via actor messaging) SourceRef — high-level overview
  • 115. SourceRef usage example (prepare) Scala
  • 117. Can we apply this to Actor messaging? Somewhat.
  • 118. Better flow control mechanisms in Typed Actors Could we combine StreamRef semantics + re-delivery… with pre-packaged Behaviors / “companions”…? Experiment here: https://github.com/akka/akka/pull/25099
  • 120. In other news… Artery (UDP, Aeron) transport – soon to become stable Artery TCP+TLS transport – new, soon to become stable Akka Cluster Multi-DC – dc awareness fully supported Akka Multi-DC Persistence* – fully supported multi-dc persistence Typed Persistence – Akka Persistence, but fully typed, soon ready Alpakka (Akka Streams connectors to various tech) 

  • 121. Remoting feature matrix Remoting “classic” Artery Remoting Artery TCP Remoting Protocol TCP TLS+TCP UDP (Aeron) TCP TLS+TCP Large messages Troublesome Dedicated lanes Dedicated connection Heartbeat and System Messages Prioritised Dedicated lanes Dedicated connection Benchmarked* throughput 70k msg/s 700k+ msg/s (up to 1m msg/s) 600k+ msg/s
  • 122. How to use Artery? single option, no new artifacts
  • 123. Artery: ActorRef Compression Compression triggered for “heavy hitters”, so “most chatty” Actors to maximise benefit. Triggers automatically & transparently.
  • 124. Artery: ActorRef / Manifest Compression
  • 125. Artery: ActorRef / Manifest Compression In this case ActorRef compression reduced the size of a small envelope size by 74% - from 162 to 42 bytes (sic!).
  • 128. Monitoring & Tracing Akka Streams MDC, Context, Metrics, Tracing… for Akka Streams (!!!) SOON…
  • 129. Tracing Akka with Jaeger or Zipkin Uber Jaeger Zipkin
  • 130. Tracing Akka with Jaeger or Zipkin Lightbend Monitoring https://developer.lightbend.com/docs/cinnamon/latest/extensions/opentracing.html
  • 131. Tracing across nodes https://developer.lightbend.com/docs/cinnamon/latest/extensions/opentracing.html Tracing transparently across: - Akka Actor messaging
 - Scala Futures
 - Akka HTTP client / server - Akka Streams (!)
  • 132. More Cloud Native-ness / aware-ness Out now: - Multi-Datacenter awareness (OSS) - Multi-Datacenter Replication for Akka Persistence (Commercial) Active new development: - “right and proper” integrations with k8s (Lightbend Orchestration,Akka Management)
  • 134. discuss.akka.io blog.akka.io Docs: https://doc.akka.io/docs/akka/2.5/typed/index.html https://doc.akka.io/docs/akka/2.5/stream/stream-refs.html More resources: https://developer.lightbend.com https://www.lightbend.com/resources Graphics used in presentation: Title slide: https://mastermind31.deviantart.com/art/Minimal-Enomoto-Takane-510564143 All other drawings and pictures — myself (CC 3.0, BY-NC) Further reading…
  • 135. “Zen of Akka”, ScalaDays NYC 2016 Underlying principles, best-practices, some anti-patterns https://www.youtube.com/watch?v=vgFoKOxrTzg Recommended viewing (selfish plug) “The best is yet to come”, Scala Days CPH 2017 How we got here, how one thing inter-ops with another, and roadmap https://www.youtube.com/watch?v=CGyIPVGB2-4 (~200 slides, 50 mins) All slides on https://www.slideshare.net/ktoso (Please give it a day for this slide deck to appear there)
  • 136. ”Why Reactive?”, free ebook, not “sponsored” content :-) Show it off to people new to reactive systems, to get “the idea” behind it. bit.ly/why-reactive Recommended reading (selfish plug)
  • 137. New free Coursera / edx course about Akka Typed & Akka Streams soon! Pre annoucement :-)
  • 138. Happy typed hakking! Konrad `ktoso` Malawski, ktoso@lightbend.com http://kto.so / http://konrad.malaw.ski / @ktosopl Akka docs: akka.io/docs Lake Ashi, Hakone, Japan