PHPackages                             spatie/laravel-rate-limited-job-middleware - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. spatie/laravel-rate-limited-job-middleware

ActiveLibrary[Queues &amp; Workers](/categories/queues)

spatie/laravel-rate-limited-job-middleware
==========================================

A middleware that can rate limit jobs

2.9.0(2mo ago)3584.0M—5.3%316MITPHPPHP ^8.2CI passing

Since Sep 28Pushed 2mo ago4 watchersCompare

[ Source](https://github.com/spatie/laravel-rate-limited-job-middleware)[ Packagist](https://packagist.org/packages/spatie/laravel-rate-limited-job-middleware)[ Docs](https://github.com/spatie/laravel-rate-limited-job-middleware)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-laravel-rate-limited-job-middleware/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (36)Used By (6)

A job middleware to rate limit jobs
===================================

[](#a-job-middleware-to-rate-limit-jobs)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ba394895653bc67020e1c3b2672b2f99df577b7a6e51d16444fed2d752bf3ecf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d726174652d6c696d697465642d6a6f622d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-rate-limited-job-middleware)[![run-tests](https://github.com/spatie/laravel-rate-limited-job-middleware/workflows/run-tests/badge.svg)](https://github.com/spatie/laravel-rate-limited-job-middleware/workflows/run-tests/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/a418fc0ea77f9f8f5f9c7676fd04728ca6e26545f178bfc5c327b922dfca4240/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d726174652d6c696d697465642d6a6f622d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-rate-limited-job-middleware)

This package contains a [job middleware](https://laravel.com/docs/master/queues#job-middleware) that can rate limit jobs in Laravel apps.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/704bfcaa41f4336e9093385a5087de03f2061d5f24d9f33a67323726805ee93a/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d726174652d6c696d697465642d6a6f622d6d6964646c65776172652e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-rate-limited-job-middleware)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

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

Usage
-----

[](#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

[](#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](https://laravel.com/docs/master/queues#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

[](#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 of 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

[](#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()`

[](#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()`

[](#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

[](#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];
}
```

### Not releasing jobs

[](#not-releasing-jobs)

If you don't want to retry a job when it is ratelimited, you can use the `dontRelease()` method. This is useful in situations where you have jobs that run periodically and you don't care about a job being skipped.

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

    return [$rateLimitedMiddleware];
}
```

### Customizing Redis

[](#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

[](#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.

[](#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)`

### Available events.

[](#available-events)

- `\Spatie\RateLimitedMiddleware\Events\LimitExceeded` when the rate limit has been exceeded.

### Testing

[](#testing)

```
composer test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

### Security

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Postcardware
------------

[](#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](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

This code is heavily based on [the rate limiting example](https://laravel.com/docs/master/queues#job-middleware) found in the Laravel docs.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

69

—

FairBetter than 100% of packages

Maintenance84

Actively maintained with recent releases

Popularity63

Solid adoption and visibility

Community32

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 54.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~71 days

Recently: every ~134 days

Total

34

Last Release

83d ago

Major Versions

0.0.3 → 1.0.02019-10-04

1.5.0 → 2.0.02021-09-15

PHP version history (4 changes)0.0.1PHP ^7.3

1.5.0PHP ^7.3|^8.0

2.0.0PHP ^8.0

2.8.1PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (112 commits)")[![riasvdv](https://avatars.githubusercontent.com/u/3626559?v=4)](https://github.com/riasvdv "riasvdv (47 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (9 commits)")[![ElRochito](https://avatars.githubusercontent.com/u/1737307?v=4)](https://github.com/ElRochito "ElRochito (7 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (6 commits)")[![tylers-username](https://avatars.githubusercontent.com/u/4887071?v=4)](https://github.com/tylers-username "tylers-username (3 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (3 commits)")[![ralphjsmit](https://avatars.githubusercontent.com/u/59207045?v=4)](https://github.com/ralphjsmit "ralphjsmit (3 commits)")[![Sammyjo20](https://avatars.githubusercontent.com/u/29132017?v=4)](https://github.com/Sammyjo20 "Sammyjo20 (3 commits)")[![stevebauman](https://avatars.githubusercontent.com/u/6421846?v=4)](https://github.com/stevebauman "stevebauman (2 commits)")[![rogerio-pereira](https://avatars.githubusercontent.com/u/13219168?v=4)](https://github.com/rogerio-pereira "rogerio-pereira (2 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (1 commits)")[![thecaliskan](https://avatars.githubusercontent.com/u/13554944?v=4)](https://github.com/thecaliskan "thecaliskan (1 commits)")[![bumbummen99](https://avatars.githubusercontent.com/u/4533331?v=4)](https://github.com/bumbummen99 "bumbummen99 (1 commits)")[![ankurk91](https://avatars.githubusercontent.com/u/6111524?v=4)](https://github.com/ankurk91 "ankurk91 (1 commits)")[![svenluijten](https://avatars.githubusercontent.com/u/11269635?v=4)](https://github.com/svenluijten "svenluijten (1 commits)")[![gauravmak](https://avatars.githubusercontent.com/u/11887260?v=4)](https://github.com/gauravmak "gauravmak (1 commits)")[![edalzell](https://avatars.githubusercontent.com/u/6069653?v=4)](https://github.com/edalzell "edalzell (1 commits)")[![jarektkaczyk](https://avatars.githubusercontent.com/u/6928818?v=4)](https://github.com/jarektkaczyk "jarektkaczyk (1 commits)")[![michaellatham](https://avatars.githubusercontent.com/u/44771437?v=4)](https://github.com/michaellatham "michaellatham (1 commits)")

---

Tags

laravelmiddlewarequeuerate-limitingspatielaravel-rate-limited-job-middleware

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/spatie-laravel-rate-limited-job-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-rate-limited-job-middleware/health.svg)](https://phpackages.com/packages/spatie-laravel-rate-limited-job-middleware)
```

###  Alternatives

[spatie/async

Asynchronous and parallel PHP with the PCNTL extension

2.8k4.5M37](/packages/spatie-async)[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[spatie/laravel-queueable-action

Queueable action support in Laravel

6993.3M15](/packages/spatie-laravel-queueable-action)[prwnr/laravel-streamer

Events streaming package for Laravel that uses Redis 5 streams

110196.9k1](/packages/prwnr-laravel-streamer)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

3786.5k](/packages/harris21-laravel-fuse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
