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

ekreative/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. Enable Annotation: Ensure Doctrine annotations are enabled in config/packages/doctrine.yaml:

    doctrine:
        orm:
            annotations:
                listen_for_updates: true
    
  3. First Use Case: Apply @RateLimit to a controller action:

    use Noxlogic\RateLimitBundle\Annotation\RateLimit;
    
    class ApiController extends AbstractController
    {
        /**
         * @RateLimit(limit=10, interval=60)
         */
        public function sensitiveAction()
        {
            // Your logic here
        }
    }
    

    This limits the action to 10 calls per minute per user (or cache key).


Implementation Patterns

Common Workflows

  1. API Rate Limiting: Use @RateLimit on API endpoints to prevent abuse:

    /**
     * @RateLimit(limit=60, interval=3600) // 60 calls/hour
     */
    public function getData()
    {
        return $this->json(['data' => '...']);
    }
    
  2. Custom Key Generation: Override the default key generator (e.g., for IP-based limits):

    # config/packages/noxlogic_ratelimit.yaml
    noxlogic_ratelimit:
        key_generator: App\Service\CustomRateLimitKeyGenerator
    

    Implement Noxlogic\RateLimitBundle\KeyGenerator\KeyGeneratorInterface:

    class CustomRateLimitKeyGenerator implements KeyGeneratorInterface
    {
        public function generateKey(Request $request): string
        {
            return $request->getClientIp();
        }
    }
    
  3. Dynamic Limits: Use a service to fetch limits from a database or config:

    /**
     * @RateLimit(limit=service("app.rate_limit_service").getLimit())
     */
    public function dynamicAction()
    {
        // ...
    }
    
  4. Middleware Integration: Combine with Symfony middleware for global limits:

    // src/EventListener/RateLimitListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->attributes->has('_rate_limit')) {
            $limit = $request->attributes->get('_rate_limit');
            // Custom logic (e.g., return 429 if exceeded)
        }
    }
    

Integration Tips

  • Caching: Defaults to Symfony’s cache system. Configure in noxlogic_ratelimit.yaml:
    noxlogic_ratelimit:
        cache_pool: cache.app
    
  • FOSOAuthServer: Works out-of-the-box. For custom auth, extend the OAuthKeyGenerator.
  • Testing: Mock the cache or use RateLimitBundle's test utilities:
    $this->container->get('noxlogic_ratelimit.cache')->clear();
    

Gotchas and Tips

Pitfalls

  1. Annotation Parsing:

    • Ensure annotations are loaded before the request is processed. Use kernel.request event if needed.
    • If using PHP 7.4+, enable attributes in config/packages/framework.yaml for attribute-based alternatives:
      framework:
          attributes:
              enabled: true
      
  2. Cache Key Collisions:

    • Default key generator uses user_id (from FOSOAuth) or ip. For shared limits (e.g., team accounts), customize the key generator to include additional context (e.g., user_id + team_id).
  3. Performance:

    • High-traffic APIs may overload the cache. Use a distributed cache (Redis) and monitor cache:clear operations.
    • Avoid overly granular limits (e.g., per-second) on shared resources.
  4. Configuration Overrides:

    • Bundle settings in noxlogic_ratelimit.yaml must match the bundle’s expected structure. Validate with:
      php bin/console debug:config noxlogic_ratelimit
      

Debugging

  • Check Limits:
    php bin/console debug:container --tag="noxlogic_ratelimit.key_generator"
    
  • Log Exceeded Requests: Extend the RateLimitListener to log 429 responses:
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($event->getException() instanceof RateLimitExceededException) {
            $this->logger->warning('Rate limit exceeded', [
                'action' => $event->getRequest()->get('_route'),
                'key' => $event->getRequest()->attributes->get('_rate_limit_key'),
            ]);
        }
    }
    

Extension Points

  1. Custom Exceptions: Override the default RateLimitExceededException:

    class CustomRateLimitException extends \Exception implements RateLimitExceededExceptionInterface
    {
        public function getRetryAfter(): int
        {
            return $this->retryAfter;
        }
    }
    

    Register in services.yaml:

    Noxlogic\RateLimitBundle\EventListener\RateLimitListener:
        arguments:
            $exceptionClass: App\Exception\CustomRateLimitException
    
  2. Async Validation: Use Symfony’s EventDispatcher to validate limits asynchronously (e.g., in a queue):

    $eventDispatcher->dispatch(new RateLimitCheckEvent($request, $limit));
    
  3. Rate Limit Headers: Add X-RateLimit-* headers manually in a subscriber:

    public function onKernelResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();
        $remaining = $this->cache->get($key . ':remaining');
        $response->headers->set('X-RateLimit-Remaining', $remaining);
    }
    
  4. Bulk Actions: For batch operations (e.g., bulk API calls), use a shared key or increment the limit dynamically:

    /**
     * @RateLimit(limit=service("app.bulk_rate_limit_service").getBulkLimit())
     */
    public function bulkAction()
    {
        // ...
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware