Field Notes

Scala: Part 17: traverse and sequence, One Rung at a Time

Scala: Part 17: traverse and sequence, One Rung at a Time

After Part 16, map, flatMap and recover on a single Future felt solid. Then I needed a list of Futures, and Future.traverse and Future.sequence stopped me cold. I read the signatures several times and they still did not stick.

What finally worked was a ladder: one tiny lookup, and one new idea per rung. Each rung had to make sense before I climbed to the next one. This post is that ladder, with the code and output from the sbt project I used.

The setup: one lookup that takes a second

Three users in a map, and a lookup that sleeps for a second to pretend it is a remote call. An unknown id fails the Future.

final case class User(id: Int, name: String)

object Main {
  private val db = Map(1 -> User(1, "Bob"), 2 -> User(2, "Zakaria"), 3 -> User(3, "Jean"))

  def getUserById(id: Int): Future[User] = Future {
    Thread.sleep(1000)
    db.getOrElse(id, throw new NoSuchElementException(s"no user $id"))
  }
}

My first version used Future.successful { Thread.sleep(1000); ... }. It compiled, it returned the right users, and it was quietly wrong. I come back to that on rung 3.

One more trap from the setup: I started with object Main extends App. When the tests called Main.getUserById, db was null, because the body of an App only runs when main runs. A plain def main(args: Array[String]) fixed it.

Rung 1: map gives the wrong shape

Mapping the lookup over a list of ids gives me a List[Future[User]]: three separate Futures. What I want is one Future that completes with the whole list. sequence turns the shape inside out, and traverse does the map and the flip in one call.

val ids = List(1, 2, 3)

val futures: List[Future[User]]     = ids.map(getUserById)
val viaSequence: Future[List[User]] = Future.sequence(futures)
val viaTraverse: Future[List[User]] = Future.traverse(ids)(getUserById)
Diagram: List[Int] mapped to List[Future[User]], then sequence turns it into Future[List[User]]
sequence starts from Futures you already have; traverse starts from the ids and the function.

Both print List(User(1,Bob), User(2,Zakaria), User(3,Jean)). The sentence I kept for myself is that traverse(xs)(f) is the same as sequence(xs.map(f)).

Rung 2: one failure fails the whole list

With List(1, 99, 2), user 99 does not exist. The result is not a list with a gap. The whole Future[List[User]] fails with NoSuchElementException: no user 99, and Bob and Zakaria are discarded even though their lookups succeeded.

My first attempt at handling it taught me more than the correct one. I put recover inside getUserById, so each lookup repaired itself before traverse ever saw a failure. The output was List(Bob, User(99,User not found), Zakaria). That is valid code, but I never saw the failure I was trying to study.

Moving recover onto the result of traverse shows the all-or-nothing behaviour. The fallback must have the same type as the Future, so it returns an empty List[User]:

val unknownUser = Future.traverse(List(1, 99, 2))(getUserById)
  .recover {
    case e: NoSuchElementException =>
      println(s"Could not load users: ${e.getMessage}")
      List.empty[User]
  }
// Could not load users: no user 99
// List()
Comparison of recover inside getUserById versus recover on the traverse result
Neither placement is wrong. They answer different questions: partial results, or all or nothing.

Rung 3: traverse does not make anything parallel

I added timing around the traverse call and printed Thread.currentThread().getName inside the lookup. Three one-second lookups finished in 1002 ms on three different threads from the global pool.

I had assumed that traverse runs the Futures in parallel. It does not. A Scala Future starts running when it is created, and Future { ... } hands the work to the ExecutionContext immediately. traverse calls the function for each id, which starts each Future, and then combines the results. In rung 1, ids.map(getUserById) had already started all three Futures before Future.sequence was called.

To check that, I ran the same Future.traverse call with my original Future.successful version:

def eager(id: Int): Future[Int] = Future.successful {
  Thread.sleep(1000)
  println(Thread.currentThread().getName)
  id
}
// main
// main
// main
// List(1, 2, 3) in 3087ms

Future.successful takes a value that is already computed, so Scala evaluates the block, sleep included, on the calling thread before the Future exists. traverse cannot parallelise work that has already happened. By the same reasoning, Future { ... } on the single-thread executor from Part 16 would also run the three lookups one after another.

Timing comparison: 1002 ms across three pool threads versus 3087 ms on the main thread
Same traverse call, different Future constructor. The parallelism comes from where the work is started.

Rung 4: the same shape with Option

Nothing about this is specific to Future. A lookup that returns Option[User] has the same problem after map: List[Option[User]] where I want Option[List[User]]. The Scala standard library only ships traverse and sequence for Future, so I added "org.typelevel" %% "cats-core" % "2.13.0", which provides them as methods for any supported wrapper type.

import cats.implicits._

def findUserById(id: Int): Option[User] = db.get(id)

ids.map(findUserById)                  // List(Some(Bob), Some(Zakaria), Some(Jean))
ids.map(findUserById).sequence         // Some(List(Bob, Zakaria, Jean))
ids.traverse(findUserById)             // Some(List(Bob, Zakaria, Jean))
List(1, 99, 2).traverse(findUserById)  // None

The rule is the same as rung 2: one miss and the result is None. Only the failure representation changes. A Future fails with an exception; an Option becomes None, with no exception and nothing to recover from.

Rung 5: writing traverse myself

The last rung was to remove the library and write it. For Option it is a short recursion: handle the first element, traverse the rest, and combine the two only if both succeeded.

def myTraverse[A](ids: List[A])(f: A => Option[User]): Option[List[User]] =
  ids match {
    case Nil => Some(Nil)
    case head :: tail =>
      (f(head), myTraverse(tail)(f)) match {
        case (Some(user), Some(users)) => Some(user :: users)
        case _                         => None
      }
  }

def mySequence(options: List[Option[User]]): Option[List[User]] =
  myTraverse(options)(identity)

Two details carry the whole behaviour. Nil => Some(Nil) says that an empty list is a success, because nothing failed; if it returned None, every call would end as None. The single case _ => None is the all-or-nothing rule from rung 2. And sequence is traverse with identity: the elements are already Options, so the function has nothing to do. My versions printed exactly what Cats printed.

What I would tell myself before starting

  • Shape: sequence turns List[F[A]] into F[List[A]]; traverse is map followed by sequence.
  • Failure: one failure fails the whole result. Where you put recover chooses between partial results and all or nothing.
  • Timing: the parallelism comes from Future { ... } starting on the execution context, not from traverse.
  • Generality: the same shape works for Option, Either and other wrappers; Cats provides it outside Future.

If a concept will not stick, the thing that helped me was not a better explanation. It was a smaller example with one new idea per rung.

Keep reading