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.
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
| Question | Database | Cache |
|---|---|---|
| Holds all the data? | Yes | Only copies of some of it |
| Survives restarts? | Yes, designed for durability | Often not guaranteed, depending on setup |
| Enforces rules like UNIQUE and foreign keys? | Yes | No |
| Answers new questions with queries? | Yes | Only what you stored |
| Always up to date? | Yes | Can 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:
- giving cached items an expiry time, after which they are fetched again
- deleting the cached copy whenever the underlying data changes
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
- Cache hit: the copy was there.
- Cache miss: it was not, so the app went to the database.
- TTL (time to live): how long a cached item is kept before it expires.
- Source of truth: the system whose data counts when copies disagree, which is your database.
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