npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ac-ratelimiter

v2.0.0

Published

Simple ratelimiter for express

Downloads

53

Readme

ac-ratelimiter

This tool provides rate-limiter that can be used as middleware with ExpressJs.

For huge production load it is recommended that you use it with Redis. However, for smaller applications you can use the build in Node Cache.

Node.js CI

Breaking changes for version 2

Version 2 is a complete re-write of this module. It is now a class and uses async/await.

// Migration example

// Version 1
const acrl = require('ac-ratelimiter')

const init = {
  routes: [
    { route: 'user/find', throttleLimit: 1, limit: 2, expires: 3, delay: 250 },
  ],
  redis: REDIS INSTANCE
  logger: winston.log INSTANCE
}

acrl.init(init)

// req.rateLimitCounter should have already the current count
acrl.limiter(req, {}, err => {
  // err.status === 900 => throttling is active
  // err.status === 429 => limiter is active
  return res.json({ status: _.get(err, 'status') })
})


// Version 2
const acrl = require('ac-ratelimiter')

const init = {
  routes: [
    { route: 'user/find', throttleLimit: 1, limit: 2, expires: 3, delay: 250 },
  ],
  redis: REDIS INSTANCE
  logger: winston.log INSTANCE
}

const rateLimiter = new acrl(init)

try {
  await rateLimiter.limiter(req)
}
catch(e) {
  // e.status === 900 => throttling is active
  // e.status === 429 => limiter is active
}

Usage

Without any dependencies

This example initiates the rate limiter with NodeCache (instead of Redis) and console.log (instead of Winston). Default limits are 150 requests within 3 seconds. Starting at 50 request, requests will be throttled by 250ms.

const acrl = require('ac-ratelimiter')

const rateLimiter = new acrl()

try {
  await rateLimiter.limiter(req)
}
catch(e) {
  // e.status === 900 => throttling is active
  // e.status === 429 => limiter is active
}

Prerequisites

Init

The ac-ratelimiter can use Redis as storage for the rate-limiter keys. By default and to run out-of-the-box it uses Node Cache.

Additionally, for logging purposes, we use Winston. But you can also use any other logger that provides logging for "warn" and "error".

Last but not least, provide an array of objects with rate limiter instructions. Each object has the following properties: Property | Type | Defaults | Remarks ---|---|---|---| routes | string | | A combination of controller and action (express) or any other identifier you can provide throttleLimit | 50 | 20 | Number of calls before throttling starts delay | integer | 250 | Number of milliseconds a throttle request is delayed (on purpose) limit | integer | 150 | Number of calls before the limiter kicks in expires | integer | 3 | Number of seconds before the rate-limiter resets

RateLimiter

The actual rateLimiter function takes two arguments, the Express request object (req) and an options object with the following optional properties:

Property | Type | Example | Remarks ---|---|---|---| name | String | myName | Identifier for the route - falls back to controller/action redisKey | String | myKey | Optional RedisKey to use for rate limiter fallbackRoute | String | fbroute | Optional fallback route identifier expires | Integer | 3 | Expire time for rate limiter - see above throttleLimit | Integer | 20 | Throttle limit for rate limiter - see above delay | Integer | 250 | Delay for throttled calls for rate limiter - see above

Good practice

It is recommended to put the determined IP to the request object as req.determinedIP.

Additionally, you can put the rateLimitCounter to the request object as req.rateLimitCounter. This way, the rate limiter does not have to fetch that value.

Both values might be retrieved prior to the rate limiter so there is no need to retrieve it once again here.

Links

Run tests

yarn run test

License

MIT License Copyright © 2009-present, AdmiralCloud AG, Mark Poepping