TL;DR

1. The problem: why do we need a CDN?

Instagram is a media-first, read-heavy product. Every time someone scrolls their feed, the app downloads dozens of images and video segments. Suppose all of that media lived only in one data center in Virginia, USA:

🧠 Analogy Think of a popular bakery with one central kitchen. If every customer in the country had to travel to the central kitchen, queues would be endless. Instead the bakery opens small shops in every neighbourhood that stock the most popular items. If a shop runs out of something rare, it orders it from the central kitchen once and then keeps it on the shelf. The neighbourhood shops are the CDN edge servers; the central kitchen is the origin.

2. How a CDN works

2.1 The building blocks

🌍 PoP (Point of Presence)

A CDN location in a city (e.g. Mumbai, Frankfurt, São Paulo), containing many edge servers. Large CDNs have 200–3,000+ PoPs, often inside ISP networks.

🖥️ Edge server

A cache server with lots of RAM and SSD that terminates the user's TLS connection and serves cached files.

🛡️ Origin shield / mid-tier

A regional cache layer between edges and origin. Many edges miss → only one shield request reaches the origin.

🏛️ Origin

The source of truth — for Instagram, the object storage cluster holding every photo/video rendition.

📱 User, Mumbai 📱 User, Berlin 📱 User, Paris Edge PoPMumbai Edge PoPFrankfurt Edge PoPParis Origin shieldAsia Origin shieldEurope OriginObject storage (S3) ~5 ms on miss rare miss
Users hit the nearest edge. Edge misses go to a regional shield; only shield misses reach the origin.

2.2 How does the user reach the nearest edge?

Two main techniques route the user to a nearby PoP:

  1. DNS-based routing (GeoDNS). When the app resolves scontent.cdninstagram.com, the CDN's authoritative DNS server looks at where the request came from and returns the IP of a nearby, healthy PoP. Different users get different IPs for the same name.
  2. Anycast. Many PoPs announce the same IP address via BGP. Internet routers naturally deliver packets to the topologically closest one. Cloudflare relies heavily on this; it also absorbs DDoS traffic by spreading it across all PoPs.

2.3 Cache hit vs cache miss

  1. The app requests https://cdn.example.com/p/9f3a…/1080.jpg. The edge computes the cache key (usually host + path, plus selected query params/headers).
  2. Cache HIT: the edge has the file and it's still fresh (within its TTL) → it returns it immediately. ⚡ ~10–30 ms total.
  3. Cache MISS: the edge asks the origin shield; if the shield also misses, the shield fetches from the origin (object storage).
  4. The response flows back, and each layer stores a copy according to the Cache-Control header, so the next user nearby gets a hit.
 User            Edge (Mumbai)           Shield (Asia)            Origin (S3)
  |  GET img.jpg      |                        |                        |
  |-----------------> |  lookup cache key      |                        |
  |                   |--- MISS -------------> |                        |
  |                   |                        |--- MISS ------------> |
  |                   |                        | <------ 200 + bytes -- |
  |                   | <------ 200 + bytes -- |  (store copy)          |
  | <-- 200 + bytes - |  (store copy)          |                        |
  |                                                                     |
  |  GET img.jpg  (another user in Mumbai, 2 s later)                   |
  |-----------------> |  HIT ✔ → served from RAM/SSD in ~10 ms          |

The single most important CDN metric is the cache hit ratio (CHR):

cache hit ratio = cache hits / (cache hits + cache misses)

Going from 90% to 99% CHR sounds small, but it means origin traffic drops from 10% to 1% of requests — a 10× reduction in origin load.

3. Pull CDN vs Push CDN

Pull CDN (origin pull)Push CDN
How content gets thereEdge fetches from origin lazily on the first miss.You upload content to the CDN ahead of time.
Setup effortMinimal — just point the CDN at your origin.You manage uploads, updates and deletions.
First requestSlower (miss goes to origin).Fast — already present.
Storage useOnly popular content is cached; unpopular content gets evicted.Everything you push occupies CDN storage.
Best forHuge, long-tail catalogs with unpredictable popularity (user-generated content).Small, predictable catalogs, large launches (game patches, a new movie release).
📸 In Instagram Instagram uses pull — there are hundreds of billions of photos and most are rarely viewed, so pre-pushing everything everywhere would be absurdly wasteful. The diagram's "origin pull" arrow from Object Storage to the CDN is exactly this. For predictable spikes (e.g. a celebrity with 600M followers posts), some systems pre-warm the cache by requesting the new object from key PoPs right after upload.

4. Controlling what gets cached (and for how long)

4.1 Cache-Control headers & TTL

The origin tells caches how to behave through HTTP headers:

Cache-Control: public, max-age=31536000, immutable   # cache for 1 year, never revalidate
Cache-Control: private, max-age=0, no-store           # never cache (e.g. personalised API responses)
Cache-Control: public, max-age=60, s-maxage=300       # browser: 60 s, shared caches (CDN): 300 s
ETag: "9f3a1c"                                        # version fingerprint for revalidation

4.2 Cache keys

The cache key decides whether two requests are "the same file". If you accidentally include a random query param (e.g. a tracking id) in the key, every request becomes a miss and your hit ratio collapses. Good practice: normalise the key — include only what changes the response (path, size, format), and strip everything else.

4.3 Invalidation: the hard part

"There are only two hard things in computer science: cache invalidation and naming things." What if a user edits or deletes a photo that's cached in 300 PoPs?

StrategyHowTrade-off
Versioned / content-addressed URLs ⭐Put a hash or version in the URL: /p/9f3a1c/1080.jpg. A changed file gets a new URL; the old one is simply never requested again.Best practice. Allows max-age=1 year, immutable. Requires the API to hand out the new URL.
Purge APICall the CDN API: "purge this URL / this tag" across all PoPs.Takes seconds to minutes to propagate; rate-limited; costly at scale.
Short TTLCache for only a few minutes.Stale for at most TTL, but hit ratio and origin load suffer.
⚠️ Deletion & privacy When a user deletes a photo or makes their account private, the content must stop being reachable. Because URLs are versioned and signed with an expiry (see below), deleting the metadata means the app never hands out the URL again, and any leaked URL expires on its own. A purge is issued as a belt-and-braces step.

5. Securing content on a CDN

6. CDNs for video: adaptive streaming

Reels and Stories videos aren't served as one giant file. The media pipeline cuts each video into small 2–6 second segments at several bitrates (240p…1080p), plus a manifest (HLS .m3u8 / DASH .mpd). The player downloads segments one by one from the CDN and switches quality based on bandwidth. Segments are just small static files — perfect for CDN caching — and the first few segments of popular videos are almost always hot in the edge cache, giving near-instant playback.

Two HTTP features make this efficient:

7. Inside an edge server

An edge server is essentially a very fast HTTP reverse proxy with a huge cache. Understanding its internals explains most CDN behaviour.

7.1 The cache hierarchy inside one PoP

Request RAM cachehottest objects · ~µs SSD cachewarm objects · ~0.1 ms Peer edge (same PoP)consistent-hash owner Origin shieldregional tier Originobject storage all miss
A lookup checks RAM, then SSD, then the peer that "owns" the key, and only then leaves the PoP.

7.2 Serving stale content when things break

Two headers let edges keep serving when the origin is slow or down:

Cache-Control: max-age=600, stale-while-revalidate=60, stale-if-error=86400

This makes the CDN a resilience layer as well as a performance layer — a pattern covered in Resilience Patterns as graceful degradation.

8. Beyond static files: dynamic acceleration & edge compute

CDNs started as static-file caches but now do much more:

CapabilityWhat it doesInstagram-style use
Dynamic site accelerationPersonalised API calls still pass through the edge. The edge terminates TCP+TLS close to the user and forwards over a pre-warmed, long-lived connection to the origin data center.A user in Chennai pays the expensive handshakes to a nearby PoP (~10 ms RTT) instead of a faraway data center (~200 ms RTT); see Networking Basics.
Edge computeRun small functions at the edge (Cloudflare Workers, Lambda@Edge, Fastly Compute).Validate signed URLs, pick the image format from the Accept header, A/B test, block bots.
On-the-fly image transformsThe edge resizes or re-encodes images per request and caches each variant.An alternative to pre-generating every rendition in the media pipeline, useful for rare sizes.
WAF & bot managementFilter malicious requests before they reach your servers.Block credential-stuffing on the login API; see Security.

9. Operating a CDN: metrics, cost and multi-CDN

9.1 What to monitor

MetricWhy it mattersHealthy target (typical)
Request hit ratioShare of requests served without leaving the edge> 90–95% for media
Byte hit ratio / origin offloadShare of bytes not fetched from origin — drives cost> 90%
Time to first byte (TTFB), p50/p95/p99User-perceived latency, per region and per ISPp95 < 100 ms on hits
Origin request rate & error rateEarly warning of misses storms or origin troubleStable; alerts on spikes
4xx/5xx at the edgeExpired signatures, bad links, origin failuresLow and flat

These feed the dashboards and SLOs described in Observability. Real-user monitoring from the app (how long images actually took to appear) is the ultimate truth.

9.2 The cost model

Commercial CDNs mostly charge per GB delivered (cheaper at higher volume and in North America/Europe, pricier in some regions), plus per-request fees and extras such as edge compute. Two levers dominate the bill: bytes delivered (shrink them with better formats like WebP/AVIF and the right rendition per screen) and origin egress (cut it with a higher byte hit ratio and an origin shield). A 30% smaller image format saves 30% of the CDN bill and makes the app faster — one of the rare wins on every axis.

9.3 Multi-CDN

Large companies that don't run their own CDN often use two or more providers at once:

The price is complexity: consistent configuration, signed-URL schemes and purges across providers, and a lower hit ratio per CDN since traffic is split.

10. How Instagram uses the CDN

📱 Appgets feed JSON
→image URLs
CDN edgenearest PoP
→on miss
Origin shield
→on miss
Object storageall renditions
  1. The Feed service returns JSON containing post metadata and signed CDN URLs — never the bytes themselves. The API path and the media path are separate.
  2. The app picks the right rendition for the device (e.g. 640px for a small phone, 1080px for a large one, WebP/AVIF if supported) — these renditions were generated by the media processing workers.
  3. The app fetches media directly from the CDN. Popular content is served from edge RAM/SSD; long-tail content triggers an origin pull from object storage.
  4. The app prefetches the next few posts' images while you scroll, so they're already on the device when you get there (see Clients).
📸 Real-world note Meta runs its own global edge network (PoPs plus caches embedded inside ISPs, called FNA — Facebook Network Appliances). Instagram media hostnames such as scontent-*.cdninstagram.com resolve to those edge caches. At this scale, building your own CDN becomes cheaper than renting one; for almost every other company, a commercial CDN is the right answer.

Rough numbers

Assume 500M daily active users view ~100 images/day at ~200 KB average:

500M × 100 × 200 KB = 10 PB/day of media egress
10 PB / 86,400 s ≈ 116 GB/s ≈ 0.93 Tbps average (peak ~2–3×)
With a 95% hit ratio → origin serves only ~5.8 GB/s; the CDN absorbs the rest.

See Back-of-the-Envelope Estimation for how to do this math yourself.

11. Trade-offs & common pitfalls

✅ Benefits

  • Much lower latency worldwide
  • Massive origin offload & bandwidth savings
  • Absorbs traffic spikes and DDoS
  • Higher availability — edges can serve stale content if origin is down

⚠️ Costs

  • Staleness — cached content can be out of date
  • Invalidation complexity
  • Vendor cost (priced per GB) and lock-in
  • Harder debugging (which PoP served what?)
  • Not useful for personalised / private dynamic data

Common pitfalls

12. Real-world technologies

ProviderNotes
AkamaiThe oldest and one of the largest; thousands of PoPs inside ISPs.
CloudflareAnycast-based, strong DDoS/WAF, edge compute (Workers).
Amazon CloudFrontTight integration with S3 as origin, origin shield option, signed URLs/cookies.
FastlyVery fast purges (~150 ms), programmable edge (VCL/Compute).
Google Cloud CDN, Azure Front DoorCloud-native options integrated with their load balancers.
Netflix Open Connect, Meta FNAIn-house CDNs built by companies whose traffic is large enough to justify it.

13. Interview corner

Why put a CDN in front of Instagram's media?

Instagram is read-heavy (~100:1 reads to writes) and media is large and immutable once processed. A CDN serves media from locations close to users, reducing latency from hundreds of ms to tens of ms, offloads 90%+ of bandwidth from the origin, and absorbs spikes when content goes viral. The API (feed JSON) still goes to our servers; only media bytes go via the CDN.

Pull or push CDN for Instagram — and why?

Pull. The catalog is enormous and long-tailed; most photos are viewed a few times, a few are viewed billions of times. Pull caches only what's actually requested and evicts cold objects automatically. Pre-warming can be added for known hot content (celebrity posts).

A user deletes a photo. How do you make sure it's no longer served?

1) Delete/mark the metadata so the API never returns the URL again. 2) URLs are signed with short expiry, so leaked links die quickly. 3) Issue a CDN purge for that object's URLs. 4) Asynchronously delete the blobs from object storage. Because URLs are content-versioned, there's no risk of serving an "old version" after an edit — an edit produces a new URL.

A celebrity posts and 50M people open it in a minute. What happens at the CDN?

Every PoP initially misses. Without protection, thousands of simultaneous misses hit the origin (thundering herd). Mitigations: request collapsing at each edge (one in-flight origin fetch per object), a tiered origin shield so only a handful of requests reach object storage, and optionally pre-warming the object in major PoPs right after processing completes.

Would you cache the feed API response on the CDN?

Generally no — it's personalised per user and changes constantly; caching it in a shared cache risks leaking data and gives a low hit ratio. Use an application cache (e.g. the Redis feed cache) instead. The CDN can still accelerate dynamic API calls by terminating TLS near the user and keeping warm connections to the origin ("dynamic site acceleration").

Your CDN bill doubled this quarter while traffic grew only 20%. How do you investigate and fix it?

Break the bill down: bytes delivered vs origin egress vs requests, per region and per content type. Typical culprits: (1) a falling byte hit ratio — e.g. a new query parameter leaked into the cache key, or longer-tail video content — fix the cache key and add an origin shield; (2) bigger payloads — a client release requesting 1080px images on small screens, or a regression to JPEG — enforce correct rendition selection and modern formats (WebP/AVIF); (3) expensive regions — consider regional pricing, ISP-embedded caches or a multi-CDN mix. Then add dashboards and alerts on byte hit ratio and bytes per view so it can't silently regress again.

14. Check your understanding

What does a cache hit ratio of 98% mean for the origin, compared with 90%?

At 90%, 10% of requests reach the origin; at 98%, only 2% do — a 5× reduction in origin load, even though the hit ratio only went up by 8 percentage points.

Why is /p/9f3a1c/1080.jpg a better URL design than /p/1080.jpg?v=2 or overwriting /p/photo.jpg?

A content hash in the path makes the URL immutable: if the file changes, the URL changes. It can be cached forever (immutable), needs no purge on update, and some CDNs ignore query strings in the cache key — so ?v=2 could still serve the old file.

What's the difference between GeoDNS and Anycast routing?

GeoDNS returns different IP addresses depending on the resolver's location. Anycast advertises the same IP from many locations and lets BGP routing deliver packets to the nearest one. Anycast reacts faster to failures (no DNS TTL to wait out) and spreads DDoS traffic naturally.

What is an origin shield and what problem does it solve?

A middle cache tier between edges and origin. When many edges miss for the same object, they all ask the shield, which makes a single request to the origin. It raises the overall hit ratio and prevents origin overload (thundering herd).

Which of these should be served via the CDN: (a) a post's 1080px JPEG, (b) the user's personalised feed JSON, (c) the first 4-second segment of a Reel, (d) a pre-signed upload URL?

(a) and (c) — both are static, immutable and shared by many users. (b) is personalised and changes constantly, so it belongs in an application cache, not a shared CDN cache. (d) is a one-time, per-user secret used to write to object storage; it must never be cached.

A PoP has 200 servers, each with 10 TB of cache. Roughly how much unique content can the PoP hold if (a) every server caches independently, (b) servers shard keys with consistent hashing?

(a) Popular objects end up duplicated on nearly every server, so in the worst case the PoP effectively holds only about 10 TB of unique content. (b) Each object lives on one owner server, so the PoP holds up to 200 × 10 TB = 2 PB of unique content — a far higher hit ratio for long-tail photos. Very hot objects are then selectively replicated so a single owner doesn't become a hotspot.

🎯 Key takeaways

Related lessons