Content delivery network (CDN)
Play this lessonThis lesson comes with an interactive animation you can break, a live-code challenge and a chapter quiz.A CDN is a network of servers spread around the world that cache static content: images, videos, CSS and JavaScript files. A user gets the files from the CDN server closest to them, so pages load faster. (Users in Los Angeles get content from a San Francisco CDN faster than users in Europe do.)
Image URLs point to the CDN's domain, for example https://mysite.cloudfront.net/logo.jpg. If the CDN doesn't have the file, it fetches it from the origin (your web server or storage like Amazon S3), along with a TTL header that says how long to cache it.
Things to think about
- Cost: CDNs charge for data transfer. Don't put rarely used files there.
- Cache expiry: not too long (stale), not too short (constant reloads from the origin).
- CDN fallback: if the CDN has an outage, clients should be able to fetch from the origin instead.
- Invalidating files: use the vendor's invalidation API, or version the URL:
image.png?v=2.
Key takeaways
- CDN = cache for static files, close to users.
- Miss → fetch from origin with a TTL → later users get a hit.
- Invalidate with an API call or a versioned URL.