简体   繁体   中英

PHP Limit total external API requests to 8 times per second

My website has a script that will call an external API when a user visits a particular page. An API request will be made when the page is accessed and a response is returned in xml format.
I am using the usual curl requests.

Right now, due to new implementations on the API side, if the API is getting too much requests, it will throw an exception and deny the request.
I want to limit the total calls to the API from my website to only 8 times per second.

How can I achieve this? Someone suggested me about queuing the requests but I've never done something like this before and I'm having a hard time finding a solution.
Sorry if my English has errors. Any help is appreciated.

For example: if 100 users accessed the web-page all at the same time, I need to queue those API requests 8 after 8 per second and so on until all are done.

$currentCount=0;
$currentSeconds;

function callAPI()
{
     if($currentCount<8 || date("s") != $currentSeconds)
     {

         if(date("s") != $currentSeconds)
         {
              $currentCount=0;
          }
         $currentSeconds=date("s");
     //call your API here
     $currentCount++;
     }
}

For each API call:

-Record the current time (just the seconds) in a variable.
-Make your API call.
-Increment a call counter.
-Check again if current seconds equal the previously stored value and if your call counter is under 8. If your call counter is under 8, you may make another call.

I have give suggest you to use one api generate to create token and match token on every request and do expiry or delete token after some time. So may be resolve your multiple request issues.

You can delay the API request for microseconds, here is sample code

usleep(1250000);//1 sec = 10,000,00 ms

function _callAPI(){
 // Your code here
}

When a user visits your site, the request will fire after a few microseconds in this way you can delay the request.

You can also maintain a log when a request is fired for the API and based on the previous request, dealy the next request.

Value of 8 call per second is low, so can save in database each call attempt and calculate number of calls per last 5 second every time.

For large values usually used counters in nosql database like Cassandra or Aerospike. Ie for each request you get current time and increase counter name "counter"+second until you got your desired limit.

Aerospike is best for this if load is really high(1000+ cps), it give very low latency. Cassandra is simpler to use and require less memory.

Even less memory is memcashed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM