spatie/guzzle-rate-limiter-middleware
Guzzle middleware to rate-limit HTTP requests by requests/second or requests/minute. When the limit is hit, it sleeps until a slot is available. Includes an in-memory store and supports custom persistence for sharing limits across processes.
HttpClient facade or standalone Guzzle instances). This ensures minimal intrusion into existing request pipelines.HttpClient facade (Guzzle 7+), requiring only middleware registration in the client stack.InMemoryStore driver enables quick adoption for single-process rate-limiting without additional dependencies.sleep() mechanism may impact latency for high-traffic endpoints if not paired with a non-blocking driver (e.g., Redis).InMemoryStore sufficient?Http::withOptions(['middleware' => [new RateLimiterMiddleware()]])).InMemoryStore for testing).InMemoryStore with Redis/database for shared state if needed.use Spatie\GuzzleRateLimiterMiddleware\RateLimiterMiddleware;
use Illuminate\Support\Facades\Http;
Http::macro('withRateLimiter', function (array $limits) {
return $this->withOptions([
'middleware' => [new RateLimiterMiddleware($limits)],
]);
});
$response = Http::withRateLimiter(['/api' => 10])->get('https://api.example.com');
Spatie\GuzzleRateLimiterMiddleware\RateLimiterStore and bind it in Laravel’s service container.RateLimitExceeded) to aid debugging.HttpClient retry logic to handle transient rate-limit errors.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Redis store downtime | Inconsistent rate-limiting | Fallback to InMemoryStore or queue retries. |
High latency due to sleep() |
Slow API responses | Use Redis driver for non-blocking checks. |
| Misconfigured rate limits | Over/under-throttling | Unit tests with time-mocking. |
| Shared state corruption | Race conditions in distributed setups | Use Redis transactions or Lua scripts. |
/payments").How can I help you explore Laravel packages today?