Actors interop


To use Akka Streams, add the module to your project:

val AkkaVersion = "2.6.9"
libraryDependencies += "com.typesafe.akka" %% "akka-stream" % AkkaVersion
versions += [
  AkkaVersion: "2.6.9",
  ScalaBinary: "2.13"
dependencies {
  compile group: 'com.typesafe.akka', name: "akka-stream_${versions.ScalaBinary}", version: versions.AkkaVersion


There are various use cases where it might be reasonable to use actors and streams together:

  • when integrating existing API’s that might be streams- or actors-based.
  • when there is any mutable state that should be shared across multiple streams.
  • when there is any mutable state or logic that can be influenced ‘from outside’ while the stream is running.

For piping the elements of a stream as messages to an ordinary actor you can use ask in a mapAsync or use Sink.actorRefWithBackpressure.

Messages can be sent to a stream with Source.queue or via the ActorRef that is materialized by Source.actorRef.

Additionally you can use ActorSource.actorRef, ActorSource.actorRefWithBackpressure, ActorSink.actorRef and ActorSink.actorRefWithBackpressure shown below.


A nice way to delegate some processing of elements in a stream to an actor is to use ask. The back-pressure of the stream is maintained by the FutureCompletionStage of the ask and the mailbox of the actor will not be filled with more messages than the given parallelism of the ask operator (similarly to how the mapAsync operator works).

implicit val askTimeout = Timeout(5.seconds)
val words: Source[String, NotUsed] =
  Source(List("hello", "hi"))

  .ask[String](parallelism = 5)(ref)
  // continue processing of the replies from the actor
Source<String, NotUsed> words = Source.from(Arrays.asList("hello", "hi"));
Timeout askTimeout = Timeout.apply(5, TimeUnit.SECONDS);

    .ask(5, ref, String.class, askTimeout)
    // continue processing of the replies from the actor
    .map(elem -> elem.toLowerCase())
    .runWith(Sink.ignore(), system);

Note that the messages received in the actor will be in the same order as the stream elements, i.e. the parallelism does not change the ordering of the messages. There is a performance advantage of using parallelism > 1 even though the actor will only process one message at a time because then there is already a message in the mailbox when the actor has completed previous message.

The actor must reply to the sender()getSender() for each message from the stream. That reply will complete the FutureCompletionStage of the ask and it will be the element that is emitted downstreams.

In case the target actor is stopped, the operator will fail with an AskStageTargetActorTerminatedException

class Translator extends Actor {
  def receive = {
    case word: String =>
      // ... process message
      val reply = word.toUpperCase
      sender() ! reply // reply to the ask
static class Translator extends AbstractActor {
  public Receive createReceive() {
    return receiveBuilder()
            word -> {
              // ... process message
              String reply = word.toUpperCase();
              // reply to the ask
              getSender().tell(reply, getSelf());

The stream can be completed with failure by sending as reply from the actor.

If the ask fails due to timeout the stream will be completed with TimeoutException failure. If that is not desired outcome you can use recover on the ask FutureCompletionStage, or use the other “restart” operators to restart it.

If you don’t care about the reply values and only use them as back-pressure signals you can use Sink.ignore after the ask operator and then actor is effectively a sink of the stream.

Note that while you may implement the same concept using mapAsync, that style would not be aware of the actor terminating.

If you are intending to ask multiple actors by using Actor routers, then you should use mapAsyncUnordered and perform the ask manually in there, as the ordering of the replies is not important, since multiple actors are being asked concurrently to begin with, and no single actor is the one to be watched by the operator.


The sink sends the elements of the stream to the given ActorRef that sends back back-pressure signal. First element is always onInitMessage, then stream is waiting for the given acknowledgement message from the given actor which means that it is ready to process elements. It also requires the given acknowledgement message after each stream element to make back-pressure work.

If the target actor terminates the stream will be cancelled. When the stream is completed successfully the given onCompleteMessage will be sent to the destination actor. When the stream is completed with failure a message will be sent to the destination actor.

val words: Source[String, NotUsed] =
  Source(List("hello", "hi"))

// sent from actor to stream to "ack" processing of given element
val AckMessage = AckingReceiver.Ack

// sent from stream to actor to indicate start, end or failure of stream:
val InitMessage = AckingReceiver.StreamInitialized
val OnCompleteMessage = AckingReceiver.StreamCompleted
val onErrorMessage = (ex: Throwable) => AckingReceiver.StreamFailure(ex)

val probe = TestProbe()
val receiver = system.actorOf(Props(new AckingReceiver(probe.ref, ackWith = AckMessage)))
val sink = Sink.actorRefWithBackpressure(
  onInitMessage = InitMessage,
  ackMessage = AckMessage,
  onCompleteMessage = OnCompleteMessage,
  onFailureMessage = onErrorMessage)

probe.expectMsg("Stream initialized!")
probe.expectMsg("Stream completed!")
Source<String, NotUsed> words = Source.from(Arrays.asList("hello", "hi"));

final TestKit probe = new TestKit(system);

ActorRef receiver = system.actorOf(Props.create(AckingReceiver.class, probe.getRef()));

Sink<String, NotUsed> sink =
        new StreamInitialized(),
        new StreamCompleted(),
        ex -> new StreamFailure(ex)); -> el.toLowerCase()).runWith(sink, system);

probe.expectMsg("Stream initialized");
probe.expectMsg("Stream completed");

The receiving actor would then need to be implemented similar to the following:

object AckingReceiver {
  case object Ack

  case object StreamInitialized
  case object StreamCompleted
  final case class StreamFailure(ex: Throwable)

class AckingReceiver(probe: ActorRef, ackWith: Any) extends Actor with ActorLogging {
  import AckingReceiver._

  def receive: Receive = {
    case StreamInitialized =>"Stream initialized!")
      probe ! "Stream initialized!"
      sender() ! Ack // ack to allow the stream to proceed sending more elements

    case el: String =>"Received element: {}", el)
      probe ! el
      sender() ! Ack // ack to allow the stream to proceed sending more elements

    case StreamCompleted =>"Stream completed!")
      probe ! "Stream completed!"
    case StreamFailure(ex) =>
      log.error(ex, "Stream failed!")
enum Ack {

static class StreamInitialized {}

static class StreamCompleted {}

static class StreamFailure {
  private final Throwable cause;

  public StreamFailure(Throwable cause) {
    this.cause = cause;

  public Throwable getCause() {
    return cause;

static class AckingReceiver extends AbstractLoggingActor {

  private final ActorRef probe;

  public AckingReceiver(ActorRef probe) {
    this.probe = probe;

  public Receive createReceive() {
    return receiveBuilder()
            init -> {
              log().info("Stream initialized");
              probe.tell("Stream initialized", getSelf());
              sender().tell(Ack.INSTANCE, self());
            element -> {
              log().info("Received element: {}", element);
              probe.tell(element, getSelf());
              sender().tell(Ack.INSTANCE, self());
            completed -> {
              log().info("Stream completed");
              probe.tell("Stream completed", getSelf());
            failed -> {
              log().error(failed.getCause(), "Stream failed!");
              probe.tell("Stream failed!", getSelf());

Note that replying to the sender of the elements (the “stream”) is required as lack of those ack signals would be interpreted as back-pressure (as intended), and no new elements will be sent into the actor until it acknowledges some elements. Handling the other signals while is not required, however is a good practice, to see the state of the streams lifecycle in the connected actor as well. Technically it is also possible to use multiple sinks targeting the same actor, however it is not common practice to do so, and one should rather investigate using a Merge operator for this purpose.


Using Sink.actorRef or ordinary tell from a map or foreach operator means that there is no back-pressure signal from the destination actor, i.e. if the actor is not consuming the messages fast enough the mailbox of the actor will grow, unless you use a bounded mailbox with zero mailbox-push-timeout-time or use a rate limiting operator in front. It’s often better to use Sink.actorRefWithBackpressure or ask in mapAsync, though.


Source.queue is an improvement over Sink.actorRef, since it can provide backpressure. The offer method returns a FutureCompletionStage, which completes with the result of the enqueue operation.

Source.queue can be used for emitting elements to a stream from an actor (or from anything running outside the stream). The elements will be buffered until the stream can process them. You can offer elements to the queue and they will be emitted to the stream if there is demand from downstream, otherwise they will be buffered until request for demand is received.

Use overflow strategy to avoid dropping of elements if the buffer is full, instead the returned FutureCompletionStage does not complete until there is space in the buffer and offer should not be called again until it completes.

Using Source.queue you can push elements to the queue and they will be emitted to the stream if there is demand from downstream, otherwise they will be buffered until request for demand is received. Elements in the buffer will be discarded if downstream is terminated.

You could combine it with the throttle operator is used to slow down the stream to 5 element per 3 seconds and other patterns.

SourceQueue.offer returns Future[QueueOfferResult]CompletionStage<QueueOfferResult> which completes with QueueOfferResult.Enqueued if element was added to buffer or sent downstream. It completes with QueueOfferResult.Dropped if element was dropped. Can also complete with QueueOfferResult.Failure - when stream failed or QueueOfferResult.QueueClosed when downstream is completed.

val bufferSize = 10
val elementsToProcess = 5

val queue = Source
  .queue[Int](bufferSize, OverflowStrategy.backpressure)
  .throttle(elementsToProcess, 3.second)
  .map(x => x * x)
  .toMat(Sink.foreach(x => println(s"completed $x")))(Keep.left)

val source = Source(1 to 10)

implicit val ec = system.dispatcher
  .mapAsync(1)(x => {
    queue.offer(x).map {
      case QueueOfferResult.Enqueued    => println(s"enqueued $x")
      case QueueOfferResult.Dropped     => println(s"dropped $x")
      case QueueOfferResult.Failure(ex) => println(s"Offer failed ${ex.getMessage}")
      case QueueOfferResult.QueueClosed => println("Source Queue closed")
int bufferSize = 10;
int elementsToProcess = 5;

SourceQueueWithComplete<Integer> sourceQueue =
    Source.<Integer>queue(bufferSize, OverflowStrategy.backpressure())
        .throttle(elementsToProcess, Duration.ofSeconds(3))
        .map(x -> x * x)
        .to(Sink.foreach(x -> System.out.println("got: " + x)))

Source<Integer, NotUsed> source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); -> sourceQueue.offer(x)).runWith(Sink.ignore(), system);

When used from an actor you typically pipe the result of the FutureCompletionStage back to the actor to continue processing.


Messages sent to the actor that is materialized by Source.actorRef will be emitted to the stream if there is demand from downstream, otherwise they will be buffered until request for demand is received.

Depending on the defined OverflowStrategy it might drop elements if there is no space available in the buffer. The strategy OverflowStrategy.backpressure is not supported for this Source type, i.e. elements will be dropped if the buffer is filled by sending at a rate that is faster than the stream can consume. You should consider using Source.queue if you want a backpressured actor interface.

The stream can be completed successfully by sending to the actor reference. If the content is the completion will be signaled immediately. If the content is already buffered elements will be signaled before signaling completion. Any other content will be ignored and fall back to the draining behaviour.

The stream can be completed with failure by sending to the actor reference.

Note: Sending a PoisonPill is deprecated and will be ignored in the future.

The actor will be stopped when the stream is completed, failed or cancelled from downstream, i.e. you can watch it to get notified when that happens.

val bufferSize = 10

val cm: PartialFunction[Any, CompletionStrategy] = {
  case Done =>

val ref = Source
    completionMatcher = cm,
    failureMatcher = PartialFunction.empty[Any, Throwable],
    bufferSize = bufferSize,
    overflowStrategy = // note: backpressure is not supported
  .map(x => x * x)
  .toMat(Sink.foreach((x: Int) => println(s"completed $x")))(Keep.left)

ref ! 1
ref ! 2
ref ! 3
ref ! Done
int bufferSize = 10;

Source<Integer, ActorRef> source =
        elem -> {
          // complete stream immediately if we send it Done
          if (elem == Done.done()) return Optional.of(CompletionStrategy.immediately());
          else return Optional.empty();
        // never fail the stream because of a message
        elem -> Optional.empty(),
        OverflowStrategy.dropHead()); // note: backpressure is not supported
ActorRef actorRef =
        .map(x -> x * x)
        .to(Sink.foreach(x -> System.out.println("got: " + x)))

actorRef.tell(1, ActorRef.noSender());
actorRef.tell(2, ActorRef.noSender());
actorRef.tell(3, ActorRef.noSender());
    new, ActorRef.noSender());


Materialize an ActorRef<T>ActorRef[T]; sending messages to it will emit them on the stream only if they are of the same type as the stream.


Materialize an ActorRef<T>ActorRef[T]; sending messages to it will emit them on the stream. The source acknowledges reception after emitting a message, to provide back pressure from the source.


Sends the elements of the stream to the given ActorRef<T>ActorRef[T], without considering backpressure.


Sends the elements of the stream to the given ActorRef<T>ActorRef[T] with backpressure, to be able to signal demand when the actor is ready to receive more elements.

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.