Play WSClient, lesson 5: a client layer and calls in parallel
Lesson 4 ended with a helper, getJson, whose future never fails, and controllers that fold an Either[UpstreamError, A] into a response. This lesson does two things with it. It moves the HTTP code out of the controllers into client classes, and it runs upstream calls in parallel. The second part comes down to one rule about Scala futures that I had read many times and only really understood once I measured it.
Stack as before: Play 3.0.12, Scala 2.13, Guice, cats 2.13, with JSONPlaceholder and httpbin as upstreams. The code is commit bd0d6cb in zakariahere/play-wsclient-lessons.
A client layer
A controller should handle the HTTP coming into my API. Talking to an upstream is a different job, so it goes into a clients package. The lesson 4 helper moves into an abstract base class, and each upstream gets a small class that only knows its own URLs:
package object clients {
type Upstream[A] = Future[Either[UpstreamError, A]]
}
abstract class JsonHttp(ws: WSClient)(implicit ec: ExecutionContext) {
protected def getJson[A: Reads](url: String, timeout: FiniteDuration = 5.seconds): Upstream[A] =
??? // unchanged from lesson 4: map on status and shape, recover on exceptions
}
@Singleton
class JsonPlaceholderClient @Inject()(ws: WSClient)(implicit ec: ExecutionContext) extends JsonHttp(ws) {
private val base = "https://jsonplaceholder.typicode.com"
def todo(id: Int): Upstream[Todo] = getJson[Todo](s"$base/todos/$id")
def user(id: Int): Upstream[UserSummary] = getJson[UserSummary](s"$base/users/$id")
def todosFor(userId: Int): Upstream[Seq[Todo]] = getJson[Seq[Todo]](s"$base/todos?userId=$userId")
def postsFor(userId: Int): Upstream[Seq[Post]] = getJson[Seq[Post]](s"$base/posts?userId=$userId")
}The Upstream[A] alias keeps signatures readable. extends JsonHttp(ws) passes the implicit ExecutionContext on without writing it, because the subclass constructor already has one in implicit scope. The error-to-HTTP mapping moved into a plain object UpstreamErrorResults, which imports play.api.mvc.Results._ to get NotFound and BadGateway outside a controller.
The controller now calls jp.todo(1) and never sees a URL. That is also what will make testing straightforward: a fake client can replace the real one without any network. With compile-time DI, which I use at work, the client is one more line in the components class, lazy val jpClient = new JsonPlaceholderClient(wsClient)(executionContext), passed to the controller's constructor.
A future starts when it is created
HttpBinClient.delay(1) calls httpbin.org/delay/1, which answers after about one second. Two endpoints make three of those calls and differ only in where the futures are created:

for does not decide whether calls run in parallel. Where the futures are created does.The sequential version took 3640 ms, and the parallel one 1418 ms, on two separate runs each. A Scala Future is eager: the request is sent as soon as the future exists. The for on the left desugars to bin.delay(1).flatMap(a => bin.delay(1).flatMap(...)), so the second call is only created once the first one has completed. On the right, all three requests are already in flight before the for runs, and the for only waits for results that are already on their way.
The two versions look almost the same, which is why this mistake is easy to make and hard to notice in review. To measure it, I used a small helper with a by-name parameter:
private def timed[A](work: => Future[A]): Future[(A, Long)] = {
val start = System.nanoTime()
work.map(a => (a, (System.nanoTime() - start) / 1000000))
}The => matters. With a plain Future[A] parameter, the futures would be created, and the requests sent, before timed read the clock.
Parallel calls with an Either
The same rule applies with EitherT from lesson 4. A profile endpoint needs a user, their todos and their posts. Creating the three futures first and then combining them with EitherT runs them in parallel:
val fUser = jp.user(id)
val fTodos = jp.todosFor(id)
val fPosts = jp.postsFor(id)
val result = for {
user <- EitherT(fUser)
todos <- EitherT(fTodos)
posts <- EitherT(fPosts)
} yield Json.obj("user" -> user, "openTodos" -> todos.count(!_.completed), "posts" -> posts.size)/par/profile/1 returns the user, 9 open todos and 10 posts. /par/profile/99 still returns a 404 naming /users/99, but there is a trade-off compared with lesson 4. There, the short-circuit meant the second call never ran. Here, all three calls are already sent before the first Left is seen. I get lower latency and pay with calls whose results are thrown away. For cheap reads that is fine. For expensive or rate-limited calls, it is a decision to make on purpose.
Many calls: best effort or all or nothing
For a list of ids, Future.traverse(ids)(f) maps each id to a future and turns the List[Future[X]] into one Future[List[X]]. Every call goes out at once. Because getJson never fails, the list always comes back complete, with the failures included as Left values. That leaves the business rule to me:

// best effort
Future.traverse(ids)(id => jp.todo(id).map(id -> _)).map { results =>
val found = results.collect { case (_, Right(todo)) => todo }
val failed = results.collect { case (id, Left(err)) => Json.obj("id" -> id, "error" -> err.productPrefix) }
Ok(Json.obj("found" -> found, "failed" -> failed))
}
// all or nothing
Future.traverse(ids)(jp.todo).map(_.sequence.fold(toResult, todos => Ok(Json.toJson(todos))))cats' .sequence turns a List[Either[E, A]] into an Either[E, List[A]], and the first Left decides the result. A page that shows what it could load wants the first version. A batch that is only valid when complete wants the second. In the best-effort call, abc did not appear in either list, because toIntOption dropped it while parsing. A real API should probably reject it with a 400 instead.
Bounding parallelism, and a measurement I got wrong
Starting every call at once does not scale to thousands of ids. You hit the upstream's rate limit or exhaust your own connection pool. A simple bound is to run fixed-size batches one after another:
private def inBatches[A, B](items: List[A], size: Int)(f: A => Future[B]): Future[List[B]] =
items.grouped(size).foldLeft(Future.successful(List.empty[B])) { (accF, batch) =>
accF.flatMap(acc => Future.traverse(batch)(f).map(acc ++ _))
}My first measurement of 20 todo calls gave 171 ms with all 20 at once and 120 ms in batches of 5. That looked like a finding: more parallelism, slower. My guess was that 20 simultaneous requests each opened a new TLS connection, while batches of 5 reused 5 pooled connections. Repeating the runs tested that guess, and it also showed that my comparison was unfair:

The first run of 20 took 156 ms, the next two took 30 and 29 ms. The cost was the connection setup, not the parallelism, and my original comparison put a cold run of 20 against a warm run of 5. Batches of 5 also varied a lot, 121 and 350 ms, because each batch waits for its slowest call before the next one starts. So the reason to bound parallelism is to protect the upstream and the connection pool, not speed, and benchmarks belong on a warm pool. A sliding window that keeps n calls in flight avoids the slowest-call wait. Pekko Streams' mapAsync provides that, and it will come back in a later lesson.
What I take from lesson 5
- Clients own URLs, timeouts and status handling. Controllers only translate the result into a response.
- A
Futurestarts when it is created. To run calls in parallel, create the futures before thefor. - Parallel calls combined with
EitherTstill give the right error, but no longer save the calls that come after it. Future.traversefires everything at once. Choose between best effort and.sequencebased on the business rule.- Bound parallelism to protect the upstream, and measure on a warm connection pool before drawing conclusions.
Next: configuration and cross-cutting concerns. Base URLs and timeouts move into application.conf, and a WSRequestFilter logs every outgoing call with its duration.