Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ratelimit Bundle Laravel Package

drefined/ratelimit-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require noxlogic/ratelimit-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Noxlogic\RateLimitBundle\NoxlogicRateLimitBundle::class => ['all' => true],
    ];
    
  2. 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' => '...']);
    }
    
  3. First Use Case Apply @RateLimit to API endpoints to restrict calls (e.g., limit=50, interval=3600 for 50 requests/hour).


Implementation Patterns

Common Workflows

  1. Annotation-Based Rate Limiting Use @RateLimit on controller methods:

    /**
     * @RateLimit(limit=100, interval=60, message="Too many requests")
     */
    public function getData()
    {
        // ...
    }
    
  2. 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
    
  3. Integration with FOSOAuthServerBundle The bundle auto-integrates with OAuth tokens. For custom auth, implement Noxlogic\RateLimitBundle\KeyGenerator\KeyGeneratorInterface.

  4. 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);
    }
    
  5. 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);
    }
    

Gotchas and Tips

Pitfalls

  1. Cache Dependency The bundle relies on Symfony’s cache system. Ensure cache:clear is run after configuration changes.

    php bin/console cache:clear
    
  2. 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');
    }
    
  3. 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
    
  4. FOSOAuthServerBundle Conflicts If not using OAuth, disable the default listener in config:

    noxlogic_ratelimit:
        listeners:
            fos_oauth: false
    

Debugging Tips

  1. 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.

  2. Log Rate Limit Events Enable debug mode to log rate limit checks:

    noxlogic_ratelimit:
        debug: true
    
  3. Test Locally Simulate rate limits with curl or Postman by rapidly calling endpoints.

Extension Points

  1. Custom Responses Override the default RateLimitException response:

    services:
        Noxlogic\RateLimitBundle\Exception\RateLimitExceptionListener:
            arguments:
                $responseFactory: App\Service\CustomRateLimitResponseFactory
    
  2. 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 }
    
  3. Redis Support Configure Redis as the cache backend for distributed rate limiting:

    framework:
        cache:
            app: cache.adapter.redis
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui