Skip to content

Caching Fundamentals

Basic 41 min read Part 7 of 18

What a cache is and why it works: hit ratio, the layers where you can cache, query vs object caching, TTLs, what not to cache, and sizing with the 80/20 rule.

Summary#

A cache is a small, fast store that keeps copies of data that is expensive to fetch or compute, so later requests are served quickly. Reading from memory takes about 100 ns and from Redis about 0.5-1 ms, while a database query often costs 5-50 ms. The key metric is the hit ratio: the share of requests the cache answers. You can cache at every layer: client, CDN, web server, application and database, and you can cache raw query results or assembled objects. A TTL (time to live) limits how stale an entry can get. Cache data that is read often and changes rarely; avoid caching data that must always be exact. Because access is usually skewed (the 80/20 rule), a cache holding 20% of the data often serves most requests.

Why It Exists#

Most systems read the same data again and again. Fetching it from the database each time wastes work, adds latency and makes the database the bottleneck. A cache turns a 20 ms query into a 1 ms lookup and can absorb 90-99% of reads. This page builds on Latency, Throughput and Performance.

How It Works#

What a cache is and why it works#

A cache sits between a client and a slower source of truth (a database, another service, a disk). On each read:

  1. Look up the key in the cache.
  2. Hit: return the cached value.
  3. Miss: fetch from the source, store a copy in the cache, return it.

Caches work because of locality: recently used and popular data is likely to be requested again, so the cache only needs the hot part.

Why caches work, in depth#

The latency ladder. Caching exists because storage technologies differ in speed by orders of magnitude, and the fast ones are small and expensive:

Where the data isTypical access timeRelative to RAM
CPU L1 cache~1 ns100x faster
Main memory (RAM)~100 ns1x
In-process cache lookup (hash map, plus deserialisation)0.1 to 10 µs1 to 100x slower
Redis or Memcached in the same data centre0.2 to 1 ms round trip~5,000x slower
Local NVMe SSD random read~100 µs~1,000x slower
Database query (indexed, warm)1 to 10 ms10,000x and up
Database query (joins, cold pages, contention)20 to 200 msa million times slower

A typical example: reading a user profile through the ORM, connection pool and query planner of a busy PostgreSQL database might take 30 to 50 ms at peak, while the same profile from Redis takes about 1 ms. That is a 30 to 50 times improvement on every read that hits. The underlying reason is that databases do much more work per read (parse, plan, lock, read pages that may be on disk, apply visibility rules), while a cache does a hash lookup in memory.

Two kinds of locality. Caches exploit patterns in how data is used:

  • Temporal locality: something used recently is likely to be used again soon. The profile you just viewed, the product on today's homepage, the session of a user who is clicking around.
  • Spatial locality: things near something used are likely to be used next. The next page of results, the other fields of the same row, the following video segment. CPUs and databases exploit this by fetching whole lines or pages. Application caches exploit it by caching whole objects, not single fields.

Real workloads also show popularity skew: a few items are far more popular than the rest. That is what lets a cache hold a small fraction of the data and still serve most requests (see the sizing section below).

A cache is a copy, never the truth. The database (or the upstream service) remains the source of truth. A cache entry is a copy that may be out of date and can disappear at any moment, through eviction, expiry, a restart or a failover. Two consequences follow. Every read path must work when the cache misses. And if the cache holds data that exists nowhere else, such as sessions stored only in Redis, it is no longer a cache but a database, and it needs the durability, replication and backup planning of one.

What you trade. A cache buys latency and offloads the backend, and you pay in three currencies:

  1. Freshness: cached data can be stale. Every cached data type needs a stated staleness budget.
  2. Memory: RAM costs far more per GB than disk, so you keep only what pays for itself.
  3. Complexity: a new system to run, plus invalidation logic, failure handling, and new kinds of bugs ("it works after I clear the cache").

The load-shield view. Beyond latency, a cache protects whatever is behind it. Suppose profile reads arrive at 500 per second at peak and each costs 30 ms of database time. That is 15 seconds of database work per second, so 15 cores busy. With a 95% hit ratio the database sees 25 reads per second, under one core. That is why teams often add a cache not because users complain about latency, but because database CPU sits at 80% during peaks and the same queries keep repeating. The flip side is that the database is now sized for the cached load, so the cache has become part of the system's capacity, and losing it is an incident (see Cache Failure Modes).

The cost of a hit is not zero. Serialisation and network add up. A 50 KB JSON blob takes measurable CPU time to encode and decode on every hit, and transfer time on the network. Compact formats (MessagePack, Protobuf), compression for large values, and caching only the fields a page needs keep hits cheap. A hit that takes 5 ms because the value is huge is still a hit, but much less useful.

Hit ratio#

Hit ratio = hits / (hits + misses). It determines how much the cache helps:

average latency = hit_ratio × cache_latency + (1 - hit_ratio) × (cache_latency + db_latency)
 
Example: cache 1 ms, database 20 ms
  hit ratio 50%: 0.5 × 1 + 0.5 × 21 = 11 ms, database sees 50% of reads
  hit ratio 90%: 0.9 × 1 + 0.1 × 21 = 3 ms,  database sees 10% of reads
  hit ratio 99%: 0.99 × 1 + 0.01 × 21 = 1.2 ms, database sees 1% of reads

Going from 90% to 99% cuts database load by 10x, so a sudden drop (a cache restart, a bad deploy) can overload the database. Hit ratio rises with cache size, longer TTLs and skewed access.

Hit ratio, in depth#

Request hit ratio versus byte hit ratio. Request hit ratio counts requests. Byte hit ratio counts bytes served from cache. They diverge when object sizes vary: a CDN might serve 95% of requests from cache (mostly small thumbnails) but only 70% of bytes (large videos miss more often). Use request hit ratio for latency and backend request load, and byte hit ratio for bandwidth and origin egress cost.

Why misses happen. Classifying misses tells you which knob to turn:

  • Cold (compulsory) misses: the first request for a key. These are unavoidable except by pre-warming. They dominate right after a deploy, a restart or a new cache node joining.
  • Capacity misses: the key was evicted because the cache is full. More memory, smaller values or a better eviction policy help.
  • Expiry misses: the TTL ran out, though the data may not have changed. Longer TTLs, or refresh-ahead, help.
  • Invalidation misses: the data changed and the entry was deleted. These are healthy, because they keep the cache correct, but a write-heavy key will always have them.

Measure them separately where you can. In Redis, INFO stats reports keyspace_hits, keyspace_misses, evicted_keys and expired_keys. A rising evicted_keys points to capacity misses.

Backend load is set by the miss ratio, not the hit ratio. Backend load = total QPS × (1 - hit ratio). For a service at 100,000 reads per second:

Hit ratioReads reaching the database
99%1,000 per second
95%5,000 per second
90%10,000 per second
0% (cache down)100,000 per second

Each step that looks small on a hit-ratio chart is a multiple on the database. Dashboards should show the miss rate in absolute requests per second next to the database's known capacity. Then a drift from 99% to 97% is seen for what it is: three times the database load.

Hit ratio and tail latency. Averages hide how misses shape percentiles. If 2% of requests miss and a miss costs 40 ms while a hit costs 1 ms, the average is about 1.8 ms, but the p99 is a miss: about 41 ms. To bring p99 near the hit latency, the miss ratio must drop below 1%, and misses must be made cheaper. Pages that make many cache lookups make this worse. A page that fetches 20 keys, each with a 2% miss rate, has a 1 - 0.98²⁰ chance, about 33%, of at least one miss. So a third of page loads pay database latency. Batching lookups (MGET) and caching assembled objects, rather than many fragments, both help.

Raising hit ratio, in rough order of effort.

  1. Cache the right thing: assembled objects reused across many pages rather than page-specific query results.
  2. Normalise keys: lower-case search terms, sort parameters and strip tracking parameters, so equivalent requests share an entry.
  3. Tune TTLs per data type to the real staleness budget (see TTL below).
  4. Add memory until the miss-ratio curve flattens.
  5. Improve the eviction policy, for example from LRU to an LFU-style policy that resists one-off scans (see Cache Eviction and Invalidation).
  6. Pre-warm after deploys and before known peaks.

Miss-ratio curves. A miss-ratio curve (MRC) plots miss ratio against cache size for a workload. It answers "what do I get for another 50 GB?" directly. Mattson, Gecsei, Slutz and Traiger (IBM Systems Journal, 1970) showed that for LRU, a single pass over an access trace computing each access's stack distance (how many distinct keys were touched since this key's previous access) yields the miss ratio for every cache size at once. Modern sampled versions (such as SHARDS, which hashes keys and analyses only a small sample) make this cheap enough to run on production traces. Tools like these let you size caches from data rather than guesswork.

Where to cache#

LayerWhat it cachesTypical latency savedExamples
ClientStatic assets, API responses, imagesWhole network round tripBrowser HTTP cache (Cache-Control), mobile app local storage
CDNStatic files, media, cacheable API responses near usersTens to hundreds of msCloudflare, Akamai, CloudFront, Fastly
Web server / reverse proxyFull pages or responsesApp and DB workNginx proxy cache, Varnish
ApplicationObjects, query results, computed valuesDB queries and computationIn-process caches (Caffeine, Guava), Redis, Memcached
DatabaseData pages, query plans, precomputed resultsDisk readsBuffer pool, materialized views

The closer to the user, the bigger the saving but the harder the invalidation (you cannot delete from millions of browsers), so changing data is cached in the application and static files at the edge with versioned names. See CDN.

An in-process cache (a map inside each server) is fastest but each server holds its own, possibly different, copy; a distributed cache (Redis, Memcached) is one shared copy one network hop away. Many systems use both. See Distributed Caching.

Each layer, in depth#

Client caches: browsers and apps. HTTP gives the server precise control through response headers:

HeaderMeaning
Cache-Control: max-age=600The client may reuse the response for 600 seconds without asking.
Cache-Control: s-maxage=3600Shared caches (CDNs, proxies) may keep it for an hour, overriding max-age for them.
Cache-Control: no-cacheStore it, but revalidate with the server before each reuse.
Cache-Control: no-storeDo not store at all. Use for sensitive data.
Cache-Control: privateOnly the user's own browser may store it, never a shared cache.
Cache-Control: immutableThe content will never change at this URL, so do not even revalidate.
ETag plus If-None-MatchRevalidation: the server replies 304 Not Modified with no body if unchanged.
stale-while-revalidate=60Serve the stale copy for up to 60 s while fetching a fresh one in the background.

Static assets with a content hash in the filename (app.3f9a2c.js) can use max-age=31536000, immutable. A new deploy produces a new name, so there is never a stale-asset problem. HTML pages that reference them get short TTLs or no-cache.

Mobile apps cache more aggressively, because networks are slow and intermittent. Offline-first apps keep the user's own data on the device and sync later. A fitness app, for example, records a run locally while the phone has no signal and uploads it when it reconnects. The backend's limitation is control. You cannot delete a value from a million phones, so client-cached data must be either safe to be stale or versioned so the app knows to refetch it.

"Client" also includes client libraries. A Redis Cluster client caches the map of which hash slots live on which node, so it sends commands straight to the right node. It refreshes the map only when a node replies MOVED. Database drivers cache prepared statements, and service-discovery clients cache endpoint lists. These small caches remove a network hop from every call.

CDN caches. A CDN keeps copies at edge locations close to users. Without one, a user in India fetching an image from an origin in Virginia waits roughly 250 to 300 ms per request. From a nearby edge it is more like 20 to 40 ms. Media delivery (images, video segments, downloads) is the classic and safest use. Modern CDNs (Cloudflare, Fastly, Akamai, CloudFront) also cache HTML and API responses, and run logic at the edge. Two rules for API responses at a CDN: only cache responses that are the same for every user (a public event search, a product page without prices tied to the user), and make sure the cache key includes everything that changes the response: path, the relevant query parameters, and headers listed in Vary. See CDN.

Web server and reverse proxy caches. Varnish, Nginx proxy_cache and similar caches store whole responses in front of application servers. Microcaching, caching dynamic pages for 1 to 5 seconds, is a powerful trick for traffic spikes. If a news homepage gets 5,000 requests per second, a 1-second cache turns that into one application render per second per proxy, with content at most a second old. See Proxies and Reverse Proxies.

In-process caches. Application servers have plenty of RAM, and a lookup in a local hash map costs microseconds with no network hop. Good candidates are small, hot and slow-changing: configuration values, feature flags, small reference datasets (country codes, currency rates), precomputed values, the handful of hottest keys, and local rate-limit counters. Libraries such as Caffeine (JVM), Guava, lru-cache (Node.js) and functools.lru_cache (Python) provide size limits and expiry. The limits come from each instance having its own copy. Two servers can disagree for up to the TTL, an update on one is invisible to the others, and memory is duplicated across every instance. Keep TTLs short, or broadcast invalidations (for example through Redis pub/sub). Treat in-process caching as a layer added after a shared cache, typically to shield hot keys.

Distributed (external) caches. Redis or Memcached on separate nodes, shared by all application servers, is the default answer when an interview calls for a cache. One shared copy means one place to invalidate, memory used once rather than per server, and built-in eviction (LRU, LFU) and per-key TTLs to keep memory bounded. The price is a network hop (sub-millisecond in the same zone) and another tier to operate. See Distributed Caching.

Caches inside databases and search engines. Databases already cache: PostgreSQL's shared_buffers (commonly about 25% of RAM, as a starting point) plus the OS page cache, MySQL InnoDB's buffer pool (often 50 to 75% of RAM on a dedicated server). Default settings target generic workloads, so tuning them for your access pattern is often the cheapest "cache" you can add. Materialized views precompute expensive aggregates inside the database. Search engines cache too. Elasticsearch has a shard-level query cache for filter results and a shard request cache for whole responses, which particularly helps aggregation-heavy queries that repeat.

Avoid local file caches on application servers. Caching on a server's local disk makes servers different from each other, complicates auto-scaling (new instances start cold) and breaks when instances are replaced. Prefer in-memory or shared caches, so any server can be cloned or killed freely.

Query vs object caching#

  • Query caching stores a query's result, keyed by query text and parameters. Easy to add, hard to invalidate: when one product changes, which cached queries include it? You usually rely on short TTLs.
  • Object caching stores assembled objects by ID (product:123 with price, images and rating). When the product changes, you delete one key, and many pages reuse the object.

Prefer object caching; keep query caching for expensive, read-mostly queries such as search results. MySQL removed its built-in query cache in 8.0 because invalidation caused contention.

Query vs object caching, in depth#

Four granularities. You can cache at several levels, each with a different hit ratio and invalidation story:

GranularityExample keyInvalidationReuse
Rowuser:42 row as storedEasy: one row changed, one keyHigh, but pages need many lookups
Query resultHash of SELECT ... WHERE category = 7 ORDER BY rank LIMIT 20Hard: any matching row change affects itLow to medium
Assembled objectproduct:123 with price, images, rating, seller nameMedium: delete when any part changesHigh, reused across pages
Rendered outputHTML fragment or full page for /product/123Medium to hardVery high for anonymous traffic

Query caching and key design. The key must capture every input that can change the result, or two different requests will share a wrong answer. For an event search, that means the keyword, the date range, filters, sort order, page, and the user's locale if results are localised, for example search:v1:q=taylor+swift:from=2025-01-01:to=2025-12-31:sort=date:page=1. Normalise inputs before building the key, by lower-casing, trimming and sorting filter lists. Otherwise "Taylor Swift" and "taylor swift " are separate entries and the hit ratio suffers. Hash long keys (search:v1: plus a SHA-1 of the normalised parameters) to keep them small.

Why query caches are hard to invalidate. When one row changes, which cached queries included it? With arbitrary queries, you cannot know cheaply. That is why the classic approach relies on short TTLs, and why MySQL removed its built-in query cache in 8.0: every write to a table invalidated all cached queries on that table, behind a global lock. Two techniques make invalidation targeted:

  • Cache tags (surrogate keys). Tag each cached result with the entities it contains (event:991, venue:12). When event 991 changes, purge everything tagged event:991. Fastly calls these surrogate keys. In Redis, you can keep a set per tag listing the keys to delete.
  • Version stamps. Include a version number for the underlying collection in the key (search:v1:catalog_ver=8812:...). Bumping catalog_ver on any change makes all old entries unreachable at once. They then age out by TTL. This is cheap and very reliable for read-heavy data that changes in batches.

Object caching and assembly. Assembling an object often takes several queries: product, prices, images, aggregate rating, seller. Caching the assembled object turns those into one lookup, and many pages share it. When any part changes, delete the object key, or update it. Objects can also be assembled asynchronously: workers consume change events and write a fresh object into the cache, so readers almost never miss. This is the cache acting as a precomputed read model. Good candidates include user sessions, activity streams, user graph data such as follower lists, and fully rendered pages for anonymous visitors.

Composite invalidation fan-out. The downside of rich objects is that one change can affect many. If a seller renames their shop, every cached product of that seller is stale. Options are to keep the seller name out of the product object and fetch the small seller object separately (two lookups with MGET, still cheap), to accept staleness up to the TTL for such fields, or to fan out deletes through an event. Split objects along lines of different change rates.

Negative caching. Caching "not found" results (user:999 = NULL for 60 seconds) stops repeated lookups for missing keys from reaching the database every time. That matters for bots probing random IDs. Give negative entries shorter TTLs than positive ones, and delete them when the object is created. See Cache Failure Modes for cache penetration.

TTL#

A TTL (time to live) is how long an entry stays valid; it caps staleness. Short TTLs mean fresher data but more misses; long TTLs mean higher hit ratios but staler data. Choose per data type (prices: seconds; descriptions: an hour; country lists: a day), and keep a TTL even when you invalidate on writes, as a safety net.

SET product:123 '{"name":"Desk lamp","price_cents":2999}' EX 3600   # Redis: 1-hour TTL
GET product:123

In HTTP, Cache-Control: max-age=60 tells browsers and CDNs how long to keep a response. See Cache Eviction and Invalidation.

TTL, in depth#

TTL is an expiry rule, not an eviction policy. Eviction (LRU, LFU) decides what to drop when memory is full. TTL decides when an entry is too old to trust, whatever the memory pressure. They work together: TTL bounds staleness, and eviction bounds memory. Sessions, tokens and API responses need TTLs because they must eventually refresh or disappear.

TTL and hit ratio for one key. Suppose a key is requested at a steady rate of r requests per second, and the entry lives for T seconds after each miss. Each miss is followed by about rT hits before it expires, so:

hit ratio for the key ≈ rT / (1 + rT)
 
hot key:   r = 10/s,   T = 60 s  → 600 / 601  ≈ 99.8%
warm key:  r = 0.1/s,  T = 60 s  → 6 / 7      ≈ 86%
cold key:  r = 0.01/s, T = 60 s  → 0.6 / 1.6  ≈ 37.5%

Two lessons follow. Popular keys reach very high hit ratios even with short TTLs, so short TTLs cost little where traffic is concentrated. And for the long tail, TTL length matters a great deal. Lengthening it from 60 seconds to 10 minutes takes the cold key above from 37.5% to 86%. Pick TTLs per data type from two inputs: how stale the data may be, and how often it is read.

Staleness budget. Ask the product question directly: "If this value changed, how long could users see the old one before it matters?"

DataTypical staleness budgetTTL approach
Product description, article bodyMinutes to hoursTTL of an hour, plus delete on edit
Price shown on a listingSeconds to minutesShort TTL, plus delete on change. Checkout reads the source of truth.
Follower count, like countMinutesTTL of minutes. Exact counts are rarely needed.
Feature flags, configSeconds to a minuteShort TTL in-process, or push updates
Session or auth tokenUntil logout or expiryTTL equal to the session length, and delete on logout
Country list, currency codesDaysLong TTL

Keep a TTL even when you invalidate on writes. Explicit deletes can fail. The delete call times out, a code path forgets to invalidate, or a race writes an old value back. A TTL caps how long such an error lives. Without it, a single missed invalidation can serve wrong data until the next restart.

Jitter. If you warm a cache with 1 million keys at once, all with a 600-second TTL, they all expire in the same second, and the database gets a burst of 1 million misses. Add random jitter, for example TTL = 600 s ± 10%, so expiries spread out. The same applies to entries created together by a batch job. See Cache Failure Modes.

Soft and hard TTLs. A two-level expiry gives the best of both freshness and availability. After the soft TTL, the entry is stale but still served, while one request refreshes it in the background. After the hard TTL, it must not be served at all. HTTP's stale-while-revalidate and stale-if-error directives express the same idea: keep serving the old copy while revalidating, or while the origin is failing. This is one of the most effective ways to keep a site up during a backend outage.

How Redis expires keys. Redis removes expired keys in two ways. Lazily, when a client touches a key and Redis notices it has expired. And actively, through a background cycle that runs about ten times a second, samples a small set of keys with TTLs (20 by default), deletes the expired ones, and repeats immediately if more than a quarter of the sample had expired. Expired keys that nobody touches can therefore linger for a while and use memory, which is why memory usage does not drop the instant TTLs pass. TTLs are set with EX/PX on SET, or EXPIRE. Note that overwriting a key with a plain SET clears its TTL unless you pass a new one, or KEEPTTL.

Layered TTLs. When content passes through several caches, their TTLs stack. A browser max-age of 60 s in front of a CDN s-maxage of 300 s means a user may see content up to 6 minutes old in the worst case. Set the outermost layer's TTL the shortest, or purge the CDN on change and use revalidation (ETag) at the browser, so the worst case stays within budget.

What to cache and what not to#

Cache itDo not cache it (or be careful)
Read often, changes rarely: product details, profiles, config, feature flagsMust be exact at use: balances during payment, stock at checkout (cache for display only)
Expensive to compute: rendered pages, aggregates, recommendationsWritten far more than read: every write invalidates, few hits
Hot items: trending posts, popular searches, celebrity profilesUnique, rarely repeated requests (long-tail searches) that only fill memory
Sessions and short-lived tokens (Redis often is the primary store)Private per-user responses in shared or CDN caches (use Cache-Control: private)

Deciding what to cache, in depth#

A quick scoring test. For each candidate data type, ask five questions:

  1. Read-to-write ratio. How many reads per write? Below about 10 reads per write, invalidations eat most of the benefit.
  2. Cost to produce. How expensive is a miss: a 2 ms indexed read, or a 200 ms multi-table join?
  3. Staleness tolerance. Can a user see a value seconds or minutes old without harm?
  4. Size. Is the value small enough to store and transfer cheaply, roughly under 100 KB, ideally a few KB?
  5. Repetition. Do many requests ask for the same key, or is every request unique?

Signals that justify a cache. Bring caching in only after naming the problem it solves, with rough numbers:

  • Read-heavy load: 10 million daily users making 20 requests each is 200 million reads a day, about 2,300 per second on average and several times that at peak, all hitting the same database. At 20 to 50 ms per query, a cache that answers in under 2 ms takes most of that work away.
  • Expensive computation: a personalised feed that joins posts, follows and likes takes 200 ms to build. Caching it for 60 seconds serves repeat views in about 1 ms.
  • High database CPU: the database sits at 80% CPU at peak, mostly running the same read queries. Caching the hot ones cuts that load by most of its share.
  • A latency target: the API must answer in under 10 ms, but the queries take 30 to 50 ms. Only memory gets you there.

When a cache is the wrong fix. Some read problems are really modelling problems. An ad-click analytics system that stores raw click events and answers advertiser queries with GROUP BY over millions of rows will not be rescued by caching query results, because every advertiser and time range is a different query, and new clicks arrive constantly. The fix is to pre-aggregate (counts per ad per minute, computed by a stream processor) and query the small aggregated table. Similarly, a slow query caused by a missing index should get the index, not a cache in front of it. See Database Performance.

Data that must be exact. Account balances during a payment, stock during checkout, and permission checks after a revocation should read the source of truth, or a cache kept strictly in sync. It is fine to cache them for display: a product page can show "3 left" from a cache that is 30 seconds old, as long as the purchase path checks the database.

Security and privacy. Caches are easy to forget in a security review:

  • Never let a shared cache key omit the user or tenant for personalised data. A key such as profile:me serves one user's data to another. Use tenant:{id}:user:{id}:... prefixes.
  • Mark personalised HTTP responses private or no-store so CDNs do not cache them.
  • Sensitive data in caches needs the same protection as in databases: encryption in transit (TLS to Redis), authentication, and deletion when the user asks for their data to be erased.

Cache sizing (80/20)#

Access patterns are usually skewed: a small share of keys gets most requests. A common rule of thumb is that about 20% of the data serves 80% of the reads. So you size the cache for the hot set, not the whole dataset.

Worked example: 100 million products at 2 KB = 200 GB. The hottest 20% is 40 GB; with ~1.5x Redis overhead, about 60 GB, a few cache nodes. Measure the real hit ratio: the curve flattens, so beyond a point more memory adds little.

Cache sizing, in depth#

Where 80/20 comes from. Popularity in many real systems is roughly Zipf-like: the item ranked k receives traffic proportional to 1/k^α, with α typically somewhere around 0.6 to 1.0 for web objects. Breslau, Cao, Fan, Phillips and Shenker's Web Caching and Zipf-like Distributions (INFOCOM 1999) measured web proxy traces and found exactly this shape. With α = 1, the share of requests going to the top C of N items is about H(C)/H(N), where H is the harmonic number, roughly ln(C)/ln(N) for large values:

N = 100 million items, Zipf α = 1
cache top 1 million (1%):   ln(1e6) / ln(1e8) ≈ 13.8 / 18.4 ≈ 75% of requests
cache top 10 million (10%): ln(1e7) / ln(1e8) ≈ 16.1 / 18.4 ≈ 87.5% of requests
cache top 20 million (20%): ln(2e7) / ln(1e8) ≈ 16.8 / 18.4 ≈ 91% of requests

So "20% of the data serves 80% of requests" is a reasonable rule of thumb for strongly skewed workloads. It also shows diminishing returns: going from 10% to 20% of items adds only about 4 points. With a lower α, less skew, a cache needs a larger share of items for the same hit ratio. Measure your own distribution by counting requests per key over a day and plotting cumulative share against key rank.

Memory per entry is more than the value. Redis stores each key with overhead for the key object, the hash-table slot, the value's encoding and the expiry entry. Plan on roughly 50 to 100 bytes per key on top of key and value sizes for small entries. Memory fragmentation adds 10 to 30% more, visible as mem_fragmentation_ratio in INFO memory. For 50 million small entries, the overhead alone can be several GB, so many small keys can be packed into Redis hashes to save memory.

A sizing worked example.

  • Catalogue: 100 million products, average assembled object 2 KB, so 200 GB in total.
  • Goal: 90% hit ratio. From the access logs, the hottest 20 million products (20%) receive about 90% of requests.
  • Data: 20 million × 2 KB = 40 GB. Keys and overhead: 20 million × (40-byte key + 80 bytes) ≈ 2.4 GB. With 20% fragmentation: about 51 GB.
  • Headroom: keep maxmemory at about 75% of node RAM for fork-based persistence, replication buffers and spikes. So about 68 GB of RAM in total.
  • Layout: three primaries with 32 GB of RAM each, plus one replica per primary for failover, is six nodes of 32 GB.

Checking throughput as well as memory. Memory is rarely the only constraint. If peak traffic is 300,000 cache reads per second, at about 100,000 simple operations per second per Redis primary (a conservative planning figure for one core), you need at least three primaries for throughput. Here that matches the memory answer. When the two numbers disagree, take the larger. Also check network bandwidth: 300,000 reads × 2 KB is 600 MB/s, about 4.8 Gbps, split across the nodes, which is fine on 10 to 25 Gbps instances, but large values can make the network the bottleneck first.

Is the memory worth it? Compare the cost of RAM with the cost of the database work it saves. If each miss costs 20 ms of database CPU, then at 100,000 requests per second, the difference between a 90% and a 95% hit ratio is 5,000 misses per second, or 100 CPU-seconds per second: about 100 database cores. Even a few hundred GB of extra cache RAM is usually much cheaper than that. At the other extreme, caching the long tail of items read once a week rarely pays for its memory. See the deep dive for the classic "five-minute rule".

Worked example: caching a product page end to end#

An e-commerce product page gets 20,000 views per second at peak across 50 million products. Here is how the layers combine, and what each one stores.

What each layer holds.

  • Browser: versioned static assets for a year (immutable). The page shell is revalidated cheaply with ETag.
  • CDN: the anonymous HTML shell and the product description, identical for all users, with s-maxage=60 and a purge on edit. At 20,000 views per second, a 60-second TTL at, say, 200 edge locations means at most a few hundred origin fetches per minute for a popular product, rather than 1.2 million.
  • In-process: pricing rules, feature flags and currency rates, a few MB, refreshed every 30 seconds.
  • Redis: the assembled product object (product:123:v3, 2 KB, TTL one hour plus delete on edit), and stock (stock:123, TTL 15 seconds, display only).
  • Database: the source of truth. Checkout reads stock here inside a transaction, never from the cache.

Personalised parts stay out of shared caches. The price may depend on the user's region or membership, and the stock call is per request, so these come from a separate API call marked private. The page is split into a cacheable shell and small personalised fragments. This split is what makes CDN caching of dynamic pages possible.

Resulting load. With a 98% Redis hit ratio on product objects, the database sees about 400 product reads per second at peak instead of 20,000. Stock, with a 15-second TTL, causes roughly one database read per product per 15 seconds while that product is popular, so the hottest products cost almost nothing. The rest of the traffic never leaves the CDN.

Cache keys and versioning#

Naming conventions. Use a predictable, hierarchical pattern: {service}:{entity}:{id}:{variant}:{version}, for example catalog:product:123:en-GB:v3. Colons are the usual separator in Redis, and tools group keys by prefix. A consistent scheme makes it possible to measure hit ratios per prefix, to find what fills memory, and to delete a family of keys safely.

Version the value format. When code changes the shape of a cached object (a field added, a type changed), old entries written by the previous deploy may break new readers, or vice versa during a rolling deploy. Putting a format version in the key (:v3 to :v4) makes the new code read and write only new-format entries. Old entries are ignored and expire by TTL. The cost is a burst of misses at deploy time. For very hot data, warm v4 before switching, or roll out a reader that understands both formats first.

Tenant and user scoping. Any key for personalised or tenant-specific data must include the tenant and user identifiers. This prevents cross-tenant leaks, and also makes it possible to delete all of a tenant's or user's cached data when required (for example on account deletion), by tracking their keys or using a per-tenant version stamp.

Keep keys short, and values bounded. Keys are stored in memory for every entry, so a 200-byte key on 50 million entries costs 10 GB. Hash long natural keys (search parameters, URLs) into fixed-length digests. Cap value sizes, because very large values (megabytes) block a single-threaded Redis while they are being written to the network, and hurt every other client. Split them, compress them, or store them in object storage with a cached pointer.

Do not iterate keys in production with KEYS. KEYS pattern scans the whole keyspace in one blocking call. Use SCAN with a cursor, or better, maintain explicit index sets (a tag set per entity, as described above) so deletes never need a scan.

Operating a cache#

Metrics that matter.

  • Hit ratio per key prefix, not just overall. A global 95% can hide one data type at 40% that is hammering the database.
  • Misses per second in absolute terms, plotted against the database's tested capacity.
  • Latency percentiles for cache calls as seen by the client (p50, p99). Rising p99 often means big values, a hot node, or network saturation.
  • Memory used versus maxmemory, evictions per second and fragmentation. Steady evictions with a falling hit ratio means the cache is too small for the working set.
  • Connections and command rate per node. Imbalance between nodes points to hot keys or a bad hash distribution.

Finding hot and big keys. Redis can report frequently accessed keys (redis-cli --hotkeys, which requires an LFU eviction policy) and the largest keys per type (redis-cli --bigkeys, --memkeys). Client-side sampling, logging one in 10,000 key accesses, is a safer way to get the same information on busy production clusters.

Warming. After a deploy that changes key versions, a cache cluster replacement, or a failover to a cold region, the hit ratio starts near zero. Options: pre-load the top N keys from a list of yesterday's hottest keys, replay a sample of recent read traffic against the new cache, or ramp traffic onto the cold cache gradually. Whatever you choose, know how long warm-up takes and what the database load is during it.

Test the cache-off scenario. Periodically confirm what happens if the cache is unavailable or empty: in staging at production load, or by disabling a fraction of cache reads in production behind a flag. If the answer is "the database falls over", you need protection (rate limiting misses, serving stale data, circuit breakers) before a real outage proves it. See Cache Failure Modes.

Capacity reviews. Hot sets grow with the product. Review memory, throughput and hit ratio monthly, and plan node additions before evictions start eroding the hit ratio, since resizing a distributed cache moves keys and briefly lowers it.

Caching computation and remote calls#

Caches are not only for database rows. Anything expensive and repeatable is a candidate.

Memoisation. A pure function (same inputs, same output, no side effects) can cache its results keyed by its arguments. Rendering a Markdown document, resizing an image to a standard size, computing a route between two fixed points, and compiling a template are classic examples. Because the output depends only on the input, the cache never needs invalidation. A content hash of the input makes a perfect key: render:sha256(markdown_source). Change the input and the key changes with it.

Third-party API responses. External APIs are slow (often 100 ms or more), rate-limited and sometimes billed per call. Caching their responses, such as geocoding results, currency rates, or a payment provider's list of supported banks, cuts latency, cost and the risk of hitting quotas. Check the provider's terms first. Some forbid caching or require short retention, and some return Cache-Control headers you should respect. For data where staleness is harmless, cached responses also keep features working when the provider is down, which is a resilience win as much as a speed win.

Expensive aggregates and rankings. Leaderboards, trending lists and dashboards are computed from large amounts of data but read far more often than they change. Compute them periodically (every 10 to 60 seconds) with a background job, and write the result into the cache under a fixed key. Readers never compute on a miss, because the key is always present. This "precompute and publish" shape avoids stampedes entirely for the most popular data, since no reader ever triggers the expensive computation.

Model inference results. Machine-learning predictions and generated content can be cached when the same input recurs: recommendations for a user for the next few minutes, a classification of the same image, or a large language model's answer to an identical prompt with identical settings. Exact-match caching of inference is safe and can save significant GPU cost. Matching similar prompts (semantic caching, using embeddings) trades correctness for hit ratio and needs careful evaluation. See Designing LLM and AI-Powered Systems.

The cache as a dependency. Once a cache is on the request path, its availability affects yours. If every request fails when Redis is unreachable, and Redis is available 99.9% of the time, the service can be no better than 99.9%. Design reads to degrade, not fail:

  • Use short client timeouts on cache calls (for example 20 to 50 ms), so a slow cache does not add seconds to every request.
  • On cache errors, fall back to the source of truth within limits, through a rate limiter or circuit breaker, so the database is not overwhelmed.
  • For non-critical data, return a default or an older in-process copy rather than an error.

With these rules, a cache outage becomes a latency and load event that the system rides out, rather than a full outage.

Common misconceptions#

  • "A cache makes the system faster, full stop." It makes hits faster. Misses get slightly slower (the extra cache round trip), and if the hit ratio is low, the average can get worse. A cache with a 30% hit ratio on cheap queries can slow a system down while adding operational cost.
  • "Redis is fast, so it can't be the bottleneck." A single Redis instance executes commands on one main thread. A hot key, a multi-megabyte value, or an O(N) command such as KEYS, SMEMBERS on a huge set, or HGETALL on a very large hash can stall every client of that node. Throughput per node is high but finite.
  • "Invalidate on write, and the cache is consistent." Concurrent readers and writers can still interleave so that an old value is written back after the delete. Cache-aside has well-known races. See Cache Eviction and Invalidation for the patterns that close them.
  • "More cache memory always helps." Past the knee of the miss-ratio curve, extra memory adds almost nothing. Measure the curve before buying.
  • "The database has a cache, so I don't need one." The buffer pool avoids disk reads, but not query parsing, planning, locking and connection costs, and it does not reduce the number of queries. An application cache removes the query entirely.

When to Use It#

  • Read-heavy workloads where the same data is requested repeatedly.
  • Expensive queries or computations whose results can be slightly stale.
  • Protecting a database or downstream service from read load.
  • Serving static and media content to users far from your servers (CDN).

When NOT to Use It#

  • When the database is already fast enough; a cache adds a system and stale data.
  • For write-heavy data with few repeated reads.
  • As a fix for missing indexes or bad queries.

How to Implement It#

  1. Measure first: find the hottest, most expensive reads.
  2. Pick the layer: CDN for static and public content, Redis for shared application data, in-process for tiny hot config.
  3. Design keys: entity:id with a version prefix (v2:product:123) so formats can change.
  4. Set TTLs per data type, and invalidate on writes for data where staleness hurts.
  5. Choose a strategy (usually cache-aside). See Caching Strategies.
  6. Monitor hit ratio, latency, memory, evictions; alert on sudden hit-ratio drops.
  7. Plan for cache failure: the database must survive a cold cache (warming, rate limits).
TechnologyFits when
RedisShared cache with rich data types, TTLs, persistence options
MemcachedSimple, multi-threaded key-value cache
Caffeine, Guava (JVM), in-process LRUUltra-fast per-instance caching
CDN (Cloudflare, CloudFront, Fastly)Static and edge-cacheable content
Varnish, Nginx proxy cacheFull-response caching in front of web servers

Trade-offs#

ChoiceGainCost
Adding a cacheLower latency, much less DB loadStale data, another system to run, invalidation logic
Longer TTLHigher hit ratioStaler data
In-process cacheFastestInconsistent copies per server, duplicate memory
Distributed cacheShared, consistent copyNetwork hop, operations
Edge (CDN/browser)Biggest latency winHardest to invalidate
Query-result cachingEasy to add for expensive queriesHard to invalidate, low reuse
Object cachingHigh reuse, targeted invalidationAssembly code and fan-out on shared fields
Soft TTL with background refreshFresh data without miss spikes, survives origin errorsServes slightly stale data by design

Common Pitfalls#

  • Caching without TTLs, leaving wrong data forever after a missed invalidation.
  • Caching per-user private data in a shared or public cache.
  • Ignoring the "cold cache" case: after a restart, the database receives all traffic at once.
  • Caching everything, so memory fills with long-tail data and hit ratio stays low.
  • Building cache keys that omit a parameter (locale, filter, tenant), so different requests share a wrong answer.
  • Expiring a large batch of keys at the same moment, with no TTL jitter.
  • Watching only the hit ratio percentage instead of absolute misses per second against database capacity.
  • Using caches as a fix for missing indexes or for analytics queries that should be pre-aggregated.

Real-World Examples#

Meta's "Scaling Memcache at Facebook" paper (NSDI 2013) describes a memcached tier serving billions of requests per second in front of MySQL, with the cache absorbing most reads.

Browsers and CDNs implement HTTP caching standards such as Cache-Control, ETag and max-age, which is why static assets with versioned filenames can be cached for a year.

Breslau and colleagues' INFOCOM 1999 study of web proxy traces showed Zipf-like popularity, which explains why modest caches achieve high hit ratios. Gray and Putzolu's five-minute rule (SIGMOD 1987) remains the standard way to reason about whether data is worth keeping in memory.

In the Interview#

Handling caching in an interview#

Establish the need first. Do not draw a cache on reflex. Point to the bottleneck with a number: "Profile reads peak at 500 per second, each about 30 ms on the primary. That's the hottest path, and the data changes rarely, so it's a good cache candidate." Interviewers want to see that the cache answers a specific problem.

Then walk through five decisions, briefly.

  1. What to cache, and the key. "User profiles, keyed user:{id}:profile:v1, and the trending feed, keyed trending:global, rebuilt every minute."
  2. Where. "Redis as the shared cache. A CDN for images. A small in-process cache only if one key gets very hot."
  3. Pattern. "Cache-aside on reads, and delete the key on profile updates." See Caching Strategies for the alternatives.
  4. Eviction and TTL. "LRU with maxmemory, and a 10-minute TTL as a safety net."
  5. Downsides. Choose the one or two that matter for this system: staleness after writes, what happens when Redis is down (the database must not be flattened, so add circuit breakers and fallbacks), or stampedes on hot keys (request coalescing or early refresh).

Use numbers. "With a 95% hit ratio, the database sees 25 profile reads per second instead of 500, and p50 latency drops from 30 ms to about 1 ms." A single sentence like this shows you understand what the cache buys.

Know when to say no. "This analytics query differs for every advertiser and time range, so caching it won't help. I'll pre-aggregate instead." Or: "Stock at checkout must be exact, so the purchase path reads the database. The product page can show cached stock." Saying where a cache does not belong is as strong a signal as adding one where it does.

For senior and staff levels, skip the basics the interviewer already assumes and go to the non-obvious: the database's capacity if the hit ratio falls to zero, cold-start after a regional failover, hot keys that one Redis node cannot serve, and invalidation races between concurrent writers.

Deep Dive: Cache hierarchies in hardware and softwareShow

CPUs have L1-L3 caches in front of RAM, operating systems keep a page cache, databases keep a buffer pool: each level is smaller and faster than the next and relies on locality.

Working set. When the actively used data outgrows the cache, hit ratio drops sharply (a "cliff"), so performance can degrade suddenly as data grows.

Zipf distributions. Web popularity is often Zipf-like (the k-th item gets about 1/k of the top item's traffic), so even small caches achieve useful hit ratios.

Deep Dive: Modelling cache hit ratios and the economics of cachingShow

Che's approximation for LRU. Under the independent reference model, each item i is requested as a Poisson process with rate λᵢ, independently of the others. Che, Tung and Wang (IEEE JSAC, 2002) observed that an LRU cache of capacity C behaves almost exactly like a cache that keeps each item for a fixed characteristic time T after its last request. T is the solution of:

sum over all items i of (1 - exp(-λᵢ · T)) = C
hit ratio of item i ≈ 1 - exp(-λᵢ · T)
overall hit ratio = sum of λᵢ · (1 - exp(-λᵢ · T)) / sum of λᵢ

Intuitively, T is "how long a key survives in the cache without being touched". Hot items (λᵢT much greater than 1) are almost always hits, and cold items (λᵢT much less than 1) are almost always misses. The approximation is remarkably accurate for realistic catalogue sizes, and it lets you predict hit ratios for a planned size from per-key request rates, without running a simulation. It also shows that TTL caches and LRU caches are close cousins: a TTL cache with TTL = T and no capacity limit has about the same per-item hit ratios as an LRU cache with characteristic time T. That is why per-key estimates like rT/(1 + rT) work well in practice.

What the model misses. Real traffic is not independent. Popularity changes over time (news, launches, viral posts), requests come in bursts, and scans (a crawler, a batch job) touch many keys once. LRU handles slow popularity changes well but is easily polluted by scans. Admission policies such as TinyLFU (which only admits a new key if it is estimated to be more popular than the eviction victim) recover most of the lost hit ratio. Measure the hit ratio on real traces before trusting any model.

The five-minute rule. Jim Gray and Franco Putzolu (SIGMOD 1987) asked when it is cheaper to keep a page in memory than to re-read it from disk each time. The break-even interval between accesses is:

break-even interval = (price per disk access per second / price per byte of RAM) / page size

With 1987 prices, the answer for 1 KB pages was about five minutes: data accessed more often than every five minutes should stay in RAM. The same reasoning applies to any cache tier. Compare the cost of the RAM holding an entry with the cost of the work a miss causes (database CPU, IOPS, cross-region egress, or a paid API call), multiplied by how often the entry would be requested. The answer shifts as prices change. Gray and others revisited the rule in later decades and found it moved with hardware, and with flash as a middle tier. But the method stays the same: keep an item in the cache if its access rate times its miss cost exceeds its memory cost.

Hierarchies and filtering. In a multi-level hierarchy (browser, then CDN edge, then CDN shield, then application cache, then database buffer pool), each level filters the stream that the next one sees. The lower levels get the misses of the upper ones, which are less skewed, because the hottest items were absorbed above. That is why a deep cache often has a lower hit ratio than you would expect from its size. It sees a flatter popularity distribution. When sizing a lower tier, model it on the miss stream of the tier above, not on the original request stream.

Key Takeaways#

  • A cache stores copies of expensive data in a faster place; hits avoid slow work.
  • Hit ratio is the key number: moving from 90% to 99% cuts backend load by 10x.
  • Cache at every layer, from client and CDN to application and database; closer to users is faster but harder to invalidate.
  • Prefer object caching by ID over query caching; always set TTLs.
  • Cache read-heavy, slowly changing data, avoid exact-at-read data, and size for the hot set (80/20).
  • Backend load equals total QPS times the miss ratio. A move from 99% to 97% hit ratio triples database load.
  • For a key read at rate r with TTL T, the hit ratio is about rT/(1 + rT). Hot keys tolerate short TTLs, the long tail does not.
  • Keep a TTL even with explicit invalidation, add jitter, and consider soft TTLs with background refresh.
  • Size for the hot set with Zipf in mind, then add per-key overhead, fragmentation and headroom, and check throughput and network too.