Belajar
← All lessons

How rate limiting works

Send requests through a limiter

Your app
Limiter
API

client.js

const res = await fetch("https://api.shop.test/orders", {  headers: { "X-API-Key": apiKey },});res.headers.get("X-RateLimit-Remaining"); // "2" if (res.status === 429) {  const wait = Number(res.headers.get("Retry-After"));  await sleep(wait * 1000);}

limiter.js

app.use((req, res, next) => {  const id = req.get("X-API-Key") ?? req.ip;  const bucket = limiter.bucket(id, { limit: 3 });  if (!bucket.take()) {    res.set("Retry-After", bucket.retryAfter());    return res.status(429).end();  }  res.set("X-RateLimit-Limit", bucket.limit);  res.set("X-RateLimit-Remaining", bucket.tokens);  next();});

The token bucket drains per request, refills with time

Tokens after your last request 10 / 10
Refill rate1 token / s
Responses

    Nothing ticks in the background. The bucket catches up when the next request arrives

    bucket.js

    function take(bucket, now) {  const seconds = (now - bucket.last) / 1000;  bucket.tokens = Math.min(bucket.capacity,    bucket.tokens + seconds * bucket.perSecond);  bucket.last = now;   if (bucket.tokens >= 1) {    bucket.tokens -= 1;    return { status: 200 };  }  const wait = (1 - bucket.tokens) / bucket.perSecond;  return { status: 429, retryAfter: Math.ceil(wait) };}

    Fixed vs sliding windows and the burst at the edge

    window.js

    // fixed: one counter per clock minutefunction fixedWindow(id, now) {  const minute = Math.floor(now / 60);  const count = counters.incr(`${id}:${minute}`);  return count <= 5;} // sliding: count only the last 60 secondsfunction slidingWindow(id, now) {  const recent = log.get(id).filter((t) => t > now - 60);  if (recent.length >= 5) return false;  log.set(id, [...recent, now]);  return true;}

    Topics

    Next: How load balancing works

    Open lesson