4

Hi I am rate limiting some methods in meteor.js with DDPRateLimiter and what I found out is that it limits method call for everyone not just that connection! For example for this rule:

var updateUsernameRule = {
    type: 'method',
    name: 'updateUsername'
};
DDPRateLimiter.addRule(updateUsernameRule, 1, 30000);

Update in one browser and then when updating in another it causes rate limit error. Documentation is kinda unclear about that and default behavior is not intuitive at all. How do I rate limit per user?

nesvarbu
  • 986
  • 2
  • 9
  • 24

1 Answers1

5

I agree, the docs need a bit of work. To make this work in your case (restrict by logged in user only), you will want something like the following:

const updateUsernameRule = {
  type: 'method',
  name: 'updateUsername',
  userId(userId) {
    if (userId) {
      return true;
    }
  }
};
DDPRateLimiter.addRule(updateUsernameRule, 1, 30000);

This will cause the updateUsernameRule rule to only be matched for user's with a set userId (logged in users). All other not logged in users will skip this rule completely, and be able to make as many requests as they want.

hwillson
  • 1,399
  • 9
  • 7
  • Your solution makes sense for this, but what if I want to limit the number of messages sent? If I do a rate limit of 10 method calls a second, that's reasonable for a single user. But if I have 100 users logged in at a time, then the limit will probably be hit. I just started looking into rate limiting and I'm very surprised it's not easier to do it by user. – gkrizek Aug 24 '16 at 17:24
  • The rate limit rule in my answer is per user, so 1 request per user within 30 seconds. If you've configured a limit of 10 method calls per user, then 100 users will be allowed 10 method calls each, with the defined interval. – hwillson Aug 24 '16 at 19:50
  • 1
    Thanks. I guess maybe your answer is a little confusing for me. Is it checking the userId of each call? Or just checking if the user has an Id? Basically: is it rate limiting all logged in users 1 request per 30 seconds, or each individual user 1 request per 30 seconds? – gkrizek Aug 24 '16 at 20:27
  • Each individual user 1 request per 30 seconds; sorry for the confusion. – hwillson Aug 25 '16 at 00:43
  • 1
    Yeah that did do the job thanks! DDPRateLimiter docs are really really lacking though. Even for something fundamental like this. Here is a ticket to create better docs for DDPRateLimiter, but seems it will stay there forever: https://github.com/meteor/meteor/issues/6087 – nesvarbu Aug 29 '16 at 14:15