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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Tracking Changes in MongoDB With Scala and Akka
  • What Is a Streaming Database?
  • Streaming in Mule
  • AWS Serverless Data Lake: Built Real-time Using Apache Hudi, AWS Glue, and Kinesis Stream

Trending

  • Chaos Engineering for Microservices
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  • Why Documentation Matters More Than You Think
  • A Modern Stack for Building Scalable Systems
  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.

By 
Piyush Rana user avatar
Piyush Rana
·
Updated Mar. 29, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
14.2K 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.

Related

  • Tracking Changes in MongoDB With Scala and Akka
  • What Is a Streaming Database?
  • Streaming in Mule
  • AWS Serverless Data Lake: Built Real-time Using Apache Hudi, AWS Glue, and Kinesis Stream

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!