Rate Limiting & Throttling — Security

Rate limiting caps the number of requests per key (what identifies the sender, such as an IP or a user id) in a span of time. It holds back brute force…

Someone is trying to guess one of your users' passwords. Not once or twice, but thousands of times a minute, and your server patiently answers every try. What stops it is rate limiting: a cap on how many requests one sender may send in a span of time.

Picture the office coffee machine that only gives out 5 cups per 10 seconds for one employee card. The sixth cup is refused, and the screen says "try again in 9 seconds". Each cup is one request. The card is the key: what identifies the sender, such as an IP or a user (not an encryption key). 5 per 10 seconds is the limit, and the message on the screen is the Retry-After header.

Why an API needs a limit

With no limit, anyone can send as many requests as they like, as fast as they like:

Rate limiting is one layer of defence against all of these. For a big DDoS, rate limiting is helped by other layers such as a CDN (a network of servers in many places that receives requests first) and a firewall (a filter for network traffic). The reason: even requests that rate limiting refuses still reach the server and put load on it.

What the server sends when the limit is used up

Calculate it before you look at the table: the limit is 5 requests per 10 seconds, and you send 6 requests within 1 second. What status does the sixth request get, and how many seconds do you have to wait?

This is a record from the Lab: a limit of 5 per 10 seconds, counted with a sliding window (how it counts is in the next section). Time is counted from the first request. A request that passes is one the server accepts.

Request Time Passed in the last 10 seconds Server's answer
1 0.0 s 0 200 OK, RateLimit-Remaining: 4
2 0.2 s 1 200 OK, RateLimit-Remaining: 3
3 0.4 s 2 200 OK, RateLimit-Remaining: 2
4 0.6 s 3 200 OK, RateLimit-Remaining: 1
5 0.8 s 4 200 OK, RateLimit-Remaining: 0
6 1.0 s 5 429 Too Many Requests, Retry-After: 9
7 10.1 s 4 (the one at 0.0 s is now over 10 seconds old) 200 OK, RateLimit-Remaining: 0

The sixth request gets 429 Too Many Requests with Retry-After: 9. What is counted is a 10 second window: the last 10 seconds up to now. The first request (at 0.0 s) only leaves that window at 10.0 s. It's now 1.0 s, so 9 seconds are left.

Three ways to count

Example: a limit of 5 per 10 seconds, then 5 requests at second 9.5 and 5 more at second 10.5.

Way How it works In that example
Fixed window A counter per fixed window (0 to 10 s, 10 to 20 s), back to 0 for each new window 10 pass within 1 second
Sliding window Counts the requests that passed in the last 10 seconds, counted back from now 5 pass, 5 get a 429
Token bucket A bucket of 5 tokens, refilled with 1 token every 2 seconds. Each request uses 1 token 5 pass, then 1 passes every 2 seconds

Sliding window code in JavaScript

This code records the time of each request that passes, per key, then counts how many are still in the window:

const LIMIT = 5
const WINDOW_MS = 10_000 // 10 seconds
const hits = new Map() // key (IP or user id) -> times of the requests that passed

function rateLimit(key, now = Date.now()) {
  const recent = (hits.get(key) ?? []).filter((t) => t > now - WINDOW_MS)
  if (recent.length >= LIMIT) {
    const retryAfter = Math.ceil((recent[0] + WINDOW_MS - now) / 1000)
    return { status: 429, headers: { 'Retry-After': String(retryAfter) } }
  }
  recent.push(now)
  hits.set(key, recent)
  return { status: 200, headers: { 'RateLimit-Limit': String(LIMIT), 'RateLimit-Remaining': String(LIMIT - recent.length) } }
}

In Laravel

Laravel adds rate limiting through the throttle middleware:

// routes/api.php: 60 requests per 1 minute
Route::middleware('throttle:60,1')->group(function () {
    Route::get('/data', [DataController::class, 'index']);
});

// AppServiceProvider::boot()
RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});

RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

Route::post('/login', [AuthController::class, 'login'])->middleware('throttle:login');

The login limiter above counts per IP only, but an attacker can try one account from many IPs. A stronger version sets two limits at the same time:

// AppServiceProvider::boot(): login counted per email AND per IP
RateLimiter::for('login', function (Request $request) {
    $email = Str::lower((string) $request->input('email'));

    return [
        Limit::perMinute(5)->by('email:'.$email),       // one account, many IPs
        Limit::perMinute(20)->by('ip:'.$request->ip()), // one IP, many accounts
    ];
});

A request is refused when either limit is used up. The prefixes email: and ip: keep the two keys different. The per-IP limit is looser, because a whole office can share one IP. For example, with 25 login attempts on one account from 25 IPs within one minute, the by($request->ip()) version lets 25 through, while this version lets only 5 through.

⚠️ Setup mistakes that make the limit leak

TL;DR: Rate limiting caps the number of requests per key (what identifies the sender, such as an IP or a user id) in a span of time. It holds back brute force, credential stuffing (trying email and password pairs leaked from other sites), scraping (copying data), and DoS or DDoS (a flood of requests that uses up the server's resources). Past the limit, the server answers 429 Too Many Requests with Retry-After (how many seconds to wait). While requests are still allowed, the server sends RateLimit-Limit and RateLimit-Remaining (the limit and what's left). There are three ways to count. Fixed window (a counter per fixed time window) has a gap at the window's edge. Sliding window counts the most recent span up to now (the last 10 seconds, for example). Token bucket (a bucket of tokens, each one the allowance for a request, that slowly refills) allows a burst (a small spike), then a steady rate. In Laravel: throttle:60,1 (60 requests per minute), and Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()) (count per user, or per IP before login). Make the login endpoint tighter, and keep the counts in Redis when you run more than one server.

⚡ A limit per key

Meaning: Rate limiting caps how many requests may come in per key (what identifies the sender, such as an IP or a user) in a span of time. The limit holds back brute force login, credential stuffing (trying email and password pairs leaked from other sites), scraping (copying data), and DoS (flooding the server until it can't serve users).

⚡ 429 and Retry-After

Guess first: the limit is 5 requests per 10 seconds, and you send 6 requests within 1 second. What does the sixth get?

429 Too Many Requests with Retry-After: 9. The first request (at 0.0 s) only leaves the 10 second window (the last 10 seconds that are counted) at 10.0 s, and the sixth arrives at 1.0 s.

Meaning: 429 is the status for "too many requests". Retry-After tells the client how many seconds to wait. RateLimit-Remaining tells it what's left of its allowance.

⚡ Three ways to count

Meaning: A fixed window counts per fixed time window (0 to 10 s, then 10 to 20 s). It has a gap at the window's edge: 10 requests can pass within 1 second (5 just before second 10, 5 just after). A sliding window closes it by counting the last 10 seconds from now. A token bucket (a bucket of tokens, each one the allowance for a request, that slowly refills) allows a small burst, then a steady rate.

⚡ In Laravel

Write:

RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

Meaning: This code limits login to 5 tries per minute for each IP. The login endpoint gets a far tighter limit than the ordinary API. With more than one server, keep the counts in Redis (a fast in-memory database), so all servers use the same numbers.

What you will learn