avatar

Andres Jaimes

Cats Effect IO - Retry with backoff pattern

By Andres Jaimes

- 1 minutes read - 56 words

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

import cats.effect.{IO, Timer}

import scala.concurrent.duration._

def retryWithBackoff[A](ioa: IO[A], initialDelay: FiniteDuration, maxRetries: Int)
  (implicit timer: Timer[IO]): IO[A] = {

  ioa.handleErrorWith { error =>
    if (maxRetries > 0)
      IO.sleep(initialDelay) *> retryWithBackoff(ioa, initialDelay * 2, maxRetries - 1)
    else
      IO.raiseError(error)
  }
}

References