Sub topic 5
Read-through caching
This chapter assumes you know the cache-aside pattern from the previous chapter, and that you are comfortable with hits, misses, and TTL. Read-through caching changes who is responsible for loading data on a miss.
What read-through means
In cache-aside, the application checks the cache, queries the database on a miss, and then fills the cache itself. In read-through caching, the application only talks to the cache. The cache sits in front of the data source. On a miss, the cache calls a loader function that you registered, stores the result, and returns it.
The caller never sees the difference between a hit and a miss, except in latency.
A minimal implementation
The cache owns the loader and the TTL. Callers pass only a key.
import time
class ReadThroughCache:
def __init__(self, loader, ttl_seconds=60):
self.loader = loader
self.ttl = ttl_seconds
self.entries = {} # key -> (value, expires_at)
def get(self, key):
entry = self.entries.get(key)
if entry is not None and entry[1] > time.monotonic():
return entry[0] # hit
value = self.loader(key) # miss: the cache loads the data
self.entries[key] = (value, time.monotonic() + self.ttl)
return value
users = ReadThroughCache(loader=lambda user_id: {"id": user_id, "name": "Ada"})
print(users.get(7)) # miss, calls the loader
print(users.get(7)) # hitCompare this with get_user from the cache-aside chapter. The caching logic has moved out of every call site and into one place.
Cache-aside compared with read-through
| Aspect | Cache-aside | Read-through |
|---|---|---|
| Who loads on a miss | Application code | Cache layer |
| Call sites | Each repeats the check-and-fill logic | One `get` call |
| Cache failure | App can fall back to the database directly | Depends on the library or provider |
| Flexibility | Each caller can load differently | One loader per cache |
| Typical home | Hand-written code with Redis or Memcached | Caching libraries and managed caches |
Where it fits
Read-through works well when many call sites read the same kind of data and you want one consistent loading rule. It also gives you a single place to add stampede protection, metrics, and retries. Libraries such as Caffeine in Java (LoadingCache) and Guava offer this form directly.
Read-through does not solve everything:
- The first request for any key is still slow. Some systems pre-warm the cache at startup to avoid this.
- Read-through covers reads only. You still need a write strategy, such as write-through or invalidation after writes.
- If the loader raises an error, decide whether callers see the error or whether the cache serves a stale value. Never cache the error as if it were a real value.
- A missing row is a common trap. If the loader returns
Noneand you do not store it, every request for that key reaches the database. Cache a "not found" marker with a short TTL.
Common errors
- Treating the cache as optional in the code path but required in practice, so a cache outage takes down reads.
- Letting the loader run unbounded work, such as a slow query, while holding a lock that blocks unrelated keys.
- Forgetting that the TTL lives in the cache, so every key shares one expiry policy unless you build per-key options.
Exercise
A read-through cache has a loader that returns None for deleted users, and the cache does not store None. A client repeatedly requests a deleted user's ID. What happens, and how do you fix it?
Show answer
Each request misses and calls the loader, so every request reaches the database and the cache gives no protection. Fix it by storing a "not found" marker (a sentinel object, not None) with a short TTL, so repeated requests for the missing key are served from the cache.