Skip to content
Shubham JangleResources
Scalability & reliability

Explore topics

Database Caching: Cache-Aside, TTL, and Cache Hit Ratio

Database Caching: Cache-Aside, TTL, and Cache Hit Ratio

  • Most applications read data far more often than they write it. A product page, a user profile, or a restaurant menu is written once and then read thousands of times.
  • Those repeated reads drive a large share of database load, and therefore of the database bill.
  • A cache keeps frequently read data in memory, so most reads never reach the database. Done well, it makes reads faster and cheaper. Done badly, it adds cost, complexity, and stale data.

The problem: the same query, again and again

  • Imagine a food-delivery app. Millions of users open the same popular restaurant menus, and those menus change only a few times a day.
  • Without a cache, every menu view runs the same query against the database:
SELECT id, name, price, is_available
FROM menu_items
WHERE restaurant_id = 42;
  • The database does the same work every time: parse the query, read pages from memory or disk, assemble rows, and send them over the network. Under heavy traffic, CPU, connections, and I/O (input/output) become the bottleneck.

The usual first fix: read replicas

  • A read replica is a copy of the primary database that receives changes from the primary and serves read queries. The primary handles writes; replicas share the read load.
  • Replicas work, but they are expensive for this kind of workload:
    • Each replica is a full database instance. It stores the whole dataset and costs about as much as the primary, even if only a small fraction of the data is "hot".
    • They scale linearly. Doubling read traffic means roughly doubling the number of replicas.
    • Replication lag. Replicas are usually asynchronous, so a read can briefly return slightly old data.
    • Every read is still a full database query, so per-request latency barely improves.
  • Replicas are the right tool when reads are varied (many different queries, reporting, ad hoc filters). When reads are repetitive (the same few results requested over and over), a cache is usually cheaper.

What a cache is

  • A cache is a fast store, usually in memory, that holds copies of data whose source of truth lives elsewhere (here, the database).
  • Common choices:
    • Redis and its open-source fork Valkey: in-memory key-value stores with rich data types, TTLs, and replication.
    • Memcached: a simpler in-memory key-value cache.
    • Managed services such as Amazon ElastiCache, Azure Cache for Redis, and Google Cloud Memorystore.
  • Why it is faster: a cache lookup is a single key-value read from RAM (random-access memory), with no query planning, joins, or disk access. Lookups typically complete in well under a millisecond inside the cache, and about a millisecond including the network round trip. A database query commonly takes several to tens of milliseconds, and much more under load.
  • A cache only stores results you choose to cache, not the whole database. That is why it can be much smaller, and cheaper, than a replica.

Cache-aside (lazy loading)

  • Cache-aside is the most common caching pattern. The application owns the logic and talks to both the cache and the database. It is also called lazy loading, because data is loaded into the cache only when someone asks for it.
  • Read path:
    1. The app checks the cache for a key, such as menu:42.
    2. Cache hit: the data is there. Return it immediately.
    3. Cache miss: the data isn't there. Query the database.
    4. Store the result in the cache with a TTL (time to live), then return it.
Request ──► Cache ── hit ──► return cached data (~1 ms)
              │
             miss
              ▼
           Database ──► save result in cache with TTL ──► return data
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const MENU_TTL_SECONDS = 300; // 5 minutes

async function getMenu(restaurantId) {
  const key = `menu:${restaurantId}`;

  // 1. Try the cache first
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached); // cache hit

  // 2. Cache miss: read from the database
  const menu = await db.query(
    "SELECT id, name, price, is_available FROM menu_items WHERE restaurant_id = $1",
    [restaurantId]
  );

  // 3. Save the result with a TTL so it eventually expires
  await redis.set(key, JSON.stringify(menu), { EX: MENU_TTL_SECONDS });
  return menu;
}
  • Why it is popular:
    • Only data that is actually requested gets cached, so memory goes to hot data.
    • If the cache is empty or restarted, the app still works; it just reads from the database until the cache warms up.
    • It works with any database and needs no special integration.
  • Its costs:
    • Miss penalty: a miss costs a cache lookup, a database query, and a cache write, so it is slightly slower than having no cache at all.
    • Stale data: if the database changes, the cache keeps serving the old value until the key expires or is invalidated.

TTL (time to live)

  • A TTL tells the cache to delete a key automatically after a set time. It bounds how stale cached data can get and frees memory for keys nobody reads anymore.
  • Choose the TTL from how stale the data is allowed to be, not from how often it changes:
    • Restaurant name and photos: hours.
    • Menu prices: minutes.
    • "Item available" flags, stock counts, live order status: seconds, or don't cache them.
  • A TTL is a safety net, not the only invalidation mechanism. When you know data changed, invalidate it directly (next section).

Handling writes: invalidate on change

  • When a restaurant edits its menu, update the database first, then delete the cache key:
async function updateMenuItem(restaurantId, item) {
  await db.query("UPDATE menu_items SET price = $1 WHERE id = $2", [item.price, item.id]);
  await redis.del(`menu:${restaurantId}`); // next read reloads fresh data
}
  • Delete rather than overwrite. Deleting is simpler and safer: the next read reloads the full, current result. Writing the new value from the write path can race with a concurrent read that is caching an older value.
  • Even "update DB, then delete key" has a small race window: a slow reader can fetch the old row, the writer updates and deletes, then the slow reader writes the old row back into the cache. The TTL limits how long that stale entry can survive. If you need tighter guarantees, use versioned keys or delete the key again after a short delay.

Other caching patterns

PatternWho loads the cacheReadsWritesTrade-off
Cache-asideApplication, on a missApp checks cache, then DBApp writes DB, then invalidates cacheSimple, resilient; first read is slow, data can be stale
Read-throughCache library or provider, on a missApp asks only the cacheUsually paired with write-throughCleaner app code; needs a cache layer that knows how to load data
Write-throughApplication or cache, on every writeUsually hitsWrite to cache and DB togetherFresh data; every write costs more, and rarely-read data fills the cache
Write-behind (write-back)Cache, on every writeUsually hitsWrite to cache; DB updated later, in batchesFast writes; risk of losing writes if the cache fails before flushing
Refresh-aheadCache, before expiryUsually hitsNot applicableAvoids miss spikes for hot keys; may refresh data nobody reads
  • In practice, many systems combine cache-aside with a TTL and selectively write-through for data that must be fresh right after an update.

The numbers: an AWS benchmark

  • AWS published a benchmark of Amazon RDS for MySQL (Relational Database Service) with Amazon ElastiCache for Redis as a query cache. The workload was a single-row lookup by ID on db.r6g.xlarge database instances and cache.m6g.xlarge cache nodes, with an 80:20 read-to-write mix and 80% of reads served from the cache.
SetupInstancesRead throughputAvg response timeMonthly cost
RDS primary only1 database~8,000 QPS200 ms~$348
RDS + 1 read replica2 databases~16,000 QPS80 ms~$696
RDS + 4 read replicas5 databases~30,000 QPS80 ms~$1,740
RDS + 1 read replica + ElastiCache2 databases + 2 cache nodes~32,000 QPS~1 ms~$780

QPS = queries per second.

  • Replacing three of the four read replicas with two cache nodes delivered slightly more throughput for about 55% less cost, and average response time dropped from about 80 ms to about 1 ms.
  • Read these numbers carefully:
    • The cached setup still kept the primary and one read replica. A cache reduces the number of replicas you need; it does not replace the database.
    • The result depends on the 80% hit ratio. A different workload will get different savings.
    • Prices are AWS list prices at the time of the benchmark and vary by region, instance type, and pricing model. Treat this as an illustration of the trend, not a quote.

Cache hit ratio decides everything

  • The cache hit ratio is the share of reads served from the cache:
hit ratio = hits / (hits + misses)
  • It controls how much load remains on the database:
database reads per second = total reads per second × (1 − hit ratio)
Hit ratioDB reads at 30,000 reads/sEffect
0%30,000 + cache overheadThe cache only adds cost and latency
50%15,000Half the load remains; modest savings
80%6,000Large reduction (the AWS benchmark case)
95%1,500Database mostly handles writes and misses
99%300Database is nearly idle for reads
  • It also controls average latency. With a ~1 ms cache lookup and an ~80 ms database query, a rough estimate is:
average latency ≈ cache lookup + (1 − hit ratio) × database query
80% hits ≈ 1 + 0.20 × 80 = 17 ms
95% hits ≈ 1 + 0.05 × 80 =  5 ms
99% hits ≈ 1 + 0.01 × 80 ≈  2 ms
  • Going from 90% to 99% matters more than it looks: it cuts database reads by 10×.

When caching does not pay off

  • Write-heavy data: if a value changes on almost every request, cached copies are invalidated before anyone reads them.
  • Unique or long-tail requests: if every request asks for a different key (search queries with free text, highly personalized feeds, one-off reports), keys are rarely reused and the hit ratio stays low.
  • Strict consistency requirements: account balances, inventory during checkout, and permissions often must be read from the source of truth.
  • Low traffic: if the database is nowhere near its limits, a cache adds a bill and an extra component to operate without real benefit.
  • In these cases, consider better indexes, query optimization, read replicas, or a different data model first.

Important qualifications

  • The cache is not the source of truth. Anything in it can disappear at any time: expiry, eviction, restart, or failover. The application must always be able to fall back to the database.
  • Cache failures can overload the database. If the cache goes down, every read hits the database at once. Use short timeouts on cache calls, size the database to survive a cold cache for a while, or rate-limit fallback reads.
  • Cache stampede (thundering herd): when a hot key expires, thousands of concurrent requests miss at the same moment and all query the database. Mitigations:
    • Add random jitter to TTLs so many keys don't expire together.
    • Let only one request rebuild a key (a lock or request coalescing) while others wait or get the old value.
    • Refresh hot keys early, before they expire.
  • Cache penetration: repeated requests for data that doesn't exist (for example menu:999999) always miss and always hit the database. Cache the "not found" result with a short TTL.
  • Eviction: when the cache reaches its memory limit (maxmemory in Redis), it evicts keys according to its eviction policy. For a pure cache, allkeys-lru (least recently used) or allkeys-lfu (least frequently used) is common. Open-source Redis defaults to noeviction, which rejects writes when memory is full; ElastiCache defaults to volatile-lru, which only evicts keys that have a TTL. Set this deliberately.
  • Cold start: after a deploy, restart, or new node, the cache is empty and the hit ratio starts at zero. Expect a temporary spike in database load, or pre-warm the hottest keys.
  • Hot keys: a single extremely popular key (one celebrity restaurant during a sale) can overload one cache node. Use replicas for reads, a small in-process cache in front of Redis, or split the key.
  • Key design: include everything that changes the result in the key, such as menu:42:lang=en. A key that omits the language, user, or permissions can serve one user's data to another. Add a version prefix (v2:menu:42) to invalidate everything safely when the data format changes.
  • Serialization and size: large values cost memory, network bandwidth, and CPU (central processing unit) to serialize. Cache the fields you need, not entire object graphs.
  • Measure it. Track hits, misses, hit ratio, evictions, memory use, and latency. Redis exposes keyspace_hits, keyspace_misses, and evicted_keys through the INFO stats command.

Caching is layered

  • A database cache is one layer among several. The same idea, keeping a copy closer to the reader, appears at every level:
    • Browser cache, controlled with HTTP Cache-Control headers.
    • CDN (content delivery network) caches at edge locations near users. See CDN vs Load Balancer.
    • In-process application cache (a small map in memory, per server).
    • Distributed cache such as Redis, shared by all app servers.
    • The database's own buffer pool, which keeps recently used pages in memory.
  • The closer to the user a request is served, the cheaper and faster it is, and the harder it is to invalidate.

Read replicas vs cache

Read replicasCache (e.g. Redis)
StoresThe entire datasetOnly cached results
ServesAny SQL queryExact keys you cached
LatencySame as a database queryAbout a millisecond
Cost growthOne full database per replicaMemory sized to hot data
FreshnessSlight replication lagStale until TTL or invalidation
App changesRoute reads to a replica endpointAdd caching and invalidation logic
Best forVaried, unpredictable readsRepeated reads of the same data

Summary

  • Read-heavy workloads repeat the same queries. A cache serves those repeated reads from memory, cutting database load, latency, and often cost.
  • Cache-aside: check the cache; on a miss, read the database, store the result with a TTL, and return it. On writes, update the database, then delete the key.
  • In AWS's benchmark, replacing three of four read replicas with two Redis nodes cut cost by about 55% and average latency from about 80 ms to about 1 ms, at an 80% hit ratio.
  • The cache hit ratio determines the benefit. Data that changes constantly or is rarely requested twice gives a low hit ratio, and the cache just becomes another bill.

References