DEV Community

Vishwa
Vishwa

Posted on Originally published at Medium

LRU Cache and Rate Limiter: Two Small Designs That Protect an API

How I would stop one user from calling an API 1,000 times a minute, with Python you can run

Imagine a link-shortening service. A script starts calling POST /shorten in a loop, say 1,000 times a minute from one API key. At the same moment, real users are opening product pages that read the same few items again and again.

Two small designs handle both problems: a rate limiter that says "enough" to the noisy caller, and an LRU cache that keeps the hot data close and throws out what nobody is reading.

The problem

Without a limit, one client can use up the capacity meant for everyone. The database fills with junk rows, latency climbs, and real users start seeing errors they did nothing to cause.

Without a sensible cache, every read goes to the database. And a cache with no size limit is not a fix either: memory is fixed, so something has to decide what leaves when it is full.

The solution, part 1: the rate limiter

A rate limit is the maximum number of requests allowed per user or key in a time window. When a client goes over it, the API returns 429 Too Many Requests.

On GCP there are three places to enforce it, and they answer different questions:

  • Cloud Armor runs at the edge, on the load balancer. It limits per IP, so it is good for bots and floods.
  • API Gateway knows the caller's API key or JWT. A fixed quota, such as 100 requests a minute per key, is configuration, not code.
  • Your own code with Redis counters is needed for dynamic limits, for example free and premium tiers with different quotas.

Here are the two algorithms I reach for. Both take an optional now so the demo is repeatable.

import time

class FixedWindowLimiter:
    def __init__(self, limit, window_s=60):
        self.limit, self.window_s = limit, window_s
        self.counts = {}                     # (user, window) -> requests

    def allow(self, user, now=None):
        now = time.time() if now is None else now
        key = (user, int(now // self.window_s))
        self.counts[key] = self.counts.get(key, 0) + 1
        return self.counts[key] <= self.limit

class TokenBucket:
    def __init__(self, capacity, refill_per_s):
        self.capacity, self.rate = capacity, refill_per_s
        self.tokens, self.last = capacity, None

    def allow(self, now=None):
        now = time.monotonic() if now is None else now
        if self.last is not None:
            self.tokens = min(self.capacity,
                              self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

fw = FixedWindowLimiter(limit=100)
print("fixed window:", sum(fw.allow("user42", now=10.0) for _ in range(1000)))
tb = TokenBucket(capacity=100, refill_per_s=100 / 60)
print("token bucket:", sum(tb.allow(now=10.0) for _ in range(1000)))
print("30 s later:", sum(tb.allow(now=40.0) for _ in range(1000)))
# fixed window: 100 / token bucket: 100 / 30 s later: 50
Enter fullscreen mode Exit fullscreen mode

Fixed window is one counter per user per minute. Token bucket allows a short burst (the capacity) and then a steady refill rate. In a real service the counter lives in Redis, not in a Python dict, so every instance sees the same count: INCR the key for this user and minute, and set an expiry so old windows clean themselves up.

The solution, part 2: the LRU cache

LRU means Least Recently Used: when the cache is full, drop the item that was read longest ago. Python's OrderedDict makes this short:

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.data = OrderedDict()

    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)          # now the most recently used
        return self.data[key]

    def put(self, key, value):
        if key in self.data:
            self.data.move_to_end(key)
        self.data[key] = value
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)   # drop the least recently used

cache = LRUCache(2)
cache.put("product:1", "Phone")
cache.put("product:2", "Shoes")
cache.get("product:1")                      # product:1 is used again
cache.put("product:3", "Shirt")             # full, so product:2 goes
print(list(cache.data))                     # ['product:1', 'product:3']
Enter fullscreen mode Exit fullscreen mode

Both get and put are O(1). In production I would not write this myself. Redis can evict least-recently-used keys when it reaches its memory limit, and I would still give every key a TTL, the way a product key gets 5 minutes plus jitter in my Flipkart-style design.

Trade-offs and limits

  • Fixed window has an edge problem. A client can send the full limit at 10:00:59 and again at 10:01:00, so twice the limit in two seconds. Token bucket or a sliding window smooths this.
  • The in-memory versions are per process. With several Cloud Run instances, each keeps its own count. Shared limits need Redis or the gateway.
  • The dict in FixedWindowLimiter never shrinks. That is fine for a demo. Redis expiry solves it in a real service.
  • LRU is not always right. An item read once by a big scan can push out items that are read all day. For skewed traffic I would look at frequency-based eviction.
  • Limit at the right layer. In my URL-shortener design, the gateway protects /shorten only. Redirects skip it, because they must stay fast.

Takeaway

Rate limiting decides who gets in. Caching decides what stays close.

Fixed window is simple; token bucket handles bursts better.

On GCP: Cloud Armor per IP, API Gateway per key, Redis for anything dynamic.

Top comments (0)