Rate limit Api endpoint with redis 'GCRA' algorithm working example
Recently, I was working on a project that required rate limiting an endpoint. I found a lot of articles on the internet and used two ways of them.
One of them I explained in this article
Again, for more theory, you can use this article on the internet that I found
I will show you my working example. Install Redis. I will use Rocky Linux 9 for this example.
1 Install Redis service
2 Enable, Start and check the status of Redis
It should look like this:
next, we need to install the python client for Redis
3 Install Redis python client
This time we are not linked to a framework, you can use this guide for any framework you use.
4 put the following code in your project
This is the main function that does the rate limiting. It uses the GCRA algorithm which is a special case of the leaky bucket algorithm. Instead of simulating a leak this one computes a “theoretical arrival time” (TAT) that the next request would have to meet. After each successful request, the TAT is increased by a small amount.
if users make requests faster than the TAT, they will be rate limited.
5 use it in your project
in my case, I had too many auth attempts from the same user, so I used this function to rate limit the login endpoint.
6 Test Functionality
when we reach the limit, we respond with a 429 status code:
As you can see, when we reach the limit, requests are denied. But every some time when current time catches up to the TAT more requests can be made.
7 Conclusion
It turns out this method is very memory efficient since it only needs to store a few variables to do this.
I hope this article was helpful to you.