avatar

Andres Jaimes

Cats Effect IO - Retry with backoff pattern

By Andres Jaimes

- 1 minutes read - 66 words

Scala example for using the retry-with-backoff pattern with Cats Effect IO.

 1import cats.effect.{IO, Timer}
 2
 3import scala.concurrent.duration._
 4
 5def retryWithBackoff[A](ioa: IO[A], initialDelay: FiniteDuration, maxRetries: Int)
 6  (implicit timer: Timer[IO]): IO[A] = {
 7
 8  ioa.handleErrorWith { error =>
 9    if (maxRetries > 0)
10      IO.sleep(initialDelay) *> retryWithBackoff(ioa, initialDelay * 2, maxRetries - 1)
11    else
12      IO.raiseError(error)
13  }
14}

References