Using CDN for Assets Hosting

In general a web application consists of 2 types of assets — Static & Dynamic. Static assets doesn’t change very often — logos, banner images, javascripts, stylesheets and other rich media contents such as audio, video can be considered as static assets. On the other hand dynamic assets can be the contents which uploaded by its users or other systems on-the-fly.

In general most web applications uses the local file system or Network Attached Storage (NAS) as the asset storage. Here is an example of a website using local file storage to host the assets.

In the example we have a web page located at http://domain.com/index.html with 2 images, a stylesheet and a javascript.

When a request is made to access the index.html, the web browser receives the response and parses the HTML, a DOM tree is built out of the HTML. However new requests are made to the web server for each new resource that is found in the HTML source (typically for all images, style sheets, and JavaScript files) — So as per this example there will be 5 requests to the web server.

List of HTTP requests from users browser to server

  1. http://domain.com/index.html
  2. http://domain.com/assets/logo.jpg
  3. http://domain.com/assets/banner.jpg
  4. http://domain.com/assets/stylesheet.css
  5. http://domain.com/assets/javascript.js

The above approach works and there is nothing wrong about it, but this is not optimal.

Here is why — Consider a situation domain.com is a high traffic website. Higher the traffic the more is going to cost as you will need to scale up the servers to meet the demand. What if we move the assets to an external CDN? as per above example out of those 5 HTTP requests only 1 request will reach the nginx server — and all the other assets will be served from external CDN, saving the bandwidth, computing resources like CPU, RAM on the primary web server(s).

Another example is — If your apps are deployed on a load balanced environment with multiple web server instances, you will need to keep each instance up to date with static contents and things will be even messy with dynamic contents as you need to either copy the assets to all the nodes or use a shared storage. But with a CDN in place you will need to copy them into one place — your CDN.

That’s some theory inedeed — In my next post on CDN I’ll try and compare these two approaches and see if this really works — in terms of improved performances as well as cost savings.