DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Akka Stream: Map And MapAsync

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.

Piyush Rana user avatar by
Piyush Rana
·
Mar. 29, 19 · Tutorial
Like (5)
Save
Tweet
Share
13.47K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Stream (computing) Akka (toolkit) Database

Published at DZone with permission of Piyush Rana. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Deploying Prometheus and Grafana as Applications using ArgoCD — Including Dashboards
  • What Is Enterprise Portal and How to Develop One?
  • What Is API-First?
  • MongoDB Time Series Benchmark and Review

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: