Skip to content

IoValkey

Avi Fenesh edited this page Apr 9, 2025 · 2 revisions

RateLimiterValkey

Rate limiting with iovalkey

Usage

const { RateLimiterValkey } = require('rate-limiter-flexible')
const Valkey = require('iovalkey')
const valkeyClient = new Valkey({
      port: 8080,
      host: '127.0.0.1',
    })

const opts = {
  storeClient: redisClient,
  points: 5, // Number of points
  duration: 1, // Per second
}

const rateLimiterValkey = new RateLimiterValkey(opts)

rateLimiterValkey.consume(userEmail)
    .then((rateLimiterRes) => {
      // ... Some app logic here ...
    })
    .catch((rejRes) => {
      if (rejRes instanceof Error) {
        // Some error happened.
        // Never happen if `insuranceLimiter` is set up.
        // Decide what to do with it in another case.
      } else {
        // Not enough points to consume.
        // The promise is rejected with number of ms before current duration ends and points are reset.
        const secs = Math.round(rejRes.msBeforeNext / 1000) || 1
        res.set('Retry-After', String(secs))
        res.status(429).send('Too Many Requests')
      }
    });

See all options here

Clone this wiki locally