- A CDN is a worldwide network of cache servers (edge servers, grouped into PoPs) that store copies of your static content close to users.
- Instead of every photo request travelling to Instagram's data center, it's served from a server maybe 20 km away instead of 8,000 km — cutting latency from hundreds of ms to tens of ms.
- It also offloads 90–99% of media traffic from the origin (object storage), which saves enormous bandwidth cost and protects the backend.
- Key ideas: pull vs push, cache keys, TTL, cache hit ratio, invalidation via versioned URLs, origin shield, and signed URLs for private content.
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:
- Latency is physics. Light in fibre travels ~200,000 km/s. A round trip Mumbai ⇄ Virginia (~13,000 km each way) takes at least ~130 ms — and a single HTTPS image fetch needs several round trips (TCP handshake, TLS handshake, request). Realistically a user in India would wait 400–800 ms per image. Scrolling would feel broken.
- Bandwidth is enormous. With ~2 billion monthly users each viewing hundreds of images a day, media egress is measured in terabits per second. No single data center uplink can handle that, and transit bandwidth across oceans is expensive.
- The origin would melt. Object storage (S3-like) is built for durability, not for serving the same viral photo 50 million times in an hour.
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.
2.2 How does the user reach the nearest edge?
Two main techniques route the user to a nearby PoP:
- 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. - 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
- 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). - Cache HIT: the edge has the file and it's still fresh (within its TTL) → it returns it immediately. ⚡ ~10–30 ms total.
- Cache MISS: the edge asks the origin shield; if the shield also misses, the shield fetches from the origin (object storage).
- The response flows back, and each layer stores a copy according to the
Cache-Controlheader, 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 there | Edge fetches from origin lazily on the first miss. | You upload content to the CDN ahead of time. |
| Setup effort | Minimal — just point the CDN at your origin. | You manage uploads, updates and deletions. |
| First request | Slower (miss goes to origin). | Fast — already present. |
| Storage use | Only popular content is cached; unpopular content gets evicted. | Everything you push occupies CDN storage. |
| Best for | Huge, long-tail catalogs with unpredictable popularity (user-generated content). | Small, predictable catalogs, large launches (game patches, a new movie release). |
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
- TTL (time to live) — how long a cached copy is considered fresh.
- Revalidation — after the TTL expires, the cache can ask the origin
If-None-Match: "9f3a1c"; the origin replies304 Not Modified(no body) if unchanged — cheap. stale-while-revalidatelets the edge serve a slightly stale copy while it refreshes in the background, hiding origin latency.
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?
| Strategy | How | Trade-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 API | Call the CDN API: "purge this URL / this tag" across all PoPs. | Takes seconds to minutes to propagate; rate-limited; costly at scale. |
| Short TTL | Cache for only a few minutes. | Stale for at most TTL, but hit ratio and origin load suffer. |
5. Securing content on a CDN
- Signed URLs / tokens: the API server generates a URL containing an expiry time and an HMAC signature, e.g.
…/1080.jpg?exp=1730000000&sig=ab12…. The edge verifies the signature without contacting the origin. Leaked links stop working after expiry. Instagram media URLs carry exactly this kind of signature (oe=,oh=params). - TLS at the edge: the edge terminates HTTPS close to the user (faster handshakes) and re-encrypts to the origin.
- DDoS absorption & WAF: CDNs have enormous aggregate capacity and filter malicious traffic before it reaches you. See Security.
- Origin protection: only CDN IPs (or authenticated requests) may reach the origin bucket.
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:
- Range requests (
Range: bytes=0-1048575) let a player fetch just part of a file, which the CDN can serve from a partially cached object. The edge often fetches large files from the origin in fixed-size chunks (e.g. 1–2 MB), so a user seeking to minute 3 doesn't force the whole file to be downloaded first. - Byte hit ratio vs request hit ratio. Video segments are big, thumbnails are tiny. A CDN can have a 95% request hit ratio but only a 80% byte hit ratio if big videos miss more often. Bandwidth cost follows the byte hit ratio, so watch both.
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
- Key ownership within a PoP. A PoP may have hundreds of servers. If each cached every object independently, the PoP would store 100 copies of the same photo and the effective cache size would shrink 100×. Instead, servers use consistent hashing on the cache key so each object has one "owner" server. Very hot objects are deliberately replicated to many servers to spread load.
- Eviction. When the disk is full, something must go. Plain LRU (least recently used) is easily polluted by "one-hit wonders" — objects requested once and never again, which are extremely common for user-generated content. CDNs therefore use smarter policies: segmented LRU, LFU-style admission, or "only cache on the second request" (admission filters, often implemented with a Bloom filter — see Caching). Meta has published research showing that smarter admission and eviction noticeably raise the hit ratio of its photo caches.
- Request collapsing (coalescing). If 1,000 requests for the same uncached object arrive within 50 ms, the edge sends one request upstream and makes the other 999 wait for that response. This is the main defence against the thundering herd described in Caching.
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
stale-while-revalidate=60: for 60 s after expiry, serve the stale copy immediately and refresh it in the background.stale-if-error=86400: if the origin returns 5xx or times out, keep serving the stale copy for up to a day.
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:
| Capability | What it does | Instagram-style use |
|---|---|---|
| Dynamic site acceleration | Personalised 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 compute | Run 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 transforms | The 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 management | Filter 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
| Metric | Why it matters | Healthy target (typical) |
|---|---|---|
| Request hit ratio | Share of requests served without leaving the edge | > 90–95% for media |
| Byte hit ratio / origin offload | Share of bytes not fetched from origin — drives cost | > 90% |
| Time to first byte (TTFB), p50/p95/p99 | User-perceived latency, per region and per ISP | p95 < 100 ms on hits |
| Origin request rate & error rate | Early warning of misses storms or origin trouble | Stable; alerts on spikes |
| 4xx/5xx at the edge | Expired signatures, bad links, origin failures | Low 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:
- Availability: if one CDN has a global outage (it happens, e.g. the June 2021 Fastly incident that briefly took down many large websites), DNS steers traffic to the other.
- Performance: real-user measurements decide, per country or ISP, which CDN is fastest.
- Cost leverage: traffic can be shifted toward the cheaper provider.
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
- 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.
- 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.
- 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.
- The app prefetches the next few posts' images while you scroll, so they're already on the device when you get there (see Clients).
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
- Caching personalised responses (e.g. a user's feed JSON) under a shared key → users see each other's data. Always mark them
private/no-store. - Cache-busting by accident — random query params in cache keys destroy the hit ratio.
- Thundering herd on the origin — a viral new post misses in 300 PoPs simultaneously. Fix with an origin shield and request collapsing (the edge sends one origin request and makes the others wait for it).
- Overwriting files in place instead of using new versioned URLs.
12. Real-world technologies
| Provider | Notes |
|---|---|
| Akamai | The oldest and one of the largest; thousands of PoPs inside ISPs. |
| Cloudflare | Anycast-based, strong DDoS/WAF, edge compute (Workers). |
| Amazon CloudFront | Tight integration with S3 as origin, origin shield option, signed URLs/cookies. |
| Fastly | Very fast purges (~150 ms), programmable edge (VCL/Compute). |
| Google Cloud CDN, Azure Front Door | Cloud-native options integrated with their load balancers. |
| Netflix Open Connect, Meta FNA | In-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.
- A CDN caches static, cacheable content close to users — for Instagram, that's all photos, video segments and thumbnails.
- Instagram-style systems use a pull CDN with object storage as origin and an origin shield.
- Use versioned (content-hashed) URLs with long TTLs; use signed URLs for access control.
- Track cache hit ratio — small improvements make huge differences to origin load.
- Keep the API path (personalised JSON) and the media path (CDN) separate.
Related lessons
- DNS — how users get routed to the nearest PoP
- Object Storage — the CDN's origin
- Media Processing — where the cached renditions come from
- Caching — the same ideas (TTL, hit ratio, invalidation) applied inside the data center
- Security — signed URLs, DDoS protection, WAF