Retry -- Generic retry logic with exponential backoff#
Provides configurable retry logic with exponential backoff, jitter, and customizable predicates for determining when to retry operations.
Installation#
Install with opam:
$ opam install retry
If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install retry
Usage#
Retry on exception#
let config = Retry.config ~max_retries:5 ()
let should_retry = function
| Failure _ -> true
| _ -> false
let run ~clock ~connect_to_server =
Retry.with_retry ~clock ~config ~should_retry (fun () ->
connect_to_server ())
Retry on Error result#
let run ~clock ~call_api =
Retry.with_retry_result ~clock ~config
~should_retry:(function `Unavailable -> true | _ -> false)
(fun () -> call_api ())
Behaviour after the last attempt#
with_retry runs the callback once, then up to max_retries more times
with exponential backoff between attempts. Delays grow as
backoff_factor * 2 ^ attempt, capped at backoff_max, and randomised
when jitter is true.
If every attempt still fails, the library surfaces the last failure unchanged:
with_retryre-raises the most recent exception from the callback. Exceptions rejected byshould_retryare re-raised immediately without further retries.with_retry_resultreturns the most recentError. AnErrorrejected byshould_retryis returned immediately.
Use Retry.calculate_backoff ~config ~attempt to inspect what the delay
would be for a given attempt without running the retry loop.
API#
Retry.config ?max_retries ?backoff_factor ?backoff_max ?jitter ()Retry.default_config-- 3 retries, 0.3s backoff factor, 120s cap, jitter on.Retry.with_retry ~clock ~config ~should_retry f-- retry on exception.Retry.with_retry_result ~clock ~config ~should_retry f-- retry on error result.Retry.calculate_backoff ~config ~attempt-- inspect the computed delay.
Licence#
MIT