Sub topic 9
Speeding up reads with a cache
This chapter assumes you know HTTP redirects, basic key-value and relational storage, and the urls table from the data model chapter. It also assumes you can read simple Python.
Why the read path needs a cache
A URL shortener is read-heavy. Creating a link happens once, but following it can happen thousands of times. A ratio of 100 reads for every write is a common planning assumption. Every redirect needs one lookup by short_code, and that lookup is the hot path.
A primary-key lookup in a database is fast, but it still costs a network round trip and disk or buffer-pool work. A cache keeps recent results in memory, which answers in well under a millisecond and takes load off the database.
Link popularity is also skewed. A small share of links gets most of the traffic, so a cache holding only the popular links can absorb most reads.
Cache-aside
The usual pattern here is cache-aside, also called lazy loading. The application owns the logic:
- Look up the code in the cache.
- On a hit, return the stored URL.
- On a miss, read the database, store the result in the cache, then return it.
The following program runs the pattern with an in-memory cache and a fake database that counts its reads.
import time
class TTLCache:
def __init__(self, ttl_seconds=3600):
self.ttl = ttl_seconds
self.items = {}
def get(self, key):
entry = self.items.get(key)
if entry is None:
return None
value, expires = entry
if expires < time.monotonic():
del self.items[key]
return None
return value
def set(self, key, value):
self.items[key] = (value, time.monotonic() + self.ttl)
def delete(self, key):
self.items.pop(key, None)
class FakeDB:
def __init__(self, rows):
self.rows = rows
self.reads = 0
def get_long_url(self, short_code):
self.reads += 1
return self.rows.get(short_code)
def resolve(short_code, cache, db):
long_url = cache.get(short_code)
if long_url is not None:
return long_url
long_url = db.get_long_url(short_code)
if long_url is not None:
cache.set(short_code, long_url)
return long_url
cache = TTLCache(ttl_seconds=60)
db = FakeDB({"aZ3k9Q1": "https://example.com/very/long/path"})
for _ in range(1000):
resolve("aZ3k9Q1", cache, db)
print("database reads:", db.reads)It prints database reads: 1. The first request misses, and the other 999 are served from memory.
Sizing and choosing a cache
Suppose peak traffic is 10,000 redirects per second and the hit ratio is 90%. The database then sees only 1,000 reads per second. At 99% it sees 100.
Memory is rarely the constraint. If an entry takes about 200 bytes including overhead, 100 million cached links need about 20 GB. Because of popularity skew, you can cache far fewer and still get a high hit ratio.
In production, use a shared cache such as Redis or Memcached, so all app servers see the same entries. Set a maximum memory size and an eviction policy. Least recently used (LRU) eviction fits this workload, because it drops cold links and keeps popular ones.
Staleness and invalidation
A cached entry can disagree with the database. Handle the common cases explicitly:
- Expiry. Never let the cache TTL run past a link's
expires_at. Use the smaller of the two. - Deletion or edit. Remove the key with
cache.delete(short_code)when a link is disabled, for example after an abuse report. Otherwise the link keeps redirecting until its TTL ends. - Immutable codes. If a short code never changes its target, staleness is rare. This is one reason to disallow editing destinations.
Failure modes
- Cache down. Requests fall through to the database, which may be overwhelmed. Plan capacity for this, or add rate limiting on the fallback path.
- Cold start. A new or restarted cache has a 0% hit ratio. Warm it gradually, or restart nodes one at a time.
- Stampede. When a hot key expires, many requests miss at once and all query the database. Add random jitter to TTLs, or let only one request refill each key.
Exercise
Your cache has a one-hour TTL. A link is reported as malicious and you set it as disabled in the database. Users still get redirected for up to an hour. What went wrong, and how do you fix it?
Show answer
Cache-aside only reads the database on a miss, so the cached entry stays valid until the TTL ends. Fix it by deleting the key from the cache at the same time as you disable the link in the database. Shorter TTLs reduce the window but do not close it.