I'm working on a Laravel application, using Guzzle 6. A lot of functionality relies on an API, of which I've created a wrapper for.
My wrapper's a single class, that creates the Guzzle client in the __construct()
, and has a variety of public functions which return responses from Guzzle requests.
The API I'm using has a limit of 40 requests every 10 seconds. I am caching things, so it would be very rare to hit this limit, but I'd like to know that my application wouldn't just die if it did!
Some notes about my app:
So, my question is, how should I make sure I do not hit this limit? A few ideas of mine are the following:
HandlerStack
for Guzzle directly. Not sure if this is possible, but I've used the HandlerStack
for caching responses before.I'm trying to not to provoke too opinionated responses, but I'm sure there's probably a better and/or easier way than the above, or if they are good ideas, any pointers or recommendations would be great.
Thanks in advance.
Wrap your API calls with Jobs and push them to separate queue:
ApiJob::dispatch()->onQueue('api');
Use mxl/laravel-queue-rate-limit package (I'm the author) to rate limit api
queue. Add this to config/queue.php
:
'rateLimit' => [
'api' => [
'allows' => 40,
'every' => 10
]
]
Run queue worker:
$ php artisan queue:work --queue api
See also this answer.
There's not enough information to really dig deep into this, but to get you started, good APIs typically return a 429 response code when you're exceeding their throttled limit.
You could use $res->getStatusCode()
from guzzle to check for this and flash a message back to the user if they're making too many requests too quickly.
Can you give some more information about what your app is doing? Are you making requests in a foreach loop? Is the view dependent on data from this API?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With