Skip to content

Instantly share code, notes, and snippets.

@fosron
Created June 8, 2025 17:16
Show Gist options
  • Save fosron/798582fc8205f7f05da9172914186649 to your computer and use it in GitHub Desktop.
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/)
<?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