Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Akka Stream: Map And MapAsync

DZone 's Guide to

Akka Stream: Map And MapAsync

We take a look at two methods of using Akka Streams to query big data sets, and explain why one is more performant than the other.

· Big Data Zone ·
Free Resource

Akka Streams

In this post, we will discuss what are “map” and “mapAsync” when used in the Akka stream and how to use them.

The difference is highlighted in their signatures:-

Flow.map takes in a function that returns a type T, while

Flow.mapAsync takes in a function that returns a type Future[T].

Let’s take one practical example to understand both:

Problem – Suppose we have a student ID and we want to fetch the student details from some database based on their student ID number.

Let’s start with solving the problem which may not be the most efficient solution.

package com.example.stream

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._

case class UserID(id:String)

object StudentDetails extends App {

  implicit val actorSystem: ActorSystem = ActorSystem("akka-streams-example")
  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val userIDSource: Source[UserId, NotUsed] = Source(List(UserID("id1")))

  val stream =
    userIDSource.via(Flow[UserID].map(getFromDatabase))
      .to(Sink.foreach(println))
      .run()

  def getFromDatabase(userID: UserID): String =
  {
    userId.id match {
      case "id1" => "piyush"
      case "id2" => "girish"
      case "id3" => "vidisha"
      case _ => "anuj"
    }
  }
}

Possible Solution – Given an Akka stream source of UserID values, we could use Flow.map within a stream to query the database and print the student's full name to the console.

This is a simple stream but it's not such an efficient solution to the problem.

One limitation that I can think of in this approach is that this stream will only make one database query at a time. Thus, the serial querying will become a “bottleneck” and will surely prevent maximum throughput in our stream.

We could try to improve performance through concurrent queries using a Future:

val userIDSource: Source[UserID, NotUsed] = Source(List(UserID("id1"),UserID("id2")))

val stream =
  userIDSource.via(Flow[UserID].map(concurrentDBLookup))
    .to(Sink.foreach[Future[String]](_ foreach println))
      .run()

def concurrentDBLookup(userID : UserID) : Future[String] =
  Future { getFromDatabase(userID) }

Though we have effectively removed the backpressure by making the Sink pull in the Future and add a foreach println, which is relatively fast compared to database queries.

But now the streams will continuously propagate demand to the Source and spawn off more  Futures inside ofFlow.map. Therefore, there is no limit to the number of database lookup functions running concurrently. Hence, we have made our program slower, as unrestricted parallel querying could eventually overload the database.

Solution: We can use the Flow.mapAsync method to help here. We can create concurrent database access while, at the same time, limiting the number of simultaneous lookups. 

val maxLookupCount = 10

val maxLookupConcurrentStream = 
  userIDSource.via(Flow[UserID].mapAsync(maxLookupCount)(concurrentDBLookup))
              .to(Sink.foreach(println))
              .run()

Also, notice that Sink.foreachhas again become simpler, it no longer takes in a Future but just the result instead.

Unordered Async Map

If maintaining a sequential order of User IDs to Names is unnecessary then you can use Flow.mapAsyncUnordered. For example, you just need to print all of the names to the console but didn’t care about the order they were printed.

Topics:
akka actors ,async ,big data ,scala tutorial ,akka streams tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}