← Building blocks

Cache the hot reads

Latency & performancefundamental

The same data is read far more often than it changes and every read hits the database.

Say it like this

Reads are 100× writes, so I put Redis in front of the database as a cache-aside layer with a TTL, and the database only sees misses.

Basic solution

Put a cache in front of the store. Read the cache first; on a miss, read the DB and write the result back with a TTL (cache-aside).

RedisMemcachedin-process LRUDynamoDB DAX

Cache-aside read and write

Reads try the cache first and populate it on a miss. Writes go to the database and then delete the cached key so the next read reloads it.

How it works

  1. The service receives a read for key K (an alias, a user id) and first asks the cache for it: GET K. No other work happens yet.
  2. If the cache returns a value (a hit), the service sends it straight back to the caller. The database is not touched at all.
  3. If the cache returns nothing (a miss), the service runs the normal database query, takes the row it gets back, and writes that row into the cache with an expiry: SET K value EX 300 means "keep this for 300 seconds". Then it returns the row to the caller, so the first reader pays for both the database read and the cache write.
  4. When the service changes a row, it writes the new values to the database first, then deletes K from the cache. The next read for K misses, loads the fresh row from the database and repopulates the cache, so stale data can only survive for the few milliseconds between the database commit and the delete.
  5. Entries leave the cache in two ways: their TTL runs out, or memory fills and the eviction policy (usually LRU, which drops whatever was read least recently) removes them to make room.

Why the application, not the cache, does the loading

  • The cache stays a dumb key-value store that knows nothing about your tables or queries, so you can change the schema without touching it.
  • Only keys that someone actually reads ever get cached, so memory is spent on the data people use (the working set) rather than on everything in the database.

Worked example

URL shortener redirects

  • 4,000 redirects/s on average and 40K at peak. Each redirect needs one lookup: alias to long URL.
  • 20% of links take 80% of the traffic. Because the cache only fills with keys that are read, it naturally ends up holding that hot 20% without you choosing which links to cache.
  • Hit rate after warm-up is about 95%, so at peak only 5% of lookups reach the database: 40K x 5% = 2K reads/s, which a single read replica handles comfortably.
  • Memory for the hot set is about 0.2 x 100M links x 500 B = 10 GB. That fits one Redis node, or two with the second as a standby for failover.
  • Latency: a Redis GET takes about 0.3 ms within a region, a database point read 2 to 5 ms. With 95% of reads never reaching the database, the redirect p99 drops to roughly the cache latency.

Variants and when each wins

Cache-aside (lazy loading)

  • The application loads a key into the cache the first time it is read and missed. It is the simplest option and only caches what is actually used, but the first read of every key pays the database cost and a write leaves a short window where the cache is stale.

Write-through

  • Every write updates the cache and the database in the same request, so the cache never holds an old value. It wins when reads right after writes must hit, and it costs extra write latency plus cache memory spent on keys nobody reads.

Write-behind (write-back)

  • Writes go only to the cache, and a background flusher pushes them to the database later in batches. It gives the fastest writes and suits counters that change thousands of times a second, but a cache crash loses whatever has not been flushed yet.

Refresh-ahead

  • A background job refreshes hot keys shortly before their TTL expires so readers never miss. It wins for a small set of very hot keys with predictable access, and is wasted effort on a long tail of rarely read keys.

Pick cache-aside by default; mention write-through when reads right after writes must hit, and write-behind for high-volume counters you can afford to lose.

Failure modes

Stale data after a write

  • You notice a user edits a record and still sees the old value on the next page load. It happens because the cache entry was never deleted after the write, or because a slow read loaded the old row just before the write and set it into the cache just after the delete. Fix it by always deleting the key after the database commit, keeping TTLs short so a missed delete self-heals, and sending reads that follow a write to the primary database for a few seconds.

Cache stampede

  • You notice the database load spikes every few minutes, exactly when a popular key expires. It happens because every request that misses at the same instant runs the same database query. Fix it by letting one request do the refresh while the others wait for it or get the old value (single-flight or stale-while-revalidate), and by adding jitter to TTLs so keys do not expire together.

Cold cache after restart or deploy

  • You notice latency and database load jump for a few minutes after a cache restart. It happens because the cache is empty, so every read misses until the hot keys have been loaded once. Fix it by warming the hottest keys from a list before taking traffic, restarting cache nodes one at a time, and keeping a replica so a restart does not empty the only copy.

Cache node loss

  • You notice the database is suddenly taking every read. It happens because the only cache node died and there is no copy of its data. Fix it with leader-follower replication and automatic failover to the follower, or, if you accept the risk, size the database to survive a full miss storm.

Hot key

  • You notice one cache node is saturated while the rest are idle. It happens because a single very popular key (a celebrity profile, a viral link) lives on that node and every read for it goes there. Fix it with a small in-process cache in each app server for the hottest keys, or by storing the key under several suffixed names spread across nodes and reading a random copy.

Interviewer follow-ups

Answer out loud before you open each one.

Why delete the cache entry on write instead of updating it?

Updating writes a value that may never be read again and races with concurrent writers, so two updates can leave the cache holding the older value. A delete is idempotent, cheap, and guarantees the next read loads the current database row.

What TTL would you pick, and why?

Long enough that most reads hit (minutes for redirects), short enough that a missed invalidation self-heals quickly. Start around 5 minutes, add 10–20% jitter so keys do not expire together, and tune from the hit-rate metric.

How do you measure whether the cache is working?

Hit ratio, p99 latency on hit vs miss, eviction rate, and memory used vs the working set. A falling hit ratio with rising evictions means the cache is too small; a low hit ratio with no evictions means the access pattern is not cacheable.

What happens to the database if the cache goes down entirely?

It takes 100% of reads. Either size it to survive that (replicas, read capacity) or fail some traffic deliberately with load shedding. Say which one you chose and why.

Connections

In study paths
Scaling reads
Built on
Hash table · LRU cache: hash map + doubly linked list · Bloom filter
Pairs with
Invalidate the cache when data changes · Protect against a cache stampede · Spread reads across replicas · Spread a hot key
Pulls against
Accept a short delay for scale
Used in
URL Shortener (TinyURL / bit.ly) · News Feed (Twitter / X timeline) · Distributed Key-Value Cache (Redis / Memcached-like)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingServiceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon ElastiCacheRedisMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon AuroraDatabaseAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB