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

Ratelimiter Laravel Package

artisansdk/ratelimiter

Laravel rate limiting package providing flexible throttling for routes and actions with configurable rules, storage drivers, and easy middleware integration. Helps protect APIs from abuse, control request bursts, and manage per-user or per-IP limits with clear, adjustable settings.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require artisansdk/ratelimiter
    

    Publish the config file:

    php artisan vendor:publish --provider="ArtisanSDK\RateLimiter\RateLimiterServiceProvider"
    
  2. Basic Configuration Edit config/ratelimiter.php to define default limits (e.g., max_attempts=100, decay_seconds=1). Example route-level limit:

    Route::get('/api/endpoint', function () {
        return response()->json(['data' => 'protected']);
    })->middleware('ratelimit:api,100,1'); // 100 requests per minute
    
  3. First Use Case Apply the middleware to a route or group:

    Route::middleware(['ratelimit:api,100,1'])->group(function () {
        Route::get('/user', 'UserController@index');
        Route::post('/user', 'UserController@store');
    });
    

    Test with curl or Postman to verify throttling behavior.


Implementation Patterns

Route-Level Granularity

  • Dynamic Limits: Use route parameters to define per-endpoint limits:
    Route::get('/api/{resource}', function ($resource) {
        return response()->json(['data' => $resource]);
    })->middleware('ratelimit:api,100,1')->name('api.resource');
    
    Override in ratelimiter.php:
    'limits' => [
        'api' => [
            'default' => ['max_attempts' => 100, 'decay_seconds' => 1],
            'resource' => ['max_attempts' => 50, 'decay_seconds' => 1], // Override for `/api/resource`
        ],
    ],
    

Middleware Integration

  • Custom Middleware: Extend the base middleware for logic (e.g., user-specific limits):
    namespace App\Http\Middleware;
    
    use ArtisanSDK\RateLimiter\Middleware\RateLimitMiddleware;
    
    class CustomRateLimitMiddleware extends RateLimitMiddleware {
        protected function resolveLimit($request) {
            return $request->user()->rate_limit ?? config('ratelimiter.limits.api.default');
        }
    }
    
    Register in app/Http/Kernel.php:
    protected $routeMiddleware = [
        'ratelimit.custom' => \App\Http\Middleware\CustomRateLimitMiddleware::class,
    ];
    

Leaky Bucket Logic

  • Burst Handling: Leverage the leaky bucket algorithm for smooth rate limiting:
    // Manually check a request (e.g., in a controller)
    $limit = config('ratelimiter.limits.api.default');
    $key = 'api|' . $request->ip();
    if (!RateLimiter::try($key, $limit['max_attempts'], $limit['decay_seconds'])) {
        return response()->json(['error' => 'Too many requests'], 429);
    }
    

Caching Backend

  • Cache Drivers: Configure the cache driver in ratelimiter.php:
    'cache' => [
        'driver' => 'redis', // Supports 'file', 'database', 'redis', etc.
        'key_prefix' => 'ratelimiter_',
    ],
    
    For Redis, ensure the predis/predis package is installed.

Gotchas and Tips

Pitfalls

  • Key Collisions: Avoid ambiguous keys (e.g., ip() alone may not suffice for shared IPs). Use:
    $key = 'api|' . $request->ip() . '|' . $request->user()->id;
    
  • Cache Stampede: Under high traffic, Redis/file cache may bottleneck. Monitor and scale cache infrastructure.
  • Middleware Order: Place ratelimit before authentication middleware if limiting unauthenticated requests.

Debugging

  • Log Exceeded Requests: Enable logging in ratelimiter.php:
    'log_exceeded' => true,
    
    Check storage/logs/laravel.log for throttled attempts.
  • Test Locally: Use php artisan ratelimiter:test to simulate rate limits.

Extension Points

  • Custom Storage: Implement ArtisanSDK\RateLimiter\Contracts\RateLimiterStorage for custom backends (e.g., database).
  • Event Hooks: Listen for ratelimit.exceeded events:
    event(new RateLimitExceeded($request, $key, $limit));
    
  • Dynamic Decay: Adjust decay_seconds per route or user:
    Route::get('/premium', function () {
        // 10 requests per 5 seconds for premium users
    })->middleware('ratelimit:premium,10,5');
    

Config Quirks

  • Default Limits: Unset max_attempts or decay_seconds in ratelimiter.php to inherit global defaults.
  • Environment Overrides: Use environment variables for dynamic limits:
    'limits' => [
        'api' => [
            'default' => [
                'max_attempts' => env('RATE_LIMIT_MAX', 100),
                'decay_seconds' => env('RATE_LIMIT_DECAY', 1),
            ],
        ],
    ],
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope