Search code examples
performancehttptcpcdnkeep-alive

Which is better regarding performance; keep-alive or CDN


Which is better in performance? keep-alive connection to get resources from same server, or getting resources from public CDN.

Edit 1:

  • I mean by performance = the page loading time
  • I am comparing between these 2 scenarios to find which is faster in page loading:

    1- If I serve HTML & javascript from one (my) server. That will benefit from connection keep-alive which will reduce the multiple TCP / TLS handshakes to different servers.

    2- If I use CDN for javascript files, that will benefit from CDN advantages, but also it will require multiple TCP connections to different servers for handshake.

Edit 2:

Please see below images from book "High Performance Browser Networking" authored by "ILYA GRIGORIK"

The next 2 images explain request for HTML from my server and CSS from another server. Keep alive will not be advantage here as 2 requests are needed from different servers which will add more time for TCP handshakes and slow start.

HTTP Request for HTML on my server Another request for CSS on CDN

This below picture is for serving HTML and CSS from the same server using keep alive

HTML & CSS request from same server using CDN

By comparing both loading times:

1- My server + CDN = 284 ms

2- Only my server + keep alive = 228 ms

The difference between both is the 56ms required for TCP handshake to CDN server.

Additionally, if I added pipelining request to a single server, it will increase page speed to be 172 ms.


Solution

  • The best is to do keep-alive with CDN.

    These are orthogonal things:

    • keep-alive is a feature of HTTP 1.1 to reduce protocol overhead,
    • CDN reduces the distance to the server and increases bandwidth.

    The goal of both is to reduce latency. Keep-alive should simply always be on. Most modern HTTP servers support it.

    Though for static content CDN will usually provide much more noticeable performance improvement. It will still use keep-alive, just with a CDN server.

    If I use CDN for javascript files ... it will require multiple TCP connections to different servers

    Even if you serve everything from your own server, most browsers open 2-4 connections simultaneously. So it doesn't matter much if you serve HTML from one server and JS from another.

    Also, most CDN's choose the server once (using DNS), and then your client communicates with the same server. So one server for HTML and one for JS at the most. Or you can choose to proxy everything, also dynamic HTML, through CDN.