Rate limiting algorithms

5 ways to count · Part of Reliability and security

Key idea

Practice

6 questions · about 3 min

Explained step by step

Leaky bucket

Leaky bucket limits with a queue. Each new request is added to the end of the queue, and requests leave at a fixed rate, first in, first out (FIFO). If the queue is full, new requests are dropped. It's like a bucket with a hole at the bottom: you can pour water in all at once, but it always comes out drop by drop, and if the bucket overflows, the extra water is lost.

Token bucket

Token bucket uses a bucket of tokens. Each incoming request must take 1 token to pass. If no tokens are left, the request is rejected and has to retry later. The bucket refills every so often, for example with 10 tokens per second. It allows short bursts while there are tokens. It's like gym passes: you get 10 a month, you can use them on 2 days in a row, but if they run out, you wait for next month.

Fixed window

Fixed window splits time into blocks of n seconds, for example 60. Each request adds 1 to the current window's counter, and if it passes the threshold, it's dropped. When the next window starts, the counter goes back to 0. It's cheap, but has a problem at the edges: with a limit of 100 per minute, you can send 100 at the end of one minute and 100 at the start of the next, 200 in 2 seconds. It's like a daily quota that resets at midnight.

Sliding log

Sliding log stores the exact time (timestamp) of each request, sorted. It discards times older than the window, for example more than 60 seconds. When a request arrives, it counts how many times remain: if it would pass the limit, it stops it. It's very precise, with no edge problem, but stores 1 item per request. It's like writing down in a notebook the time of every coffee you drink and counting how many you've had in the last hour.

Sliding window

Sliding window mixes the previous 2: it has fixed window's low cost and sliding log's precision at the edges. It keeps 1 counter per fixed window, but adds a part of the previous window's counter, based on how much of it falls within the last 60 seconds. If 15 seconds of the new minute have passed, it adds 75% of the previous minute. That smooths the spikes. It's like a moving average: it doesn't reset all at once, it keeps sliding.

Rate limiting

Each algorithm has its place. Leaky bucket smooths the output at a fixed rate. Token bucket allows short bursts. Fixed window is the cheapest, but fails at the edges. Sliding log is the most precise, but stores a lot. Sliding window is a good middle ground. It's like picking a payment method: cash, debit or credit; they all pay, but each works best in one case.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

5 ways to count