Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

Caches and data partitioning

By the end of this chapter, you'll be able to

  • Set up a cache-aside cache with an LRU eviction policy
  • Measure a cache's hit rate and the impact of its size
  • Recognise and avoid a stampede on an expired key
  • Distribute keys with consistent hashing and limit movements when a node is added

The cache-aside pattern

The most common pattern is called cache-aside: the application first looks in the cache (fast memory such as Redis); on a miss, it reads the database, then stores the result in the cache for next time. A cache has a limited size: when it is full, an entry must be evicted. The LRU policy (Least Recently Used) evicts the one used longest ago.

from collections import OrderedDict
import random

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

    def read(self, key, load):
        if key in self.data:
            self.data.move_to_end(key)           # becomes the most recent
            self.hits += 1
            return self.data[key]
        self.misses += 1
        value = load(key)                        # slow read, from the database
        self.data[key] = value
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)        # evicts the least recent
        return value

# 10,000 products, but a small share gets most of the visits (Zipf's law)
random.seed(42)
products = list(range(10_000))
weights = [1 / (rank + 1) for rank in products]
requests = random.choices(products, weights=weights, k=50_000)

for capacity in (100, 1_000, 5_000):
    cache = LRUCache(capacity)
    for p in requests:
        cache.read(p, lambda key: f"product {key}")
    rate = cache.hits / len(requests)
    print(f"cache of {capacity:>5} entries: {rate:.0%} hits, {cache.misses:>6} database reads")
cache of   100 entries: 39% hits,  30512 database reads
cache of  1000 entries: 67% hits,  16541 database reads
cache of  5000 entries: 85% hits,   7311 database reads

With only 1% of the products cached, nearly 40% of reads are avoided, and two thirds with 10%: popularity is very uneven, and that is what makes caches so effective. But the gains shrink: the 4,000 entries added between 1,000 and 5,000 bring less than the 900 added between 100 and 1,000.

Time to live and invalidation

Cached data can become stale: the price has changed in the database, the cache serves the old one. Two tools:

  • a time to live (TTL): the entry expires after, say, 60 seconds. Simple, but you accept up to 60 seconds of delay;
  • invalidation: when you change the data, you delete the cache entry. Precise, but you must never forget it, on every write path.

In practice both are combined: invalidation on write, and a TTL as a safety net. And you don't cache what must be exact to the second (a bank balance, stock at the moment of payment).

Partitioning data

When a single machine is no longer enough (in volume or throughput), the data is partitioned (sharding): each node holds part of the keys. The naive method is modulo: node = hash(key) % number_of_nodes. Problem: adding a node changes the result for almost every key, and the whole cache becomes wrong at once.

Consistent hashing places nodes and keys on the same ring of values. Each key belongs to the first node met going clockwise. Adding a node only moves the keys of the portion of the ring it takes over. Each node is placed at several positions (virtual nodes) to balance the load.

D takes over portions from the other three; the other keys do not move.

Step 5 of 5
Text description of the animation
  1. Imagine all the hash values closed into a circle.
  2. Each node is hashed 100 times, under different names: these are its virtual nodes.
  3. The key is hashed onto the same ring.
  4. Go round to the next node point: the key belongs to B.
  5. D takes over portions from the other three; the other keys do not move.
import bisect
import hashlib

def h(text):
    """Stable hash (unlike hash(), which changes every time Python starts)."""
    return int.from_bytes(hashlib.md5(text.encode()).digest()[:4], "big")

class Ring:
    def __init__(self, nodes, virtual=100):
        self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(virtual))
        self.values = [v for v, _ in self.points]

    def node(self, key):
        i = bisect.bisect(self.values, h(key)) % len(self.points)
        return self.points[i][1]

keys = [f"cart:{i}" for i in range(20_000)]

before_mod = {k: h(k) % 3 for k in keys}
after_mod = {k: h(k) % 4 for k in keys}
moved_mod = sum(before_mod[k] != after_mod[k] for k in keys)

before = Ring(["A", "B", "C"])
after = Ring(["A", "B", "C", "D"])
moved_ring = sum(before.node(k) != after.node(k) for k in keys)

print(f"modulo            : {moved_mod / len(keys):.0%} of keys moved")
print(f"consistent hashing: {moved_ring / len(keys):.0%} of keys moved")
distribution = {n: 0 for n in "ABCD"}
for k in keys:
    distribution[after.node(k)] += 1
print("distribution over 4 nodes:", distribution)
modulo            : 75% of keys moved
consistent hashing: 24% of keys moved
distribution over 4 nodes: {'A': 5077, 'B': 5076, 'C': 5060, 'D': 4787}

With modulo, going from 3 to 4 nodes moves three quarters of the keys: that many cache misses, or that much data to copy. With the ring, only about a quarter, which is the share the new node naturally has to take over. This technique is used by many distributed caches and databases.

Your turn

Worked exercise

Worked exercise: a cache with a time to live

Add a time to live to the cache: read(key, load, now) reloads the entry if it was stored more than ttl seconds ago. The time is passed as a parameter (now) so it can be tested without waiting. Check the scenario: reads at t = 0, t = 30, then t = 61 with a TTL of 60 s.

Hint 1
Store a pair (value, stored_at) for each key.
Hint 2
The entry is valid if now - stored_at < ttl.
Show the solution and common mistakes
class TTLCache:
    def __init__(self, ttl):
        self.ttl = ttl
        self.data = {}
        self.loads = 0

    def read(self, key, load, now):
        entry = self.data.get(key)
        if entry and now - entry[1] < self.ttl:
            return entry[0]
        self.loads += 1
        value = load(key)
        self.data[key] = (value, now)
        return value

    def invalidate(self, key):
        self.data.pop(key, None)

prices = {"mango": 300}
cache = TTLCache(ttl=60)
for t in (0, 30, 61):
    print(f"t={t:>2} s: {cache.read('mango', prices.get, t)} F CFA, loads = {cache.loads}")

prices["mango"] = 350
print("without invalidation:", cache.read("mango", prices.get, 70))
cache.invalidate("mango")
print("after invalidation:", cache.read("mango", prices.get, 71))
t= 0 s: 300 F CFA, loads = 1
t=30 s: 300 F CFA, loads = 1
t=61 s: 300 F CFA, loads = 2
without invalidation: 300
after invalidation: 350

At t = 30, the entry is still fresh: no load. At t = 61, it has expired: it is reloaded. After the price change, the cache serves the old value until the entry is invalidated.

Common mistakes:

  • Using time.time() directly in the class: the tests then have to wait real seconds. Injecting the time makes the code testable.
  • Forgetting invalidation on one of the write paths (the admin interface, a file import): users see the old price until expiry.
  • Giving the same TTL to all keys created at the same moment: they expire together and cause a stampede.

Summary

  1. 1Cache-aside: read the cache, and on a miss read the database then fill the cache.
  2. 2Uneven popularity makes a small cache very effective; the gains then shrink.
  3. 3Time to live and invalidation are combined; don't cache what must be exact to the second.
  4. 4A popular key that expires can cause a stampede: single reload, early refresh, jitter.
  5. 5Consistent hashing only moves about 1/n of the keys when an n-th node is added.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.