Caching and content deliveryReuse the useful work. Keep freshness in view.
Caching and content delivery. Learn the concepts, explore a model and defend your design.
06SYSTEM DESIGN
DEFINITION
Caching stores a reusable result so later requests can avoid repeating expensive work or travelling the same long path. The cached representation needs a key, an authority, an allowed freshness window and a failure policy. A hit finds a usable value; a miss needs another path. A CDN delivers suitable cached content from distributed edge locations.
A cached copy has a different authority
CONCEPTDatabaseAuthoritative accepted record
CONCEPTCacheReusable copy; may expire
CONCEPTReaderMust tolerate the stated staleness
Keep financial invariants and permissions anchored in an authoritative check.
CONCEPT 1
Keep a useful copy close to the reader
The notebook example
If you look up the same timetable repeatedly, keeping a copy in your notebook saves trips to the office. A cache does a similar job for software. It stores a reusable result near the place that needs it. The benefit is less repeated work or a shorter retrieval path. The difficulty is deciding whether the copy is still acceptable after the source changes.
Hit, miss and source of truth
A cache hit finds a usable value. A miss requires another path, often reading the source. The source of truth is the representation that decides the authoritative value; a cache usually should not silently become that authority for business rules. A cache key names the value. For a private response, the key must include the dimensions that affect what this caller may see.
A simple read calculation
If 1,000 requests per second read the same class of data and the assumed hit rate is 80 percent, around 200 requests per second reach the source before other work is counted. This estimate ignores writes, refreshes, correlated misses and changing traffic. A good hit rate can reduce load, but does not prove every response is correct or that a cold cache is safe.
CONCEPT 2
Learn the main cache patterns
Cache-aside
The application checks the cache. On a miss, it reads the database and stores a copy in the cache for reuse. A later read may use that copy. On a write, a common approach is to update the database and invalidate affected cache keys. The application owns this sequence, including what happens if a cache operation fails.
Write-through and write-back
In a write-through arrangement, the write path updates the backing source as part of accepting the cache write under that system's contract. Write-back, also called write-behind in some designs, can acknowledge a change before it reaches the backing source. That can improve a write path but creates a durability question if the cache fails before propagation. Clarify the exact product behavior rather than assuming the pattern name settles it.
TTL is different from eviction
Time to live, or TTL, limits how long an entry remains usable under an expiration policy. Eviction removes entries to manage resources such as memory. Least recently used prefers keeping recently used data; least frequently used considers use frequency. Exact implementations vary. A short TTL may reduce staleness but increases misses. An eviction policy is not a substitute for deciding how fresh a value must be.
Cache-aside on a miss
STEP 11. Look up keyNo cached value found
STEP 22. Read databaseFetch authoritative data
STEP 33. Fill cacheReturn value with bounded TTL
A hit skips the database read. A miss includes both the lookup and retrieval work.
CONCEPT 3
Why invalidation is harder than deleting one key
Walk through a stale-fill race
An old read starts and sees version A in the database. A writer commits version B and removes the cache entry. The old read then finishes and fills the cache with A. The writer did invalidate, yet an older value returned afterward. A TTL bounds its remaining life in that policy, but does not make the read instantly correct. Version-aware updates or a different read contract may be needed.
A stampede is many misses together
If thousands of popular entries expire simultaneously, many requests can rush to the database. Giving expiry times a small random variation spreads some of that work. Request coalescing lets one in-flight fetch serve several requests for the same missing key. These solve different problems. They do not make an overloaded database unlimited, so also plan admission and cold-cache recovery.
Choose what can be stale
A public event description might tolerate a short delay. Available ticket stock and a user's current permission often need a stronger decision path. Caching everything under one freshness rule is risky. Measure source load, errors, eviction and stale-response incidents alongside hit rate, and test what happens when the cache is empty or unavailable.
A stale fill can race with invalidation
STEP 1ReaderFetches old database value
STEP 2WriterUpdates DB; deletes cache
STEP 3ReaderPuts old value into cache
Deletion alone cannot prevent this race. Use a policy such as versions and bounded staleness.
CONCEPT 4
A CDN is an edge cache with rules
Bring suitable content nearer
A content-delivery network, or CDN, has delivery locations that can serve suitable content nearer to users. A large public image can be delivered without every viewer downloading from the application's main server. This can reduce origin load and network distance for some requests. The result depends on where users are and what the CDN can safely reuse.
Immutable files are easier
A versioned file name such as app.v3.css can identify content that does not change under that name. New content gets a new name. That makes long-lived caching easier than replacing a file in place while different caches retain old copies. For mutable pages, define cache lifetimes and invalidation behavior. A response's caching policy must match whether it is public, personalized or private.
The private-page mistake
Suppose the edge caches Riya's private receipt without including the required identity boundary. It might reuse that receipt for another student. TLS does not fix the mistake because the wrong bytes were served through an encrypted connection. Test shared-cache behavior for authenticated endpoints. Decide what a revoke or delete action means while old copies may remain at edges.
A CDN moves eligible content closer
STEP 1OriginPublishes an object
STEP 2Edge cacheStores eligible representation
STEP 3Nearby userDownloads the cached bytes
Cache keys and access rules must prevent private representations from being shared.
Key learning points
Name the source of truth before adding a cached representation.
Include every ownership or representation dimension that changes the permitted response.
TTL controls expiration; eviction responds to memory/resource policy.
Plan stale-fill races and synchronized misses, not only ordinary hits.
A cache hit can still be an incorrect or unauthorized response.
Compare the important ideas
Caching and content delivery: concepts and trade-offs
Pattern or policy
Behavior
Use and caution
Cache-aside
Read cache, fetch source on miss, fill
Simple reuse; application must manage races and fallback
Write-through
Accept the write under a backing-store update contract
Clarify actual atomicity and product behavior
Write-back
Source update may happen after acceptance
Check data-loss exposure before propagation
TTL
Expire under a lifetime policy
Shorter age means more misses, not instant correctness
LRU-like eviction
Prefer keeping recently used entries
Useful locality assumption, not an authorization policy
CDN caching
Serve suitable responses near users
Private data and revocation require explicit cache rules
WORKED EXAMPLE
A miss does not have to become a stampede
At 1,000 reads/s with an assumed 80 percent hit rate, about 200 reads/s reach the source before refreshes and writes. If many popular keys expire together, the source can receive a much larger correlated burst. Coalesce requests for one missing key and vary suitable expiry times across different keys. Test a completely cold cache rather than assuming yesterday's hit ratio will persist.
Further reading
Original teaching explanations by Buildfest Learn. Check these primary references for the underlying concepts and implementation details.
Increase the hit rate, then simulate a cold cache. What happens to the database read demand?
11,000 reads/s
280% effective hit rate
3200 source reads/s
200 database reads/s in this model
Source reads = offered reads x (1 - hit fraction). A cold cache can suddenly direct all reads toward the source, requiring bounded warm-up and protection.
Chapter review: two questions
Attempt both questions before opening the model answers.
Question 1
At 2,000 read requests/s, a modeled hit rate is 85 percent. Estimate source reads/s, then explain what changes during a complete cold start.
Reveal model answer
The simple steady-state estimate is 2,000 x 0.15 = 300 source reads/s before other work. At a cold start, hits may initially be zero, so all offered reads may try the source. Request coalescing, admission limits and warming can protect it; the steady-state estimate is not a recovery guarantee.
Question 2
Draw an old read, a new database write and invalidation in an order that refills the cache with stale data. State one acceptable freshness contract or stronger mitigation.
Reveal model answer
An old read obtains version A; a writer commits B and invalidates; the old read then fills A. A declared short stale window can be acceptable for some descriptions. Correctness-sensitive values may need version-aware updates or authoritative reads. TTL alone does not eliminate the race.
Answers stay in this tab. Download before leaving. This practice is not graded or saved to your account.