[Do] not use CDN

Almost every article or tool for website speed optimization includes a modest section that says 'use CDN'. In general, CDN stands for content delivery network. At 'Method Lab', we often encounter questions from clients about this topic, with some even enabling CDN on their own. The purpose of this article is to clarify what CDN can provide in terms of website loading speed, what problems may arise, and in which situations the use of CDN is justified.

[Do] not use CDN

The delays circled in the image are caused by the use of CDN.

A Bit of History

Like many technologies, CDN emerged out of necessity. As internet channels developed for users, online video services began to appear. Naturally, video content requires significantly more bandwidth than regular website content (images, text, and CSS or JS code).

When attempting to stream a video feed to multiple clients from a single server, the bottleneck is likely to be the server's internet channel. Typically, just a few thousand streams can saturate a typical server channel. Of course, there may be other resource limitations, but they are not important at this moment. It's also essential to note that expanding the server channel is usually too expensive (and sometimes impossible), as well as impractical. The load on the channel during broadcasts will have a cyclical nature.

The issue of bandwidth limitation for a single server is excellently addressed by CDN. Clients connect not directly to the server, but to the nodes of the CDN network. Ideally, the server sends one stream to the CDN node, and thereafter the network utilizes its own resources to deliver this stream to numerous users. From an economic standpoint, we only pay for the resources actually consumed (which may be bandwidth or traffic) and achieve excellent scalability for our service. Using CDN for delivering heavy content is entirely justified and logical. However, it's worth noting that the largest players in this field (such as Netflix) build their own CDNs rather than using large commercial CDNs (Akamai, Cloudflare, Fastly, etc.).

As the web has evolved, web applications themselves have become more complex and heavier. The issue of loading speed has come to the forefront. Site speed enthusiasts quickly identified several main problems that lead to slow website loading. One of these is network latency (RTT β€” round trip time or ping time). Latencies affect many processes in loading a website: establishing a TCP connection, starting a TLS session, loading each individual resource (image, JS file, HTML document, etc.).

The problem was exacerbated by the fact that when using the HTTP/1.1 protocol (the only option before the advent of SPDY, QUIC, and HTTP/2), browsers open no more than 6 TCP connections to a single host. All of this led to idle connections and inefficient use of bandwidth. The issue was partly resolved by domain sharding – creating additional hosts to overcome connection limits.

Here comes the second capability of CDNs – reducing latencies (RTT) due to the large number of points and the proximity of nodes to the user. Distance plays a crucial role here: the speed of light is limited (about 200,000 km/s in fiber optics). This means that every 1000 km adds 5 ms of delay or 10 ms to RTT. These are the minimum time costs for transmission, as there are additional delays on intermediate equipment. Since CDNs can typically cache objects on their servers, we can benefit from loading such objects through the CDN. The necessary conditions for this are: the object being in the cache and the proximity of the CDN point to the user compared to the web application server (origin server). It is important to understand that geographic proximity of the CDN node does not guarantee low latencies. The routing between the client and the CDN can be arranged in such a way that the client connects to a host in another country, or even on another continent. This is where the relationships between telecom operators and the CDN service come into play (peering, presence of interconnections, participation in IX, etc.) along with the traffic routing policy of the CDN itself. For example, Cloudflare, when using the two initial plans (free and low-cost), does not guarantee content delivery from the nearest node – the host selection will be made to achieve the lowest cost.

Many leading internet companies draw public interest (from web developers and service owners) to the topic of website loading speed and performance. Among these companies are Yahoo (via the Yslow tool), AOL (WebPageTest), and Google (the Page Speed Insights service), which develop their recommendations for speeding up websites (primarily focused on client-side optimization). Later on, new speed testing tools emerge, also providing advice on increasing website speed. Each of these services or plugins consistently recommends, "Use a CDN." The typical explanation for the benefits of a CDN is reduced network latency. Unfortunately, not everyone is prepared to understand how exactly the acceleration effect of a CDN is achieved and how it can be measured, leading many to accept the recommendation at face value as a postulate. In reality, not all CDNs are equally beneficial.

Using a CDN Today

To assess the usefulness of CDNs, they need to be categorized. What we can currently see in practice (the examples in parentheses, of course, are not exhaustive):

  1. Free CDNs for distributing JS libraries (MaxCDN, Google, Yandex).
  2. CDNs for client-side optimization services (for example, Google Fonts for fonts, Cloudinary, Cloudimage for images).
  3. CDNs for static content and resource optimization in CMS (available in Bitrix, WordPress, and others).
  4. General-purpose CDNs (StackPath, CDNVideo, NGENIX, MegaFon).
  5. CDNs for speeding up websites (Cloudflare, Imperva, Airy).

The key difference between these types lies in the following: which part of the traffic passes through the CDN. Types 1-3 involve delivering only part of the content: from a single request to several dozen (usually images). Types 4 and 5 imply full traffic proxying through the CDN.

In practice, this refers to the number of connections used to load the website. When using HTTP/2, we utilize a single TCP connection to the host to handle any number of requests. If we separate resources between the primary host (origin) and the CDN, we need to distribute requests across multiple domains and create several TCP connections. In the worst-case scenario, this results in: DNS (1 RTT) + TCP (1 RTT) + TLS (2-3 RTT) = 6-7 RTT. This formula does not account for delays in mobile networks for activating the device's radio channel (if it was inactive) and delays at the cell tower.

Here is how it looks on the website loading waterfall (delays for CDN connections highlighted at RTT 150 ms):

[Do] not use CDN

If the CDN covers all website traffic (except external services), we can use a single TCP connection, saving on delays when connecting to additional hosts. Of course, this applies to HTTP/2 connections.

Further differences are defined by the functionality of a specific CDN – for the first type, it's just a hosting static file, while for the fifth, it involves changing several types of website content for optimization.

CDN Capabilities for Accelerating the Website

Let's describe the full range of CDN capabilities for speeding up websites, without regard for the functionality of specific types of CDNs, and then see what is implemented in each of them.

1. Compression of Text Resources

The most basic and straightforward capability; however, it is often poorly implemented. All CDNs declare compression as a feature for speeding up, but if you look closer, shortcomings become apparent:

  • low levels of dynamic compression may be used – 5-6 (for gzip, the maximum is 9);
  • in static compression (files in cache), additional capabilities (such as zopfi or brotli at level 11) are not utilized.
  • there is no support for effective brotli compression (savings of about 20% compared to gzip).

If you are using a CDN, it’s worth checking these few points: take a file received from the CDN, record its size in compressed form, and recompress it manually for comparison (you can use an online service that supports brotli, such as Π²ΡΡ‘ΡΠΆΠ°Ρ‚ΡŒ.Ρ€Ρ„).

2. Setting Client Caching Headers

Also a simple speed-up feature: set headers for client (browser) content caching. The most relevant header is cache-control, and the outdated one is expires. Etag may also be used. The main thing is that the max-age for cache-control is sufficiently large (a month or more), and if you are ready to cache the resource very strictly, the immutable option can be added.

CDNs can reduce the max-age value, forcing users to reload static content more frequently. It's unclear whether this is an attempt to increase traffic or to enhance compatibility with sites that cannot clear caches. For instance, the default caching time in Cloudflare headers is 1 hour, which is quite low for immutable static content.

3. Image Optimization

Since CDNs handle caching and delivering images, it makes sense to optimize them on the CDN side and serve them in this form to users. This feature is only available for CDN types 2, 3, and 5.

Images can be optimized in various ways: using advanced compression formats (such as WebP), more efficient encoders (MozJPEG), or simply removing unnecessary metadata.

In general, there are two types of such optimizations: lossy and lossless. CDNs typically aim for lossless optimization to avoid potential customer complaints about changes in image quality. In such cases, the improvements will be minimal. In reality, the quality level of JPEG often exceeds what is necessary, allowing for recompression at a lower quality level without sacrificing user perception. However, it is challenging to set a universal quality level and settings for all possible web applications, so CDNs use more conservative settings compared to those that could be applied considering the context (image purpose, type of web application, etc.).

4. TLS Connection Optimization

Most traffic is now transmitted over TLS connections, meaning we are spending additional time on TLS handshake. Recently, new technologies have been developed to speed up this process. For example, these include EC cryptography, TLS 1.3, session cache and session tickets, hardware encryption acceleration (AES-NI), and more. Proper TLS configuration can reduce connection time to 0-1 RTT (excluding DNS and TCP).

With modern software in place, implementing such practices on one's own infrastructure is not difficult.

Not all CDNs implement the best practices for TLS. This can be verified by measuring the time of the TLS connection (for example, in Webpagetest). Ideally, for a new connection, it's 1RTT; 2RTT is an average level; 3RTT or more is poor.

It is also important to note that even when using TLS at the CDN level, the server with our web application must also handle TLS from the CDN's side, because the traffic between the server and the CDN passes through a public network. In the worst case, we could experience double delays for the TLS connection (the first to the CDN host and the second between it and our server).

For certain applications, it is worth paying attention to security issues: usually, traffic is decrypted at the CDN nodes, which poses a potential risk for traffic interception. A way to operate without disclosing traffic is typically offered in premium plans for an additional fee.

5. Reducing Connection Latency

The main advantage of CDNs that everyone talks about: low latency (shorter distance) between the CDN host and the user. This is achieved by creating a geographically distributed network architecture where hosts are located at user concentration points (cities, traffic exchange points, etc.).

In practice, priorities for different networks may exist in specific regions. For example, Russian CDNs will have more points of presence in Russia. American ones will primarily develop their networks in the USA. For instance, one of the largest CDNs, Cloudflare, has only two points in Russia β€” Moscow and Saint Petersburg. This means we can save about 10 ms of latency compared to direct hosting in Moscow.

Most Western CDNs do not have any points in Russia. By connecting to them, you may only increase latencies for your Russian audience.

6. Content Optimization (Minification, Structural Changes)

This is the most complex and technical point. Changing content upon delivery can be very risky. Even with minification: reducing the source code (by eliminating unnecessary spaces, irrelevant constructs, etc.) can affect its functionality. When it comes to more serious changes β€” moving JS code to the end of HTML, merging files, and similar actions β€” the risk of disrupting the site's functionality is even higher.

Therefore, only a few type 5 CDNs handle this. Of course, it's impossible to automate all the necessary changes for acceleration – manual analysis and optimization are required. For example, removing unused or duplicate code falls into the category of manual tasks.

As a rule, all such optimizations are controlled by settings and the most dangerous ones are disabled by default.

Support for acceleration features by types of CDN

So, let's take a look at what potential acceleration features different types of CDNs offer.

For convenience, let's summarize the classification.

  1. Free CDNs for distributing JS libraries (MaxCDN, Google, Yandex).
  2. CDNs for client-side optimization services (for example, Google Fonts for fonts, Cloudinary, Cloudimage for images).
  3. CDNs for static content and resource optimization in CMS (available in Bitrix, WordPress, and others).
  4. General-purpose CDNs (StackPath, CDNVideo, NGENIX, MegaFon).
  5. CDNs for speeding up websites (Cloudflare, Imperva, Airy).

Now let's match the features with the types of CDN.

Possibility of
Type 1
Type 2
Type 3
Type 4
Type 5

Text compression
+–
–
+–
+–
+

Cache headers
+
+
+
+
+

Images
–
+–
+–
–
+

TLS
–
–
–
+–
+

Delays
–
–
–
+
+

Content
–
–
–
–
+

In this table, '+' indicates full support, '–' indicates absence, and '+–' indicates partial support. Of course, deviations from this table may occur in reality (for instance, some general-purpose CDN may implement image optimization features), but it is useful for a general understanding.

Summary

I hope that after reading this article you will have a clearer picture regarding the recommendation to 'use CDNs' for accelerating websites.

As in any case, one should not trust the marketing promises of any service. The effect needs to be measured and verified under real conditions. If you're already using a CDN, check its effectiveness against the criteria described in the article.

It's possible that using a CDN right now is slowing down your website.

As a general recommendation, you might consider the following: study your audience and determine their geographical boundaries. If your main audience is concentrated within a radius of 1-2 thousand kilometers, you don't need a CDN for its primary purpose – reducing delays. Instead, you can place your server closer to the users and configure it accordingly, obtaining most of the optimizations described in this article (for free and continuously).

If your audience is truly geographically distributed (more than 3000 kilometers), using a quality CDN will indeed be beneficial. However, it is essential to understand in advance what exactly your CDN can accelerate (see the capabilities table and its description). Speeding up the website remains a complex task that cannot be resolved solely by connecting a CDN. In addition to the mentioned optimizations, the most effective acceleration methods outside of a CDN include server-side optimization, advanced client-side changes (removing unused code, optimizing the rendering process, working with content, fonts, responsiveness, etc.).

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers πŸ”₯ Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster