What a Cache Is, and Why It Is Not Your Database

You will hear about caches, and tools such as Redis or Memcached, as soon as you read about web apps at scale. Beginners sometimes wonder whether a cache replaces the database. It does not. This post explains what a cache is, in plain words.

Designing related tables illustration

The everyday idea

A cache is a place to keep a copy of something you need often, so you can get it faster next time. Your browser caches images from websites. Your brain caches your own phone number. In apps, a cache usually keeps copies of results that are slow or costly to produce, such as the answer to a database query.

How it looks in an app

1. App needs the list of top songs.
2. Ask the cache: "do you have top_songs?"
3a. Yes  -> use the copy. Fast.
3b. No   -> ask the database, then store a copy in the cache for next time.

That pattern has a name: cache-aside. The database remains the real, complete record. The cache only holds convenient copies.

The key-value idea

Many caches are key-value stores: you store a value under a name (the key) and get it back by name.

SET top_songs  "[...list...]"
GET top_songs

There are no tables, joins or WHERE clauses in the simplest use. That is part of why they are fast, and also why they are not a replacement for a relational database.

Why the database stays the source of truth

QuestionDatabaseCache
Holds all the data?YesOnly copies of some of it
Survives restarts?Yes, designed for durabilityOften not guaranteed, depending on setup
Enforces rules like UNIQUE and foreign keys?YesNo
Answers new questions with queries?YesOnly what you stored
Always up to date?YesCan be stale

The hard part: stale data

When data changes in the database, the copy in the cache becomes out of date, or stale. Apps handle this by:

A famous programmer's joke says there are only two hard things in computer science, and cache invalidation is one of them. You can see why.

Should a beginner use a cache?

Usually not yet. A cache adds another system to run and another way for data to be wrong. Most beginner projects are fast enough with a well-designed database. Learn tables, keys and queries first. When a real page is slow, first check the query itself; see your first slow query. Reach for a cache only when the same expensive result is read again and again.

Words to remember

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Get new pages by email

Related pages on this site