Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

LRU Cache & Rate Limiter

Two pieces of infrastructure every backend runs: a least-recently-used cache that evicts cold keys under a memory ceiling, and a token-bucket rate limiter that decides who gets a 429.

Advanced 4 steps 145 XP ~50 min

How it works in the real world

Caches and rate limiters answer the same question — what do I do when I cannot serve everything?

  1. Cache — remember expensive results so the second call is free.
  2. Evict — memory is finite, so when full, drop the least recently used key. Recency is a good proxy for what you'll need next.
  3. Measure — a cache with a poor hit rate is pure overhead, so count hits and misses.
  4. Limit — a token bucket refills at a steady rate and allows a burst up to its size. Stripe, GitHub and Cloudflare all shape traffic this way.

OrderedDict gives you O(1) recency tracking, which is exactly how functools.lru_cache works underneath.

Build progress0 / 4 steps
1

A cache with hit tracking

Cache slow_lookup results in a dict. Count hits and misses across the call sequence, then print both and the hit rate to one decimal.

Blank · autosaved
PYstep_1.py
Run your code to check this step…
2

Evict the least recently used

With a capacity of 3, evict the least recently used key whenever a new one arrives full. A repeat access counts as a use. Print the evicted keys in order and what remains.

Blank · autosaved
PYstep_2.py
Run your code to check this step…
3

Wrap it in a class

Build an LRUCache class with get and put, tracking hits and misses. Exercise it with capacity 2 and print the lookups, the counters and the surviving keys.

Blank · autosaved
PYstep_3.py
Run your code to check this step…
4

Token-bucket rate limiting

Each user gets a bucket of 3 tokens refilling at 3/second. A request costs one token; with none left, answer 429. Print each request's verdict.

Blank · autosaved
PYstep_4.py
Run your code to check this step…
Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path