Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Security › Web attacks and defenses

Rate limiting

Three meanings of "accept only 5 requests per second"

Why it exists — If the number of requests is not limited, when requests beyond the processing capacity pile up, threads and DB connections run out, and all requests become slow or fail together. Rate limiting counts requests at the entrance and returns those over the limit with 429 before work starts, so that the requests that were accepted are still processed properly.

Where it's used today — It is used on public APIs to set the number of calls per minute for each API key or user, and in places where repeated attempts must be blocked, such as login or sending verification text messages. When there are several servers, the counts each one has taken do not add up, so counting is done together in a shared store such as Redis or in an API gateway (Spring Cloud Gateway's RequestRateLimiter filter provides a token bucket implementation that counts with Redis).

When requests arrive all at once, the server rejects some of them to protect itself (429 Too Many Requests). Even the same limit of "5 requests per second" lets different requests through, depending on how you count.

Partly checked against real execution · The code on the screen was run on Redis 8.10.2, Jedis 8.1.0, and Bucket4j 8.23.0 and the nine combinations were compared. The result table matched in all ten runs on the real clock, and every single request matched for eight combinations (the sliding window with even requests, which falls exactly on a 1-second boundary, can differ from run to run; with the screen times given to the clock, all nine matched)

Concepts in this lab

Rate limiting
Limiting the number of requests that are allowed in a given period of time. It stops a specific user or client from sending excessive requests and affecting the whole system, and it makes the system accept requests only within the range it can handle. Requests over the limit usually get a response with the 429 status code.
HTTP status codes
Why it exists — If results were reported only as text in the body, each server would write them differently, and browsers, proxies, and monitoring tools could not tell whether a request succeeded. A status code reports the result as a fixed number, so these tools can do caching, retries, and error counting without being adjusted for each server.
Where it's used today — It is used to branch handling by the kind of error, such as a frontend that sends the user to the login screen on a 401 and to a "page not found" notice on a 404. In operations, you watch the ratio of 5xx responses and, if it suddenly rises, treat it as an outage and send an alert.
A three-digit number that shows the result of the server's handling of a request. 2xx means success, 3xx means a move to another location (redirection), 4xx means a problem with the client's request, and 5xx means an error on the server side. Common ones are 200 (success), 201 (created), 400 (bad request), 401 (authentication required), 403 (no permission), 404 (not found), and 500 (server error).
API gateway
The single entry point that receives all client requests first and forwards them to the right internal service. It handles common functions such as authentication, rate limiting, and logging in one place. Clients do not need to know the layout and addresses of the internal services.

Try these

Running with the default settings

  1. Request #1 at 0.80s: The counter for the window starting at 0s is 1. That is 5 or less, so it passes.
  2. Request #2 at 0.84s: The counter for the window starting at 0s is 2. That is 5 or less, so it passes.
  3. Request #3 at 0.88s: The counter for the window starting at 0s is 3. That is 5 or less, so it passes.
  4. Request #4 at 0.92s: The counter for the window starting at 0s is 4. That is 5 or less, so it passes.
  5. Request #5 at 0.96s: The counter for the window starting at 0s is 5. That is 5 or less, so it passes.
  6. Request #6 at 1.02s: The counter for the window starting at 1s is 1. That is 5 or less, so it passes.
  7. Request #7 at 1.06s: The counter for the window starting at 1s is 2. That is 5 or less, so it passes.
  8. Request #8 at 1.10s: The counter for the window starting at 1s is 3. That is 5 or less, so it passes.
  9. Request #9 at 1.14s: The counter for the window starting at 1s is 4. That is 5 or less, so it passes.
  10. Request #10 at 1.18s: The counter for the window starting at 1s is 5. That is 5 or less, so it passes.
  11. Request #11 at 2.20s: The counter for the window starting at 2s is 1. That is 5 or less, so it passes.
  12. Request #12 at 2.40s: The counter for the window starting at 2s is 2. That is 5 or less, so it passes.
  13. Request #13 at 2.60s: The counter for the window starting at 2s is 3. That is 5 or less, so it passes.
  14. Request #14 at 2.80s: The counter for the window starting at 2s is 4. That is 5 or less, so it passes.

Result of this run

Code

// Only lines inside a method are shown (declarations and imports omitted; tooManyRequests is an example method)
// redis is a Jedis client object that sends commands to a Redis server (its method names match the Redis commands INCR and EXPIRE)
// Fixed window: key = user + the current second
String key = "rate:" + userId + ":" + (now / 1000);
long count = redis.incr(key);            // add 1 to the request count of this second
if (count == 1) redis.expire(key, 1);    // disappears after 1 second
if (count > 5) return tooManyRequests(); // 429

Assumptions of this model

The limit is fixed at 5 requests per second. The sliding window records the time of every request that passed (a sliding window log), and the token bucket is refilled as time passes, the way refillGreedy of Bucket4j does it. A real service counts separately for each user, IP address, or API key. Java and Spring provide no API of their own for the fixed window and the sliding window, so the code shows them written by hand with Redis commands. The code on the screen was put into method bodies as it is and the nine combinations were run on Redis 8.10.2, Jedis 8.1.0, and Bucket4j 8.23.0 (verify/spring/ratelimit_probe.out.txt; the Java program ran in a container on the same Docker network as Redis). When the code on the screen was run as it is (now is System.currentTimeMillis(), and Bucket4j uses its default clock) ten times, sending the requests at the times on the screen, the result table matched the screen in all ten runs for all nine combinations, and whether each request passed or was rejected also matched in all ten runs for eight combinations. Only in the combination of the sliding window with requests arriving evenly, 4 to 6 requests were passed or rejected the other way round from the screen in four of the ten runs (the number that passed was the same, 15). This combination has moments when two requests are exactly 1 second apart (such as 0 seconds and 1 second), so if the request 1 second earlier was handled 1 to 2 milliseconds late, its record has not been deleted yet. The screen calculates as if each request is handled exactly at its time. So the code was also run with the request times on the screen given to the now in the code and to the clock of Bucket4j (one line, withCustomTimePrecision, was added to Bucket4j to replace its clock), and then, for all nine combinations, whether each request passed and the counter value, the number of records, and the number of tokens (the integer part) matched the screen. When the 12 requests that arrive at one moment were handled at the same time by 12 threads, each with its own connection, the number that passed was the same. With code that sends the sliding window as three separate commands instead of one Lua script, handling 12 simultaneous requests starting from no records was repeated 20 times, and more than the limit of 5 passed in 13 of the 20 runs (11 at most). No HTTP server was started and the code on the screen was called directly, so the part that really sends a 429 response was not run (tooManyRequests is an example method).

Previous lab: Information leakage · Next lab: Dependencies and the supply chain

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these