All Projects → spatie → Laravel Rate Limited Job Middleware

spatie / Laravel Rate Limited Job Middleware

Licence: mit
A job middleware to rate limit jobs

Projects that are alternatives of or similar to Laravel Rate Limited Job Middleware

Laravel Localize Middleware
Configurable localization middleware for your Laravel >=5.1 application
Stars: ✭ 92 (-44.58%)
Mutual labels:  middleware, laravel
Node Rate Limiter Flexible
Node.js rate limit requests by key with atomic increments in single process or distributed environment.
Stars: ✭ 1,950 (+1074.7%)
Mutual labels:  queue, rate-limiting
Speedbump
A Redis-backed rate limiter in Go
Stars: ✭ 107 (-35.54%)
Mutual labels:  middleware, rate-limiting
Rabbitevents
Nuwber's events provide a simple observer implementation, allowing you to listen for various events that occur in your current and another application. For example, if you need to react to some event published from another API.
Stars: ✭ 84 (-49.4%)
Mutual labels:  laravel, queue
Aspnetcoreratelimit
ASP.NET Core rate limiting middleware
Stars: ✭ 2,199 (+1224.7%)
Mutual labels:  middleware, rate-limiting
Laravel Analytics
Analytics for the Laravel framework.
Stars: ✭ 91 (-45.18%)
Mutual labels:  middleware, laravel
Guzzle Advanced Throttle
A Guzzle middleware that can throttle requests according to (multiple) defined rules. It is also possible to define a caching strategy, e.g. get the response from cache when the rate limit is exceeded or always get a cached value to spare your rate limits. Using wildcards in host names is also supported.
Stars: ✭ 120 (-27.71%)
Mutual labels:  middleware, rate-limiting
Laravel Elasticbeanstalk Queue Worker
Stars: ✭ 48 (-71.08%)
Mutual labels:  laravel, queue
Laravel Queue Monitor
Monitoring Laravel Jobs with your Database
Stars: ✭ 136 (-18.07%)
Mutual labels:  laravel, queue
Laravel Authz
An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.
Stars: ✭ 136 (-18.07%)
Mutual labels:  middleware, laravel
Go Web
A new Golang MVC Framework. Like Laravel... but faster!
Stars: ✭ 79 (-52.41%)
Mutual labels:  middleware, laravel
Request Migrations
HTTP Request Migrations for API Versioning like Stripe
Stars: ✭ 149 (-10.24%)
Mutual labels:  middleware, laravel
Laravel Queue Rabbitmq
RabbitMQ driver for Laravel Queue. Supports Laravel Horizon.
Stars: ✭ 1,175 (+607.83%)
Mutual labels:  laravel, queue
Depictr
A middleware for rendering static pages when crawled by search engines
Stars: ✭ 92 (-44.58%)
Mutual labels:  middleware, laravel
Laravel Remember Uploads
Laravel Middleware and helper for remembering file uploads during validation redirects
Stars: ✭ 67 (-59.64%)
Mutual labels:  middleware, laravel
Sansdaemon
Batch process Laravel Queue without a daemon; Processes queue jobs and kills the process
Stars: ✭ 119 (-28.31%)
Mutual labels:  laravel, queue
Htmlcache
Laravel middleware to cache the rendered html
Stars: ✭ 35 (-78.92%)
Mutual labels:  middleware, laravel
Laravel Queue Database Ph4
Laravel Database Queue with Optimistic locking
Stars: ✭ 37 (-77.71%)
Mutual labels:  laravel, queue
L5 Very Basic Auth
Stateless HTTP basic auth for Laravel without the need for a database.
Stars: ✭ 127 (-23.49%)
Mutual labels:  middleware, laravel
Has Parameters
A trait that allows you to pass arguments to Laravel middleware in a more PHP'ish way.
Stars: ✭ 149 (-10.24%)
Mutual labels:  middleware, laravel

A job middleware to rate limit jobs

Latest Version on Packagist run-tests Total Downloads

This package contains a job middleware that can rate limit jobs in Laravel apps.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-rate-limited-job-middleware

This package requires Redis to be set up in your Laravel app.

Usage

By default, the middleware will only allow 5 jobs to be executed per second. Any jobs that are not allowed will be released for 5 seconds.

To apply the middleware just add the Spatie\RateLimitedMiddleware\RateLimited to the middlewares of your job.

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Spatie\RateLimitedMiddleware\RateLimited;

class TestJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function handle()
    {
        // your job logic
    }

    public function middleware()
    {
        return [new RateLimited()];
    }
}

Configuring attempts

When using rate limiting, the number of attempts of your job may be hard to predict. Instead of using a fixed number of attempts, it's better to use time based attempts.

You can add this to your job class:

/*
 * Determine the time at which the job should timeout.
 *
 */
public function retryUntil() :  \DateTime
{
    return now()->addDay();
}

Customizing the behaviour

You can customize all the behaviour. Here's an example where the middleware allows a maximum of 30 jobs to performed in a timespan off 60 seconds. Jobs that are not allowed will be released for 90 seconds.

// in your job

public function middleware()
{
    $rateLimitedMiddleware = (new RateLimited())
        ->allow(30)
        ->everySeconds(60)
        ->releaseAfterSeconds(90);

    return [$rateLimitedMiddleware];
}

Implementing Exponential Backoff

Often remote services such as APIs have rate limits or otherwise respond with a server error. Under these circumstances it makes sense to increment our delay before trying again. You can replace releaseAfter methods with releaseAfterBackoff($this->attempts() to use the default Rate Limiter interval of 5 seconds. Otherwise, you may chain the releaseAfter calls to adjust the backoff interval.

Example: releaseAfterOneMinute()

// in your job

/**
 * Attempt 1: Release after 60 seconds
 * Attempt 2: Release after 180 seconds
 * Attempt 3: Release after 420 seconds
 * Attempt 4: Release after 900 seconds
 */
public function middleware()
{
    $rateLimitedMiddleware = (new RateLimited())
        ->allow(30)
        ->everySeconds(60)
        ->releaseAfterOneMinute()
        ->releaseAfterBackoff($this->attempts());

    return [$rateLimitedMiddleware];
}

Example: releaseAfterSeconds()

// in your job

/**
 * Attempt 1: Release after 5 seconds
 * Attempt 2: Release after 15 seconds
 * Attempt 3: Release after 35 seconds
 * Attempt 4: Release after 75 seconds
 */
public function middleware()
{
    $rateLimitedMiddleware = (new RateLimited())
        ->allow(30)
        ->everySeconds(60)
        ->releaseAfterSeconds(5)
        ->releaseAfterBackoff($this->attempts());

    return [$rateLimitedMiddleware];
}

Example: Customize Backoff Rate

releaseAfterBackoff() accepts the rate multiplier as the second argument. By default, the multiplier is 2.

Below is an example of setting the rate to 3. You'll notice that as the attempts grow, the difference between a rate of 2 vs. a rate of 3 becomes significantly greater.

// in your job

/**
 * Attempt 1: Release after 5 seconds
 * Attempt 2: Release after 20 seconds
 * Attempt 3: Release after 65 seconds
 * Attempt 4: Release after 200 seconds
 */
public function middleware()
{
    $rateLimitedMiddleware = (new RateLimited())
        ->allow(30)
        ->everySeconds(60)
        ->releaseAfterBackoff($this->attempts(), 3);

    return [$rateLimitedMiddleware];
}

Customizing Redis

By default, the middleware will use the default Redis connection.

The default key that will be used in redis will be the name of the class that created the instance of the middleware. In most cases this will be name of job in which the middleware is applied. If this is not what you expect, you can use the key method to customize it.

Here's an example where a custom connection and custom key is used.

// in your job

public function middleware()
{
    $rateLimitedMiddleware = (new RateLimited())
        ->connectionName('my-custom-connection')
        ->key('my-custom-key');

    return [$rateLimitedMiddleware];
}

Conditionally applying the middleware

If you want to conditionally apply the middleware you can use the enabled method. If accepts a boolean that determines if the middleware should rate limit your job or not.

You can also pass a Closure to enabled. If it evaluates to a truthy value the middleware will be enable.

Here's a silly example where the rate limiting is only activated in January.

// in your job

public function middleware()
{
    $shouldRateLimitJobs = Carbon::now()->month === 1;

    $rateLimitedMiddleware = (new RateLimited())
        ->enabled($shouldRateLimitJobs);

    return [$rateLimitedMiddleware];
}

Available methods.

These methods are available to be called on the middleware. Their names should be self-explanatory.

  • allow(int $allowedNumberOfJobsInTimeSpan)
  • everySecond(int $timespanInSeconds = 1)
  • everySeconds(int $timespanInSeconds)
  • everyMinute(int $timespanInMinutes = 1)
  • everyMinutes(int $timespanInMinutes)
  • releaseAfterOneSecond()
  • releaseAfterSeconds(int $releaseInSeconds)
  • releaseAfterOneMinute()
  • releaseAfterMinutes(int $releaseInMinutes)
  • releaseAfterRandomSeconds(int $min = 1, int $max = 10)

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

This code is heavily based on the rate limiting example found in the Laravel docs.

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].