Rate Limiting in PHP: A Complete Guide to Request Throttling

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Rate Limiting in PHP: API Protection and Load Optimization

Rate limiting is a critical mechanism for any PHP web application, especially for public APIs. It prevents abuse, protects against DDoS attacks, reduces server load, and ensures fair resource distribution among users. In this article, we will thoroughly examine popular libraries and tools for implementing rate limiting in PHP.



Basic Rate Limiting Algorithms

Before choosing a library, it is important to understand the basic algorithms:

  • Token Bucket — the most flexible algorithm. The bucket contains N tokens, each request consumes one token. Tokens are replenished at a specified rate.
  • Leaky Bucket — requests are processed at a constant rate. Excess requests are discarded or queued.
  • Fixed Window — requests are counted within a fixed interval (e.g., 60 seconds). Simple, but may allow peak loads at window boundaries.
  • Sliding Window — a more precise algorithm that considers requests within a floating time window. Uses logs or counters with timestamps.


Popular Libraries for Rate Limiting in PHP



1. Symfony Rate Limiter (symfony/rate-limiter)

An official Symfony component, but also works as a standalone library. Supports all major algorithms: Token Bucket, Fixed Window, Sliding Window. Ideal for Symfony or Laravel projects.

use Symfony\\Component\\RateLimiter\\RateLimiterFactory;use Symfony\\Component\\RateLimiter\\Storage\\InMemoryStorage;

$factory = new RateLimiterFactory([ 'id' => 'api', 'policy' => 'token_bucket', 'limit' => 100, 'rate' => ['interval' => '1 minute'],], new InMemoryStorage());

$limiter = $factory->create('user_123');

if ($limiter->consume(1)->isAccepted()) { // Process request} else { // Return 429 Too Many Requests header('HTTP/1.1 429 Too Many Requests'); echo json_encode(['error' => 'Rate limit exceeded']);}


2. nikic/FastRoute with middleware rate limiting

A lightweight solution for projects without frameworks. Uses a PHP implementation of Token Bucket with storage in Redis or Memcached.

class RateLimitMiddleware {    private $redis;    private $maxRequests = 100;    private $window = 60; // seconds

public function handle($request, $next) { $key = 'rate_limit:' . $_SERVER['REMOTE_ADDR']; $current = $this->redis->incr($key); if ($current === 1) { $this->redis->expire($key, $this->window); }

if ($current > $this->maxRequests) { return new Response('Too Many Requests', 429); }

return $next($request); }}


3. Laravel Rate Limiter (built-in)

In Laravel, rate limiting is built into the core. Uses Redis or cache. Supports named limiters and user-based segmentation.

// In RouteServiceProvideruse Illuminate\\Cache\\RateLimiting\\Limit;use Illuminate\\Http\\Request;

protected function configureRateLimiting(){ RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); });}

// In controllerpublic function index(){ $executed = RateLimiter::attempt( 'send-message:'.$user->id, $perMinute = 5, function() { // Send message } ); if (! $executed) { return response('Too Many Attempts.', 429); }}


4. PHP RateLimit (php-rateLimit/php-rateLimit)

A universal

Recommendations