System Design on caching and CDNs
A cache trades freshness for speed
- A cache keeps a copy of an answer in memory, so the next request skips the slow work.
- It works best for data read often and changed rarely, like where a short link points.
- The price: a cached copy can be out of date. Decide how stale is acceptable.
Cache-aside is the usual pattern
- Look in the cache first. On a hit, return the copy.
- On a miss, read the database, put the result in the cache, then return it.
- Only data that is asked for gets cached, and an empty cache still gives right answers.
Hit
- App
- Cachefound
- Return it
Miss
- App
- Cachenot found
- Databaseread the real value
- Fill cache, return it
On a write, change the database, then delete the entry
- Update the database first, then remove the cached copy. The next read refills it.
- The other order is a bug: a reader can put the old value back in between.
- Even done right, readers can briefly see old data. Cache-aside is not a guarantee.
A TTL limits how stale data can get
- A time to live (TTL) expires an entry after a set time, such as 5 minutes.
- Too short and most requests miss. Too long and users see old data.
- When memory fills, most caches evict the least recently used entries.
An expired hot entry can stampede the database
- When a popular entry expires, many requests miss at once and all hit the database.
- Let one request rebuild the entry while the others wait or get the old copy.
- Add a little randomness to TTLs so entries do not all expire together.
A CDN is a cache close to the user
- A content delivery network (CDN) keeps copies in data centers around the world.
- Each request goes to a nearby one. On a hit, your own servers are never called.
- It suits static files: images, CSS, JavaScript. Cloudflare skips HTML by default.
- CloudFront keeps a file 24 hours by default unless your headers say otherwise.
- Browserhas its own cache
- CDNstatic files, near the user
- Load balancer
- App server + cachehot data in memory
- Databasethe source of truth
Cache-Control headers tell caches what to do
- Your server sets this header on a response. Browsers and CDNs read it.
- max-age=3600 means fresh for an hour. s-maxage sets that for shared caches only.
- private lets only the user's browser store it. no-store forbids any copy.
- Mark per-user pages private, or a CDN may serve one user's page to another.