When Optimizations Backfire

Spanish audio is available in the player settings
Rate this content
Bookmark
The talk examines scenarios where common optimizations can backfire, making apps slower. Adding a CDN to a web app, for instance, can delay the First Contentful Paint due to the connection process involving DNS resolution, TCP connection, and TLS handshake. This delay was highlighted using tools like webpagetest.org. The discussion also covers the importance of avoiding excessive code splitting, which can introduce a waterfall of requests, slowing down rendering. Lazy loading images too aggressively can negatively impact the Largest Contentful Paint. To mitigate such issues, prioritize critical images and avoid using the load and lazy attribute for images above the fold. Using link, pre-connect, and pre-load headers can help, but only if files are loaded later. Implementing a pull CDN for the whole origin and handling critical CSS and JavaScript properly are essential for optimizing performance.

From Author:

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.

This talk has been presented at JSNation 2023, check out the latest edition of this JavaScript Conference.

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 Transcription

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
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize 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
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
Watch video: React Concurrency, Explained
React 18's concurrent rendering, specifically the useTransition hook, optimizes app performance by allowing non-urgent updates to be processed without freezing the UI. However, there are drawbacks such as longer processing time for non-urgent updates and increased CPU usage. The useTransition hook works similarly to throttling or bouncing, making it useful for addressing performance issues caused by multiple small components. Libraries like React Query may require the use of alternative APIs to handle urgent and non-urgent updates effectively.
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Today's Talk discusses the future of performance tooling, focusing on user-centric, actionable, and contextual approaches. The introduction highlights Adi Osmani's expertise in performance tools and his passion for DevTools features. The Talk explores the integration of user flows into DevTools and Lighthouse, enabling performance measurement and optimization. It also showcases the import/export feature for user flows and the collaboration potential with Lighthouse. The Talk further delves into the use of flows with other tools like web page test and Cypress, offering cross-browser testing capabilities. The actionable aspect emphasizes the importance of metrics like Interaction to Next Paint and Total Blocking Time, as well as the improvements in Lighthouse and performance debugging tools. Lastly, the Talk emphasizes the iterative nature of performance improvement and the user-centric, actionable, and contextual future of performance tooling.
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
PlayCanvas is an open-source game engine used by game developers worldwide. Optimization is crucial for HTML5 games, focusing on load times and frame rate. Texture and mesh optimization can significantly reduce download sizes. GLTF and GLB formats offer smaller file sizes and faster parsing times. Compressing game resources and using efficient file formats can improve load times. Framerate optimization and resolution scaling are important for better performance. Managing draw calls and using batching techniques can optimize performance. Browser DevTools, such as Chrome and Firefox, are useful for debugging and profiling. Detecting device performance and optimizing based on specific devices can improve game performance. Apple is making progress with WebGPU implementation. HTML5 games can be shipped to the App Store using Cordova.
Power Fixing React Performance Woes
React Advanced Conference 2023React Advanced Conference 2023
22 min
Power Fixing React Performance Woes
Top Content
Watch video: Power Fixing React Performance Woes
This Talk discusses various strategies to improve React performance, including lazy loading iframes, analyzing and optimizing bundles, fixing barrel exports and tree shaking, removing dead code, and caching expensive computations. The speaker shares their experience in identifying and addressing performance issues in a real-world application. They also highlight the importance of regularly auditing webpack and bundle analyzers, using tools like Knip to find unused code, and contributing improvements to open source libraries.

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 🤐)
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.
Maximize App Performance by Optimizing Web Fonts
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
Lazar Nikolov
Lazar Nikolov
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion