Rate Limit Middleware
CakePHP 5.3 Feature
RateLimitMiddleware provides built-in request rate limiting to protect your application from abuse.
This demo shows how to limit requests by IP address. Try refreshing this page multiple times quickly!
Request Counter
You've made 1 requests in this session.
Rate Limit: 5 requests per minute per IP address
If you exceed the limit, you'll receive a 429 Too Many Requests response.
Implementation Example
// src/Http/Middleware/DemoRateLimitMiddleware.php
use Cake\Http\Middleware\RateLimitMiddleware;
class DemoRateLimitMiddleware extends RateLimitMiddleware
{
public function __construct()
{
parent::__construct([
'limit' => 5, // Max requests
'window' => 60, // Time window (seconds)
'identifier' => 'ip', // Identify by IP address
'strategy' => 'sliding_window', // Rate limit strategy
'headers' => true, // Add X-RateLimit-* headers
]);
}
}
Features
- Multiple Strategies:
sliding_window,token_bucket, orfixed_window - Built-in Identifiers:
ip,user,session, or custom via callback - Automatic Headers: Sends
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset - 429 Response: Returns standard HTTP 429 status when limit exceeded
- Cache Integration: Uses CakePHP cache for efficient rate tracking
Common Use Cases
- API rate limiting (per API key or user)
- Login attempt throttling (prevent brute force)
- Contact form spam protection
- Resource-intensive endpoint protection

