How to Call Other Services Reliably with the Client
In this guide, we take a ZIO HTTP Client that calls another service and make it hold up when that service misbehaves. By the end, you will have one client that logs every request, gives up on a request that takes too long, sends a request again when the service answers with a 5xx status or does not answer in time, and keeps a sized pool of connections to the service.
We build the client one concern at a time: logging first, so we can watch the later steps work, then a timeout, then retries, then the connection pool. The last section puts all four into one small client class.
The Problem
A service that calls another service over HTTP inherits that service's bad moments. A deploy restarts it and it answers 503 Service Unavailable for a few seconds; a slow database query keeps a request open for half a minute; a burst of traffic opens hundreds of connections at once. If the calling code sends each request once, with no time limit, one slow call holds a fiber and a connection until the remote side gives up, and one 503 becomes an error for your own user even though the next attempt a moment later would have worked.
Handling this by hand means a loop around every call. With the JDK's own HTTP client, a call with a timeout and three retries looks like this:
import java.net.URI
import java.net.http.{HttpClient, HttpRequest, HttpResponse}
import java.time.Duration
val http = HttpClient.newHttpClient()
def getStock(sku: String): String = {
val request =
HttpRequest
.newBuilder(URI.create(s"http://inventory.internal/stock/$sku"))
.timeout(Duration.ofSeconds(5))
.build()
var attempt = 0
var delayMillis = 100L
var result: String = null
var lastError: Throwable = null
while (result == null && attempt < 4) {
attempt += 1
try {
val response = http.send(request, HttpResponse.BodyHandlers.ofString())
if (response.statusCode() >= 500) lastError = new RuntimeException(s"server answered ${response.statusCode()}")
else result = response.body()
} catch {
case e: java.io.IOException => lastError = e
}
if (result == null && attempt < 4) {
Thread.sleep(delayMillis)
delayMillis *= 2
}
}
if (result == null) throw lastError
result
}
The retry policy, the backoff, the status check and the logging (still missing here) are tangled with the call itself, so every other call to every other service copies the loop, and the copies drift: one retries 404, another forgets the backoff, a third blocks a thread in Thread.sleep.
With ZIO HTTP, each concern is a separate value: a client aspect for logging, ZIO#timeoutFail for the timeout, a Schedule for the retry policy and a ZClient.Config for the pool. The request code stays one line.
Prerequisites
Everything in this guide is in the core module:
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"
The snippets use these imports:
import java.util.concurrent.TimeoutException
import zio._
import zio.http._
This guide assumes you can send a request with Client#batched and provide Client.default. If not, start with the Client reference page.
The Service We Call
The runnable examples call a small inventory service that runs in the same program, on any open port, so they work without network access. It has three endpoints, each standing in for one kind of bad moment:
GET /stock/<sku>answers503 Service Unavailableto the first two requests it receives, then200 OKwith a stock count, like a service that is restarting.GET /slowwaits thirty seconds before it answers, like a service stuck on a slow query.GET /prices/<sku>waits 200 milliseconds before it answers, like a healthy service under load.
InventoryService.start installs these routes on the Server in the environment and returns the service's base URL, such as http://localhost:38291. The snippets below take that URL as baseUrl. You can read the service in InventoryService.scala, which each runnable block below includes.
Logging Each Request with ZClientAspect.requestLogging
Before we change how the client behaves, we make it tell us what it does. ZClientAspect.requestLogging is a client aspect: a value that we attach to a client with @@, and that wraps every request the client sends. It writes one log line per request with the method, URL, status code and duration:
val logRequests =
ZClientAspect.requestLogging(
level = (status: Status) => if (status.isError) LogLevel.Warning else LogLevel.Info,
)
The level function picks the log level from the response status. By default every response is logged at Info; here, 4xx and 5xx responses are logged at Warning, so they stand out. A request that fails without a response, for example because the connection is refused, is logged at the failureLevel parameter's level, Warning by default, with the message Http client request failed and the cause.
We attach the aspect to the client from the environment and send requests as usual:
def program(baseUrl: URL): ZIO[Client, Throwable, Unit] =
for {
client <- ZIO.serviceWith[Client](_ @@ logRequests)
_ <- client.batched(Request.get(baseUrl / "stock" / "42"))
_ <- client.batched(Request.get(baseUrl / "prices" / "42"))
} yield ()
With ZIO's default logger, each request becomes one line, with the details as annotations (trimmed here to the interesting ones):
level=WARN message="Http client request" method=GET duration_ms=3023 url=http://localhost:34289/stock/42 status_code=503 ...
level=INFO message="Http client request" method=GET duration_ms=286 url=http://localhost:34289/prices/42 status_code=200 ...
The first request in a fresh JVM is slow because it also pays for warm-up and for opening the connection; later requests take milliseconds.
The first call to /stock/42 gets the service's first 503. The client returned it as a normal response, and the code carried on: a 5xx status is not an error to the client. We come back to that when we add retries.
requestLogging has more parameters: loggedRequestHeaders and loggedResponseHeaders add the named headers to the line, and logRequestBody and logResponseBody add the bodies, when they are already in memory. Every parameter has a default, so you name only the ones you change.
Runnable version, with the inventory service from InventoryService.scala: RequestLoggingExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
package example.clientresilience
import zio._
import zio.http._
/**
* The service the client examples call. It runs in the same program, on any
* open port, so each example works without network access:
*
* - `GET /stock/<sku>` answers `503 Service Unavailable` to the first two
* requests it receives, then `200 OK`.
* - `GET /slow` waits thirty seconds before it answers.
* - `GET /prices/<sku>` waits 200 milliseconds before it answers.
*/
object InventoryService {
def routes(unavailableLeft: Ref[Int]): Routes[Any, Response] =
Routes(
Method.GET / "stock" / string("sku") -> handler { (sku: String, _: Request) =>
unavailableLeft.getAndUpdate(n => (n - 1).max(0)).map { left =>
if (left > 0) Response.status(Status.ServiceUnavailable)
else Response.text(s"42 units of $sku in stock")
}
},
Method.GET / "slow" -> handler {
ZIO.sleep(30.seconds).as(Response.text("finally"))
},
Method.GET / "prices" / string("sku") -> handler { (sku: String, _: Request) =>
ZIO.sleep(200.millis).as(Response.text(s"$sku costs 9.99"))
},
)
/**
* Starts the service on the `Server` in the environment and returns its base
* URL, such as `http://localhost:38291`.
*/
val start: ZIO[Server, Nothing, URL] =
for {
unavailableLeft <- Ref.make(2)
port <- Server.install(routes(unavailableLeft))
url <- ZIO.fromEither(URL.decode(s"http://localhost:$port")).orDie
} yield url
/** A server layer that listens on any open port. */
val server: ZLayer[Any, Throwable, Server] =
Server.defaultWith(_.onAnyOpenPort)
}
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file InventoryService.scala
// Run from this folder: scala-cli run RequestLoggingExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.clientresilience.RequestLoggingExample"
package example.clientresilience
import zio._
import zio.http._
/**
* Call Other Services Reliably — Logging Each Request
*
* `ZClientAspect.requestLogging` logs one line per request with its method,
* URL, status code and duration. Error statuses are logged at the warning
* level.
*/
object RequestLoggingExample extends ZIOAppDefault {
val logRequests =
ZClientAspect.requestLogging(
level = (status: Status) => if (status.isError) LogLevel.Warning else LogLevel.Info,
)
val program =
for {
baseUrl <- InventoryService.start
client <- ZIO.serviceWith[Client](_ @@ logRequests)
_ <- client.batched(Request.get(baseUrl / "stock" / "42"))
_ <- client.batched(Request.get(baseUrl / "prices" / "42"))
} yield ()
def run = program.provide(Client.default, InventoryService.server)
}
Bounding Each Request with a Timeout
A request to /slow keeps a fiber waiting for thirty seconds. To give up sooner, we put a time limit on the effect that sends the request. ZIO#timeoutFail runs an effect and, if it has not finished after the given duration, interrupts it and fails with the error we pass:
def get(client: Client, url: URL): Task[Response] =
client
.batched(Request.get(url))
.timeoutFail(new TimeoutException(s"GET $url took longer than 2 seconds"))(2.seconds)
Calling get(client, baseUrl / "slow") now fails after two seconds:
Left(java.util.concurrent.TimeoutException: GET http://localhost:44625/slow took longer than 2 seconds)
Interrupting the request does not leave a half-used connection in the pool: the client removes the connection of an interrupted request from the pool instead of returning it, so no later request reuses it.
We use timeoutFail rather than ZIO#timeout, which succeeds with None when time runs out. A failure keeps the timeout in the error channel, which is where the retry in the next section looks.
Because the limit is on the effect, each call site can choose its own. That is the difference from the timeouts in ZClient.Config, which apply to every request of the client and measure one stage of the connection each:
connectionTimeoutlimits how long opening a connection may take. The default config has none.idleTimeoutfails a request when its connection receives no data for that long. The default is 50 seconds.bodyReadTimeoutfails a request when, after the headers arrive, no new part of the body arrives for that long. When it is not set,idleTimeoutapplies instead.
None of the three limits the whole request: a service that sends one byte every 40 seconds never trips the default idleTimeout. Set them as a floor for every request, and use timeoutFail for the time a caller is willing to wait. The connection pool section shows how to provide a client with a custom config.
requestLogging writes its line when a request completes or fails. A request that a timeout interrupts does neither, so it leaves no line. The next section logs timed-out attempts with ZIO#tapError.
Runnable version, which starts the inventory service and prints the result of the timed-out call: PerRequestTimeoutExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file InventoryService.scala
// Run from this folder: scala-cli run PerRequestTimeoutExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.clientresilience.PerRequestTimeoutExample"
package example.clientresilience
import java.util.concurrent.TimeoutException
import zio._
import zio.http._
/**
* Call Other Services Reliably — Bounding Each Request with a Timeout
*
* `ZIO#timeoutFail` interrupts a request that takes longer than the given
* duration and fails with the given error instead.
*/
object PerRequestTimeoutExample extends ZIOAppDefault {
def get(client: Client, url: URL): Task[Response] =
client
.batched(Request.get(url))
.timeoutFail(new TimeoutException(s"GET $url took longer than 2 seconds"))(2.seconds)
val program =
for {
baseUrl <- InventoryService.start
client <- ZIO.service[Client]
result <- get(client, baseUrl / "slow").either
_ <- Console.printLine(result)
} yield ()
def run = program.provide(Client.default, InventoryService.server)
}
Retrying Transient Failures with a Schedule
A 503 from a restarting service, or a request that timed out, often succeeds when we send it again a moment later. ZIO describes "again, and when" with a Schedule. This one waits 100 milliseconds before the first retry and doubles the wait each time, with random jitter so that many clients do not retry in lockstep, and allows at most three retries, so four attempts in total:
val retryPolicy: Schedule[Any, Any, Any] =
Schedule.exponential(100.millis).jittered && Schedule.recurs(3)
&& combines two schedules into one that continues while both continue and waits for the longer of their two delays.
A retry only happens on a failure, and a 503 response is a success to the client. So we first turn server errors into failures:
final case class ServerError(status: Status) extends Exception(s"server answered ${status.code}")
def failOnServerError(response: Response): IO[ServerError, Response] =
if (response.status.isServerError) ZIO.fail(ServerError(response.status))
else ZIO.succeed(response)
Status#isServerError is true for codes 500 to 599. We leave 4xx responses alone: a 404 or a 400 means the request itself is wrong, and sending it again gets the same answer.
Now we can retry the whole call with ZIO#retry:
def get(client: Client, url: URL): Task[Response] =
client
.batched(Request.get(url))
.flatMap(failOnServerError)
.timeoutFail(new TimeoutException(s"GET $url took longer than 5 seconds"))(5.seconds)
.tapError(error => ZIO.logWarning(s"GET $url failed: ${error.getMessage}"))
.retry(retryPolicy)
The order of the operators decides what each one covers:
timeoutFailcomes beforeretry, so it limits each attempt, not all of them together.tapErrorlogs every failed attempt, including the timed-out ones thatrequestLoggingdoes not see.retryruns everything before it again: the request, the status check and the timeout.
With the logging aspect attached, calling get(client, baseUrl / "stock" / "42") shows two 503 attempts and then the success:
level=WARN message="Http client request" method=GET duration_ms=2149 url=http://localhost:39213/stock/42 status_code=503 ...
level=WARN message="GET http://localhost:39213/stock/42 failed: server answered 503"
level=WARN message="Http client request" method=GET duration_ms=23 url=http://localhost:39213/stock/42 status_code=503 ...
level=WARN message="GET http://localhost:39213/stock/42 failed: server answered 503"
level=INFO message="Http client request" method=GET duration_ms=79 url=http://localhost:39213/stock/42 status_code=200 ...
42 units of 42 in stock
When all four attempts fail, retry fails with the error of the last attempt.
Retry only requests that are safe to send twice. A GET, PUT or DELETE should have the same effect however many times it arrives, but a POST that creates an order can create it twice if the first attempt reached the service and only the response was lost. Retry a POST only when the service deduplicates it, for example with an idempotency key header.
The client also has a retry method of its own. Client#retry returns a client that sends a request again when sending it fails, such as when the connection is refused or drops:
val retryingClient: URIO[Client, Client] =
ZIO.serviceWith[Client](_.retry(retryPolicy))
Client#retry sees only failures of the transport, below status codes and timeouts: it never retries a 503, because the client received a response, and a ZClient#mapZIO that fails on a 503 does not change that, because retry wraps the sending of the request, not the decoding of the response. Use it when connection failures are all you want to retry; use ZIO#retry as above when you also want to retry on status codes and timeouts.
To retry only some failures, combine the policy with a schedule that inspects each error. Schedule.recurWhile continues while its predicate holds for the error:
val transientOnly: Schedule[Any, Throwable, Any] =
retryPolicy && Schedule.recurWhile[Throwable] {
case _: ServerError | _: TimeoutException => true
case _ => false
}
Runnable version, which sends the retried request to the service and prints the body: RetryExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file InventoryService.scala
// Run from this folder: scala-cli run RetryExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.clientresilience.RetryExample"
package example.clientresilience
import java.util.concurrent.TimeoutException
import zio._
import zio.http._
/**
* Call Other Services Reliably — Retrying Transient Failures with a Schedule
*
* A `5xx` response is a successful call as far as the client is concerned, so
* we turn it into a failure first. Then `ZIO#retry` sends the request again,
* following an exponential backoff schedule. The timeout sits inside the retry,
* so it bounds each attempt.
*/
object RetryExample extends ZIOAppDefault {
final case class ServerError(status: Status) extends Exception(s"server answered ${status.code}")
def failOnServerError(response: Response): IO[ServerError, Response] =
if (response.status.isServerError) ZIO.fail(ServerError(response.status))
else ZIO.succeed(response)
val retryPolicy: Schedule[Any, Any, Any] =
Schedule.exponential(100.millis).jittered && Schedule.recurs(3)
val retryingClient: URIO[Client, Client] =
ZIO.serviceWith[Client](_.retry(retryPolicy))
val transientOnly: Schedule[Any, Throwable, Any] =
retryPolicy && Schedule.recurWhile[Throwable] {
case _: ServerError | _: TimeoutException => true
case _ => false
}
val logRequests =
ZClientAspect.requestLogging(
level = (status: Status) => if (status.isError) LogLevel.Warning else LogLevel.Info,
)
def get(client: Client, url: URL): Task[Response] =
client
.batched(Request.get(url))
.flatMap(failOnServerError)
.timeoutFail(new TimeoutException(s"GET $url took longer than 5 seconds"))(5.seconds)
.tapError(error => ZIO.logWarning(s"GET $url failed: ${error.getMessage}"))
.retry(retryPolicy)
val program =
for {
baseUrl <- InventoryService.start
client <- ZIO.serviceWith[Client](_ @@ logRequests)
response <- get(client, baseUrl / "stock" / "42")
body <- response.body.asString
_ <- Console.printLine(body)
} yield ()
def run = program.provide(Client.default, InventoryService.server)
}
Sizing the Connection Pool
Opening a TCP connection, and a TLS session on top of it, costs more than sending a request over one that is already open. So the client keeps a pool of open connections for each location, that is, each combination of scheme, host and port, and reuses them. The default config, ZClient.Config.default, has a fixed pool of 10 connections per location. When every connection to a location is busy, a new request to it waits until one is released.
To choose the pool size, and the client-wide timeouts from the timeout section, we build a ZClient.Config and provide it with Client.fromConfig instead of Client.default:
val config: ZClient.Config =
ZClient.Config.default
.fixedConnectionPool(4)
.connectionTimeout(1.second)
.idleTimeout(10.seconds)
def program(baseUrl: URL): ZIO[Client, Throwable, Unit] =
for {
client <- ZIO.service[Client]
_ <- ZIO.foreachParDiscard(1 to 20) { i =>
client.batched(Request.get(baseUrl / "prices" / i.toString))
}
} yield ()
def run(baseUrl: URL): Task[Unit] =
program(baseUrl).provide(
ZLayer.succeed(config),
Client.fromConfig,
)
The twenty requests run in parallel, but only four connections exist, so they go out four at a time. Each /prices request takes 200 milliseconds, and the runnable example measures the batch once the JVM has warmed up:
20 requests took 1122 ms
That is five rounds of 200 milliseconds, one for each group of four requests.
ZClient.Config has three methods for the pool:
fixedConnectionPool(size)keepssizeconnections per location.dynamicConnectionPool(minimum, maximum, ttl)keeps betweenminimumandmaximumconnections per location, and closes connections aboveminimumafter they stay unused forttl. Use it when traffic to a service comes in bursts.disabledConnectionPoolopens a new connection for every request.
The pool is the client's concurrency limit for each service it calls. Size it to what the remote service can take: a large pool lets a burst of requests through all at once, and a small one makes requests queue in your service instead. The connection pooling section of the client reference lists the per-host variants of these configurations.
Runnable version, which times the twenty requests after a warm-up run: ConnectionPoolExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file InventoryService.scala
// Run from this folder: scala-cli run ConnectionPoolExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.clientresilience.ConnectionPoolExample"
package example.clientresilience
import zio._
import zio.http._
/**
* Call Other Services Reliably — Sizing the Connection Pool
*
* The client keeps a pool of connections for each host. With a fixed pool of
* four connections, twenty parallel requests that each take 200 milliseconds
* run four at a time, so they take about one second in total once the JVM has
* warmed up.
*/
object ConnectionPoolExample extends ZIOAppDefault {
val config: ZClient.Config =
ZClient.Config.default
.fixedConnectionPool(4)
.connectionTimeout(1.second)
.idleTimeout(10.seconds)
val program =
for {
baseUrl <- InventoryService.start
client <- ZIO.service[Client]
twenty = ZIO.foreachParDiscard(1 to 20) { i =>
client.batched(Request.get(baseUrl / "prices" / i.toString))
}
_ <- twenty // the first run also pays for JVM warm-up and opening connections
elapsed <- twenty.timed.map(_._1)
_ <- Console.printLine(s"20 requests took ${elapsed.toMillis} ms")
} yield ()
def run =
program.provide(
ZLayer.succeed(config),
Client.fromConfig,
InventoryService.server,
)
}
Putting It Together
The complete example wraps the four pieces in an InventoryClient class, so the rest of a program calls inventory.get("/stock/42") and gets the logging, the timeouts, the retries and the pool without repeating them. It differs from the sections in four ways: get takes a path and builds the URL from the service's base URL, an outer timeoutFail gives up after twelve seconds in total however many attempts are left, the class reads the response body so get returns a String, and the pool has eight connections.
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file InventoryService.scala
// Run from this folder: scala-cli run CompleteExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.clientresilience.CompleteExample"
package example.clientresilience
import java.util.concurrent.TimeoutException
import zio._
import zio.http._
/**
* Call Other Services Reliably — Putting It Together
*
* One client that logs every request, bounds each attempt with a timeout,
* retries `5xx` responses and timeouts with exponential backoff, gives up after
* twelve seconds in total, and uses a sized connection pool.
*/
object CompleteExample extends ZIOAppDefault {
final case class ServerError(status: Status) extends Exception(s"server answered ${status.code}")
final class InventoryClient(client: Client, baseUrl: URL) {
private val retryPolicy: Schedule[Any, Any, Any] =
Schedule.exponential(100.millis).jittered && Schedule.recurs(3)
private def failOnServerError(response: Response): IO[ServerError, Response] =
if (response.status.isServerError) ZIO.fail(ServerError(response.status))
else ZIO.succeed(response)
def get(path: String): Task[String] = {
val url = baseUrl.addPath(path)
client
.batched(Request.get(url))
.flatMap(failOnServerError)
.timeoutFail(new TimeoutException(s"GET $url took longer than 5 seconds"))(5.seconds)
.tapError(error => ZIO.logWarning(s"GET $url failed: ${error.getMessage}"))
.retry(retryPolicy)
.timeoutFail(new TimeoutException(s"GET $url did not succeed within 12 seconds"))(12.seconds)
.flatMap(_.body.asString)
}
}
object InventoryClient {
val logRequests =
ZClientAspect.requestLogging(
level = (status: Status) => if (status.isError) LogLevel.Warning else LogLevel.Info,
)
def make(baseUrl: URL): URIO[Client, InventoryClient] =
ZIO.serviceWith[Client](client => new InventoryClient(client @@ logRequests, baseUrl))
}
val config: ZClient.Config =
ZClient.Config.default
.fixedConnectionPool(8)
.connectionTimeout(1.second)
.idleTimeout(10.seconds)
val program =
for {
baseUrl <- InventoryService.start
inventory <- InventoryClient.make(baseUrl)
stock <- inventory.get("/stock/42")
_ <- Console.printLine(stock)
slow <- inventory.get("/slow").either
_ <- Console.printLine(slow)
} yield ()
def run =
program.provide(
ZLayer.succeed(config),
Client.fromConfig,
InventoryService.server,
)
}
The call to /stock/42 succeeds on the third attempt, as in the retry section. The call to /slow times out twice, after five seconds each, and the outer timeout ends the third attempt at twelve seconds:
42 units of 42 in stock
level=WARN message="GET http://localhost:46585/slow failed: GET http://localhost:46585/slow took longer than 5 seconds"
level=WARN message="GET http://localhost:46585/slow failed: GET http://localhost:46585/slow took longer than 5 seconds"
Left(java.util.concurrent.TimeoutException: GET http://localhost:46585/slow did not succeed within 12 seconds)
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/clientresilience/. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.clientresilience.<ObjectName>". Each example starts the inventory service on an open port and calls it, so nothing else needs to be running.
Going Further
- The Client reference covers the other client aspects, such as
ZClientAspect.debugandZClientAspect.followRedirects, and the rest ofZClient.Config, including SSL and proxies. - How to Log HTTP Requests and Add Log Annotations does for a server what the logging section does for a client: one log line per request, with
Middleware.requestLogging. - ZIO's Schedule documentation lists the other schedules and combinators, such as
Schedule.spacedfor a fixed delay andSchedule.upTofor a time budget. - To check how your service reacts when a dependency misbehaves, test it against a fake service as in How to Test HTTP Applications.