Created
June 8, 2025 17:16
-
-
Save fosron/798582fc8205f7f05da9172914186649 to your computer and use it in GitHub Desktop.
Simple backoff using a lookup table (original code https://commaok.xyz/post/simple-backoff/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function backoffAttempt(callable $request, int $maxAttempts = 10): void { | |
$delays = [1,2,4,8,16,32,60,60,60,60]; // in seconds | |
for ($i = 0; $i < $maxAttempts; $i++) { | |
$success = $request(); | |
if ($success) { | |
return; | |
} | |
$delay = $delays[$i]; | |
$jitterFactor = 0.75 + mt_rand() / mt_getrandmax() * 0.5; // 0.75–1.25 | |
$sleep = $delay * $jitterFactor; | |
usleep((int)($sleep * 1e6)); | |
} | |
throw new RuntimeException("Failed after $maxAttempts attempts"); | |
} | |
// Example usage: | |
try { | |
backoffAttempt(fn() => makeHttpRequest()); | |
} catch (RuntimeException $e) { | |
echo $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment