Skip to content

Content Delivery Network (CDN)

What it is

A CDN is a globally distributed network of proxy servers that serves content from locations closer to the user. Typically used for static files (HTML/CSS/JS, photos, videos); some CDNs (e.g., Amazon CloudFront) also support dynamic content. The site's DNS resolution tells clients which CDN server to contact.

Why it improves performance

  1. Users receive content from data centers close to them.
  2. Your origin servers don't have to serve the requests the CDN fulfills.

Two models

Push CDNs

  • Receive new content whenever changes occur on your server.
  • You upload content directly to the CDN and rewrite URLs to point to it.
  • You control when content expires and updates.
  • Content is uploaded only when new/changed → minimizes traffic, maximizes storage.
  • Best for: low-traffic sites, or content that rarely changes.

Pull CDNs

  • Grab new content from your server when the first user requests it.
  • Content stays on your server; you rewrite URLs to point to the CDN.
  • First request is slower until content is cached.
  • TTL determines how long content is cached.
  • Minimizes storage on the CDN, but can cause redundant traffic if files expire and are re-pulled before they actually change.

  • Best for: heavy-traffic sites (spreads load, keeps only recently-requested content).

Push vs Pull at a glance

Push CDN Pull CDN
Who uploads content You (on change) CDN (on first request)
Storage usage High Low
Traffic Minimal Potential redundancy
Best for Low traffic / rare updates High traffic

Disadvantages of CDNs

  • Cost can be significant depending on traffic (weigh against the cost of not using one).

  • Content can be stale if updated before TTL expires.

  • Requires changing URLs for static content to point to the CDN.

Key takeaways

  • A CDN is essentially a geographically distributed cache.
  • It reduces both latency (proximity) and origin load (offload).
  • Push vs pull is a storage-vs-traffic trade-off.

Common Interview Questions

Design a content delivery network (CDN) like Cloudflare

Why it's asked here: this is the direct CDN question.

Key points to discuss:

  • Push vs pull model and which fits the workload.
  • Edge PoPs, the origin server, and cache eviction (LRU) plus TTL.
  • How DNS routes users to the nearest PoP (anycast).
  • Cache invalidation and stale-content trade-offs.
flowchart LR
    U[User] --> E[Edge POP]
    E -->|cache hit| U
    E -->|cache miss| O[Origin server]
    O --> E
Design a photo-sharing system like Instagram

Why it's asked here: media delivery is a textbook CDN use case.

Key points to discuss:

  • Store originals in object storage (S3) and serve via CDN.
  • Generate multiple resolutions; serve the right size at the edge.
  • Push uploads to the CDN vs pull on first request.
  • Separate the metadata (DB) path from the media (CDN) path.
flowchart LR
    U[User] --> A[App server]
    A -->|upload| S3[(Object storage)]
    A --> DB[(Metadata DB)]
    U --> CDN[CDN]
    CDN --> S3

Further reading


Design a Video Streaming Service like YouTube

A video streaming service has two main paths: an upload/ingest path and a playback/delivery path. The upload path accepts raw video from creators and is write-heavy only in comparison with ordinary user uploads; playback is massively read-heavy and dominated by streaming video bytes. For planning, assume 500 million daily active users, 5 billion video views per day, and about 200,000 uploads per day. At 5 billion views per day, the average playback request rate is roughly 58,000 views per second, and popular videos can create much larger local spikes. The data volume is dominated by video files, not metadata: a single two-minute 1080p video might be 200 MB raw, and generating multiple renditions and segments can double or triple the stored bytes. The architecture must therefore optimize for cheap, horizontally scalable object storage and aggressive CDN offload while keeping metadata small and indexed for search and playback.

The high-level architecture separates upload, processing, metadata, and delivery. Clients upload through a stateless API tier behind a load balancer; the gateway authenticates the user and validates the file. The raw video is written directly or through a resumable upload protocol to object storage. After upload, a job is placed on a message or task queue. A pool of transcoding workers consumes the job, splits the video into short segments, and produces multiple renditions at different resolutions and bitrates, such as 240p, 360p, 720p, 1080p, and sometimes 4K. The transcoded segments and playlists or manifests, usually HLS or MPEG-DASH, are written back to object storage. The metadata service stores a video record with title, description, owner, visibility, status, and the locations of the renditions. For playback, the client requests the manifest from the API or directly from a CDN, selects the appropriate rendition based on current bandwidth, and fetches segments through a CDN edge node, which caches hot segments near users.

The key data model has a relational core for users, videos, channels, comments, likes, and subscriptions because these are structured and require indexing and transactional updates. The video binary segments and manifests should not go into the relational database; they belong in object storage such as S3 or GCS because object storage is designed for large immutable objects and cheap scale. A video metadata row might contain video_id, owner_id, title, description, status, duration, thumbnail_location, and manifest_location. Rendition records or a JSON document map a rendition to its codec, resolution, bitrate, and segment path prefix. View counts, search suggestions, and session state can use NoSQL or Redis-style stores because they are high-volume and can tolerate eventual consistency.

The core mechanism is the video processing and adaptive-bitrate delivery pipeline. After ingest, the transcoding workers decode the original video and re-encode it into multiple renditions using codecs such as H.264, VP9, or AV1. Each rendition is split into short media segments, usually a few seconds long, and a manifest lists the segments for each bitrate. During playback, the client measures available bandwidth and switches between renditions between segments, avoiding buffering when the network degrades and using higher quality when the network improves. This is more important than simply serving one high-bitrate file because real users have variable connections and device sizes. The CDN caches the manifests and segments; popular videos are served almost entirely from edge nodes instead of the origin.

For scaling and availability, every service tier should be stateless behind a load balancer so it can scale horizontally. The transcoding pipeline is asynchronous, so uploads do not block on the expensive encode step, and failed jobs can be retried without losing the source video. Object storage is replicated across availability zones and, for very popular catalogs, copied to multiple regions. The CDN provides both availability and capacity by absorbing the heavy read load and degrading gracefully if an edge node fails. Metadata databases are sharded, typically by user or video id, and replicated with read replicas because the playback path is read-dominant. Caches hold hot metadata, manifests, search results, and session data. Views and analytics are sent through an async queue and processed later, avoiding synchronous updates to the video record on every play.

The main trade-offs are cost versus quality and freshness versus scalability. Storing and converting many renditions improves playback quality and compatibility but increases storage, compute, and egress cost. Caching video in the CDN reduces origin load dramatically but makes cache invalidation and replacement harder, especially after a creator edits a video or removes it. Serving metadata strongly is feasible because it is small and transactional, while view counts and analytics should be eventually consistent because they are high-volume and do not need to be exact on every read. Finally, multi-region replication improves latency and availability but adds storage and cross-region bandwidth cost, so most services replicate only metadata and hot videos while leaving long-tail videos in a smaller number of regions.

flowchart LR
    U[Creator uploads video] --> API[Upload API / Gateway]
    API --> OS[(Object Storage)]
    API --> Q[Transcoding Queue]
    Q --> W[Transcoding Workers]
    W --> OS[(Object Storage)]
    OS --> CDN[CDN Edge Nodes]
    P[Viewer] --> CDN
    P --> M[Metadata Service]
    M --> DB[(Sharded SQL Metadata DB)]
    P --> C[(Redis Cache)]
    DB --> C
    CDN -.-> OS

Full Design: CDN like Cloudflare

To design a CDN like Cloudflare, start with workload and scale. Assume the CDN serves 10 million requests per second at peak, with a 95% cache-hit ratio, 100 Tbps of edge egress, 200 points of presence, and 1 PB of hot cacheable content at the edge. The functional requirements are to deliver cached web content to users from a nearby location, fetch an object from the customer origin on a cache miss, and support cache invalidation. The non-functional requirements are low global latency, high availability, horizontal scalability, and protection from flash crowds and DDoS attacks.

The high-level architecture has a global control plane and many edge points of presence. Each edge site exposes one or more anycast IPs, and BGP routing together with DNS steering sends a client request to the nearest healthy edge. Inside an edge site, a layer-4 or layer-7 load balancer forwards the request to a cache node. The cache node checks the request against its local store using a normalized URL or customer-defined cache key. On a hit, it returns the object directly. On a miss, it selects a parent tier or the customer origin, fetches the object, stores it according to cache policy, and then responds. A separate control plane distributes zone configurations, certificates, cache rules, purge commands, and health status to the edge nodes.

The data model is about content objects rather than relational records. Cache keys are derived from the request URL, request headers, or a customer-defined key. Cache metadata such as TTL, object location, and cache-control directives lives at the edge and may be coordinated through a fast distributed key-value store. The source of truth is the customer origin, which can be an origin web server or object storage. A relational database is generally not used on the hot edge path because CDN operations are key-value lookups and content retrieval, not multi-row SQL queries.

The core mechanism is pull-through caching combined with anycast-based global routing. Anycast routing selects a low-latency edge for the user. Inside the edge, the cache uses key lookup, TTL expiration, and eviction such as LRU to decide whether an object is fresh. If the object is absent or stale, the edge performs a cache fill from the origin or from a parent cache tier. This offloads most repeated traffic from the origin and reduces latency. Purging and invalidation are handled through the control plane, which pushes invalidation commands to edges or relies on short TTLs so changed content propagates without remaining stale for too long.

For scaling and availability, the CDN grows by adding edge sites and cache nodes instead of enlarging one central location. Anycast allows traffic to route around a failed edge, although failover is not always instant because BGP and DNS changes take time to converge. Inside each edge, load balancers and many stateless cache nodes support horizontal scaling. Cache nodes can be partitioned by content or hashed by cache key to prevent hot spots. A tiered cache architecture places parent cache servers between many edge nodes and the origin so the origin is not overwhelmed by concurrent cache misses. The control plane is replicated, and edge nodes continue serving cached content during temporary control-plane failures.

The main trade-offs are freshness versus efficiency, push versus pull, and cost versus latency. A pull CDN caches only content that users request, which saves storage but makes the first request slower. A push CDN preloads content, which improves first-byte time and consistency but wastes storage and bandwidth for rarely requested objects. Longer TTLs reduce origin load and improve cache hit ratio, but they can serve stale content longer. Shorter TTLs improve freshness but increase origin traffic. Anycast routing is simple and fast, but route convergence and DNS caching mean failover is not always immediate. Security features such as DDoS absorption and TLS termination add value but increase edge compute and operational complexity.

flowchart LR
    U[User] --> R[Recursive Resolver]
    R --> A[Anycast DNS / BGP]
    A --> P1[Edge PoP 1]
    A --> P2[Edge PoP 2]
    U --> P1
    P1 --> C1[(Cache Node)]
    P1 --> C2[(Cache Node)]
    C1 -->|hit| U
    C1 -->|miss| O[Customer Origin / Object Storage]
    O --> C1
    O --> C2
    CP[Control Plane] --> C1
    CP --> C2
    CP --> O

Design a Content Delivery Network (CDN) like Cloudflare

To size a Cloudflare-like CDN, assume it must serve 10 million HTTP requests per second at peak, with a hot working set of about 5 PB spread across 300 edge points of presence. The functional requirements are to accept a customer origin configuration, resolve the customer domain to an edge node, serve cached objects, fetch and cache misses from the origin, and support cache invalidation and purge. The non-functional requirements are low user latency, high availability even when individual edge nodes fail, very high read throughput, and eventual consistency that is acceptable for cached static and semi-dynamic content.

The high-level architecture uses DNS and anycast to route a user request to the nearest edge point of presence, or PoP. A domain owner delegates DNS through a CNAME to the CDN, whose authoritative DNS returns an anycast IP shared by many PoPs. At the PoP, an edge proxy terminates TLS and applies customer rules such as URL rewriting, redirects, Web Application Firewall rules, and header injection. It first checks a local high-speed cache. On a cache hit, it returns the object directly. On a miss, it selects an origin or an intermediate cache shard, fetches the object, stores it according to cache policy, and returns it. A separate control plane manages customer configuration, TLS certificates, purge commands, and health checks.

The data model is centered on cached entities and control-plane metadata rather than a single relational schema. Cached objects are stored in edge caches keyed by a cache key, which usually combines host, URL, request method, and normalized headers or cookies that affect the response. The cached value includes the response body, headers, status, TTL, and freshness metadata. The control plane stores origin mappings, TLS certificates, WAF rules, cache policies, and purge tokens in a globally replicated configuration store. Edge nodes consume this configuration asynchronously, so the request path does not query the configuration database directly.

The core mechanism is cache lookup and replacement. On each request, an edge node hashes the cache key and consults a local multi-tier cache built from memory and disk. If the object is fresh, the edge returns it. If the object is stale, the edge revalidates with the origin using conditional requests such as ETag or If-Modified-Since. If the object is missing, the edge fetches it, optionally rewrites internal links, and inserts it. Objects are removed by TTL, LRU eviction, or explicit purge. A pull model is common because it lets the CDN cache only what users actually request, while a push model is better for low-traffic content that must exist at the edge before the first request. Purge and invalidation commands travel through the control plane to all edge nodes so updated or deleted assets do not remain visible.

Scaling and availability come from horizontal edge expansion, anycast, tiered caching, and per-PoP redundancy. Anycast lets many geographically separate PoPs share one IP, so when a PoP fails routing shifts traffic to another PoP without a DNS change. Inside each PoP, multiple edge servers share requests through a local load balancer, and health checks remove failed machines. Tiered caching inserts an intermediate cache layer between the edge and the origin, so many edge misses collapse into fewer origin fetches and the origin is protected from flash crowds. Origin shield nodes and replicated control-plane metadata prevent a single failed server or control-plane region from taking down the CDN. Cache purges are eventually consistent, so a purge can leave stale content on some edge nodes for a short time, which is usually acceptable for static content.

The important trade-offs are freshness versus cache hit ratio, push versus pull, and cost versus proximity. Long TTLs reduce origin load and improve latency but make content harder to update. Short TTLs improve freshness but reduce the hit ratio. Purge-based invalidation solves correctness quickly but cannot guarantee instant global consistency across hundreds of PoPs. Pull CDNs minimize storage and suit long-tail content, while push CDNs provide first-byte freshness at higher storage and upload cost. Adding edge PoPs improves latency but increases infrastructure and operational cost, so regional placement and tiered caching are decisions about cost, capacity, and failover behavior.

flowchart LR
    U[User] --> DNS[Authoritative DNS]
    DNS -->|anycast / geo| P1[Edge PoP 1]
    DNS -->|anycast / geo| P2[Edge PoP 2]
    P1 --> L1[Local LB]
    P2 --> L2[Local LB]
    L1 --> E1[Edge cache server]
    L2 --> E2[Edge cache server]
    E1 -->|miss / revalidate| T1[Tiered cache / origin shield]
    E2 -->|miss / revalidate| T1
    T1 --> O[Customer origin]
    CP[Control plane] --> P1
    CP --> P2

Design a Photo-Sharing System like Instagram

To size the system, assume 500 million monthly active users, 100 million new photos per day, and a read-to-write ratio around 10:1. Average uploads are roughly 1,200 photos per second, with reads around 10,000 to 20,000 per second at peak. A typical original photo averages 200 KB, but the system stores multiple thumbnails per photo, so media storage grows by several petabytes per year. Functional requirements include user accounts, photo upload, captions, likes, comments, following, and a home feed. Non-functional requirements are low latency for feed and image delivery, high durability for user-generated media, high availability, and horizontal scalability.

The high-level architecture separates the media path from the metadata path. Clients upload through stateless application servers behind a load balancer. The application server authenticates the request and writes the original image to object storage such as S3. It then enqueues an image-processing job and returns quickly, so users do not wait for resizing. A worker pool consumes the job, generates multiple resolution variants such as thumbnail, medium, and high, and writes those variants back to object storage. Clients fetch images from a CDN, which caches from object storage and serves the right resolution based on device and connection. Metadata operations such as follows, likes, comments, and feed reads go through the application tier to a relational database and a Redis cache. This split keeps large binary media off the application and database tiers.

The data model uses several storage types. User accounts, photo records, follows, likes, and comments are relational because they need indexes, uniqueness, and transactional consistency. A photo record stores photo_id, user_id, caption, created_at, object_storage_key, thumbnail_keys, and status. The actual image bytes are not stored in the database; they live in object storage because object storage is cheap, durable, replicated, and designed for large immutable objects. The social graph may be represented by a follows table in SQL or a graph store, depending on how much traversal is needed. Feed caches and photo metadata caches use Redis because they are read-heavy, hot, and can tolerate eventual consistency. If feed history volumes are very high, a NoSQL store such as Cassandra can store precomputed feed entries by user.

The core mechanism is asynchronous image processing combined with feed fan-out. After upload, the original image is safely stored, and image-processing workers produce several sizes, apply filters or compression, and write the variants back to object storage. For the home feed, the system chooses between write-time fan-out and read-time fan-out. For ordinary users, posting a photo inserts a reference into the timeline cache of each follower so the home feed assembles quickly. For very popular accounts, write-time fan-out to millions of followers is too expensive, so the system merges the celebrity's recent posts into followers' feeds at read time. Likes and comments are stored individually and counted asynchronously so they do not slow down photo browsing.

Scaling and availability come from stateless horizontal scaling and replication. The application tier is stateless behind a load balancer, so it can scale out by adding instances. The relational database is sharded by user ID or photo ID to spread write load, with read replicas for read-heavy queries. Redis is sharded and replicated for feed and metadata caches. Image-processing workers are stateless and can scale by adding more consumers to the job queue. Object storage is highly durable and replicated across availability zones, while the CDN absorbs most media read traffic and reduces origin load. Failure handling is layered: a failed app server is removed from rotation, a failed worker redrives its job, a failed database primary fails over to a replica, and a failed cache node is replaced by its replica.

The main trade-offs are fan-out strategy, consistency, and cost. Fan-out on write makes timeline reads very fast but is expensive and creates huge write bursts for popular accounts, which is why a hybrid fan-out is used. Feed and like counts are often eventually consistent to reduce write overhead, while photo ownership and comments are kept strongly consistent because they are central to the user experience. CDN caching makes image reads cheap and low-latency but introduces staleness after updates or deletes unless the system uses invalidation or versioned URLs. Storing many image copies improves performance for different devices but increases storage and processing cost. Finally, separating metadata from media increases complexity because the two systems must stay consistent through asynchronous updates and retries.

flowchart LR
    U[Client] --> LB[Load Balancer]
    LB --> A[Stateless App Servers]
    A --> D[(Sharded SQL Metadata DB)]
    A --> C[(Redis Feed and Profile Cache)]
    A --> Q[Image Processing Queue]
    Q --> W[Image Processor Workers]
    A -->|store original| S3[(Object Storage)]
    W -->|store thumbnails| S3
    U --> CDN[CDN]
    CDN --> S3
    A --> CDN