Skip to content

Instantly share code, notes, and snippets.

@nickkraakman
Last active June 8, 2023 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nickkraakman/56d088c545d32b76e567a1581087d595 to your computer and use it in GitHub Desktop.
Save nickkraakman/56d088c545d32b76e567a1581087d595 to your computer and use it in GitHub Desktop.
API call with max number of retries and exponential backoff in PHP
<?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