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

Technical Evaluation

Architecture Fit

  • Strengths:

    • Laravel 13 Support: Explicitly adds compatibility with Laravel 13, aligning with the latest LTS release cycle and ensuring long-term viability for new projects or migrations.
    • Leaky Bucket Algorithm: Retains its suitability for burst-handling APIs (e.g., payment gateways, auth systems) where fixed-window limits are inflexible.
    • Middleware Integration: Continues to leverage Laravel’s native middleware stack, reducing boilerplate and improving maintainability.
    • Storage Backends: Maintains flexibility with Redis (distributed) and database (simpler deployments) backends, though no new backends were added.
  • Weaknesses:

    • No Built-in Distributed Locking: Still lacks atomic operations for multi-server setups unless explicitly configured (e.g., Redis Lua scripts). This remains a critical gap for high-concurrency environments.
    • Limited Metrics/Observability: No native integration with Prometheus/StatsD or Laravel’s monitoring tools (e.g., laravel-debugbar). Custom instrumentation is still required.
    • No Circuit Breaker Tie-In: Continues to lack integration with Laravel’s RateLimiter facade or third-party circuit breakers (e.g., spatie/laravel-circuitbreaker), which could complement rate limiting during failures.
  • Key Use Cases:

    • API Rate Limiting: Ideal for public APIs (e.g., /api/v1/users) with burst traffic patterns.
    • Abuse Prevention: Mitigates brute-force attacks on auth endpoints (/login, /forgot-password).
    • Cost Control: Useful for SaaS metered endpoints (e.g., /billing/webhooks) to enforce tiered limits.
    • Laravel 13 Projects: Now a first-class citizen for new Laravel applications, reducing friction for teams adopting the latest framework version.

Integration Feasibility

  • Laravel Ecosystem Compatibility:

    • Laravel 13 Support: Confirmed via explicit PR, ensuring compatibility with Laravel’s latest features (e.g., improved dependency injection, new HTTP client).
    • Service Provider: Continues to adhere to Laravel’s register/boot methods, maintaining best practices for package integration.
    • Configuration: Supports .env variables for dynamic tuning (e.g., RATE_LIMIT=60/second), enabling environment-specific configurations.
  • Dependencies:

    • Redis: Still required for distributed setups but optional for single-server apps. Assumes Redis is pre-configured in config/database.php.
    • PHP Extensions: No additional requirements beyond Laravel’s defaults (e.g., predis or php-redis for Redis).
    • Laravel 13-Specific: May implicitly rely on Laravel 13’s updated Illuminate\Support\Facades or Illuminate\Http components, though no breaking changes are noted.
  • Customization Points:

    • Leaky Bucket Parameters: Adjustable capacity and refill_rate per route remain unchanged.
    • Response Customization: Override default 429 Too Many Requests responses via middleware handle() method.
    • Storage Fallback: Database fallback persists but may need testing with Laravel 13’s updated query builder.

Technical Risk

  • High-Risk Areas:

    • Redis Misconfiguration: Incorrect TTL settings or missing persistence could still lead to rate limit bypasses or data loss in distributed environments.
    • Concurrency Issues: Without explicit Redis locking (e.g., SETNX or Lua scripts), race conditions may inflate token counts, especially in Laravel 13’s more concurrent request-handling model.
    • Laravel 13 Compatibility: While officially supported, untested edge cases (e.g., new middleware pipeline behavior, updated facades) could introduce subtle bugs.
    • Cold Starts: Database-backed storage may still introduce latency spikes during initial requests, particularly with Laravel 13’s optimized bootstrapping.
  • Mitigation Strategies:

    • Redis Best Practices: Enforce atomic operations (e.g., Lua scripts) for token updates, especially in multi-server setups. Consider extending the package with a useAtomicOperations() flag.
    • Load Testing: Validate under Laravel 13’s concurrent request handling (e.g., using spatie/laravel-horizon for queue workers) to ensure bucket refill behavior is stable.
    • Fallback Mechanism: Implement graceful degradation (e.g., allow requests if Redis fails but log violations) using Laravel 13’s improved error handling (e.g., Problem exceptions).
    • Laravel 13-Specific Testing: Test with Laravel 13’s new features (e.g., app()->bind() changes, updated Route caching) to catch integration issues early.
  • Open Questions:

    • How does the package handle sub-second precision for token refills in Laravel 13’s optimized event loop? (Critical for high-frequency APIs like WebSockets or real-time dashboards.)
    • Are there built-in retries for transient Redis failures in Laravel 13, or does it fail closed? Clarify if Laravel 13’s Illuminate\Redis\Connections\Connection changes affect this.
    • Does it support dynamic key generation (e.g., user-specific or request-attribute-based keys) out of the box, or requires custom middleware? This is increasingly important for Laravel 13’s API resource-based auth (e.g., Sanctum v3).
    • How does the package interact with Laravel 13’s new HTTP client (Illuminate\Http\Client) if used for async rate-limiting checks?

Integration Approach

Stack Fit

  • Laravel Version Compatibility:

    • Laravel 13 Support: Officially compatible, making it a viable choice for new projects or migrations to Laravel 13. Verify composer.json constraints:
      "require": {
          "laravel/framework": "^13.0",
          "artisansdk/ratelimiter": "^1.2"
      }
      
    • Backward Compatibility: No indication of Laravel 9.x/10.x deprecation, but test thoroughly if supporting older versions.
  • Tech Stack Synergy:

    • Redis: Ideal for high-throughput Laravel 13 apps (e.g., livewire, queues, or serverless). Pair with laravel-redis v13 for consistency.
    • Database: Suitable for monolithic Laravel 13 apps but risks performance under scale. Use mysql/pgsql with proper indexing on the key column (Laravel 13’s query builder may optimize this further).
    • Queue Workers: If using async rate limiting (e.g., for delayed jobs), ensure Redis is shared across Laravel 13’s queue workers (e.g., horizon or laravel-queues).
  • Alternatives Considered:

    • spatie/laravel-rate-limiter: Fixed-window algorithm (less burst-friendly) but may integrate better with Laravel 13’s new scheduling system.
    • digitalcreative/laravel-ratelimiter: Token bucket alternative (may lack leaky bucket features or Laravel 13 support).
    • Custom Solution: Rolling your own with Redis scripts (higher maintenance) but offers full control over Laravel 13’s new features (e.g., app()->singleton()).

Migration Path

  1. Assessment Phase:

    • Audit current rate-limiting logic (e.g., custom middleware, throttle middleware, or Laravel 10’s RateLimiter).
    • Identify Laravel 13-specific endpoints requiring granular limits (e.g., /livewire/updates, /api/resources).
  2. Proof of Concept:

    • Install package: composer require artisansdk/ratelimiter:^1.2.
    • Configure in config/ratelimiter.php (publish config with php artisan vendor:publish --provider="ArtisanSdk\RateLimiter\RateLimiterServiceProvider").
    • Test with a Laravel 13 route:
      Route::middleware([\ArtisanSdk\RateLimiter\Middleware\RateLimiterMiddleware::class])
           ->get('/test', function () { return response()->json(['status' => 'ok']); });
      
  3. Phased Rollout:

    • Phase 1: Replace global throttle middleware with RateLimiterMiddleware for critical Laravel 13 endpoints (e.g., /api/v1/resources).
    • Phase 2: Migrate remaining routes, adjusting capacity/refill_rate based on load tests with Laravel 13’s optimized request handling.
    • Phase 3: Deprecate legacy rate-limiting logic (e.g., custom Redis scripts) and update documentation for Laravel 13’s new features.
  4. Configuration Example (Laravel 13):

    // config/ratelimiter.php
    'limits' => [
        'auth.login' => [
            'driver' => 'redis',
            'capacity' => 5,
            'refill_rate' => 1,
            'key' => 'rate_limit_auth_login_{$ip}',
            'middleware' => ['web
    
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