System Analysis: Rate Limiters
Short analysis on rate limiters
Today let’s dive into rate limiters.
The main work of rate limiters is exactly what they are supposed to do. i.e rate limit requests to an API or server. If you think about it in terms of designing a system, it is quite straight forward. In a normal application you make requests to a server and if the number of requests reaching that server exceeds a threshold you just stop serving any more requests.

Why do you need a rate limiter
One of the major reasons for having a rate limiter is so that you can protect your application from a Denial of Service attack (DoS) . This attack involves sending a large number of requests to a service with the malicious aim of taking it down.
How can you implement a simple rate limiter
You could have a counter, which counts the number of requests from a given IP address and then if the counter exceeds a particular value just stop serving requests.
Some of the drawbacks in this are that this rate limiter is distributed and hence would require synchronization between different services making the counter encounter race conditions. So lets look at some formal algorithms that are used in rate limiters
Token bucket algorithm: In a token bucket algorithm you can have a fixed number of tokens inside a bucket which would refill periodically. For every request you would consume one token and if there are no tokens the api request would get throttled
Leaky Bucket algorithm: The leaky bucket is a simple concept used in computer networking to control the rate at which data is sent from one point to another. It's called a "leaky bucket" because it metaphorically represents a bucket that leaks at a controlled rate. However in a leaky bucket you have to fine tune a lot of parameters like bucket size and data flow, which if not regulated can cause the network to underperform
Sliding window log algorithm:
Dividing time into windows: The algorithm divides time into a series of windows, with each window having a fixed size (for example, one second).
Tracking requests: For each incoming request, the algorithm increments a counter associated with the current window.
Checking the rate limit: If the number of requests in the current window exceeds a specified rate limit, the algorithm blocks the incoming request. Sliding the window: At the end of each window, the algorithm slides the window to the next time period and resets the counter.
How to make this rate limiter distributed ?
We generally would have a middleware or a layer in between the front end applications and the backend services. However we need to make this distributed. One rate limiter is not enough. One of the solutions is to use a distributed memcache instance between these rate limiters that can check for shared and distributed data.
Further Reading:
https://www.enjoyalgorithms.com/blog/design-api-rate-limiter
https://systemsdesign.cloud/SystemDesign/RateLimiter