Rate limiting

A cap on requests · Part of Reliability and security

Key idea

Practice

6 questions · about 3 min

Explained step by step

Rate limiting

Rate limiting is preventing an operation from happening more times than a defined limit. For example, 100 requests per minute per user. In large systems it's used to protect the underlying services and resources, and to keep shared resources available. It also protects APIs from overuse, whether unintended or malicious. It's like a limit of 3 tickets per person at a concert: that way one person can't buy them all.

In a distributed system, counting is hard. If each of 4 nodes counts on its own, a user with a limit of 100 can make 100 on each node: 400 in total. One solution is sticky sessions in the load balancer, so each user always goes to the same node, but you lose fault tolerance and scaling. Another is a central store like Redis, which adds latency and opens the door to race conditions. It's like 4 ticket booths that don't talk to each other: each sells 3 tickets per person and someone buys 12.

When a client goes over the limit, the server answers with an error, for example HTTP 429 «too many requests», and usually tells it when it can try again. A well-built client waits and retries, ideally with exponential backoff, instead of insisting instantly. It's like a full shop's «come back in 10 minutes»: if you come back in 1 second, they tell you the same thing.

DoS attack

Rate limiting helps: avoid running out of resources from a denial-of-service (DoS) attack, which is flooding a server with requests to knock it down; control costs, capping how much things scale on their own, so the bill doesn't grow uncontrolled; defend against other common attacks, like trying thousands of passwords; and control the flow of data in APIs that process a lot. It's like a club bouncer: they don't let in more people than fit.

Race condition

A race condition happens with the naive «get then set» approach: read the counter, add 1 and store it. If 2 requests read 99 at once, both store 100, and 2 got in when there was room for 1. That way a client can bypass the limit by sending many requests together. It's like 2 people eyeing the last free chair at the same time and both sitting down.

Distributed lock

To avoid the race condition you can use a distributed lock on the key: while one process uses the counter, no other can read or write it. But the lock becomes a bottleneck and doesn't scale well. Better is «set then get»: add 1 in a single atomic operation and look at the result. It's like a deli ticket dispenser: each person takes their number in 1 single step and nobody can get the same one.

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

A cap on requests