Lua retry with jittered exponential backoff
Lua
local function retry(fn, opts)
opts = opts or {}
local attempts, base, cap = opts.attempts or 5, opts.base or 0.2, opts.cap or 5
local sleep = opts.sleep or function(s) os.execute(('sleep %.2f'):format(s)) end
local lastErr
for i = 1, attempts do
local ok, res = pcall(fn)
if ok then return res end
lastErr = res
if i < attempts then
local delay = math.min(cap, base * 2.0 ^ (i - 1))
sleep(delay * (0.5 + math.random() * 0.5)) -- jitter of 50-100 percent
end
end
error(('retry failed after %d attempts: %s'):format(attempts, tostring(lastErr)), 0)
end
return retry