Buildfest Learn System DesignRead and experiment freely · Chapter activities stay in this tab
Practice librarySystem DesignCaching and content delivery

LESSON 06 • SYSTEM DESIGN

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.

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
  1. CONCEPTDatabaseAuthoritative accepted record
  2. CONCEPTCacheReusable copy; may expire
  3. 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
  1. STEP 11. Look up keyNo cached value found
  2. STEP 22. Read databaseFetch authoritative data
  3. 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
  1. STEP 1ReaderFetches old database value
  2. STEP 2WriterUpdates DB; deletes cache
  3. 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
  1. STEP 1OriginPublishes an object
  2. STEP 2Edge cacheStores eligible representation
  3. 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 policyBehaviorUse and caution
Cache-asideRead cache, fetch source on miss, fillSimple reuse; application must manage races and fallback
Write-throughAccept the write under a backing-store update contractClarify actual atomicity and product behavior
Write-backSource update may happen after acceptanceCheck data-loss exposure before propagation
TTLExpire under a lifetime policyShorter age means more misses, not instant correctness
LRU-like evictionPrefer keeping recently used entriesUseful locality assumption, not an authorization policy
CDN cachingServe suitable responses near usersPrivate 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.