Sub topic 9
Speeding up reads with a cache
A URL shortener spends nearly all of its time on one operation: turning a short code into a long URL and sending a redirect. This chapter adds a cache in front of the database to serve that operation. It covers where the cache sits, how big it must be, how entries leave it, and what goes wrong when the cache and database disagree.
This chapter assumes you know HTTP status codes and headers, have used a relational or key-value database, and can read simple Python. It builds on the urls table from the data model chapter and the redirect choice from the 301 versus 302 chapter.
Why the read path suits a cache
Creating a link happens once. Following it can happen thousands of times. A ratio of 100 reads to 1 write is a common planning assumption. Three properties make caching work well here:
- Reads dominate. Most database load is lookups by primary key, so removing them removes most of the load.
- Entries are tiny. A code is about 7 bytes and a typical URL about 100 bytes. With key and metadata overhead, plan on roughly 200 bytes per entry.
- Popularity is skewed. A few links, such as a viral post or a marketing campaign, get most of the clicks. A cache holding only the popular codes can still answer most requests.
Entries also rarely change. A code maps to the same URL for its whole life, so the cache is seldom invalid.
Sizing the cache
Take these assumptions: 100 million redirects per day, and 10 million distinct codes requested in a day.
- Average load is 100,000,000 / 86,400, or about 1,150 requests per second. At 3 times that for peak, plan for about 3,500 per second.
- Caching every distinct code from a day takes 10,000,000 × 200 bytes = 2 GB.
2 GB fits in memory on one node of a store such as Redis or Memcached. You do not have to cache everything. If 20% of those codes cover most of the traffic, a 400 MB cache gives a high hit rate. Measure the real hit rate and adjust.
The cache-aside pattern
In cache-aside, the application owns the logic. It checks the cache first. On a miss it reads the database, then writes the result to the cache for later requests. The cache never talks to the database itself.
The basic version looks like this:
def resolve(short_code: str, 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_urlThis version has two gaps. It never expires entries, and an unknown code goes to the database on every request. The next sections fix both.
Eviction and expiry
A cache has finite memory, so entries must leave. Two mechanisms work together.
| Mechanism | What it does | Why a shortener needs it |
|---|---|---|
| LRU eviction | When full, removes the least recently used entry | Keeps hot codes and drops the long tail |
| TTL (time to live) | Removes an entry after a fixed time | Bounds staleness and honors link expiry |
LRU matches the skewed popularity above. A TTL gives a safety net: even if an invalidation is missed, the wrong value lives only a limited time. Redis can combine both with maxmemory-policy allkeys-lru plus a per-key expiry.
A runnable example
The code below implements a small in-process LRU cache with TTL. It also adds negative caching and ties the cache TTL to the link's expires_at. It is a teaching model of what Redis does for you.
import time
from collections import OrderedDict
NOT_FOUND = "__not_found__"
class TTLCache:
def __init__(self, max_items: int, default_ttl: float):
self.max_items = max_items
self.default_ttl = default_ttl
self._data = OrderedDict()
def get(self, key):
item = self._data.get(key)
if item is None:
return None
value, expires_at = item
if expires_at <= time.monotonic():
del self._data[key]
return None
self._data.move_to_end(key) # mark as recently used
return value
def set(self, key, value, ttl=None):
ttl = self.default_ttl if ttl is None else ttl
self._data[key] = (value, time.monotonic() + ttl)
self._data.move_to_end(key)
while len(self._data) > self.max_items:
self._data.popitem(last=False) # evict least recently used
class FakeDb:
"""Maps code -> (long_url, expires_at epoch seconds or None)."""
def __init__(self, rows):
self.rows = rows
self.queries = 0
def get_row(self, short_code):
self.queries += 1
return self.rows.get(short_code)
def resolve(short_code, cache, db, ttl=3600, negative_ttl=60):
cached = cache.get(short_code)
if cached == NOT_FOUND:
return None
if cached is not None:
return cached
row = db.get_row(short_code)
if row is None:
cache.set(short_code, NOT_FOUND, ttl=negative_ttl)
return None
long_url, expires_at = row
if expires_at is not None:
remaining = expires_at - time.time()
if remaining <= 0:
cache.set(short_code, NOT_FOUND, ttl=negative_ttl)
return None
ttl = min(ttl, remaining) # never outlive the link
cache.set(short_code, long_url, ttl=ttl)
return long_url
if __name__ == "__main__":
db = FakeDb({"aB3xK9z": ("https://example.com/very/long/path", None)})
cache = TTLCache(max_items=1000, default_ttl=3600)
for _ in range(5):
resolve("aB3xK9z", cache, db)
for _ in range(5):
resolve("zzzzzzz", cache, db)
print("database queries:", db.queries) # 2, not 10Ten requests cause only two database queries: one for the real code and one for the unknown code. The remaining eight are served from the cache.
Failure modes
A cache adds new ways to fail. These are the ones that matter for a shortener.
Stale entries
If a link is deleted or its target changes, the cache may keep serving the old URL until the TTL ends. The usual fix is to delete the cache key on every update or delete, and to keep a TTL as a backstop. Delete rather than overwrite, so a racing reader cannot re-insert an old value. If your product promises that a deleted link stops working at once, keep TTLs short or check a deletion flag.
Negative caching and enumeration
Requests for codes that do not exist always miss, so each one reaches the database. Attackers who scan random codes can use this to bypass the cache. Storing a "not found" marker with a short TTL, as in the example, absorbs repeats. Keep that TTL short. A code created a moment after a miss should not look missing for an hour.
Cache stampede
When a very popular entry expires, many concurrent requests miss together and all query the database. Three common defenses:
- Request coalescing. Let one request per key fetch from the database while others wait for its result.
- TTL jitter. Add a random amount to each TTL so popular keys do not expire together.
- Early refresh. Refresh a hot entry shortly before it expires.
Cache outage
If the cache is down, every request falls through to the database, which was sized assuming the cache absorbs most reads. Options are to treat cache errors as misses and shed load with rate limits, or to run the cache as a replicated cluster. The availability chapter returns to this.
Interaction with redirect type
A 301 response tells browsers and intermediaries to remember the redirect, so repeat visits may never reach your servers. That is a second cache, outside your control. A 302 sends every click through your service, so your cache then carries the full load, and you can count clicks. The choice affects both cache sizing and analytics.
Where to put the cache
| Placement | Benefit | Cost |
|---|---|---|
| In-process memory on each app server | No network hop, fastest | Each server warms separately, and invalidation must reach every server |
| Shared cache (Redis, Memcached) | One copy, one place to invalidate | Network round trip, one more service to run |
| Both, as two tiers | Very hot codes served locally | More complexity, and staleness can add up |
Start with a shared cache. Add a small in-process tier only if measurements show the network hop matters.
Exercise
A code is requested 50 times in a row but does not exist in the database. The cache uses the basic resolve function from this chapter, which has no negative caching. How many database queries occur? What change reduces that number, and what risk does the change introduce?
Show answer
There are 50 database queries, because a missing code is never stored in the cache. Storing a "not found" marker with a short TTL reduces this to one query per TTL window. The risk is that a link created during that window looks missing until the marker expires, so the negative TTL should be short, such as 30 to 60 seconds.
Exercise
Using this chapter's assumptions of 200 bytes per entry and 10 million distinct codes per day, how much memory does it take to cache every distinct code, and why might you provision less?
Show answer
10,000,000 × 200 bytes is 2 GB. You can provision less because popularity is skewed. A small share of codes receives most requests, so an LRU cache holding only the hot codes can still reach a high hit rate. You should measure the hit rate and size the cache from that.