Sub topic 5
Read-through caching
This chapter assumes you know cache-aside, hit ratio, and TTL from the earlier chapters. It also assumes you can read basic Python and know how threads share data. Read-through caching uses the same lookup logic as cache-aside. The difference is where that logic lives.
What read-through means
In cache-aside, the application owns the miss logic. It checks the cache, calls the database on a miss, and writes the result back. In read-through, the cache owns that logic. The application asks the cache for a key. On a miss, the cache calls a loader function that you registered, stores the result, and returns it. The application never talks to the database for reads.
Some products ship with this behavior, such as caching libraries with a loading function and some managed data-grid products. You can also build it as a thin wrapper around a plain cache, which is what the example below does.
Cache-aside compared with read-through
| Aspect | Cache-aside | Read-through |
|---|---|---|
| Who handles a miss | Application code | The cache layer |
| Where the loading code lives | Repeated at every call site | One registered loader |
| Cache failure | App can fall back to the database directly | Depends on the wrapper; you must decide |
| Data model | Cache can store any shape | Cache stores what the loader returns |
| Flexibility | High, each call site can differ | Lower, one loader per cache |
Read-through removes duplicated miss-handling code, so every caller gets the same behavior. The cost is flexibility. If different callers need different queries or different TTLs for the same key space, a single loader fits poorly.
A working implementation
The class below takes a loader and a TTL. It checks freshness, takes a per-key lock on a miss, checks again, then loads. The second check means concurrent callers for the same key trigger only one load. Later chapters cover stampedes in detail. A read-through layer without this guard would run the loader once per waiting caller.
import threading
import time
class ReadThroughCache:
def __init__(self, loader, ttl_seconds=60):
self.loader = loader
self.ttl = ttl_seconds
self.entries = {} # key -> (value, expires_at)
self.locks = {}
self.guard = threading.Lock()
def _lookup(self, key):
entry = self.entries.get(key)
if entry is not None and entry[1] > time.monotonic():
return True, entry[0]
return False, None
def get(self, key):
hit, value = self._lookup(key)
if hit:
return value
with self.guard:
lock = self.locks.setdefault(key, threading.Lock())
with lock:
hit, value = self._lookup(key) # another thread may have loaded it
if hit:
return value
value = self.loader(key)
self.entries[key] = (value, time.monotonic() + self.ttl)
return value
calls = []
def load_user(user_id):
calls.append(user_id)
time.sleep(0.2) # simulate a slow database
return {"id": user_id, "name": f"user-{user_id}"}
cache = ReadThroughCache(load_user, ttl_seconds=30)
threads = [threading.Thread(target=cache.get, args=(7,)) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print("loader calls:", len(calls))
print(cache.get(7))Running it prints loader calls: 1 and then the user dictionary. Five threads asked for key 7 at the same moment. Four of them waited on the lock and reused the result.
The lookup returns a pair, (hit, value), instead of returning None for a miss. That lets the cache store a legitimate None result, such as "no such user". Storing that result is called negative caching. Without it, a request for a missing key hits the database every time.
Design decisions to make
What the loader returns and raises
Decide what happens when the loader fails. There are three common choices:
- Let the exception propagate and cache nothing. This is the simplest option and the safest default.
- Return a stale value if one exists. This keeps the application running during a database outage but needs the cache to keep expired entries around.
- Cache the failure for a short time. This protects a struggling database from a retry storm, but it can hide recovery.
In the code above, an exception from self.loader leaves the lock released by the with block and writes nothing to entries. The next caller retries the load.
Negative results
A missing record is a valid answer. Cache it with a shorter TTL than positive results. Records are often created soon after a first lookup fails, and a long negative TTL makes new data look absent.
Loader scope
Keep the loader narrow: it maps a key to a value. If it needs information not in the key, such as a tenant or a locale, put that information in the key. The key design chapter covers this. A loader that reads hidden state, like the current request, produces entries that are wrong for other callers.
Cold starts
A new read-through cache is empty, so the first requests all miss. If the database cannot handle that load, warm the cache before routing traffic to it. Warming means calling get for the hottest keys ahead of time. Because the loader is already registered, warming is a simple loop.
Common errors
- Treating it as a write strategy. Read-through says nothing about writes. If your code updates the database and does not invalidate or update the cache, readers see old data until the TTL ends. Pair it with write-through, invalidation, or short TTLs.
- Loader with side effects. The cache may call the loader at unpredictable times, including after expiry and during warming. A loader that writes data, sends messages, or increments counters will do so at surprising moments. Keep loaders read-only.
- No timeout on the loader. A slow database call holds the per-key lock. Every waiting thread is blocked behind it. Set a timeout in the loader and decide what callers see when it fires.
- Unbounded
locksdictionary. The example keeps one lock per key forever. With millions of distinct keys this leaks memory. A production version removes locks after loading, or uses a fixed pool of striped locks that keys hash into. - One lock scope per process. The per-key lock stops duplicate loads only inside one process. With ten application servers, a popular key can still load ten times. A shared cache with its own request coalescing, or a distributed lock, covers that case.
- Mutable cached values. The cache returns the same object to every caller. If one caller modifies the returned dictionary, all later callers see the change. Return copies or use immutable values.
When read-through fits
Read-through works best when many call sites read the same kind of data and a single loader describes how to build it. Typical examples are user profiles, product records, and configuration lookups. It fits less well when:
- reads vary widely in shape, so no single loader serves them;
- you want the application to keep working if the cache layer is down, since the application then has no direct read path;
- you need per-call control over TTL or fallback behavior.
In those cases, cache-aside gives the call site more control at the price of more repeated code.
Exercise
A read-through cache has a 60 second TTL. The application updates a user's name in the database, and a reader then asks the cache for that user 10 seconds later. The entry was loaded 30 seconds before the update. What does the reader get, and what two changes would fix it?
Show answer
The reader gets the old name, because the cached entry is still fresh for another 20 seconds and read-through never checks the database for a fresh entry. One fix is to delete the cached key (or write the new value into it) as part of the update, which is invalidation or write-through. The other is to shorten the TTL so stale data lives for less time, which trades more database load for fresher data.
Exercise
In the ReadThroughCache example, why does get call _lookup a second time after acquiring the per-key lock?
Show answer
Several threads can miss at the same time, and all of them then wait for the lock. The first one loads the value and stores it. Without the second check, each waiting thread would call the loader again after it got the lock. With the check, the later threads find the fresh entry and return it without a database call.