How Instagram loads massive photos instantly for users all over the world.
If you build a photo app and store all the images in an AWS S3 bucket in Virginia, users in Virginia will see the photos load instantly. But a user in Australia will stare at a loading spinner for 2 seconds while the 5MB photo travels across the ocean. To solve this, large apps use a CDN (Content Delivery Network). A CDN is a massive network of caching servers placed in hundreds of cities worldwide. When an Australian user requests a photo, they fetch it from a CDN server in Sydney, not Virginia.
A CDN sits exactly between the User and your actual storage server (the Origin). The very first time someone in Australia requests a specific photo, the CDN doesn't have it. This is a Cache Miss. The CDN fetches it from the US, serves it to the user, and keeps a copy on its Sydney hard drive. The next time anyone in Australia asks for that photo, it's a Cache Hit, and it loads instantly.
// Pseudocode of a CDN Edge Server in Sydney
function handleRequest(url) {
// 1. Check local SSD cache in Sydney
if (localCache.has(url)) {
return localCache.get(url); // Cache Hit (Fast!)
}
// 2. Cache Miss! Fetch from the Origin server in Virginia
const image = fetchFromOrigin("https://my-bucket.s3.us-east-1.amazonaws.com" + url);
// 3. Save a copy locally so the next Aussie gets it fast
localCache.save(url, image, timeToLive="1 year");
return image;
}
CDNs are amazing for static, immutable files (like photos, videos, and CSS bundles). But they introduce Cache Invalidation problems. If a user uploads a new profile picture to the same URL (/profile.jpg), the Origin server is updated, but the CDN in Sydney still holds the old picture. You have to explicitly send a "Purge" command to hundreds of edge servers worldwide, which can take minutes, or you use Cache Busting (changing the URL to /profile_v2.jpg).