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

Laravel Rate Limited Job Middleware Laravel Package

spatie/laravel-rate-limited-job-middleware

Laravel job middleware to rate limit queued jobs. Allow a configurable number of jobs per second and automatically release throttled jobs for a delay. Easy to attach per job via middleware, with support for time-based attempts when rate limiting.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Native Integration: The package leverages Laravel’s built-in job middleware system, ensuring seamless integration with Laravel’s queue workers (e.g., app/Jobs/*). This aligns perfectly with Laravel’s event-driven and asynchronous architecture, making it ideal for systems where job throttling is critical (e.g., API rate limiting, background processing, or external service calls).
  • Decoupled Design: The middleware pattern allows for non-intrusive rate limiting—jobs can be wrapped without modifying their core logic. This adheres to the Single Responsibility Principle (SRP) and Open/Closed Principle (OCP).
  • Extensibility: Supports custom rate-limit strategies (e.g., per-job, per-user, global) via configuration, enabling granular control over throttling rules.

Integration Feasibility

  • Low Friction: Requires minimal setup—just install via Composer, publish the config, and attach the middleware to jobs or globally. No database migrations or complex dependencies.
  • Queue Worker Compatibility: Works with all Laravel-supported queue drivers (database, Redis, SQS, etc.), though Redis is recommended for distributed rate limiting (e.g., across multiple workers).
  • Laravel Version Support: Explicitly supports Laravel 10.x (as of 2026-02-25), but likely backward-compatible with Laravel 9.x. Check for breaking changes if upgrading from older versions.

Technical Risk

  • Performance Overhead: Rate limiting introduces locking mechanisms (e.g., Redis SETNX or database transactions), which may add latency if not optimized. Benchmark under expected load.
  • Distributed Systems Complexity: In multi-worker or multi-server setups, improper Redis configuration (e.g., no shared cache) could lead to false positives/negatives in rate limiting.
  • Job Retry Logic: If jobs are requeued after rate limiting, ensure the middleware doesn’t create infinite loops (e.g., via shouldQueue() checks or retryUntil()).
  • Monitoring Gaps: No built-in metrics for rate-limited jobs; requires custom logging or integration with tools like Laravel Horizon or Prometheus.

Key Questions

  1. Rate-Limit Storage Backend:
    • Will Redis be used for distributed rate limiting, or is a database-based solution sufficient?
    • What are the expected QPS (queries per second) for rate-limited jobs?
  2. Job Criticality:
    • Are rate-limited jobs idempotent? If not, how will failures be handled (e.g., retries, dead-letter queues)?
  3. Existing Infrastructure:
    • Does the system already use Laravel Horizon or another queue monitor? If so, how will rate-limited jobs be visualized?
  4. Customization Needs:
    • Are default rate-limit strategies (e.g., 60 requests per minute) sufficient, or will dynamic rules (e.g., per-user tiers) be required?
  5. Testing Requirements:
    • How will rate-limiting behavior be tested in CI/CD (e.g., mocking Redis or using in-memory stores)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Ideal for Laravel applications using queues (e.g., dispatch(), bus:work). Works alongside other Spatie packages (e.g., laravel-activitylog) if unified logging is needed.
  • Queue Drivers:
    • Redis: Best for scalability and low-latency rate limiting (recommended for production).
    • Database: Simpler but less performant under high concurrency.
    • SQS/SNS: Possible but requires custom logic for rate limiting (not natively supported).
  • Middleware Placement:
    • Global: Apply to all jobs via HandleJobsMiddleware in app/Http/Kernel.php.
    • Per-Job: Attach to specific jobs (e.g., public function middleware() { return [\Spatie\RateLimitedJobMiddleware\RateLimitedJobMiddleware::class]; }).

Migration Path

  1. Assessment Phase:
    • Audit existing jobs to identify candidates for rate limiting (e.g., API consumers, external webhooks).
    • Define rate-limit rules (e.g., 100 requests/hour per user).
  2. Pilot Deployment:
    • Start with non-critical jobs to validate performance impact.
    • Use database-backed rate limiting initially for simplicity.
  3. Production Rollout:
    • Migrate to Redis for distributed environments.
    • Implement feature flags to toggle rate limiting dynamically.
  4. Monitoring Setup:
    • Add logging for rate-limited jobs (e.g., Spatie\RateLimitedJobMiddleware\Events\JobRateLimited).
    • Integrate with Laravel Horizon or Prometheus for observability.

Compatibility

  • Laravel Versions: Tested on Laravel 10.x; verify compatibility with Laravel 9.x if needed.
  • PHP Version: Requires PHP 8.1+ (check for str_contains/array_key_first usage).
  • Dependencies:
    • Redis: Only required for distributed rate limiting (not for local testing).
    • Predis: If using Redis, ensure predis/predis is installed (or use spatie/laravel-redis).
  • Conflict Risk: Low—uses Laravel’s native middleware system. Potential conflicts with other job middleware (e.g., Spatie\QueueableJobMiddleware).

Sequencing

  1. Installation:
    composer require spatie/laravel-rate-limited-job-middleware
    php artisan vendor:publish --provider="Spatie\RateLimitedJobMiddleware\RateLimitedJobMiddlewareServiceProvider"
    
  2. Configuration:
    • Define rate limits in config/rate-limited-job-middleware.php:
      'limits' => [
          'api-webhook' => '100|minute',
          'default' => '60|hour',
      ],
      
  3. Middleware Attachment:
    • Global: Add to app/Http/Kernel.php:
      protected $middlewareGroups = [
          'web' => [...],
          'api' => [...],
          'jobs' => [
              \Spatie\RateLimitedJobMiddleware\RateLimitedJobMiddleware::class,
          ],
      ];
      
    • Per-job: Annotate job class:
      public function middleware()
      {
          return [\Spatie\RateLimitedJobMiddleware\RateLimitedJobMiddleware::class];
      }
      
  4. Testing:
    • Unit test middleware logic (e.g., mock Redis).
    • Load test with expected concurrency to validate throttling.

Operational Impact

Maintenance

  • Configuration-Driven: Rate limits are managed via config/rate-limited-job-middleware.php, reducing code changes.
  • Dependency Updates: Monitor Spatie’s releases for breaking changes (e.g., Laravel version drops).
  • Logging:
    • Default logs rate-limited events to storage/logs/laravel.log.
    • Extend with custom logging (e.g., Monolog channels) for analytics.

Support

  • Troubleshooting:
    • Common issues: Redis connection failures, misconfigured rate limits, or job retry loops.
    • Debug with php artisan queue:failed and check middleware logs.
  • Documentation: Comprehensive README with examples; Spatie’s support channels available.
  • Community: Active GitHub repo (356 stars, recent releases) with responsive maintainers.

Scaling

  • Horizontal Scaling:
    • Redis-backed rate limiting scales with worker count (ensure Redis cluster is sized appropriately).
    • Database-backed solutions may require optimized queries (e.g., indexed job_key columns).
  • Rate-Limit Granularity:
    • Adjust limits config dynamically (e.g., via environment variables or a database table).
    • Use Laravel’s config caching (php artisan config:cache) for performance.
  • Fallback Mechanisms:
    • Implement circuit breakers for Redis failures (e.g., fall back to database or allow all jobs).

Failure Modes

Failure Scenario Impact Mitigation
Redis connection loss Rate limiting fails (jobs unthrottled) Fallback to database or allow all jobs temporarily.
Database lock contention Jobs stall under high load Use Redis; optimize database queries or increase connection pool size.
Misconfigured rate limits Over/under-throttling Validate configs in staging; use feature flags to toggle rate limiting.
Job retry loops Infinite rate-limited retries Add retryUntil() logic or dead-letter queue for failed jobs.
Middleware bypass Jobs skip rate limiting Audit job middleware chains; enforce
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport