Last active
September 28, 2024 00:07
-
-
Save nickkraakman/56d088c545d32b76e567a1581087d595 to your computer and use it in GitHub Desktop.
API call with max number of retries and exponential backoff in PHP
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 | |
$retries = 0; // Init the retries variable | |
$maxRetries = 5; // Means we try max 6 times | |
$retry = false; // Should we retry or not? | |
$initialWait = 1.0; // Initial wait time in seconds | |
try { | |
do { | |
// If it is not the first try, calculate exponential backoff and wait | |
if ($retries > 0) { | |
$waitTime = pow(2, $retries); | |
sleep($initialWait * $waitTime); | |
} | |
// Call the "risky" API function | |
$result = callExternalAPI(); // Here we assume this function returns an HTTP status code if it fails | |
// Retry if server error (5XX) or throttling error (429) occurred | |
if ($result == 500 || $result == 503 || $result == 429) { | |
$retry = true; | |
} else { | |
$retry = false; | |
} | |
} while ($retry && ($retries++ < $maxRetries)); | |
} catch (Exception $e) { | |
throw $e; | |
} | |
// If you get to here, your API call has succeeded |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment