Full stack developer Timo Prüße has created a Guzzle middleware that helps you set up advanced API request throttling within your Guzzle handler stack.
Here’s the description from the GitHub repository about what
guzzle-advanced-throttle can do for external APIs that you are using that might have rate limits:
A Guzzle middleware that can throttle requests according to (multiple) defined rules. It is also possible to define a caching strategy, e.g. get the response from cache when the rate limit is exceeded or always get a cached value to spare your rate limits.
Guzzle Middlware Package
If you need to use the middleware directly outside of a Laravel project, you configure your rules as follows, which shows how flexible the middleware can be:
1use hamburgscleanest\GuzzleAdvancedThrottle\RequestLimitRuleset;23$rules = new RequestLimitRuleset([4 [5 'host' => 'https://www.google.com',6 'max_requests' => 20,7 'request_interval' => 18 ],9 [10 'host' => 'https://www.google.com',11 'max_requests' => 100,12 'request_interval' => 12013 ]14]);
And here’s how you add the middleware to your handler stack within Guzzle:
1$stack = new HandlerStack();2$stack->setHandler(new CurlHandler());3$stack->push((new ThrottleMiddleware($rules))->handle());45// Pass the stack to the client6$client = new Client([7 'base_uri' => 'https://www.google.com',8 'handler' => $stack9]);
Timo has a Laravel Wrapper package for this Guzzle middleware, which makes it easy to configure the cache and rules for use within a Laravel application.
You can use the
GuzzleThrottle facade in your Laravel projects to get a new Guzzle client instance with the Guzzle rate limit caching Handler stack:
1$client = GuzzleThrottle::client([2 'base_uri' => 'https://www.google.com'3]);
And here’s what the example configuration looks like from the project’s README:
1return [2 'cache' => [3 // Name of the configured driver in the Laravel cache config file / Also needs to be set when "no-cache" is set! Because it's used for the internal timers4 'driver' => 'default',5 // Cache strategy: no-cache, cache, force-cache6 'strategy' => 'cache',7 // TTL in minutes8 'ttl' => 9009 ],10 'rules' => [11 [12 // host (including scheme)13 'host' => 'https://www.google.com',14 // maximum number of requests in the given interval15 'max_requests' => 20,16 // interval in seconds till the limit is reset17 'request_interval' => 118 ],19 [20 // host (including scheme)21 'host' => 'https://www.google.com',22 // maximum number of requests in the given interval23 'max_requests' => 100,24 // interval in seconds till the limit is reset25 'request_interval' => 12026 ]27 ]28];
If you want to learn more about the
guzzle-advanced-throttle middleware, check out hamburgscleanest/guzzle-advanced-throttle. For the accompanying Laravel package, check out hamburgscleanest/laravel-guzzle-throttle.