Installation
composer require noxlogic/ratelimit-bundle
Add to config/bundles.php:
return [
// ...
Noxlogic\RateLimitBundle\NoxlogicRateLimitBundle::class => ['all' => true],
];
Basic Usage
Annotate a controller action with @RateLimit:
use Noxlogic\RateLimitBundle\Annotation\RateLimit;
/**
* @RateLimit(limit=10, interval=60)
*/
public function sensitiveAction()
{
return response()->json(['data' => '...']);
}
First Use Case
Apply @RateLimit to API endpoints to restrict calls (e.g., limit=50, interval=3600 for 50 requests/hour).
Annotation-Based Rate Limiting
Use @RateLimit on controller methods:
/**
* @RateLimit(limit=100, interval=60, message="Too many requests")
*/
public function getData()
{
// ...
}
Custom Key Generation Override the default key generator (e.g., for IP-based or user-specific limits):
# config/packages/noxlogic_ratelimit.yaml
noxlogic_ratelimit:
key_generator: App\Service\CustomRateLimitKeyGenerator
Integration with FOSOAuthServerBundle
The bundle auto-integrates with OAuth tokens. For custom auth, implement Noxlogic\RateLimitBundle\KeyGenerator\KeyGeneratorInterface.
Middleware for Global Rate Limiting Apply rate limits globally via middleware:
public function handle($request, Closure $next)
{
if ($request->is('api/*')) {
$this->rateLimitService->check('global_api', 100, 60);
}
return $next($request);
}
Dynamic Limits via Dependency Injection
Inject the RateLimitService to enforce limits programmatically:
public function __construct(private RateLimitService $rateLimitService) {}
public function dynamicAction()
{
$this->rateLimitService->check('dynamic_key', $limit, $interval);
}
Cache Dependency
The bundle relies on Symfony’s cache system. Ensure cache:clear is run after configuration changes.
php bin/console cache:clear
Key Collisions
Default key generation uses Request::getClientIp(). For shared IPs (e.g., load balancers), override the key generator:
public function generateKey(Request $request): string
{
return 'shared_key_' . $request->headers->get('X-Forwarded-For');
}
Annotation Parsing
The @RateLimit annotation must be parsed by Doctrine’s annotation reader. If using PHP 8+, ensure doctrine/annotations is installed:
composer require doctrine/annotations
FOSOAuthServerBundle Conflicts If not using OAuth, disable the default listener in config:
noxlogic_ratelimit:
listeners:
fos_oauth: false
Check Cache Entries
Inspect rate limit keys in the cache (e.g., php bin/console cache:pool:list).
Use php bin/console debug:cache to verify cache pools.
Log Rate Limit Events Enable debug mode to log rate limit checks:
noxlogic_ratelimit:
debug: true
Test Locally
Simulate rate limits with curl or Postman by rapidly calling endpoints.
Custom Responses
Override the default RateLimitException response:
services:
Noxlogic\RateLimitBundle\Exception\RateLimitExceptionListener:
arguments:
$responseFactory: App\Service\CustomRateLimitResponseFactory
Event Listeners Extend functionality via events (e.g., log rate limit hits):
use Noxlogic\RateLimitBundle\Event\RateLimitEvent;
public function onRateLimit(RateLimitEvent $event)
{
// Custom logic (e.g., logging)
}
Register in services.yaml:
services:
App\EventListener\RateLimitLogger:
tags:
- { name: kernel.event_listener, event: noxlogic.ratelimit, method: onRateLimit }
Redis Support Configure Redis as the cache backend for distributed rate limiting:
framework:
cache:
app: cache.adapter.redis
How can I help you explore Laravel packages today?