Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

A Guide to Rate Limiting with Examples in JavaScript

Learn 2 rate limiting strategies you should avoid and 2 strategies you should be using and how to implement them in Node and JavaScript.

Forbes Lindesay
Level Up Coding
Published in
7 min readNov 25, 2019

--

Rate limiting is an effective and relatively easy way to mitigate security risks. It will not be the only thing you do secure your applications, and it might not even be the most important thing you do to secure your applications, but it should ALWAYS be in your toolbox.

Let’s take a case where an attacker tries to guess a user’s password. If you set a limit on the number of times a password can be attempted per day, it will cripple the hacker’s attack and keep your users safe.

If you don’t rate limit, attackers can use your CPU and Memory to crack your users’ passwords!

If you accidentally allow users to read any arbitrary record from your database instead of only the records they should have access to, the problem will be much less severe if they can only read one un-authorised record per minute rather than extracting at 1000 records per minute.

Rate limiting makes the effects of being compromised less severe

We’ll consider two good types of rate limiting in this post, but first let's look at a few examples that are bad but commonly used.

Fixed Window Rate Limiting — Don’t Use This

Fixed window rate limiting is very simple. You say something like — each user can make 10 requests to my API per hour. The implementation is simple:

  1. Keep a counter per user for the current hour
  2. Increment the counter each time the user makes a request
  3. Reject the request if the counter is over the threshold
  4. Reset all the counters at the start of each hour

The trouble is, this can be very frustrating and very unfair.

❌ Users who start making requests just before the hour ends get to make many more requests in the first few minutes than users who start making requests just as the hour has started.

❌ A user who uses more than you expected can be given a very harsh penalty. E.g. If I get to make 10 requests per hour, I…

--

--

Written by Forbes Lindesay

JavaScript enthusiast and maintainer of many open source projects.

Responses (3)

Write a response