Caching layers and invalidation
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Apply cache-aside with a TTL and explain the read path.
- Invalidate on write and avoid stale reads.
- Use HTTP caching headers for safe responses.
Overview
#A cache trades a small staleness window for lower latency and less database load. The hard part is invalidation: knowing when a cached value is no longer true.
Cache-aside
Read from the cache; on a miss, read from the database and populate the cache with a TTL.
async function getArticle(id) {
const key = `article:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const article = await db.query('SELECT * FROM articles WHERE id = $1', [id]);
await redis.set(key, JSON.stringify(article.rows[0]), 'EX', 60);
return article.rows[0];
}
Invalidation
On write, delete or update the cache key so the next read repopulates it. A TTL bounds how long a missed invalidation can persist.
Cache stampede
When a hot key expires, many requests miss at once and hit the database together. Mitigate with a short lock, stale-while-revalidate, or jittered TTLs.
HTTP caching
For safe, user-independent responses, send Cache-Control: public, max-age=60 and an ETag. A conditional request with If-None-Match can return 304 Not Modified with no body.
Common pitfalls
- Caching per-user data under a shared key, leaking one user's data to another.
- Setting a long TTL on data that changes often.
- Forgetting to invalidate on write, so readers see stale values.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Debug
After an article is updated, readers still see the old version for minutes. Explain and fix.
starter.javascriptawait db.query('UPDATE articles SET title = $1 WHERE id = $2', [title, id]); // no cache changeReveal the reference answer
reference.javascriptawait db.query('UPDATE articles SET title = $1 WHERE id = $2', [title, id]); await redis.del(`article:${id}`);Authored expected output: The cache key is deleted on write, so the next read repopulates it with the new title.
The write path did not invalidate the cache, so the TTL governed staleness. Deleting the key on write makes the next read fresh.
Exercise 2Predict
A hot cache key expires and 500 requests arrive at once. What happens without mitigation?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.txtkey TTL expires -> all requests miss
Common misconceptions
#- A cache is always consistent with the database: it is eventually consistent within the TTL unless you invalidate on write.
- ETag is a security feature: it is a cache validator, not an authorization mechanism.
Follow-up practice
#- backend-databases-observability
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.