Home

Posts

Tags

Design a Rate Limiter

Designing a rate limiter is a classic problem in system design interviews. Its primary job is to control the rate of traffic sent by a client or a service to ensure the system remains stable and protected against abuse (like DDoS attacks) or cascading failures.

We will discuss here the rate limiter algorithms (the “how” of the logic), the architecture (the “where” and “who”), and the high level requirements (the “what”), like low latency, high availability, and how to handle “hard” vs “soft” limits.

Algorithms

We can start with different rate limiter algorithms.

Here is the list we will be exploring,

Each one solves a specific problem. For example, some are great for saving memory, while others are better at making sure your servers don’t crash during a sudden spike.

Token Bucket

This is simplest algorithm. Here, we have a bucket with a pre-defined capacity.

Leaky Bucket

Like token bucket, we will have bucket with a pre-defined capacity.

Fixed Window Counter

This is the simplest algorithm to implement.

Sliding Window Log

This is the most “accurate” algorithm because it tracks every single request.

Sliding Window Counter

Assume following scenario

LastMRionlultie7n0g%Minute30%CurrentMinute

To calculate requests in current rolling minute

Sliding window counter is a clever hybrid that tries to get the accuracy of the log without the high memory cost. The number of requests in the rolling window is calculated using the following formula,

Current Window Count + (Previous Window Count × Percentage of overlap)

Using this formula, we get 3 + 5 * 0.7% = 6.5 request. Depending on the use case, the number can either be rounded up or down. In our example, it is rounded down to 6.

Tags: