Skip to content

Automatically retry when rate limit is reached #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/example.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
echo $response->body();
echo $response->headers();

// GET with auto retry on rate limit
$query_params = ['limit' => 100, 'offset' => 0];
$request_headers = ['X-Mock: 200'];
$retryOnLimit = true;
$response = $client->api_keys()->get(null, $query_params, $request_headers, $retryOnLimit);
echo $response->statusCode();
echo $response->body();
echo $response->headers();

// POST
$request_body = [
'name' => 'My PHP API Key',
Expand Down
34 changes: 25 additions & 9 deletions lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,20 @@ class Client
protected $curlOptions;
/** @var array */
private $methods;
/** @var bool */
private $retryOnLimit;

/**
* Initialize the client
*
* @param string $host the base url (e.g. https://api.sendgrid.com)
* @param array $headers global request headers
* @param string $version api version (configurable)
* @param array $path holds the segments of the url path
* @param array $curlOptions extra options to set during curl initialization
* @param string $host the base url (e.g. https://api.sendgrid.com)
* @param array $headers global request headers
* @param string $version api version (configurable)
* @param array $path holds the segments of the url path
* @param array $curlOptions extra options to set during curl initialization
* @param bool $retryOnLimit set default retry on limit flag
*/
public function __construct($host, $headers = null, $version = null, $path = null, $curlOptions = null)
public function __construct($host, $headers = null, $version = null, $path = null, $curlOptions = null, $retryOnLimit = false)
{
$this->host = $host;
$this->headers = $headers ?: [];
Expand All @@ -51,6 +54,8 @@ public function __construct($host, $headers = null, $version = null, $path = nul
$this->curlOptions = $curlOptions ?: [];
// These are the supported HTTP verbs
$this->methods = ['delete', 'get', 'patch', 'post', 'put'];

$this->retryOnLimit = $retryOnLimit;
}

/**
Expand Down Expand Up @@ -134,10 +139,11 @@ private function buildUrl($queryParams = null)
* @param string $url the final url to call
* @param array $body request body
* @param array $headers any additional request headers
* @param bool $retryOnLimit should retry if rate limit is reach?
*
* @return Response object
*/
public function makeRequest($method, $url, $body = null, $headers = null)
public function makeRequest($method, $url, $body = null, $headers = null, $retryOnLimit = false)
{
$curl = curl_init($url);

Expand Down Expand Up @@ -169,8 +175,17 @@ public function makeRequest($method, $url, $body = null, $headers = null)
$responseHeaders = array_map('trim', $responseHeaders);

curl_close($curl);

$response = new Response($statusCode, $responseBody, $responseHeaders);

if ($statusCode == 429 && $retryOnLimit) {
$headers = $response->headers(true);
$sleepDurations = $headers['X-Ratelimit-Reset'] - time();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please explain the idea behind this algorithm.

I want to make sure we don't overload our servers when something has gone wrong. I was hoping for a backoff strategy that eventually fails after a certain period of time.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every request we made to sendgrid will have X-Ratelimit-Reset in the header, where it tell us when the rate limit is reset in sendgrid.
So when ever we have error 429(rate limit reached) we use X-Ratelimit-Reset to determine how long the script need to wait before make another call to sendgrid.
This way we don't use a random time or predefined time.

sleep($sleepDurations > 0 ? $sleepDurations : 0);
return $this->makeRequest($method, $url, $body, $headers, false);
}

return new Response($statusCode, $responseBody, $responseHeaders);
return $response;
}

/**
Expand Down Expand Up @@ -211,7 +226,8 @@ public function __call($name, $args)
$queryParams = isset($args[1]) ? $args[1] : null;
$url = $this->buildUrl($queryParams);
$headers = isset($args[2]) ? $args[2] : null;
return $this->makeRequest($name, $url, $body, $headers);
$retryOnLimit = isset($args[3]) ? $args[3] : $this->retryOnLimit;
return $this->makeRequest($name, $url, $body, $headers, $retryOnLimit);
}

return $this->_($name);
Expand Down
4 changes: 2 additions & 2 deletions test/unit/MockClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ class MockClient extends Client
protected $requestHeaders;
protected $url;

public function makeRequest($method, $url, $requestBody = null, $requestHeaders = null)
public function makeRequest($method, $url, $requestBody = null, $requestHeaders = null, $retryOnLimit = false)
{
$this->requestBody = $requestBody;
$this->requestHeaders = $requestHeaders;
$this->url = $url;
return $this;
}
}
}