How to implement Laravel Redis Rate Limiting

Viewed 8102

Trying to implement Rate Limiting for the queue to run one job per second that makes an HTTP request to external API and load one types of data.

But not getting how to call the job, tried different option but not working. In the example:

Redis::throttle('key')->allow(10)->every(60)->then(function () {
    // Job logic...
}, function () {
    // Could not obtain lock...
    return $this->release(10);
});

What will put in // Job logic... dispatch the queue and this code will be within the queue class? and how to name the key? my queue name is loader.

Any help?

2 Answers

Put it inside the handle method of the Job.

public function handle() {
    Redis::throttle('key')->allow(10)->every(60)->then(function () {
        // Job logic...
    }, function () {
        // Could not obtain lock...
        return $this->release(10);
    });
}

The key should be any unique string. It will identify the restriction: "allow(10)->every(60)".

You can also use this package to use rate limiting with Redis or another source. Uses settings to set bucket size and rate as fractions of the time limit, so very small storage.

composer require bandwidth-throttle/token-bucket

https://github.com/bandwidth-throttle/token-bucket

Related