Read Replicas vs. Caching

Difficulty: Intermediate

Question

Your database is overloaded with reads. When would you add a read replica, and when would you put a cache like Redis in front of it instead?

Answer

Use a read replica when you need to offload arbitrary SQL reads (filters, joins, reports, search pages) that are hard to cache and must stay close to the source of truth. Use a cache like Redis when a small set of hot, repeatedly requested results (a product page, a user session, a config blob) dominates traffic and can tolerate being served from memory with explicit invalidation. Many production systems use both: Redis for the hottest keys, replicas for everything else.

How each one reduces load

A read replica is a full copy of the database that applies the primary's change stream (PostgreSQL WAL, MySQL binlog). Your app sends read-only queries to it. It can answer any query the primary can, with indexes and joins, but it costs as much as a database server and is still bound by disk and query execution speed.

A cache stores the result of a computation keyed by something simple, such as product:123 or feed:user:42:page:1. A Redis GET is a sub-millisecond in-memory lookup, so one Redis node can serve far more simple reads than a database. But it can only serve what you explicitly put in it, under keys you can predict.

AspectRead replicaRedis cache
What it can serveAny SQL queryOnly precomputed keys
FreshnessReplication lag, usually milliseconds to secondsUntil TTL or invalidation
Consistency workHandle read-your-writesHandle invalidation and stampedes
Best forVaried queries, reports, search, listings with filtersHot objects, sessions, counters, rate limits
Scaling costA full DB instance per replicaCheap memory, very high QPS

When a replica is the better choice

  • Queries are diverse: an admin dashboard where every filter combination is a new query, so the cache hit rate would be poor.
  • You need SQL features: joins, aggregations, full-text search.
  • Analytics or report jobs are hurting the primary; point them at a dedicated replica.
  • The team does not want to own cache invalidation logic.

When a cache is the better choice

  • Traffic is skewed: on a Flipkart sale day a few thousand product pages get most of the hits.
  • The same expensive result is requested many times (a computed leaderboard, a home page).
  • You need latency in single-digit milliseconds at very high QPS.
  • Data tolerates slight staleness or you can invalidate on write cleanly.

Gotchas with each

Replicas: replication lag breaks read-your-writes. A user updates their profile, the next request reads from a replica that has not caught up, and they see old data. Fixes include reading from the primary for a short window after a write, routing a user's reads to the primary when their session has a recent write, or waiting for the replica to reach a known LSN. Replicas also do not help write load at all.

Caches: invalidation is the hard part. Prefer cache-aside with delete-on-write rather than update-on-write to avoid races, set TTLs as a safety net, and protect against stampedes (many requests missing the same key at once) with request coalescing or a short lock. Never treat the cache as the source of truth unless you have designed for it.

A sensible order of operations

  1. Fix the queries first: missing indexes and N+1 queries cause most read overload.
  2. Cache the few hottest, simplest reads.
  3. Add replicas for the remaining varied read traffic and reporting.
Read path with cache and replica. Hot keys are served from Redis; misses and complex queries go to a replica while writes go to the primary.
  1. App receives read request: Decide by query shape where to send it.
  2. Check Redis by key: Hit returns in under a millisecond.
  3. On miss, query read replica: Full SQL, may lag the primary slightly.
  4. Store result in Redis with TTL: Next request for this key is a hit.
  5. Writes go to primary: Primary invalidates the cache key and streams WAL to replicas.

Code examples

Cache-aside in front of a read replica

import { Redis } from "ioredis";
import { Pool } from "pg";

const redis = new Redis(process.env.REDIS_URL!);
const primary = new Pool({ connectionString: process.env.PRIMARY_URL });
const replica = new Pool({ connectionString: process.env.REPLICA_URL });

export async function getProduct(id: number) {
  const key = "product:" + id;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  // miss: read from replica, not primary
  const { rows } = await replica.query("SELECT * FROM products WHERE id = $1", [id]);
  if (rows[0]) await redis.set(key, JSON.stringify(rows[0]), "EX", 300);
  return rows[0] ?? null;
}

export async function updatePrice(id: number, pricePaise: number) {
  await primary.query("UPDATE products SET price_paise = $1 WHERE id = $2", [pricePaise, id]);
  await redis.del("product:" + id); // delete, do not overwrite
}

Reads try Redis first and fall back to a replica, so the primary only handles writes. On update the key is deleted rather than rewritten, which avoids races where an older value overwrites a newer one.

Key points

  • Replicas scale arbitrary SQL reads; caches scale a small set of hot, predictable keys.
  • Neither helps write throughput; that needs sharding or write optimisation.
  • Replication lag breaks read-your-writes unless you route recent writers to the primary.
  • Cache-aside with delete-on-write plus a TTL is the safest default invalidation pattern.
  • Fix indexes and N+1 queries before adding either.

Common follow-up questions

  • How would you guarantee a user sees their own update immediately when reads go to replicas?
  • What is a cache stampede and how do you prevent it?
  • Why delete the cache key on write instead of updating it?
  • How would you decide the TTL for a product page cache?

Interview tips

  • Frame the answer around query shape: varied SQL goes to replicas, repeated simple lookups go to cache.
  • Raise replication lag and cache invalidation unprompted; these are the real costs interviewers look for.
  • Mention that you would first check for missing indexes; it shows you would not reach for infrastructure prematurely.

Concepts covered

Read Replicas, Redis Cache, Replication Lag, Cache Invalidation, Read Scaling

More Database Design questions