Caching Strategies

Concepts covered: functools

A cache keeps the result of a slow call so the next call with the same input skips the work. Memoizing with a dict already does that. Running a cache in a long-lived service adds 2 questions: how often does a key come back, and when should an entry leave? The share of lookups answered from the cache is its hit rate. A cache with a 0% hit rate costs memory and saves nothing.

WorkloadKeysStrategy
Currency code to display nameAbout 30, never changePlain dict, no limit
Listing details for search pagesMillions, a few thousand hotLRU with a size limit
Exchange rate per currencyFew, value changes hourlyTTL expiry plus a size limit
Fraud score per payment idEvery key uniqueNo cache: hit rate 0%

A dict with no limit grows forever

A memo dict never forgets an entry. That suits a small, fixed key space such as currency codes. Keyed on something that keeps arriving, such as listing ids from search traffic, it gains one entry per new key until the process runs out of memory. A size limit forces a choice of what to throw away, and the common answer is the entry used least recently, the LRU policy.

LRU on top of dict ordering

A dict remembers insertion order, so it can double as the recency list. On a hit, pop the key and insert it again, which moves it to the end. On a miss with the cache full, the first key is the least recently used one, and next(iter(self.data)) reads it without building a list of all the keys.

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

    def get(self, key):
        if key not in self.data:
            return None
        value = self.data.pop(key)
        self.data[key] = value
        return value

    def put(self, key, value):
        if key in self.data:
            self.data.pop(key)
        elif len(self.data) == self.capacity:
            oldest = next(iter(self.data))
            del self.data[oldest]
            print("evict", oldest)
        self.data[key] = value

cache = LRUCache(3)
for listing in ["L1", "L2", "L3", "L1", "L4", "L2"]:
    if cache.get(listing) is None:
        print("miss", listing)
        cache.put(listing, listing.lower())
    else:
        print("hit", listing)
print(list(cache.data))
miss L1
miss L2
miss L3
hit L1
miss L4
evict L2
miss L2
evict L3
['L1', 'L4', 'L2']

L1 survives because its hit on the 4th access moved it behind L2 and L3. When L4 arrives, L2 is the oldest untouched entry and is evicted. However long the stream runs, data never holds more than 3 entries, and memory stays fixed at whatever 3 cached values cost.

collections.OrderedDict provides move_to_end() and popitem(last=False) for the same 2 moves, if you prefer named operations.

This loop uses the LRUCache class from the animation. What does it print?

cache = LRUCache(2)
for key in ["A", "B", "A", "C", "B"]:
    if cache.get(key) is None:
        cache.put(key, key.lower())
print(list(cache.data))

Expiring entries with a time limit

Some values go stale. An exchange rate is right for an hour and then wrong. A TTL (time to live) cache stores each value with the moment it expires and treats an expired entry as a miss. Passing now in as an argument, instead of reading the clock inside, lets the example run with fixed numbers and print the same result every time.

class TTLCache:
    def __init__(self, ttl_seconds):
        self.ttl = ttl_seconds
        self.data = {}

    def get(self, key, now):
        entry = self.data.get(key)
        if entry is None:
            return None
        value, expires_at = entry
        if now >= expires_at:
            del self.data[key]
            return None
        return value

    def put(self, key, value, now):
        self.data[key] = (value, now + self.ttl)

rates = TTLCache(ttl_seconds=3600)
rates.put("EUR", 1.08, now=0)
print(rates.get("EUR", now=1800))
print(rates.get("EUR", now=3600))
print(len(rates.data))

Output:

1.08
None
0

Expiry fires only on a read. A key that is never read again stays in data forever, so a TTL by itself bounds staleness without bounding size. Production caches apply both rules: an entry leaves when it expires or when the size limit pushes it out.

Every caller shares the cached object

cache = {}

def city_listings(city):
    if city not in cache:
        cache[city] = ["L1", "L3", "L4"] if city == "Lisbon" else []
    return cache[city]

mine = city_listings("Lisbon")
mine.append("L9")
print(city_listings("Lisbon"))

Output:

['L1', 'L3', 'L4', 'L9']

The cache returns the list it stores, so mine and cache["Lisbon"] are the same object. One caller's append changed what every later caller receives, and the cache now serves a listing that does not exist.

Do
  • Measure the hit rate before and after adding a cache
  • Give every cache that sees unbounded keys a size limit
  • Pair a TTL with a size limit so unread entries still leave
  • Store immutable values, or hand callers a copy
Avoid
  • Cache results keyed on ids that never repeat
  • Let a memo dict live as long as a server process
  • Read the clock inside cache logic you need to test
  • Return a cached list that callers can append to

About this lesson

This section is part of the Data Structures: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.