Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 42 ยท Caching and Application Patterns

Caching Patterns

Learn Redis caching patterns: cache-aside, read-through, write-through and write-behind, how to choose TTLs, and how to design versioned cache keys.

Caching is the most common job for Redis. The idea is simple: keep a copy of an expensive result (a database query, a rendered page, an API response) in fast memory, and serve repeat requests from that copy. A well-placed cache can cut response times from tens of milliseconds to under one, and take most of the read load off your main database.

The difficulty is not storing the copy. It is keeping the copy honest: deciding when it is created, when it is updated, and when it is thrown away. The patterns in this lesson are the standard answers to those questions. They differ in who is responsible for filling the cache, and in what happens to writes.

Real Redis commands appear in read-only blocks. The runnable examples are JavaScript models with a fake clock and a fake database that counts its queries, so you can see exactly how much work each pattern saves and what each can get wrong.

The cache-aside pattern

Cache-aside (also called lazy loading) is the default choice. The application owns the logic and talks to both the cache and the database:

  1. Look in the cache. If the value is there (a hit), return it.
  2. If it is not (a miss), read the database.
  3. Store the result in the cache with a TTL (time to live), then return it.
TEXT
GET product:1001:v1          # miss: (nil)
# ... application reads the database ...
SET product:1001:v1 "{...}" EX 300
GET product:1001:v1          # hit

Only data that is actually requested ever enters the cache, and if Redis goes down the application still works, only slower. The costs: the first request for each item is slow, and the cache can briefly serve data that changed in the database.

Cache-aside in three steps

Check cache A hit returns immediately.
Read database Only on a miss.
Fill cache Store with a TTL, then answer.

The application owns the logic.

1 / 2
JS Cache-aside with a fake database and a fake clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Six requests cost only three database reads. One miss was the cold start, one was the expired TTL, and one followed the update. The update did two things in order: it wrote the database first and then deleted the cache entry. Deleting is safer than updating the cached copy, because a deleted entry is rebuilt from the database on the next read and cannot disagree with it.

There is still a narrow race: a reader can fetch the old row, a writer can update and delete the key, and the reader can then store the old row. The stale entry lives until its TTL ends, which is why TTLs are a safety net even when you invalidate. More on this in Cache Invalidation and Stampedes.

Read-through

Read-through is cache-aside with the logic moved out of your application. You ask the cache layer for a key, and it loads from the database on a miss using a loader you configured. Redis itself does not do this: it is a feature of a caching library, a data grid or a proxy in front of Redis. The application code becomes shorter (cache.get(id) always returns a value), and the loading logic lives in one place. In practice you can get the same effect by wrapping the cache-aside steps in one function, as getProduct did above.

Write-through

With write-through, every write goes to the cache and the database in the same operation, so the cache is always warm and consistent with the database for written keys. Reads of recently written data are hits. The cost is slower writes (two destinations) and a cache full of data nobody reads again, so pair it with a TTL.

Write-behind (write-back)

With write-behind, the application writes only to the cache. A background process copies the changes to the database later, in batches. Writes are very fast and the database sees fewer, larger operations. The cost is durability: if the cache loses data before the flush, those writes are gone. Use it only for data you can afford to lose or rebuild, such as view counters, and flush often.

The model below applies one update to each strategy and then simulates a crash before the flush.

JS Write-through vs write-behind vs invalidate

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trade-off shows plainly. Write-through and invalidate-on-write need five database writes. Write-behind needs one, but until the flush the database is behind the cache, and a crash in between loses writes. No pattern is free; you choose which cost you can live with.

Choosing TTLs

A TTL is a promise about how stale the data may be. Pick it from the business answer, not from habit:

  • How wrong can it be, and for how long? A product description can be an hour old. An account balance probably cannot be minutes old.
  • How expensive is a miss? Costly computations deserve longer TTLs.
  • Add jitter. If thousands of keys are created together with EX 3600, they all expire together and the database takes the whole load at once. Spread them, for example 3600 + random(0, 300).
  • Always set one. A key with no TTL is a promise to remember it forever, and a cache that only grows eventually hits its memory limit (see Memory Limits and Eviction).
  • Use SET key value EX seconds in one command, rather than SET followed by EXPIRE, so a crash between them cannot leave a key without a TTL.

Key design and versioning

A cache key must identify everything the value depends on. A key like product:1001 is wrong if the result also depends on the language or currency, because two users would share one entry: use product:1001:en:usd. Include every input that changes the output, and nothing else.

Version prefixes solve a different problem: changing the format of cached values. When the code that builds the value changes, bump the version in the key (v1 to v2) and old entries are never read again. They expire naturally.

A namespace version goes one step further and lets you invalidate a whole group at once without scanning for keys: store a counter such as catalog:version, include its value in every key of the group, and INCR it to retire them all.

JS Invalidate a whole group with a namespace version

Press Run (or Ctrl + Enter) to see the console output here.

No output.

One INCR retired every entry in the group in constant time. The old keys stay in memory until their TTL removes them, which is why you should still give every cached value a TTL. The trade-off is one extra GET per read to fetch the current version, which you can pipeline or cache briefly in the application (see Pipelining and Pub/Sub).

Why cache, and where

Caching pays off in six ways: lower latency (memory instead of disk or a remote query), less load on the database, higher throughput from the same hardware, easier scaling (you add cache nodes before database nodes), less network traffic, and lower cost. Caches also exist at several levels. A browser or CDN cache holds static files and whole pages close to the user. An in-process cache (a map inside your application) is the fastest, but each server has its own copy. A shared cache such as Redis is one step slower, but every server sees the same data. Many systems stack them: a tiny in-process layer in front of Redis, in front of the database.

There are two ways to load a cache. In application-managed loading your code reads the cache, falls back to the database and fills the cache itself (this is cache-aside). In cache-managed loading the cache fetches missing data on its own through a loader you register (this is read-through). Redis does the first natively; the second needs a client library or a layer such as Spring's cache abstraction.

Do not cache everything

A cache earns its place when reads far outnumber writes, the result is expensive, and a little staleness is acceptable. Skip it for data that changes on almost every read, results unique to each request, and anything where an outdated value causes harm (like the final price at checkout). Measure the hit rate (hits divided by hits plus misses); a cache with a low hit rate adds latency and complexity without helping.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the cache-aside pattern, who loads data into the cache on a miss?

    In cache-aside the application checks the cache, reads the database on a miss, and fills the cache. Only read-through moves that logic into a cache layer.
  2. 2. After updating the database, why is deleting the cached entry usually safer than overwriting it?

    Rebuilding from the source of truth avoids storing a value that might differ from the database because of races or partial updates.
  3. 3. What is the main risk of write-behind?

    Write-behind acknowledges writes before they reach the database, trading durability for speed.
  4. 4. Why add random jitter to TTLs?

    Keys created at the same moment with the same TTL expire at the same moment, producing a burst of misses.
  5. 5. How can you invalidate a whole group of cached keys without scanning?

    Keys that embed the old version number are never requested again; they expire by TTL.

Summary

  • Cache-aside is the default: check the cache, read the database on a miss, store with a TTL; deleting the entry on write is safer than rewriting it.
  • Read-through hides the loading logic in a cache layer; write-through writes both stores together; write-behind is fastest but can lose unflushed writes.
  • Choose TTLs from how stale the data may be, add jitter, and always set one, ideally with SET key value EX seconds.
  • A cache key must contain every input of the value; use version prefixes for format changes and a namespace version to invalidate a group with one INCR.
  • Watch the hit rate, and do not cache data that changes constantly or must always be exact.

Next, learn what goes wrong at scale and how to prevent it in Cache Invalidation and Stampedes.