When Optimizations Backfire

Spanish audio is available in the player settings
Rate this content
Bookmark

Ever loaded a font from the Google Fonts CDN? Or added the loading=lazy attribute onto an image? These optimizations are recommended all over the web – but, sometimes, they make your app not faster but slower.


In this talk, Ivan will show when some common performance optimizations backfire – and what we need to do to avoid that.

FAQ

A CDN, or Content Delivery Network, is a service that brings your files closer to the user by storing copies of your data in multiple geographical locations. When a user requests data, the request is routed to the closest server, reducing the time it takes for the data to travel, thereby potentially speeding up load times.

While CDNs generally improve site speed by reducing the physical distance between the server and the user, they can also introduce delays if the browser needs to establish a new connection to a different domain where the CDN is hosted. This involves DNS lookups, TCP connections, and TLS handshakes, which can add significant latency.

First Contentful Paint (FCP) is a performance metric that measures the time from when the page starts loading to when any part of the page's content is rendered on the screen. It is crucial because it provides an indication of how quickly a user can see visible content, which affects the perceived speed of the site.

Adding a CDN can increase connection costs if the CDN's domain is different from the origin server's domain. This requires the browser to establish a new connection, involving DNS resolution, TCP connections, and TLS handshakes, each adding additional time before the content can be fetched.

Cache partitioning is a browser security feature that isolates cached files by the website. This means a file cached from one site won't be used by another, even if both request the same file from a CDN. This prevents shared caching benefits across different domains, affecting CDN performance by requiring fresh downloads for each site.

Code splitting is a technique where a web application's codebase is divided into smaller, manageable chunks that are loaded as needed rather than all at once. While it can reduce the initial load time, improper implementation could lead to increased overall load time if additional roundtrips are needed to fetch necessary code chunks after initial execution.

A pull CDN automatically pulls content from the origin server when it is first requested and caches it for subsequent requests, reducing setup complexity. In contrast, a push CDN requires the content to be manually pushed to the CDN's servers, which can be more labor-intensive and potentially lead to configuration errors impacting performance.

Critical CSS and JavaScript, which are essential for rendering the initial view of a page, should be inlined or loaded as soon attached to the initial HTML response. This avoids additional roundtrips for fetching these resources, thus improving the First Contentful Paint time.

Ivan Akulov
Ivan Akulov
26 min
01 Jun, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

The Talk discusses cases where common optimizations can make the app slower instead of faster, highlighting the impact of a CDN implementation on performance. The delay in the CDN connection process caused the first contentful paint to be delayed. Code splitting, while reducing bundle size, resulted in delayed rendering and worsened performance. Lazy loading images can cause performance issues, and image optimization needs to be carefully managed. Link, pre-connect, and pre-load headers can help with connection and loading cascades, but only if files are loaded later.

1. Optimizations Backfire: The CDN Dilemma

Short description:

The talk discusses cases where common optimizations can make the app slower instead of faster. The speaker shares their experience with implementing a CDN to improve the performance of a web app. However, performance tests revealed that the site became slower after adding the CDN. The speaker explains the importance of the lighthouse score and how it is calculated based on different metrics. They highlight that while most metrics remained the same, the First Contentful Paint metric worsened after adding the CDN. The speaker emphasizes the need to analyze the frame-by-frame rendering and network waterfall to understand the impact of optimizations. In this case, the speaker observed that the responses took less time with the CDN, but the First Contentful Paint metric suffered.

So, yeah, the subject of my talk is when optimizations backfire. It's about cases when you achieve some common optimization but it, in turn, makes the app slower, not faster.

So first, let's talk about CDNs. So who here uses a CDN in production? Hm, quite a lot of people. Nice. So one time, a while ago, I was a developer in a big complex web app, and the tab was slow. Slow apps aren't nice, so we had a project to make the app faster, and as part of that project, we decided to shape a CDN.

Now, a CDN is a service that brings your files closer to the user, right? If your server is in the US, and the user is in India with a CDN, the request for the bundle does not need to go all the way back to the US. It can just go to the CDN server close to the user in India. So our server was in the US, and our users were all around the world. So we decided to try this optimization. We configured the buckets to upload built results into, we configured the CDN in front of that, and we pointed all URLs in the app to that CDN server. Basically, our index.html, instead of looking like this, started looking like this, with the CDN origin in front of all the URLs.

So far so good, right? But when we run performance tests, we discover that suddenly, the site became not faster, but slower. Anyone, by the way, has an idea why? Based on the optimizations, based on the change we made, does anyone have an idea why this happens? No hands. Good. Well, good for me. So let's try to investigate this, as if I was investigating it today with the knowledge and the methods I have now.

So what's important to know about the lighthouse score is it's not just an abstract performance score, right? It's calculated based on these five metrics. If one metric gets worse, the whole score gets worse. If one metric gets better, the whole score gets better. There's even a calculator for this. Now, most metrics in these two tests, before adding a CDN and after adding a CDN, stayed more or less the same. Lars' Contentful Paint even got better, which is good, but one metric, First Contentful Paint, got significantly worse. So First Contentful Paint is a metric that measures how quickly the first content renders. It's the time from the moment the site started loading to the moment the site rendered its first content, and it got worse.

So now, whenever I have a site that has better rendering speeds, like First Contentful Paint or Lars' Contentful Paint, what I like to do is I like to look at the frame-by-frame rendering of that site, at the network waterfall of that site, and then compare them to try to figure out what the heck has happened. So in this case, if I compare both versions of this site, one without CDN and one with, I'll notice two big things. The first one is the responses now actually take less time, as intended. With the CDN, these tests were made from Canada, for example, using webpagetest.org, and with the CDN, this error was closer to the users, so the round trip was shorter, so the file took less time to download than without CDN.

2. CDN Connection Delay and First Contentful Paint

Short description:

Despite the files taking longer to download, the first paint happened later with the CDN. The delay was due to the connection process, which consists of DNS resolution, TCP connection, and TLS handshake. By adding a CDN on a separate domain, the CSS files were delayed, causing the first contentful paint to also be delayed. This issue was not initially understood, leading to the abandonment of the CDN optimization. However, the speaker now knows how to avoid this problem.

Second, even despite our files taking longer to download, the first paint actually happened later. You can see that, without the CDN, the first paint happened around the 2.0 second mark. And when we added the CDN, the first paint started happening three seconds mark. And if I try to figure out why it happens, if I look through the part of the waterfall that precedes the first paint, the first paint and try to compare what changed, I will notice this.

Does anyone know what that means? Oh, I can't hear from here, turns out. But, okay. Some people are raising their hand. Oh, okay. Somebody knows. Great. So, this bit of the waterfall, this piece of the waterfall is what beat us back then when we were trying to set up a CDN. And now that I'm working with clients, now that I'm an independent consultant, I see it biting my clients as well.

The issue is whenever we try to load something from a new domain, the browser has to set up a connection to that domain first. And that is surprisingly slow. So the connection process consists of three steps. The first step is DNS resolution. The browser gets the domain name that you have referenced in your HTML or something and looks up its IP address. That ideally takes one round trip. The second step is the TCP connection. Once the browser has the server's IP address, it needs to set up a connection to the server behind that address. That involves one round trip. So one ping to the server and then one response from the server. So if there's a 100 millisecond delay between the client and the server, this is going to take 200 milliseconds. And the third step is the TLS handshake. Once the browser has connected to the server, it needs to encrypt the connection to upgrade HTTP to HTTPS, and this takes two more round trips. So setting up a connection has these three steps and on a typical 4G connection, these steps typically take 500, 600 milliseconds to complete, like in this waterfall.

So in this case, what happened was by adding a CDN, we also accidentally added the connection delay, because the CDN was on a separate domain, and as a result of that, we delayed the CSS files the page uses by 600 milliseconds and because the page can't render without CSS, the first contentful paint also got delayed. So we moved CSS files to the CDN, CSS files got delayed, first contentful paint happened late. Right? So, back then, we actually did not figure out what happened, so we had to ditch the CDN optimization. Today, luckily, I know how to fix this, I know how to avoid this.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
Optimizing HTML5 Games: 10 Years of Learnings
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Optimizing HTML5 Games: 10 Years of Learnings
Top Content
The open source PlayCanvas game engine is built specifically for the browser, incorporating 10 years of learnings about optimization. In this talk, you will discover the secret sauce that enables PlayCanvas to generate games with lightning fast load times and rock solid frame rates.
Power Fixing React Performance Woes
React Advanced Conference 2023React Advanced Conference 2023
22 min
Power Fixing React Performance Woes
Top Content
Next.js and other wrapping React frameworks provide great power in building larger applications. But with great power comes great performance responsibility - and if you don’t pay attention, it’s easy to add multiple seconds of loading penalty on all of your pages. Eek! Let’s walk through a case study of how a few hours of performance debugging improved both load and parse times for the Centered app by several hundred percent each. We’ll learn not just why those performance problems happen, but how to diagnose and fix them. Hooray, performance! ⚡️

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Performance Debugging
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
High-performance Next.js
React Summit 2022React Summit 2022
50 min
High-performance Next.js
Workshop
Michele Riva
Michele Riva
Next.js is a compelling framework that makes many tasks effortless by providing many out-of-the-box solutions. But as soon as our app needs to scale, it is essential to maintain high performance without compromising maintenance and server costs. In this workshop, we will see how to analyze Next.js performances, resources usage, how to scale it, and how to make the right decisions while writing the application architecture.