Lesson 1 · Unit 02
Caching
Serve hot reads from memory without serving lies
What you practise
- Cache-aside, write-through and write-behind, TTLs and invalidation, eviction (LRU), stampedes and how to stop them, what is safe to serve stale
Try a question from this lesson
Pick one
A product page takes 200 ms to build from the database. It is viewed 1,000 times a minute and changes once a day. What is the cheapest way to make it fast?
Correct answer
Build it once, keep the result in memory, reuse it
Why
The same answer is being computed 1,000 times a minute. Keep it in memory and the work happens once; every other view is a lookup that takes about a millisecond. That is a cache, and no hardware can match it for the money.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Cache-aside
The app owns the cache. On a read it looks there first. A hit returns at once. A miss goes to the database, and the answer is stored so the next read is a hit.
The TTL (time to live) is how long an entry may be served before it expires and is fetched again.
read(key):
value = cache.get(key)
if value is missing: # a miss
value = db.read(key)
cache.set(key, value, ttl)
return valueConcept
What happens on a write
Three common answers:
Cache-aside: write the database, then delete the cache entry. The next read reloads it.
Write-through: write the cache and the database together. Reads are always warm; writes are slower.
Write-behind: write the cache now and the database a little later. Very fast, and a crash can lose the writes that were still waiting.
10 more exercises in the app
- 1× order the lines
- 2× type the answer
- 4× multiple choice
- 1× match the pairs
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.