question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Rate limiter per job name

See original GitHub issue

Want to explore the possibility to rate limit a queue based on the job name. This would be a worker-level config which would enable applying a rate limiter to specific job names. This would be similar to the groupKey but would remove the need to pass an extra groupKey param in job data, the job name itself would act as the groupKey. I like this because it centralizes the rate limit implementation to solely the worker, doesn’t matter what is passed as job data as long as the job name is correct.

My thoughts are something along these lines:

const worker = new Worker("myQueue",  async job => {

    switch (job.name) {
      case "limitedJob": {
        // rate limited 
        break;
      }
      case "normalJob": {
       // no rate limiting applied
        break;
      }
      default:
       
    }
  },
  {
    limiter: {
      jobs: {
          // this key indicates the job name to be limited
         limitedJob: {
            // same rate limit config as usual
            max: 30,
            duration: 1000
         }
      }
    }
  }
);

Happy to look into implementing this myself if it’s a possibility!

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Kukunincommented, Sep 23, 2021

Here is a code snippet that I have in my project:

const { RateLimiterRedis } = require('rate-limiter-flexible')

const withRateLimit = (fn, { key, max, duration }) => {
  const limiter = new RateLimiterRedis({
    storeClient: new Redis(),
    points: max,
    duration: duration,
    keyPrefix: key,
  })

  const wrapper = async (...args) => {
    try {
      await limiter.consume('')
      return fn(...args)
    } catch (e) {
      if (e instanceof Error) {
        throw e
      }
      const delay = e.msBeforeNext
      if (delay > 0) {
        await new Promise((resolve) => setTimeout(resolve, delay))
      }
      return wrapper(...args)
    }
  }
  return wrapper
}

I can use it as:

new Worker('queue', withRateLimit(async () => {
  // job handler here
}, { key: 'my queue', max: 10, duration: 60 })

The only limitation, that duration is in seconds.

1reaction
Kukunincommented, Sep 23, 2021

As an alternative to implementing this into BullMQ, a separate limiter might be useful, such as https://github.com/microlinkhq/async-ratelimiter.

The core feature of any limiter is just await delay(X) where X depends on previous calls, so it’s possible to write a simple wrapper around the job handler that will wait a correspondent amount of time (0 if it’s under the limit). Or, a wrapper that will reschedule the job with the right delay (if BullMQ allows it)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Rate limiting - BullMQ
The rate limiter is global, so if you have for example 10 workers for one queue with the above settings, still only 10...
Read more >
Laravel 8 Job Rate Limiter that can be used without Redis
Laravel 8 Job Rate Limiter that can be used without Redis - AppServiceProvider.php.
Read more >
A job middleware to rate limit jobs - Freek.dev
Introducing laravel-rate-limited-job-middleware​​ You can use the RateLimited middleware by letting the middleware method of your job return it.  ...
Read more >
Rate Limiting - Laravel - The PHP Framework For Web Artisans
The Illuminate\Support\Facades\RateLimiter facade may be used to interact with the rate limiter. The simplest method offered by the rate limiter is the attempt ......
Read more >
Announcing Rate Limiting for .NET - Microsoft Developer Blogs
Rate limiting is the concept of limiting how much a resource can be accessed. For example, you know that a database your application ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found