upstash/ratelimit-js

How to use multiple ratelimiters?

sean-nicholas opened this issue · 8 comments

What is the best practice here?

  • Creating two Ratelimit instance with two different prefixes?
  • Using one Ratelimit instance and using a prefixed identifier? Downside: Only one Ratelimit Strategy / options possible for limiter.

Hey,

I'd recommend using 2 limiters, do you have any concerns with this?

you could do something like this:

const ratelimit = {
 free: new Ratelimit({...}),
 payed: new Ratelimit({...})
}


await ratelimit.free.limit("identifier")

Just to be clear: These would need different prefixes, otherwise they might collide, correct?

Would be helpful to put that in the documentation, I guess. It makes totally sense if you know how the ratelimiter works, but I had to look into the redis & source code to understand how the keys are getting generated.

Ah yes, different prefixes are required
Let me add this example to the readme

Ah yes, different prefixes are required
Let me add this example to the readme

Ah yes, different prefixes are required
Let me add this example to the readme

Ah yes, different prefixes are required
Let me add this example to the readme

Looks like github is broken, I'll update the readme as soon as I can :D

here's a full example:

import { Redis } from "@upstash/redis"
import { Ratelimit from "@upstash/ratelimit"

const redis = Redis.fromEnv()

const ratelimit = {
  free: new Ratelimit({
    redis,
    analytics: true,
    prefix: "ratelimit:free",
    limiter: Ratelimit.slidingWindow(10, "10s"),
  }),
  payed: new Ratelimit({
    redis,
    analytics: true,
    prefix: "ratelimit:payed",
    limiter: Ratelimit.slidingWindow(60, "10s"),
  })
}


await ratelimit.free.limit(ip)
// or for a payed user you might have an email or userId available:
await ratelimit.payed.limit(userId)

@sean-nicholas actually you don't technically need different prefixes, as long as you use different identifiers, for example the ip address for free users and an email for payed users.

If you use the same type of identifier, then you need to set different prefixes.