StackPractices
intermediate By Mathias Paulenko

Read-Through Cache Pattern

A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.


Overview

Read-through puts the cache in charge of reads: the app calls the cache and never the database. If the key is cached, the answer comes straight back. If it isn’t, the cache itself fetches the data from the backing store, stores it, and returns it — the database never sees a read request directly.

That’s the opposite of cache-aside, where the application owns cache population. Read-through pushes that job down into the cache layer or a caching library, so application code stays simple and every read path behaves the same way.

When to Use

  • Several read paths access the same data and you want consistent caching behavior
  • You want to decouple application code from cache management logic
  • Your cache layer supports a read-through callback (Redis with Lua, memcached with callbacks)
  • You need predictable cache behavior without relying on every developer calling cache correctly
  • Read latency is more critical than write latency

Skip read-through when writes dominate — a write-through cache keeps reads hot without extra misses — or when some keys need conditional caching logic, which cache-aside handles better. For a proactive variant that refreshes entries before they expire, see the Refresh-Ahead Cache Pattern.

Solution

Python with Redis

import redis
import json
import pickle
from typing import Callable, TypeVar, Optional

T = TypeVar('T')

class ReadThroughCache:
    def __init__(self, redis_client: redis.Redis, ttl: int = 3600):
        self.redis = redis_client
        self.ttl = ttl

    def get_or_load(self, key: str, loader: Callable[[], T], ttl: Optional[int] = None) -> T:
        cached = self.redis.get(key)
        if cached is not None:
            return pickle.loads(cached)

        value = loader()
        self.redis.setex(key, ttl or self.ttl, pickle.dumps(value))
        return value

    def get_or_load_json(self, key: str, loader: Callable[[], dict], ttl: Optional[int] = None) -> dict:
        cached = self.redis.get(key)
        if cached is not None:
            return json.loads(cached)

        value = loader()
        self.redis.setex(key, ttl or self.ttl, json.dumps(value))
        return value


cache = ReadThroughCache(redis.Redis(host='localhost', port=6379))

def get_user(user_id: str) -> dict:
    return cache.get_or_load_json(
        f"user:{user_id}",
        lambda: db.query_one("SELECT id, name, email FROM users WHERE id = %s", [user_id]),
        ttl=1800
    )

TypeScript with Redis

import { createClient } from 'redis';

class ReadThroughCache {
  private client: ReturnType<typeof createClient>;
  private defaultTtl: number;

  constructor(client: ReturnType<typeof createClient>, ttl = 3600) {
    this.client = client;
    this.defaultTtl = ttl;
  }

  async getOrLoad<T>(key: string, loader: () => Promise<T>, ttl?: number): Promise<T> {
    const cached = await this.client.get(key);
    if (cached !== null) {
      return JSON.parse(cached) as T;
    }

    const value = await loader();
    await this.client.set(key, JSON.stringify(value), { EX: ttl ?? this.defaultTtl });
    return value;
  }

  async invalidate(key: string): Promise<void> {
    await this.client.del(key);
  }
}

// Usage
const redisClient = createClient({ url: 'redis://localhost:6379' });
await redisClient.connect();
const cache = new ReadThroughCache(redisClient);

async function getUser(userId: string): Promise<User> {
  return cache.getOrLoad(
    `user:${userId}`,
    () => db.query('SELECT id, name, email FROM users WHERE id = $1', [userId]),
    1800
  );
}

Java with Caffeine

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;

public class ReadThroughCacheManager {

    private final Cache<String, Object> cache;

    public ReadThroughCacheManager() {
        this.cache = Caffeine.newBuilder()
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .maximumSize(10_000)
            .build();
    }

    @SuppressWarnings("unchecked")
    public <T> T getOrLoad(String key, java.util.function.Function<String, T> loader) {
        return (T) cache.get(key, k -> loader.apply(k));
    }

    public void invalidate(String key) {
        cache.invalidate(key);
    }
}

// Usage
ReadThroughCacheManager cache = new ReadThroughCacheManager();

User user = cache.getOrLoad("user:" + userId, k -> {
    return userRepository.findById(Long.parseLong(k.split(":")[1]))
        .orElseThrow(() -> new NotFoundException("User not found"));
});

Atomic Check-and-Fill with a Lua Script

A Lua script can’t reach your database — the loader always runs in the application. What Lua buys you is atomicity: the check-then-set happens server-side in a single step, with no race between GET and SETEX. This is useful when the source value also lives in Redis (for example, a denormalized copy written by a sync job).

-- check_and_fill.lua
-- KEYS[1]: cache key
-- KEYS[2]: source key holding the value to cache
-- ARGV[1]: TTL in seconds

local cached = redis.call('GET', KEYS[1])
if cached then
  return cached
end

local value = redis.call('GET', KEYS[2])
if value then
  redis.call('SETEX', KEYS[1], ARGV[1], value)
  return value
end
return nil
# Using the Lua script — the application still loads the source key
script = r.register_script(lua_script)
result = script(keys=["user:123", "user:123:db"], args=[3600])

Explanation

The read-through pattern shifts cache management from the application to the cache layer:

  1. Cache hit — the cache has the data and returns it immediately, without touching the database.
  2. Cache miss — the cache calls a loader function (or callback) that knows how to fetch the data from the backing store. The fetched data is stored in the cache with a TTL and returned to the caller.
  3. Subsequent reads — later requests hit the cache until the TTL expires or someone invalidates the entry.
flowchart diagram: Client

Transparency is what separates this from cache-aside. With cache-aside, the application checks the cache, misses, fetches from the database, and populates the cache. With read-through, the application calls cache.get(key) and the cache handles the rest — every read path gets caching for free, without each developer having to wire it up.

Variants

ApproachLayerBest For
Application-level libraryPython/TS/Java cache wrapperMost use cases, full control
Redis Lua scriptRedis serverAtomic read-through without round trips
CDN read-throughCDN edgeStatic and semi-static content
Database proxy cacheProxy layerTransparent caching without code changes
ORM second-level cacheORM layerJava/Hibernate, automatic entity caching

Best Practices

  • For a deeper guide, see Refresh-Ahead Cache Pattern.

  • Set a TTL on every entry — an entry with no TTL can serve stale data forever. Choose TTLs based on how often the data changes.

  • Use consistent key naming — a predictable entity:id scheme (e.g. user:123, product:456) makes debugging and invalidation much easier.

  • Handle loader failures gracefully — if the database is down, a stale cached copy beats a failed request, so serve it when you can.

  • Serialize efficiently — JSON is fine for simple objects; reach for MessagePack or Protobuf when payloads get complex. Skip payloads big enough to pressure cache memory.

  • Monitor cache hit ratio — under ~80%, the cache is probably earning its keep poorly. Check TTLs, key patterns, and cache size.

Common Mistakes

  • No TTL on cache entries — entries live forever and quietly go stale. Always set a TTL — even a generous one like 24h beats none.
  • Caching too aggressively — caching every read burns memory on cold keys and multiplies the stale data you end up managing. Cache hot keys and expensive queries, not every read.
  • Not invalidating after writes — after a write, the cached copy goes stale until the TTL expires. Either call cache.invalidate(key) right after the write, switch to write-through, or pick an approach from the cache invalidation strategies.
  • Large objects in cache — a 10MB object in cache eats memory and adds serialization overhead on every hit. Cache projections, not full entities.
  • Ignoring cache stampede — when a hot key expires, a burst of concurrent misses can all hit the database at once. Use a lock or single-flight pattern.

Advanced Topics

Scenario: Read-Through Cache with Redis

// Read-Through: the cache manages DB reads transparently
class ReadThroughCache {
  constructor(private redis: RedisClient, private db: Pool, private ttlSec: number = 300) {}

  async get<T>(key: string, queryFn: () => Promise<T>): Promise<T> {
    // 1. Try cache
    const cached = await this.redis.get(key);
    if (cached) return JSON.parse(cached) as T;

    // 2. Cache miss: the cache handles reading and filling
    const data = await queryFn();
    await this.redis.setex(key, this.ttlSec, JSON.stringify(data));
    return data;
  }

  // Batch read-through: multiple keys in one operation
  async getBatch<T>(keys: string[], queryFn: (keys: string[]) => Promise<Record<string, T>>): Promise<Record<string, T>> {
    const results: Record<string, T> = {};
    const missingKeys: string[] = [];

    // 1. Read all keys from cache
    const cached = await this.redis.mget(...keys);
    keys.forEach((key, i) => {
      if (cached[i]) { results[key] = JSON.parse(cached[i]) as T; }
      else { missingKeys.push(key); }
    });

    // 2. Read missing from DB
    if (missingKeys.length > 0) {
      const dbData = await queryFn(missingKeys);
      // 3. Fill cache for missing keys
      const cacheEntries: string[] = [];
      for (const [key, value] of Object.entries(dbData)) {
        results[key] = value;
        cacheEntries.push(key, JSON.stringify(value));
      }
      if (cacheEntries.length > 0) {
        await this.redis.mset(...cacheEntries);
        for (const key of Object.keys(dbData)) {
          await this.redis.expire(key, this.ttlSec);
        }
      }
    }

    return results;
  }
}

// Usage
const cache = new ReadThroughCache(redis, dbPool, 300);

// Single read
const user = await cache.get("user:123", async () => {
  const res = await dbPool.query("SELECT * FROM users WHERE id = $1", ["123"]);
  return res.rows[0];
});

// Batch read
const users = await cache.getBatch(["user:1", "user:2", "user:3"], async (ids) => {
  const res = await dbPool.query("SELECT * FROM users WHERE id = ANY($1)", [ids]);
  return Object.fromEntries(res.rows.map((r: any) => [`user:${r.id}`, r]));
});

Lessons:

  • Read-through: the cache manages transparent reads
  • The client only calls get() — it doesn’t know whether data came from cache or DB
  • Cache-aside: the client manages cache and DB separately
  • Batch read-through: mget + mset reduce round-trips
  • TTL as safety net: if invalidation fails, the TTL cleans up
  • Use a Redis pipeline to reduce latency in batch operations

Further Reading

Frequently Asked Questions

What is the difference between read-through and cache-aside?

In cache-aside, the application manages cache population: check cache, miss, fetch from DB, populate cache. In read-through, the cache layer handles population via a loader callback. Read-through centralizes cache logic; cache-aside gives the application more control.

When should I use read-through over cache-aside?

Reach for read-through when you want identical caching behavior on every read path, without trusting each developer to wire it up. Go with cache-aside when you need fine-grained control over what gets cached and when.

How do I handle cache stampede in read-through?

Use a lock or single-flight mechanism: when a cache miss occurs, only one request fetches from the database while others wait. Redis distributed locks or language-level single-flight libraries work well.

Can I use read-through with a distributed cache?

Yes — this works fine on top of Redis or Memcached. For Redis, wrap the check-and-fill in a Lua script to keep it atomic. At the application level, any cache wrapper that accepts a loader callback does the job.