OCaml retry loop with capped exponential backoff
OCaml
let retry ?(base = 0.05) ?(cap = 2.0) ?(tries = 5) f =
let delay attempt =
let d = Float.min cap (base *. (2. ** float_of_int attempt)) in
d +. Random.float (d *. 0.25) (* jitter avoids synchronized retries *)
in
let rec loop attempt =
match f () with
| value -> Ok value
| exception e when attempt >= tries -> Error e
| exception _ ->
Unix.sleepf (delay attempt);
loop (attempt + 1)
in
loop 0