Search code examples
phpjsonwordpressapifile-get-contents

Json API Rate Limiting


example.com/series/title-series-A/ cached with wordpress plugin for 1 day, but when cache expired and visitor access post series

example visitor access url below at same time

  • example.com/series/title-series-A/
  • example.com/series/title-series-B/
  • example.com/series/title-series-C/

so all series getting access by visitor will request to api at same time, any solution for this ?

( in this all posttype 'series' has api php request )

function curl_get_contents($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
$agent  = array('http' => array('user_agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'));
        $api = 'https://api.example.com/v3/title-series-here';
        $results = curl_get_contents($api, false, stream_context_create($agent));
    $results = json_decode($results, true);

And api.example.com has Rate Limiting 4 sec each request, if more than that will blocked


Solution

  • This is my solution:

    • Check response header api, if header response 429 use sleep(5); or die();
    if(($httpcode == 429)) { sleep(5); }
    
    • cache curl result