Field Notes

Play WSClient, lesson 4: when the upstream does not answer

Play WSClient, lesson 4: when the upstream does not answer

Up to lesson 3, every failure I handled was a polite one: the upstream answered, just with a 404 or a body that did not fit my model. Real upstreams are ruder. They are slow, their hostname does not resolve, or nothing listens on the port. This lesson handles those cases with Play's WSClient, and it ends with controllers that no longer nest a match inside a match for every call.

Stack as before: Play 3.0.12, Scala 2.13, Guice, cats 2.13. The upstreams are JSONPlaceholder and httpbin, which can delay a response or return any status on demand. The code is commit b45bc01 in zakariahere/play-wsclient-lessons.

Two kinds of failure

ws.url(...).get() returns a Future[WSResponse], and it can go wrong in two different ways. If the server answers, the future succeeds, whatever the status. A 500 is a successful future holding a response that says the upstream is broken. Only when there is no answer at all, because of a timeout, a DNS failure or a refused connection, does the future itself fail with an exception.

Two columns. The Future succeeds when the server answered: 200 with fitting JSON gives Right, 200 with wrong JSON gives Left BadShape, 404 gives Left Missing, 500 or 429 gives Left BadStatus, handled with map. The Future fails when there is no answer: TimeoutException gives Left TimedOut, UnknownHostException and ConnectException give Left Unreachable, handled with recover.
map deals with bad answers, recover with missing ones. Both end in the same type.

Lessons 1 to 3 only covered the left column. A failed future went straight to Play's error handler and came out as a 500, which tells my caller that my service is broken when the real problem is one hop further away.

A sealed error model

sealed trait UpstreamError extends Product with Serializable

object UpstreamError {
  final case class Missing(url: String)                     extends UpstreamError
  final case class BadStatus(status: Int, body: String)     extends UpstreamError
  final case class BadShape(details: JsObject)              extends UpstreamError
  final case class TimedOut(url: String)                    extends UpstreamError
  final case class Unreachable(url: String, reason: String) extends UpstreamError
}

sealed means every subtype lives in this file, so the compiler knows the complete list and warns when a match misses a case. Add a sixth error later and every incomplete match shows up at compile time. extends Product with Serializable keeps Scala 2 from inferring Product with Serializable with UpstreamError when cases are mixed in one expression. I avoided names like NotFound on purpose: inside a controller that name is already a Play Result.

One helper whose future never fails

private def getJson[A: Reads](url: String,
                              timeout: FiniteDuration = 5.seconds): Future[Either[UpstreamError, A]] =
  ws.url(url)
    .withRequestTimeout(timeout)
    .get()
    .map[Either[UpstreamError, A]] { r =>
      r.status match {
        case OK =>
          r.json.validate[A] match {
            case JsSuccess(a, _) => Right(a)
            case e: JsError      => Left(BadShape(JsError.toJson(e)))
          }
        case NOT_FOUND => Left(Missing(url))
        case other     => Left(BadStatus(other, r.body.take(200)))
      }
    }
    .recover {
      case _: TimeoutException     => Left(TimedOut(url))
      case e: ConnectException     => Left(Unreachable(url, s"connect: ${e.getMessage}"))
      case e: UnknownHostException => Left(Unreachable(url, s"dns: ${e.getMessage}"))
      case NonFatal(e)             => Left(Unreachable(url, s"${e.getClass.getSimpleName}: ${e.getMessage}"))
    }

map covers the answered cases, with the status checked before the shape as in lesson 2. recover turns each exception into a value. The explicit type on .map[Either[UpstreamError, A]] gives recover a clear type to stay within, which avoids the same widening trap that cost me a compile error in lesson 3. NonFatal catches ordinary exceptions and lets fatal JVM errors such as OutOfMemoryError through.

Translating errors into HTTP happens in exactly one function:

private def toResult(error: UpstreamError): Result = error match {
  case Missing(url)             => NotFound(Json.obj("error" -> "not_found", "upstream" -> url))
  case BadStatus(status, body)  => BadGateway(Json.obj("error" -> "bad_status", "upstreamStatus" -> status, "upstreamBody" -> body))
  case BadShape(details)        => BadGateway(Json.obj("error" -> "bad_shape", "details" -> details))
  case TimedOut(url)            => GatewayTimeout(Json.obj("error" -> "timeout", "upstream" -> url))
  case Unreachable(url, reason) => BadGateway(Json.obj("error" -> "unreachable", "upstream" -> url, "reason" -> reason))
}

def todo(id: Int): Action[AnyContent] = Action.async {
  getJson[Todo](s"$baseUrl/todos/$id").map(_.fold(toResult, t => Ok(Json.toJson(t))))
}

Every endpoint is now .map(_.fold(toResult, ...)). I added one endpoint per failure: a two-second timeout against httpbin.org/delay/5, the reserved .invalid TLD for DNS, localhost:1 for a refused connection, httpbin.org/status/{code}, and a user decoded as a Todo for a wrong shape. These are the real results:

Measured results: todo/9999 Missing 404; slow TimedOut 504 after 2.04 seconds; nohost Unreachable 502 with dns No such host is known; refused Unreachable 502 with connect Connection refused; status/500 BadStatus 502; shape BadShape 502 with userId, title and completed missing; dashboard/99 Missing 404 stopped at users/99.
Each failure gets its own name, and toResult picks its status.

The timeout came back after 2.04 seconds, not five. Both ConnectException and UnknownHostException reached their own cases rather than the NonFatal fallback, which I had not been sure of before running it.

recover and recoverWith

The difference is the same as between map and flatMap. recover takes a Throwable => A and replaces the failure with a value. recoverWith takes a Throwable => Future[A] and replaces it with another asynchronous call:

ws.url("https://httpbin.org/delay/5").withRequestTimeout(2.seconds).get()
  .recoverWith { case _: TimeoutException => ws.url(s"$baseUrl/todos/1").get() }
  .map(r => Ok(Json.obj("servedBy" -> r.uri.getHost, "body" -> r.json)))

This answered 200 after 2.12 seconds with servedBy: jsonplaceholder.typicode.com: two seconds waiting for the slow upstream, then a fast fallback.

Chaining calls with EitherT

The model pays off when one endpoint needs several calls. Chaining two Future[Either[...]] values by hand means a flatMap with a Left case to forward at every step. cats' EitherT wraps both layers so one for-comprehension handles them:

Left: nested flatMap with case Left and case Right for two calls. Right: a for-comprehension over EitherT of getJson for the user and the todos, then result.value.map with fold toResult.
EitherT waits on the future and unwraps the Either. The first Left ends the chain.

/errors/dashboard/1 returns the user and a count of 9 open todos. /errors/dashboard/99 returns 404, and the error names /users/99: the first call failed, so the todos call never ran. No extra cats import was needed. Since cats 2.2 the Future instances are found automatically, as long as an implicit ExecutionContext is in scope.

Who waits during a timeout?

While the slow call is in flight, no Play thread is blocked. The request goes to AsyncHttpClient, whose few Netty event-loop threads watch every open socket through one selector. A timer owned by the client holds the two-second deadline. When it fires, it fails the promise behind the future, and my recover runs on Play's ExecutionContext. Until then, the future is just a stored list of callbacks with no thread attached.

To check this, I sent ten /errors/slow requests at once. They did not queue: each took about two seconds. The run also gave me an unplanned result. Three of the ten came back within 0.4 seconds as bad_status, because httpbin answered with a 429 and a message saying its limit is four slow requests per second per client IP, with a retry after one second. The error model reported it accurately instead of folding it into a timeout. Next, I will carry the Retry-After header through BadStatus and map 429 to a 503.

Do not return upstream details in production

The JSON bodies above include upstream URLs, upstream bodies and exception messages. That is useful while learning, and in a banking context it is a leak of internal topology and possibly of upstream data. The production version logs the full UpstreamError with a correlation id and returns a generic body to the client. Because every error goes through toResult, that change touches one function.

What I take from lesson 4

  • A response with a bad status is a successful future. Only a missing answer fails it.
  • Make the helper's future never fail: map and recover both produce Either[UpstreamError, A].
  • Map errors to HTTP status codes in one function, and let sealed make the compiler check that every case is handled.
  • recover gives a value, recoverWith gives another call.
  • EitherT chains calls that can each fail, and it stops at the first failure.
  • Nothing blocks while waiting. The Netty event loop and a timer handle it.

Next: moving getJson out of the controller into a proper client class, and running calls in parallel instead of one after another.

Keep reading