A rate limiter middleware for Guzzle. Here's what you need to know:
- Specify a maximum amount of requests per minute or per second
- When the limit is reached, the process will
sleepuntil the request can be made - Implement your own driver to persist the rate limiter's request store. This is necessary if the rate limiter needs to work across separate processes, the package ships with an
InMemoryStore.
You can install the package via composer:
composer require spatie/guzzle-rate-limiter-middlewareCreate a Guzzle middleware stack and register it on the client.
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Spatie\GuzzleRateLimiterMiddleware\RateLimiterMiddleware;
$stack = HandlerStack::create();
$stack->push(RateLimiterMiddleware::perSecond(3));
$client = new Client([
'handler' => $stack,
]);You can create a rate limiter to limit per second or per minute.
RateLimiterMiddleware::perSecond(3); // Max. 3 requests per second
RateLimiterMiddleware::perMinute(5); // Max. 5 requests per minuteBy default, the rate limiter works in memory. This means that if you have a second PHP process (or Guzzle client) consuming the same API, you'd still possibly hit the rate limit. To work around this issue, the rate limiter's state should be persisted to a cache. Implement the Store interface with your own cache, and pass the store to the rate limiter.
use MyApp\RateLimiterStore;
use Spatie\GuzzleRateLimiterMiddleware\RateLimit;
RateLimiterMiddleware::perSecond(3, new RateLimiterStore());A Laravel example of a custom Store:
<?php
namespace MyApp;
use Spatie\GuzzleRateLimiterMiddleware\Store;
use Illuminate\Support\Facades\Cache;
class RateLimiterStore implements Store
{
public function get(): array
{
return Cache::get('rate-limiter', []);
}
public function push(int $timestamp)
{
Cache::put('rate-limiter', array_merge($this->get(), [$timestamp]));
}
}composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.
We publish all received postcards on our company website.
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.
The MIT License (MIT). Please see License File for more information.