Backoff and Retry

Example

object Example:

  var counter: Int = 3

  val tendToFail: zio.ZIO[Any, Throwable, Int] =
    zio.ZIO.attempt {
      if (counter > 0) then
        println(s"Failing with counter = ${counter}")
        counter = counter - 1
        throw new Exception("nope")
      else 42
    }

  val keepTry: zio.ZIO[Any, Throwable, Unit] =
    import zio.durationInt
    tendToFail
      .retry(
        zio.Schedule.exponential(1.second)
          && zio.Schedule.recurs(5)
      )
      .map(result => println(result))

Usage

object Main extends zio.ZIOAppDefault:

  override def run: zio.ZIO[Any, Throwable, Unit] =
    Example.keepTry

Demo

This file is literate Scala, and can be run using Codedown:

$ curl https://earldouglas.com/posts/scala/zio/backoff.md |
  codedown scala > script.scala |
  scala-cli -q --scala 3.1.3 --dep dev.zio::zio:2.0.0 _.scala
Failing with counter = 3
Failing with counter = 2
Failing with counter = 1
42