upstash / ratelimit-js

Rate limiting library for serverless runtimes
https://ratelimit-with-upstash.vercel.app/
MIT License
1.72k stars 33 forks source link

How to use multiple ratelimiters? #38

Closed sean-nicholas closed 1 year ago

sean-nicholas commented 1 year ago

What is the best practice here?

chronark commented 1 year ago

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")
sean-nicholas commented 1 year ago

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.

chronark commented 1 year ago

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

chronark commented 1 year ago

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

chronark commented 1 year ago

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

chronark commented 1 year ago

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

chronark commented 1 year ago

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)
chronark commented 1 year ago

@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.