Haskell capped exponential retry with jitter
Haskell
import Control.Concurrent (threadDelay)
import Control.Exception (SomeException, try)
import System.CPUTime (getCPUTime)
retryWithBackoff :: Int -> IO a -> IO (Either SomeException a)
retryWithBackoff maxTries action = go 1 100000
where
go attempt delay = do
result <- try action
case result of
Right value -> pure (Right value)
Left err
| attempt >= maxTries -> pure (Left err)
| otherwise -> do
jitter <- (`mod` 50000) <$> getCPUTime
threadDelay (min 2000000 delay + fromIntegral jitter)
go (attempt + 1) (min 2000000 (delay * 2))