<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[DriveTribe Engineering - Medium]]></title>
        <description><![CDATA[Building the future of social content. Or giving it a bloody good go. - Medium]]></description>
        <link>https://medium.com/drivetribe-engineering?source=rss----857fcd880bce---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>DriveTribe Engineering - Medium</title>
            <link>https://medium.com/drivetribe-engineering?source=rss----857fcd880bce---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:03:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/drivetribe-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Towards achieving a 10x compile-time improvement in a Flink codebase]]></title>
            <link>https://medium.com/drivetribe-engineering/towards-achieving-a-10x-compile-time-improvement-in-a-flink-codebase-a69596edcb50?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/a69596edcb50</guid>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Aris Koliopoulos]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 21:42:17 GMT</pubDate>
            <atom:updated>2019-01-10T21:42:17.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JV6h4eWazqURMOwKLc7TmA.jpeg" /><figcaption>All Flink related articles must start with a squirrel.</figcaption></figure><p>This article aims to outline how we managed to achieve a 10x improvement in compile-time performance of our <a href="https://flink.apache.org/"><strong>Apache Flink</strong></a> codebase in <strong>Scala</strong>. More specifically, it presents an approach to managing TypeInformation instances in large Scala codebases.</p><p>Apache Flink processes all data ever generated at <a href="http://www.drivetribe.com/"><strong>DRIVETRIBE</strong></a>. A couple of years in, the number of execution graphs currently running in production is over 100. This entails tens of thousands of lines of Scala and a very heavy load for the compiler.</p><p><em>More information on the hows and the whys of our architecture can be found </em><a href="https://data-artisans.com/blog/drivetribe-cqrs-apache-flink"><em>here</em></a><em> and </em><a href="https://www.youtube.com/watch?v=0cJ565r2FVI"><em>here</em></a><em>.</em></p><p>On top of that, we have introduced a fair amount of type-level trickery using <a href="https://github.com/milessabin/shapeless"><strong>Shapeless</strong></a>, we handle our JSON serialisation/deserialisation using <a href="https://github.com/circe/circe"><strong>Circe</strong></a> and we also use a fair amount of the functional programming abstractions in <a href="https://github.com/typelevel/cats"><strong>Cats</strong></a>. All of the above have contributed a large number of type classes and quite a heavy implicit resolution workload for the compiler.</p><p>Adding up all of the above:</p><pre>ariskoliopoulos@Ariss-MacBook-Pro ~/D/backend&gt; <strong>sbt -J-Xss20m -mem 4000 data-processing/clean data-processing/compile</strong></pre><pre>[info] Loading global plugins from /Users/ariskoliopoulos/.sbt/0.13/plugins</pre><pre>[info] Loading project definition from /Users/ariskoliopoulos/Desktop/backend/project</pre><pre>[info] Set current project to backend (in build file:/Users/ariskoliopoulos/Desktop/backend/)</pre><pre>[success] Total time: 0 s, completed 23-Dec-2018 16:36:12</pre><pre>[info] Compiling 110 Scala sources to /Users/ariskoliopoulos/Desktop/backend/data-processing/target/classes...</pre><pre><strong>[success] Total time: 879s</strong>, completed 23-Dec-2018 16:50:51</pre><p>We found ourselves in the rather unfortunate situation of having to wait up to 15 minutes for a clean compilation. Given the lack of tooling in Scala 2.11, debugging wasn’t exactly a trivial task. Intuitively, implicit searches and macro expansions are to blame. Given however our heavy use of type classes, how can this be pinpointed to a small, fixable subset of the codebase?</p><p>To make things worse, while trying to upgrade from Flink 1.4.2 to 1.6.0, the compiler hung in what looked like a infinite recursion:</p><p><a href="https://pastebin.com/fuQPrwWA">Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.91-b14 mixed mode): &quot;p - Pastebin.com</a></p><p>The end result was a StackOverflow exception. Increasing the stack size only delayed the inevitable for a little while. This stack trace provides a valuable clue: Flink’s TypeAnalyzer’s macros are stuck in an infinite loop. Looking at how TypeInformation instances are generated may be a good candidate for resolving the issue (or a red herring).</p><p>Flink requires a TypeInformation instance implicitly available for every type it processes. Flink uses those instances to generate serialisers and comparators, which in turn enable passing data from one operator to the next, storing data to the various state backends and so on and so forth. More info on this can be found <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.7/dev/types_serialization.html">here</a>.</p><p>One of the most annoying compile time errors Flink developers run into:</p><pre><strong>scala&gt;</strong> case class User(id: String, name: String, age: Int)</pre><pre>defined class User</pre><pre><strong>scala&gt;</strong> environment.fromElements(User(&quot;asd&quot;, &quot;Joe&quot;, 32))</pre><pre>&lt;console&gt;:16: <strong>error: could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[User]</strong></pre><pre>environment.fromElements(User(&quot;asd&quot;, &quot;Joe&quot;, 32))</pre><p>Which can be trivially resolved with a magic import:</p><pre><strong>scala&gt;</strong> <strong>import org.apache.flink.streaming.api.scala._</strong></pre><pre>import org.apache.flink.streaming.api.scala._</pre><pre><strong>scala&gt;</strong> environment.fromElements(User(&quot;asd&quot;, &quot;Joe&quot;, 32))</pre><pre>res1: org.apache.flink.streaming.api.scala.DataStream[User] = org.apache.flink.streaming.api.scala.DataStream@711823c0</pre><p><a href="https://github.com/apache/flink/blob/89eafb4d207e4342f55ea3dd81ef131d29da9978/flink-streaming-scala/src/main/scala/org/apache/flink/streaming/api/scala/package.scala#L37">Inspecting the contents</a> of the package object reveals the following line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d35cda6454b68f3e47bdf8ee1f91d855/href">https://medium.com/media/d35cda6454b68f3e47bdf8ee1f91d855/href</a></iframe><p>This is an implicit macro. Given the lack of context bounds, this macro can generate TypeInformation[T] for any type T. This makes it eligible for any implicit search for a TypeInformation[T] instance. If no other non-ambiguous implicit is found before createTypeInformation is matched, then the compiler will expand the macro inline.</p><p>This is fantastic when bootstrapping a project as it uses Scala macro voodoo magic to hide internal complexities related to Flink’s type handling system. A file may contain tens of transformations DataStream[T] =&gt; KeyedStream[K, T] =&gt; DataStream[R]and so on without the boilerplate of defining TypeInformation instances for T,K or R. There is however a caveat.</p><p>The macro-generated instances cannot be shared between different implicit searches. createTypeInformation doesn’t have access to previous expansions and thus it has to recompute the same TypeInformation[T] every time Flink needs it. For example:</p><pre>scala&gt; <strong>compileTime</strong>(&quot;&quot;&quot;</pre><pre>| import org.apache.flink.streaming.api.scala._</pre><pre>| val env = StreamExecutionEnvironment.getExecutionEnvironment</pre><pre>| case class SimpleType(a: String, b: String, c: Int)</pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre>| &quot;&quot;&quot;).toMillis</pre><pre>res43: Long = <strong>160</strong></pre><p><em>Note: shapeless.test.compileTime isn’t exactly deterministic. Those are medians out of 5-9 runs.</em></p><p>Let’s duplicate the DataStream generator a few times:</p><pre>scala&gt; compileTime(&quot;&quot;&quot;</pre><pre>| import org.apache.flink.streaming.api.scala._</pre><pre>| val env = StreamExecutionEnvironment.getExecutionEnvironment</pre><pre>|</pre><pre>| case class SimpleType(a: String, b: String, c: Int)</pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre><strong>20 more times</strong></pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre>| &quot;&quot;&quot;).toMillis</pre><pre>res44: Long = <strong>353</strong></pre><p>And a bit more:</p><pre>scala&gt; compileTime(&quot;&quot;&quot;</pre><pre>| import org.apache.flink.streaming.api.scala._</pre><pre>| val env = StreamExecutionEnvironment.getExecutionEnvironment</pre><pre>|</pre><pre>| case class SimpleType(a: String, b: String, c: Int)</pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre><strong>50 more times</strong></pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre>| &quot;&quot;&quot;).toMillis</pre><pre>res47: Long = <strong>593</strong></pre><p>The compiler needs to expand the macro every time a TypeInformation[SimpleType] is needed. 50+2=52 times in the example above. Hence 593 milliseconds.</p><p>This is quite a lot of time for 50 lines of Scala. Macro expansions can be slow. Unnecessarily duplicated macro expansions over complex nested types can be very slow. Around ~300 types and a few tens of thousands of lines later one can end up in a situation where it is not clear whether the compiler is stuck or just very slow. To make things worse changes introduced after 1.4.2 made it impossible to successfully terminate a compilation due to some infinite recursion.</p><p>The solution?</p><p>Similar to what people in the Scala world people call <a href="https://www.scala-lang.org/blog/2018/06/04/scalac-profiling.html#typeclass-derivation-for-the-win">semi-automatic derivation</a>. There is a way to compute TypeInformation[T] only once for every T and use it in every instance Flink needs to process T. In fact, we don’t even need to invoke the macro if we use the TypeInformation’s Java interface as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9814c8cb4f6c10fc4f42d772105a5f97/href">https://medium.com/media/9814c8cb4f6c10fc4f42d772105a5f97/href</a></iframe><p>This has the benefit of being a lot faster on it own:</p><pre>scala&gt; compileTime(&quot;&quot;&quot;</pre><pre>| import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</pre><pre>| import org.apache.flink.api.common.typeinfo.TypeInformation</pre><pre>| val env = StreamExecutionEnvironment.getExecutionEnvironment</pre><pre>|</pre><pre>| case class SimpleType(a: String, b: String, c: Int)</pre><pre>| <strong>implicit val typeInfo = TypeInformation.of(classOf[SimpleType])</strong></pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre>| &quot;&quot;&quot;).toMillis</pre><pre>res8: Long = <strong>26</strong></pre><p>It also gets computed exactly once:</p><pre>scala&gt; compileTime(&quot;&quot;&quot;</pre><pre>| import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</pre><pre>| import org.apache.flink.api.common.typeinfo.TypeInformation</pre><pre>| val env = StreamExecutionEnvironment.getExecutionEnvironment</pre><pre>|</pre><pre>| case class SimpleType(a: String, b: String, c: Int)</pre><pre>| implicit val typeInfo = TypeInformation.of(classOf[SimpleType])</pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre><strong>50 more times</strong></pre><pre>| <strong>env.fromElements(SimpleType(&quot;foo&quot;,&quot;bar&quot;, 100))</strong></pre><pre>| &quot;&quot;&quot;).toMillis</pre><pre>res34: Long = <strong>42</strong></pre><p>And thus it is an order of magnitude faster.</p><p>The downside of this approach is that it creates quite a bit of boilerplate. One has to manually define TypeInformation instances for all types. This is normally achieved using one of the three following methods:</p><ul><li>In the companion object. The compiler will always look in the companion object of T for an implicit F[T] . This pattern is quite popular amongst adopters of JSON libraries that use a type class pattern such as Circe. Small subtle difference here is that the example below will compile even if there is no instance for Bar available.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77661ebe65df2977ddc1b3243b7d5ccc/href">https://medium.com/media/77661ebe65df2977ddc1b3243b7d5ccc/href</a></iframe><ul><li>A trait containing all the implicits. This can be converted to an object and imported or mixed in a package object. This solution is suitable if the model is in a different module which doesn’t need to depend on Flink.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef18b0b157a07462e7c46e1a4484b5dd/href">https://medium.com/media/ef18b0b157a07462e7c46e1a4484b5dd/href</a></iframe><ul><li>In current scope, right where it is needed. This is the fastest as this is where the compiler looks first. However, if a type is used in multiple files this definition will need to be repeated.</li></ul><p>We decided to go for the second approach. The results:</p><pre>ariskoliopoulos@Ariss-MacBook-Pro ~/D/backend&gt; <strong>sbt -J-Xss20m -mem 4000 data-processing/clean data-processing/compile</strong></pre><pre>[info] Loading global plugins from /Users/ariskoliopoulos/.sbt/0.13/plugins</pre><pre>[info] Loading project definition from /Users/ariskoliopoulos/Desktop/backend/project</pre><pre>[info] Set current project to backend (in build file:/Users/ariskoliopoulos/Desktop/backend/)</pre><pre>[success] Total time: 0 s, completed 23-Dec-2018 18:56:12</pre><pre>[info] Compiling 110 Scala sources to /Users/ariskoliopoulos/Desktop/backend/data-processing/target/classes...</pre><pre><strong>[success] Total time: 89s</strong>, completed 23-Dec-2018 18:57:42</pre><p>This is a 9.87x speedup 🎉🎉🎉</p><p>In Scala 2.11, compile-time inefficiencies required decent knowledge of compiler internals combined with loads of experiments and quite some patience. And a hunch.</p><p>In Scala 2.12, <a href="https://github.com/scalacenter/scalac-profiling">scalac-profiling</a> provides a nice toolchain to debug implicit searches and macro expansions. Introducing the plugin:</p><p>addCompilerPlugin(“ch.epfl.scala” %% “scalac-profiling” % “1.0.0”)</p><p>and adding the following</p><pre>&quot;-Ystatistics&quot;,<br>&quot;-P:scalac-profiling:no-profiledb&quot;,<br>&quot;-P:scalac-profiling:show-profiles&quot;,<br>&quot;-P:scalac-profiling:print-failed-implicit-macro-candidates&quot;,<br>&quot;-P:scalac-profiling:generate-macro-flamegraph&quot;</pre><p>will reveal a plethora of stats and debugging info. A lot more on this <a href="https://www.scala-lang.org/blog/2018/06/04/scalac-profiling.html">here</a>. It’s a long read but very well worth it.</p><p>If you reached that far and for some bizarre reason you would like to solve difficult Flink and Scala related problems for a living, we are <a href="https://drivetribe.bamboohr.co.uk/jobs/view.php?id=15">hiring</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a69596edcb50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/towards-achieving-a-10x-compile-time-improvement-in-a-flink-codebase-a69596edcb50">Towards achieving a 10x compile-time improvement in a Flink codebase</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Googlebot is the new IE]]></title>
            <link>https://medium.com/drivetribe-engineering/googlebot-is-the-new-ie-2c5a30ef3c8a?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c5a30ef3c8a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Fri, 11 May 2018 15:31:42 GMT</pubDate>
            <atom:updated>2018-05-11T15:32:57.217Z</atom:updated>
            <content:encoded><![CDATA[<h4>Googlebot is stuck on Chrome 41, which lacks support for many modern JavaScript features. SPA and library authors haven’t escaped the legacy browsers yet.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6GAat-0ADsslprJMyInZA.jpeg" /></figure><p>One of my favourite new features in JavaScript is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">Proxy</a>. As a library author, it’s exciting to think of the possibilities it opens for new APIs.</p><p>In <a href="https://popmotion.io/pose">Pose</a>, I use it to make a simple syntax for defining animated versions of any DOM element (e.g. posed.div) without maintaining a comprehensive list of tag names.</p><p>I use it in <a href="https://github.com/popmotion/vekta">Vekta</a> to make a vector unit type that can be used as a normal array while supporting GLSL-style swizzling (e.g. pos.xy = pos.yz).</p><p>There are other ways of achieving these capabilities, but they require either a compromise on filesize and/or syntax.</p><p>Unlike many post-lightspeed JavaScript features, Proxy can’t be transpiled, and it can’t be effectively polyfilled. So, browsers that don’t support Proxy don’t support these libraries.</p><p>Until yesterday, I thought this was no problem! For many website authors, IE usage is practically a statistical error (check your stats!) All major browsers support Proxy, so I felt confident implementing it and allowing consumers to decide whether to support legacy browsers or not.</p><h3>Except…</h3><p>Of course, in web development things are rarely that simple. The other day, I received <a href="https://github.com/Popmotion/popmotion/issues/312">this GitHub issue</a>. It read:</p><blockquote>I learn that googlebot is using chrome 41 for rendering websites and if it encounters not supported syntax without polyfill it won’t render the page if it’s a SPA without prerenderd content.</blockquote><p>The implication being, sites that rely exclusively on client rendering and wish to be indexed by Google <em>are blocked from using any JavaScript feature not supported in Chrome 41, unless it can be transpiled or polyfilled</em>.</p><p>By extension, if you’re a library author who wants your library to be widely consumed, you can’t use these features either.</p><p>This means no Proxy, at all. And it has wider implications, still.</p><p>For instance, the popular <a href="https://babeljs.io/docs/plugins/preset-env/">Babel env preset</a> is used to transpile in line with browser feature sets using rules like &quot;last 2 versions&quot;. This has always felt, to me, like a reasonable setting to use, but at the time of writing Chrome 41 is 15 versions ago!</p><p>There’s a long list of popular <a href="https://caniuse.com/#compare=chrome+41">features that Chrome 41 doesn’t support</a>:</p><ul><li>Proxy</li><li>IntersectionObserver</li><li>class</li><li>Rest parameters</li><li>Arrow functions</li><li>Array methods find, findIndex and includes</li><li>Object.values, Object.assign</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUaVuAvauX7yV4prleawIw.png" /><figcaption>My heart</figcaption></figure><p>If your SPA relies on any of the above, and these features aren’t transpiled or polyfilled, Google will be unable to index it.</p><h3>🙋🏽‍ I write an SPA, what can I do?</h3><p>First, check your site with <a href="https://www.google.com/webmasters/tools/googlebot-fetch">Fetch as Google</a>. If you write a SPA and it isn’t being indexed properly, you can use this tool to render your site as Google does.</p><p>If your site looks broken, it’s possible your site isn’t transpiling or polyfilling a JavaScript feature and Chrome is throwing an error. You can debug this by downloading <a href="https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win/310958/">Chrome 41 from Google</a>.</p><h4>Server-side rendering</h4><p>If your SPA is dependent on Google indexing, then it’s likely to be a content site. Personally, I think that content sites should be rendered server-side (SSR). It’s better for performance and reliability, so it’s better for users.</p><p>SSR was once a black art, but since the advent of <a href="https://nextjs.org/">Next.js</a> there’s almost no excuse. If you write a React app, Next.js makes it trivial to write and deploy a version that can be rendered on the server and then enhanced by the client.</p><p>If your site doesn’t rely on sessions or dynamic data, you can even use Next.js to output a static site, which will be even more performant still.</p><h3>🙋‍ I write a library, what can I do?</h3><p>People who write libraries have a choice to make. You, as an author, need to think about who your audience is.</p><p>I want Pose to be enjoyed by as many people as possible, so after receiving this GitHub issue I made the compromise towards increasing filesize and added an array of all valid DOM nodes. Over time, I’ll revise this list to remove the esoteric elements and signpost the existing-but-undocumentedposed(&#39;caption&#39;) syntax for lesser-used DOM elements.</p><p>On the other hand, Vekta is more of a personal project that I made simply to probe the capabilities of Proxy. Its unique syntax is difficult to replicate without it. So I’m happy to leave it as-is.</p><p>Whatever you choose, knowledge about Googlebot’s limitations with SPAs isn’t as commonplace as browser compatibility. So, if you use a feature like Proxy, or a library that relies on an optional polyfill, mention this in your readme.</p><h3>Conclusion</h3><p>I thought that with the impending burial of IE11 we were close to leaving behind some of the limitations around adopting new JavaScript technologies.</p><p>Sadly it seems like SPA and library authors will be stuck in 2015 for another year or more. I searched for any reference to when a Googlebot upgrade might occur, and I could only find this tweet from <a href="https://medium.com/u/6ba49af237a9">Ashley</a> back in March:</p><h3>Ashley on Twitter</h3><p>Looking for Google to update rendering from Chrome v.41 to the latest version? @JohnMu estimates later this year or early next year. It&#39;s a big project. wah. #SMX #smxmunich</p><p>Wah indeed.</p><h4>Recommendations recap:</h4><p>If you’re an SPA author and Google indexing is important to you, ensure it can see your site properly by using Fetch as Google and debug with Chrome 41. In the longer arc, consider SSR and the benefits that could bring your users on slower connections.</p><p>If you’re a library author, think about the degree of adoption you want your library to enjoy, and how that might affect your choices in how you implement features. If you choose to use unsupported features, signpost this in your documentation so developers of SPAs don’t have to find out via the scenic route.</p><p>Finally, if you work near Whitecross St in London, the extra spicy pork, chorizo and guac burrito from Luardos is an absolute banger. Thank me later.</p><h3>Further reading</h3><ul><li><a href="https://www.elephate.com/blog/chrome-41-key-to-website-rendering/">Chrome 41: The Key to Successful Website Rendering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5a30ef3c8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/googlebot-is-the-new-ie-2c5a30ef3c8a">Googlebot is the new IE</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Slack, web standards, and bloody cynicism]]></title>
            <link>https://medium.com/drivetribe-engineering/on-slack-web-standards-and-bloody-cynicism-25af702db063?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/25af702db063</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-standards]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Thu, 01 Feb 2018 15:52:48 GMT</pubDate>
            <atom:updated>2018-02-01T15:52:47.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>Slack announced video chat was unsupported in Firefox. You’ll believe what happened next.</h4><p>Recently, Slack declared their video chat feature wasn’t supported in Firefox.</p><h3>Slack on Twitter</h3><p>@geoffdoesstuff @firefox It requires significant effort for us to build out support and triage issues on each browser, so we&#39;re focused on providing a great experience in Chrome and our desktop apps. We are listening to all feedback, though. 👂</p><p>Adherence to web standards is, for many people, a deeply-held question of morality. The encroaching Twitterstorm could be seen from shore.</p><p>Most respondents made the fair point that companies <strong>should</strong> put in the extra time to support all browsers wherever possible, and they directed that point to the company as a whole. Fine.</p><p>Unacceptably though, some called into question the capability or work ethic of the Slack developers themselves:</p><h3>André Melancia on Twitter</h3><p>@SlackHQ @geoffdoesstuff @firefox Have you ever heard of INTERNET STANDARDS? Good competent developers know how to use them to have websites work on ALL compliant browsers...</p><h3>David Burns on Twitter</h3><p>adds @SlackHQ web engineers to list of people to never hire * Significant effort? Is that how we spell lazy these days? https://t.co/gSnZJtcBYl</p><p>This final tweet, and the <a href="https://twitter.com/AutomatedTester/status/959019553526296576">subsequent argument that I tumbled into</a>, inspired this post because it was particularly nasty, and I’m bored of the cynical attitude it is founded upon.</p><p>Look. Let’s begin by agreeing on one simple and uncontroversial fact:</p><p><em>Nobody</em><strong> </strong>outside of Slack knows the chain of events leading to, or the reasoning behind, the decision not to support Firefox for their initial release of this feature.</p><p>Nobody.</p><p>Yet here we have a guy (who works for Mozilla) publicly blacklisting <em>all</em> Slack developers and calling them out as lazy.</p><p>Nobody!</p><p>Why would anyone jump to this conclusion?</p><h4><strong>Things that are true</strong></h4><p>Ultimately, decisions like this are <em>usually</em> made by the business. It has a limited resource (time) that they’ve purchased off their developers.</p><p>Time is, I sadly have to explain, an inflexible resource. The practical reality for all businesses is that at any given point they have a specific quantity of it, so in order to get anything done they have to prioritise.</p><p>The business asks for a feature. They have some of this “time” and wish the feature to be delivered within a set amount of it. Compromises happen to make it so.</p><p>The tough shit of the matter is these compromises do not always align with your moral alignment.</p><p>In my experience web developers <em>generally</em> believe in supporting standards, and they <em>generally</em> argue, often quite pedantically, in favour of them.</p><p>Lastly, as pioneers of the magic link login system, and builders of a very robust and occasionally delightful app, the developers behind Slack are very good.</p><h4>What probably happened</h4><p>So, given the above, it is most probable that this was a business-led decision.</p><p>A compromise was probably made with the developers where they delivered the feature in Chrome initially, with the promise to bring it to Firefox <em>if</em> it performed well enough to justify further investment.</p><p>They probably disagreed with the decision, and said so, but because they’re reasonable human beings and this was a reasonable compromise, they agreed.</p><p>They <em>didn’t </em>chop their fingers off in protest and get themselves fired, as I assume these Twitter soldiers would prefer.</p><p>Personally I find it difficult, in the face of this messy but probable conflation of events and opinions, to identify room for cyncism.</p><p>Such deeply-held cynicism that you feel like emboldened to attack the character of people<em>, </em>who are actually real and have feelings and probably didn’t do anything wrong, because you <em>assume</em> them to be moral transgressors.</p><p>That assumption is based on the most cynical of many possibilities. The developers are lazy. They are incompetent. They are unemployable.</p><p>Or even that they’re acting out of malice:</p><h3>David Burns on Twitter</h3><p>@popmotionjs The web was designed to gracefully degrade when features are not available. If you don&#39;t do that and you actively block browsers that&#39;s a sign of malice or laziness. I&#39;ve been doing cross browser testing for a decade I know how much effort is required.</p><p>How cynical, to consider that a lack of Firefox support could be sourced from <em>malice</em>? To consider laziness before the probable, dirty amalgamation of the truths I outlined above?</p><p>Assume the worst, cynical, bloody cynical.</p><p>We have more than enough cynicism in the world, thanks.</p><h4>:)</h4><p>As a pallet-cleanser, here’s a response from someone with plenty of experience of life on the other end of this nonsense. The Webpack whipping-boy himself, <a href="https://medium.com/u/393110b0b9e4">Sean T. Larkin</a>:</p><h3>Sean à Paris pour @ngEurope on Twitter</h3><p>@SlackHQ @geoffdoesstuff @firefox Hey hey, drop me a DM and maybe we can identify pain points that we at @MSEdgeDev can help unblock for y&#39;all? Empathy is two way, and although folks are giving y&#39;all crap, we understand the burden of work involved to support compat. Let&#39;s work together to make it ezpz gg!</p><p>More like this please.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25af702db063" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/on-slack-web-standards-and-bloody-cynicism-25af702db063">On Slack, web standards, and bloody cynicism</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading DriveTribe to React 16]]></title>
            <link>https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-bonus-round-react-16-f98455fdabe6?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/f98455fdabe6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Wed, 03 Jan 2018 16:07:10 GMT</pubDate>
            <atom:updated>2018-01-05T09:53:10.917Z</atom:updated>
            <content:encoded><![CDATA[<h4>A 33% speed increase for doing as close to nothing as this profession allows</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8PKxSoSRcrIUdYdtbWPwg.png" /></figure><p>While writing the upcoming part 4 of my <a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-1-analysis-a776951e829a">performance deep-dive</a> into the DriveTribe website, I published our first open source project: <a href="https://github.com/drivetribe/react-intersection">React Intersection</a>.</p><p>I’m using the new module to reinstate lazy-loaded images on the website and measuring the effect that has on load times.</p><p>Through a freak misconfiguration (or moment of raw negligence, you decide), I initially set React 16 as a peer dependency. DriveTribe is still built on 15.5, and as 16 is said to bring both filesize <em>and</em> performance benefits (with more on the roadmap), I thought this was a perfect time to ignore my mistake and upgrade instead.</p><h3>The upgrade process</h3><p>The DriveTribe website codebase is a big place and I presumed (spoiler: wrongly) that the upgrade process might take as long as a couple of weeks.</p><p>This was based on the misconception that <a href="https://reacttraining.com/react-router/">React Router</a> would need upgrading from version 2 to 4. Its wildly different API would entail a radical refactor.</p><p>Luckily, React Router 3 is compatible with React 16 and only threw a minor roadblock in the need to upgrade <a href="https://github.com/taion/react-router-scroll">React Router Scroll</a> to version 0.4.4.</p><p>To give you a flavour of just how minor, this code:</p><pre>import useScroll from &#39;react-router-scroll&#39;;</pre><p>Became this:</p><pre>import { useScroll } from &#39;react-router-scroll&#39;;</pre><h4>What I didn’t do</h4><p>While writing this blog post I received the following tweet from <a href="https://medium.com/u/3ae919666f51">Damon Bauer</a>:</p><h3>Damon Bauer on Twitter</h3><p>@popmotionjs @DRIVETRIBE @reactjs How did you all handle Error Boundaries?</p><p>It’s a great question. React 16 introduces a <a href="https://reactjs.org/blog/2017/09/26/react-v16.0.html">bunch of new toys to play with</a>, like the aforementioned error boundaries, and fragments.</p><p>I’m really excited about the new features, but just as the React team focused on backwards compatibility first, I thought it’d be safer to simply install React 16 while keeping everything else equal.</p><p>Any potential bugs arising from the adoption of new features would muddy the source of any bugs created from the upgrade.</p><p>However, as a courtesy, I did swap ReactDOM.render for the new ReactDOM.hydrate method, but in a sensible mood I would have left that for a future PR.</p><p>This entire process, from branch to merge, took less than an hour. On January 2nd no less! A day when the average person is still experiencing Christmas meat sweats and maybe some New Year Eve heart stuff.</p><p>That’s pretty incredible when you consider that 16 is a ground-up rewrite.</p><h3>Impact</h3><p>As mentioned, the purported benefits of React 16 are a smaller bundle size (a third smaller!) and faster server-side rendering performance.</p><h4>Bundle size</h4><p>As identified in the initial part of this blog series, reducing our bundle size is a priority.</p><p>Our main.js did decrease by the advertised amount (15kb), but it’s still a whopping 218kb.</p><p>When we created the site, main.js was 100kb and React was about half of that. The flipside of our current situation is that, at the very least, we’re now in a position where the bloat is under our control.</p><p>We’ll be exploring ways to reduce and maintain small bundle sizes in an upcoming post. For now, I’m happy to save an amount that could itself fit the entirety of <a href="https://popmotion.io/">Popmotion</a>, with cola and fries. Large.</p><h4>Rendering performance</h4><p>Much has been made about the performance improvements React 16 brings to server-side rendering.</p><p>I didn’t measure any notable speed increase in client-side rendering. Server-side, things are indeed a different story.</p><p>The render time, which we measure as the duration of the blocking renderToString call was previously 90ms.</p><p>Now, that’s down to 62ms. A <strong>33% speed increase</strong>. For doing as close to nothing as this profession allows. Doffed caps all round.</p><p>This duration is promised to decrease further when we upgrade Node.</p><h3>The future</h3><p>React 16 is yet to bear all its fruit, which is promised to be bountiful.</p><p>Already, fragments offer the ability to reduce the depth of the DOM, which will reduce memory footprint and improve rendering speeds.</p><p>A new renderToNodeStream method will potentially allow us to stream our response rather than wait for renderToString to complete. However, this is contingent on it playing nicely with the rewind functions in React Helmet and Styled Components, which I’ve heard it might not.</p><p>In the near future, client-side rendering will benefit from 16’s new asynchronous Fiber architecture, which you can learn more about in <a href="https://www.youtube.com/watch?v=ZCuYPiUIONs">cartoon form</a>.</p><p>Reductively, it means fewer blocking renders, which will help keep animations and other interactions smooth. Once you’ve made it over the major bump, this will come for free in a future release.</p><h3>Conclusion</h3><p>Upgrading React took under and hour, yet shaved off 15kb and reduced server-render duration by 33%.</p><p>More importantly, we can now leverage its new features in an incremental fashion, as well as incorporate upcoming Fiber improvements for free.</p><p>If you use the now-defunctcreateClass, you’ll need to install this as a <a href="https://reactjs.org/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactcreateclass">separate library</a>. In my personal opinion it’s worth migrating (as a second pass!) as you’ll thank yourself for weening your team off a framework-specific API and onto a native one.</p><p>I can’t overstate how effortless the upgrade was. If you’re still a hold-out, find yourself a free morning and cross an easy item off your list to start your year.</p><p><strong>Update 5/1/2018: </strong>The original version of this article incorrectly stated that users of createClass would face a steeper upgrade path. <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a> got in touch to let us know that you can include support for this as a <a href="https://reactjs.org/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactcreateclass">separate library</a>. The article has been updated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f98455fdabe6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-bonus-round-react-16-f98455fdabe6">Upgrading DriveTribe to React 16</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Unravelling Tale of Performance, Part 3: Time to First Byte]]></title>
            <link>https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-3-time-to-first-byte-60d0ae0d8162?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/60d0ae0d8162</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[react-router]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Mon, 04 Dec 2017 16:35:29 GMT</pubDate>
            <atom:updated>2017-12-15T09:50:29.731Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time to First Byte is a controversial metric, but ours is shit so let’s optimise it anyway.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQqeA_zH-kcyBexaHB7Ctg.jpeg" /></figure><p><em>The story so far: </em><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-1-analysis-a776951e829a"><em>Analysis</em></a><em>, </em><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-2-render-blocking-css-68f0fff588ec"><em>Render blocking CSS</em></a></p><p>Time to First Byte (TTFB) is the amount of time between the moment a client requests a resource, and the moment it receives the first byte of it.</p><p>Despite Google PageSpeed Insights, Lighthouse and WebPageTest all featuring it as a prominent indication of the performance of a website, it doesn’t follow that a low TTFB automatically leads to a fast experience for the user.</p><p>For instance, it would be simple for a server to optimistically ping a quick 200 success response to a client before even resolving a route. Beyond that, it might run into all sorts of turbulence. Slow or failed API calls, poor rendering performance, heavy payload, anything. But because of that initial 200, its TTFB would be considered low even though the overall speed of the request is slow.</p><p>While it’s an odd metric, there is <a href="https://moz.com/blog/how-website-speed-actually-impacts-search-ranking">research that suggests a high TTFB negatively impacts Google PageRank</a>. So this will negatively effect our SEO, and if there’s a way to quickly and correctly respond to a request sooner, we should take it.</p><p>It’s also true that things that contribute to high TTFB, like a needlessly blocking API request, <em>can</em> have knock-on effects for the rest of the load order. Which will result in a degraded user experience.</p><p>In this post, I’m going to explain how DriveTribe handles incoming requests and highlight areas for improvement. When a fix can be achieved within a reasonable amount of time, I’ll implement, measure and deploy.</p><h3>How DriveTribe handles requests</h3><p>Here’s my first and hopefully last ever flow diagram, that roughly explains how we handle all incoming requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sr642YtR3PzAbWXNj2Hchw.png" /></figure><p>There are two major sources of inefficiency here.</p><h3>1. Client authentication</h3><p>All requests to our API need to be authenticated. At the start of our request, we check (via cookies) to see if the client is recognised. If it isn’t we generate a UUID.</p><p>Later, when request the route’s data dependencies, we first need to check whether the current user is authenticated. A request to /user is fired with this ID. If we receive a 401, we create an anonymous user on the API.</p><p>Finally, we are authenticated. We can make remaining data requests.</p><p>For first time requests, this process involves <strong>two</strong> blocking round trips for a performance penalty of <strong>~250ms</strong>. This is terrible.</p><h4>The history and the solution</h4><p>If it doesn’t look like this was a designed process, that’s because it wasn’t.</p><p>Originally, every API request required a registered user. So, if no authToken was found on the client we could simply show a login screen. If a user <strong>was</strong> registered they’d already be cookied with an authToken so we could run all requests in parallel. Zero blocking requests.</p><p>Later, we opened some endpoints up and for reasons that aren’t entirely relevant to this deep dive, we introduced a form of authentication for clients that were logged out in the form of a clientId.</p><p>This has been implemented in a way that doesn’t take advantage of the fact that <em>we already know</em> if the client has a clientId and/or authToken.</p><p><strong>If we do</strong>, we can make our user request in parallel with our other requests. Zero blocking requests.</p><p><strong>If we don’t</strong>, we can make our anonymous user request <em>without waiting for an error from the </em><em>/user endpoint.</em> One blocking request.</p><p>In both scenarios we remove a whole blocking request. Thanks to the laws of physics, this will definitely result in a lower TTFB.</p><p>Because this is a <em>blocking</em> request, it means that whatever we save in TTFB is time saved on the entire request. For every x milliseconds saved, we can deliver the page x ms sooner, and request images and JavaScriptx ms sooner too. It’s not just SEO-benefitting fluff.</p><p>Unlike:</p><h3>2. Resolving all data before returning headers</h3><p>The second inefficiency is that all data dependencies are resolved as part of the route matching process.</p><p>This means that if a valid route is matched, we don’t even know that we can respond with a 200 success header until all its data has been received.</p><p>If someone requests, for instance, the homepage, we know for a fact that this is a 200 response as its existence doesn’t depend on the result of a given API call.</p><p>We’re still using <a href="https://reacttraining.com/react-router/">React Router</a> 2. It provides a match function to resolve routes, which is configured using a route definition object.</p><p>These are provided to a function that compiles them into the route config format that React Router 2 accepts. That format allows a getComponent property, which is designed to resolve the React component. However, I’ve hijacked it (always a safe idea) to resolve the route’s data dependencies in parallel.</p><h4>The (potential) solution</h4><p>Instead, we want a solution where we can know if a route has been matched <em>before</em> we fetch its data dependencies.</p><p>We’ll also need to know, per route, whether a simple match is enough knowledge to respond with a status header.</p><p>With the homepage, this is clearly true. / is always going to be a correct address.</p><p>However, a route defined aspost(/:id) is only <em>potentially</em> matching route. Whether we respond with a 200 or 404 depends entirely on the response from the API’s post endpoint.</p><p>React Router 4 provides a less-opinionated version of match which would allow us to write completely custom data resolution.</p><h4>However…</h4><p>Moving the site to React Router 4 would be a serious rewrite. Which in and of itself is a black mark against a refactor that would be good for SEO but ultimately wouldn&#39;t make any difference to overall load times or to the end user.</p><p>Crucially, React Router 4 doesn’t support server-side rendering <em>and</em> code splitting out of the box. That’s a deal-breaker.</p><p>It remains an improvement to keep in mind for the future. But it’s not for today.</p><h3>The ideal flow</h3><p>Dammit. <em>This</em> is my last flow diagram. For posterity, here’s how the server response flow would look in an ideal situation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ew8XER3zBGKSLctfRyiZBg.png" /></figure><p>While we can’t respond with a status header before retrieving data dependencies, <em>we can</em> still refactor the user authentication flow.</p><p>In ideal situations, the user object will now be retrieved <em>in parallel</em> to the rest of the data. The trade-off being if that request returns an error, we need to fetch an anonymous user and re-run all the data requests. This should be an edge case, however.</p><p>In the majority of cases we’ll be down to either zero or one blocking user requests.</p><h3>Results</h3><p>By moving the anonymous user request upfront for first time users, and changing the recognised user request from blocking to parallel, we managed to make some serious savings.</p><p>Here’s the mean timings, from 50 samples, between the moment a homepage request is received, and the moment we’ve resolved all the data and components needed to render it:</p><h4>Before</h4><ul><li>New users: <strong>406ms</strong></li><li>Returning users: <strong>370ms</strong></li><li>Registered users: <strong>357ms</strong></li></ul><h4><strong>After</strong></h4><ul><li>New users: <strong>304ms (-100ms)</strong></li><li>Returning users: <strong>282ms (-90ms)</strong></li><li>Registered users: <strong>268ms (-90ms)</strong></li></ul><p>Again this was only 50 samples (with some noise removed), but it paints a clear picture: A saving of between 90 and 100ms, roughly 25% of the previous routing time, for every user.</p><p>As this optimisation has a knock-on effect for every subsequent action and request, everything will happen 90-100ms sooner.</p><p>And, because the homepage currently depends on a whopping <strong>seven</strong> endpoints, excluding user data, we can assume that these savings are an even greater saving, relatively, for lighter routes.</p><h3>Next</h3><p>We currently request dozens of images from the initial HTML payload, whether or not they reside in the viewport. This clogs up a user’s bandwidth for assets that are crucial to render the initial view.</p><p>In the next part, we’ll look at strategies for deferring the request and rendering of images and even components until they’re visible to the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60d0ae0d8162" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-3-time-to-first-byte-60d0ae0d8162">An Unravelling Tale of Performance, Part 3: Time to First Byte</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Unravelling Tale of Performance, Part 2: Render Blocking CSS]]></title>
            <link>https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-2-render-blocking-css-68f0fff588ec?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/68f0fff588ec</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Tue, 21 Nov 2017 16:24:37 GMT</pubDate>
            <atom:updated>2017-12-04T17:39:35.292Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two CSS files, two DNS resolutions, both blocking rendering. Let’s kill ‘em.</h4><p><em>The story so far: </em><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-1-analysis-a776951e829a"><em>Analysis</em></a></p><p>Browsers generally treat CSS files as <em>render blocking</em>. That is, the browser will show an empty white screen until the CSS is downloaded and parsed.</p><p>If browsers showed content <em>before</em> styles had loaded, there’d be a flash of plain, unstyled content. From a user’s perspective, this wouldn’t just be ugly — it’d be <em>difficult to use</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnDlGaRk5dt9vKOvTFEklw.png" /><figcaption>LGTM</figcaption></figure><p>Users on a desktop might see the flash only briefly, but users on a slow mobile connection will have enough time to parse layout information on the page. Then, when the CSS loads, the page layout will change, leading to the disorientating cognitive overhead of having to re-parse what they’re seeing.</p><p>There’s also the considerable chance that they try and press a link or button, which, between them moving their finger towards the screen and actually hitting it, changes position as the CSS loads. This would leave the user pressing nothing, or worse, a totally different action.</p><p>We’ve all had this frustrating experience when an advert or image pushes content around (looking at you, <a href="https://tfl.gov.uk/">TFL</a>).</p><p>So it makes sense that browsers treat CSS as render blocking in order to avoid these situations. However, it can mean that users spend longer waiting to read their content on slower connections.</p><h4>The situation on DriveTribe</h4><p>Our <a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-1-analysis-a776951e829a">analysis in part one</a> identified two render blocking CSS files:</p><ul><li><strong>Google Fonts</strong>: Defines a series of web fonts, and the conditions under which they load.</li><li><strong>Global stylesheet</strong>: A 32kb stylesheet that includes styles for the entire website.</li></ul><p>As we can see from the waterfall diagram from <a href="https://www.webpagetest.org/">WebPageTest</a>, these assets are also both served from different domains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*cb46_qevCY3NMBVigVt8fQ.png" /><figcaption>The turquoise, orange and pink bars are DNS and SSL overhead.</figcaption></figure><p>Many users will spend more time <em>connecting to the servers</em> that these files are served from, than downloading the files themselves.</p><p>If we can figure out how to ditch these two requests, we’ll save <em>at least</em> 100ms (much more on slow connections).</p><p>This might not sound<em> </em>like a lot of time, but ideally we’d serve a readable website to a mobile user within a second. This quickly gives us a new perspective on that figure.</p><p>So, let’s take a look at both files, and see how we can get rid of them.</p><h3>Google Fonts</h3><p>The default method <a href="https://fonts.google.com/">Google Fonts</a> provides for embedding its fonts is as a blocking CSS resource (this is the method we implemented):</p><pre>&lt;link href=&quot;https://fonts.googleapis.com/css?family=Open+Sans:400,700&quot; rel=&quot;stylesheet&quot;&gt;</pre><p>This links to a tiny CSS file that contains a series of @font-face rules that look like this:</p><pre>/* latin */<br>@font-face {<br>  font-family: &#39;Open Sans&#39;;<br>  font-style: normal;<br>  font-weight: 400;<br>  src: local(&#39;Open Sans Regular&#39;), local(&#39;OpenSans-Regular&#39;), url(https://fonts.gstatic.com/s/opensans/v15/cJZKeOuBrn4kERxqtaUH3ZBw1xU1rKptJj_0jans920.woff2) format(&#39;woff2&#39;);<br>  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;<br>}</pre><p>Here, the unicode-range rule tells the browser that if it detects a character within the given range, it should download the referenced file.</p><p>It’s essentially code-splitting for fonts, allowing web fonts to support a range of international character sets while minimising the payload for the user.</p><p>A whole DNS resolution feels like overkill to receive one tiny file of font definitions (the file is under 1kb gzipped). <em>Especially</em> when the fonts themselves are served from a separate domain, requiring yet another DNS resolution(!)</p><h4>Potential solutions</h4><p>The first potential solution that comes to mind is to simply copy and paste this file into a style tag as part of our initial HTML payload.</p><p>This would be an “all other things being equal” approach that would keep our loading strategy exactly the same except with one fewer blocking network request.</p><p>There are two potential issues I can imagine:</p><h4>1. Maintaining manual references</h4><p>We’d now be maintaining a manual reference to the font files themselves. This feels brittle; I have no knowledge of whether Google is likely to remove those files when they add a new version.</p><p>Also, each file has an id like cJZKeOuBrn4kERxqtaUH3ZBw1xU1rKptJj_0jans92. To get the new one, the maintainer will need to manually call this CSS file rather than make an educated guess.</p><p>On the other hand, the fact that these font files are versioned instinctively means it’s unlikely (but possible) that Google are deleting past versions.</p><h4>2. Flash of invisible text</h4><p>Currently, browsers treat the <em>fonts themselves </em>as a semi-blocking resource. This means they’ll typically wait for a duration of time (of their choosing) for the font to load before falling back to a system font.</p><p>This results in a flash of invisible text (FOIT). The page is rendered, but none of the text is visible. Our current approach results in FOIT.</p><p>A possible alternative is to allow the browser to use a fallback font in the first instance and <em>then</em> replace it with the web font once it’s successfully loaded.</p><p>This results in a flash of unstyled text (FOUT), which looks messy but doesn’t present any major cognitive overhead. However, there is still a minor amount of reflow which, if you’re loading multiple fonts, isn’t great for performance.</p><p>FOUT also reduces the extra amount of time a user has to wait until text is displayed from up to <em>thirty seconds</em> to something on the order of milliseconds<em>.</em></p><h4>Alternatives</h4><p>Zach Leatherman has an <a href="https://www.zachleat.com/web/comprehensive-webfonts/">excellent run-down of all web font loading strategies</a> on his blog. Each has an extensive list of pros and cons. The bottom line is, there’s currently no one-size-fits-all solution to web fonts.</p><p>One of the most promising approaches is “FOUT with a class.” This uses JavaScript to load the fonts asynchronously. When all fonts have downloaded, a class is added to the html tag, which applies the web fonts via CSS.</p><p>On the plus side, it allows us to show content immediately. We also batch the multiple reflows into just one.</p><p>However, we’re still downloading an external dependency just to load the fonts. The <a href="https://css-tricks.com/loading-web-fonts-with-the-web-font-loader/">Web Font Loader, recommended by this CSS Tricks article</a>, is 16kb itself. That’s bigger than a typical JavaScript library, and about the same size as any one of our font files!</p><p>It also wouldn’t allow us to continue to define fonts as unicode ranges, a great benefit of the vanilla @font-face CSS rules.</p><h4>font-display</h4><p>Zach’s blog post reminded me of the <a href="https://css-tricks.com/almanac/properties/f/font-display/">font-display CSS property</a>. We already use this for our locally-hosted brand fonts, but the external CSS file from Google omits it.</p><p>font-display allows developers to define their own strategy for displaying content while web fonts are loading. Browser support is currently very good, with only Microsoft browsers lacking it.</p><p>The font-display: fallback rule is a compromise between the ugly FOUT and the slow-connection unfriendly FOIT. It will wait a smaller amount of time (around 100ms) before rendering text with a fallback font. If the web font is loaded after that, we’ll experience a FOUT.</p><p>Users with a fast connection won’t notice any FOUT, while users on a slow connection will be able to read their content sooner.</p><p>The only remaining barrier to inlining the CSS provided by Google’s external file is maintaining links to the font files on Google’s servers.</p><p>And do you know what? Sod it. In my opinion this approach strikes the best balance, and it’s fully standard. No hacks or polyfills, no JavaScript. If we were hosting the files locally, it’s definitely the solution I’d choose. So there’s no value in worrying about what if’s. Let’s give it a go. I’ll update this article if and when I get burned.</p><p>Which leaves us with the final render blocking file…</p><h3>Global stylesheet</h3><p>The majority of sites rely on at least one external CSS file. Ours is a 32kb global CSS file that contains styles for the whole website.</p><p>Here’s the thing: The homepage doesn&#39;t need it. Or, at least, it <em>probably</em> doesn’t. As I explained in my explanation of <a href="https://medium.com/drivetribe-engineering/why-were-slowly-migrating-to-styled-components-2f284d4b5d95">why we’re moving to Styled Components</a>, a major attraction is moving to the promised land, where only the styles required to render the current view are loaded.</p><p>All the styles required for the homepage are currently inlined with the initial HTML payload. The only potential issue is ensuring that legacy components, like the alerts menu, are all ported to Styled Components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONgNNcUSpSjDHIw3mDhIkQ.jpeg" /><figcaption>This will almost certainly break</figcaption></figure><p>As components with missing styles will silently inherit visual bugs, this will be a process of 1) removing the global stylesheet and 2) checking every potential action on the page to ensure any hidden dialogs are correctly ported and styled.</p><h4>Onward routes</h4><p>Of course, the rest of the site does need this global stylesheet, so we need a strategy for loading it.</p><p>We could potentially make the global stylesheet opt-in by including it in every other component with <a href="https://github.com/nfl/react-helmet">React Helmet</a>.</p><pre>&lt;Helmet&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;/path/to/global.css&quot; /&gt;<br>&lt;/Helmet&gt;</pre><p>This would inject the global.css tag only into pages that need it.</p><p>My concern with this approach stems from the reason we’re here in the first place: browsers treat CSS as a render blocking resource. With React Helmet, a user could land on a page that doesn’t include the CSS. When they navigate to a route that does, React will need to render it <em>before we even know we need to request it</em>.</p><p>This will almost certainly result in a flash of unstyled content.</p><h4>The solution</h4><p>Every route on DriveTribe is configured by a route definition file. It contains stuff like data dependencies, root component, a path generation function and an assortment of other settings. It looks a little like this:</p><pre>const chatRoute: RouteDefinition = {<br>  path: (id: string) =&gt; `/chat/${id}`,<br>  view: () =&gt; import(<em>/* webpackChunkName: &quot;chat&quot; */</em>&#39;./Chat&#39;),<br>  data: {<br>    check: (state, { params }) =&gt; getChat(state, params.resourceId),<br>    fetch: ({ params }) =&gt; getChatRequest(params.resourceId)<br>  }<br>};</pre><p>All route definitions are included in main.js (which is a potential optimisation for a later article). Conventionally, a React component will define its own data dependencies. This is the approach taken by <a href="https://github.com/zeit/next.js/">Next.js</a> amongst others.</p><p>However, that means a component needs to be downloaded and parsed before we can even fetch the data. With this configuration file approach, we can fetch the data in parallel with the component.</p><p>I’m going to add a new parameter to RouteDefinition, isStylesheetBlocking?: true. As a legacy config, I’ll add it to all routes <em>except</em> the homepage.</p><p>Then, in the HTML template I’ll add the following code:</p><pre>isStylesheetBlocking<br>  ? `&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;${cssPath}&quot;&gt;`<br>  : `&lt;link rel=&quot;preload&quot; as=&quot;style&quot; href=&quot;${cssPath}&quot; onload=&quot;this.rel=&#39;stylesheet&#39;&quot;&gt;`;</pre><p>On pages that require it, the stylesheet will continue to be loaded as a blocking resource.</p><p>On newer pages, we can use the &lt;link rel=&quot;preload&quot; /&gt; tag to asynchronously fetch the CSS file.</p><p>The onload=&quot;this.rel=&#39;stylesheet&#39;&quot;<em> </em>attribute is a tiny JS command that the tag can use to convert itself to a regular stylesheet resource once the CSS has loaded.</p><p>rel=&quot;preload&quot; doesn’t, as with so much in life, enjoy wide browser support. Instead, I’ll inline <a href="https://github.com/filamentgroup/loadCSS">loadCSS</a> at the bottom of the HTML template. This micro script from Filament Group will polyfill the functionality and load the CSS async as desired.</p><p>As a final benefit, this approach means that we don’t have to port any remaining components that aren’t immediately visible to Styled Components. As the global CSS is still ultimately loaded, it’s unlikely that that the styles for hidden dialogs will load after the JavaScript that powers the dialogs themselves.</p><h3>Results</h3><p>I ran some tests locally before deploying to production. Part due diligence (have I made things worse?) and part sheer curiosity.</p><p>While I didn’t expect this to necessarily reflect the gains I’d see on production (where assets are hosted on CDNs, minified and gzipped), I was so shocked by them I ran the tests again. And again. And for good measure… well, I actually left it at three attempts, but I was tempted.</p><p>The time until first render on a “fast 3G”, locally, currently sat at 1060ms. After making only the above adjustments, that had plummeted to <strong>295ms</strong>.</p><p>Encouraged, I deployed to production.</p><h4>Results, actually</h4><p>I chose the render blocking CSS as the first performance issue to tackle because I thought it’d be a quick win.</p><p>Compared to some of the other identified performance issues, I assumed it would result in relatively minor gains for relatively minor effort. Instead, this has ended up making a big difference to the performance for users on slower connections.</p><p>Here’s two filmstrip views of the site throttled to “fast 3G,” before and after:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*08XUkzFpUzNsUK1IaSdThg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*PuGmbGp3FY0i1sEP_0emjw.png" /></figure><p>We can see that originally, our first render didn’t happen until 1.05 seconds, whereas now it happens at <strong>370ms</strong>.</p><p>The user couldn’t previously read content until 1.16 seconds, whereas now that’s down to <strong>555ms</strong>. We could lower this further by using a more aggressive FOUT approach, though I’m happy with this for now.</p><p>Lighthouse reports “First meaningful paint” as being reduced from 2 to 1.5 seconds, with a Perceptual Speed Index score improvement of ~500 points (from ~3200 to ~2700).</p><p>This speed increase has a knock-on effect all the way down the request chain, providing benefits for the unoptimised assets too. On the throttled Lighthouse test our JavaScript previously didn’t load for 8 seconds, that’s down to 7.5.</p><h3>Conclusion</h3><p>Removing the render blocking CSS assets took a day or so of research and development, in return for substantial speed improvements.</p><p>Inlining the Google Fonts asset request may prove brittle, but for now it’s knocked out an unnecessary DNS resolution.</p><p>Our global stylesheet is now asynchronously loaded by default. Going forward, new routes will enjoy the same performance benefits as the homepage and we’ve put in place a final piece for easing our transition to Styled Components.</p><p>If you think all this is exciting, in the next part we’re going to look at ways we can improve our <strong>time to first byte</strong>. And ultimately, what could be more exciting than that? Literally nothing.</p><p><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-3-time-to-first-byte-60d0ae0d8162"><em>Read Part 3: Time to First Byte</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f0fff588ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-2-render-blocking-css-68f0fff588ec">An Unravelling Tale of Performance, Part 2: Render Blocking CSS</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Unravelling Tale of Performance, Part 1: Analysis]]></title>
            <link>https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-1-analysis-a776951e829a?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/a776951e829a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Thu, 16 Nov 2017 18:05:26 GMT</pubDate>
            <atom:updated>2017-11-21T17:01:54.819Z</atom:updated>
            <content:encoded><![CDATA[<h4>A classic tale of love, loss, and web performance.</h4><p>We launched our <a href="https://drivetribe.com/">new homepage</a> last month. It’s a massive refresh of our original design. Clean, bold, focused, lots of whitespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbqjWMSfeQuftGS3s0L4WA.jpeg" /></figure><p>It is, like most startup output, the product of an MVP mentality. Launch, learn, iterate.</p><p>This is a good approach to rapidly arrive at a product that works better for users. But as the feature machine trundles ever-forward, this process can leave “good enough” features in its substantial wake.</p><p>We’re finally at a point where concentrating on performance and polish will yield better returns than Yet Another Feature. The new homepage itself has been tweaked to satisfaction across a good balance of users.</p><p>The site was originally designed with performance in mind, but after a year of API, design and feature iteration, it’s time for a performance audit.</p><p>In this post, I’m going to audit the DriveTribe homepage with online reporting tools, Chrome DevTools and Google Analytics. I’ll outline my findings and formulate a plan, the execution of which we’ll follow in following posts.</p><h3>The audit</h3><p>It’s easy for us developers to sit here in our silicon towers, browsing with our Macbook Pros and swanky city office internet connections, to mistakenly believe our sites are fast.</p><p>This often isn’t true. To get a more objective measure of page performance, we can use a combination of:</p><ol><li><strong>Reporting tools</strong>, like <a href="https://developers.google.com/speed/pagespeed/insights">Google PageSpeed Insights</a>, to generate high-level reports, suggestions, and a headline meta-score. <a href="https://www.webpagetest.org/">WebPageTest</a> can test from practically anywhere on Earth and returns a detailed waterfall view of every request.</li><li><strong>Chrome DevTools </strong>to leverage connection and CPU throttling with flimstrip capturing to get a feel of what people on slow devices experience.</li><li><a href="https://analytics.google.com/"><strong>Google Analytics</strong></a>, to measure the real effect this has on users. For instance, what is our bounce rate on the homepage?</li></ol><p>With appendages firmly crossed, let’s dive in.</p><h4>Reporting tools</h4><p>The majority of our (human kind’s) search traffic comes from Google, and they take performance into consideration for page ranking. So it seems prudent to use <a href="https://developers.google.com/speed/pagespeed/insights">Google PageSpeed Insights</a> and the <a href="https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk?hl=en">Google Lighthouse</a> Chrome plugin to generate performance reports.</p><p>These reports analyse how fast your site is across desktop and mobile, and make a series of actionable suggestions. It’s a reasonable assumption that making good on these suggestions will contribute to a better PageRank.</p><p>I ran the reports, and this was the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYcIFAPTZ2SbesJeoNK1OQ.jpeg" /><figcaption>Ice cold</figcaption></figure><p>Not… great.</p><p>Both reports cite off-screen images and render-blocking CSS requests as an issue. We only have one stylesheet, but a whole load of images. This is a potential win.</p><p>The Lighthouse report suggests our first meaningful paint doesn’t happen for a whopping 9.6 seconds, which doesn’t match my experience. So I ran it again. And lo, the second time we received a time of 3.6 seconds, which is still too slow.</p><p>This highlights that you might want to run Lighthouse a few times to get a better sense of the numbers. The perceptual speed index in the image above halved, again still too slow, but its worth bearing in mind the weather.</p><p>Both Lighthouse and PageSpeed Insights report it takes ~0.65 seconds for the server to even respond, a measurement known as Time To First Byte (TTFB). When we first launched DriveTribe, this was nearly instantaneous, so it’ll be interesting to see what’s changed there.</p><h4>Digging deeper</h4><p>I then threw the page to WebPageTest, tenderised raw meat into the maw of a rabid dog. What fresh hell would await?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*MsFMWzbXWduJFy3SSbCLUA.png" /></figure><p>Oh. Not as bad (at first glance)! TTFB is still a clear problem. LA servers are reporting around 1.2 seconds (hence the F), whereas London servers are predictably reporting 0.65 seconds which resulted in an A.</p><p>WebPageTest provides a very clear waterfall diagram of each request. Chrome can also be used for this, but personally I think WebPageTest is clearer.</p><p>If we look at our first three requests, we can actually see the massive TTFB as the light blue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*3wt9uqmzqqvjzGSNcLZIMA.png" /></figure><p>The CSS files, that Google described to us as “blocking”, finish downloading before the page itself does. It would be easy to take this as a suggestion that they’re not blocking in a <em>practical </em>sense, but as pages can render without the full HTML payload that isn’t true.</p><p>There was also this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3im4zbLAT_dEDaOuSx8Qw.png" /></figure><p>All those purple bars are image requests, and we know from the previous reports that most of these aren’t needed to render the initial viewport. Also, those numbers run from 21 to 53, which means there are <em>at least 32</em> totally unnecessary requests.</p><p>The good news is that vertical gold line is “DOM interactive”, which means users can still use the page before the images have loaded.</p><p>However, sending all these requests isn’t just a matter of performance, it’s a matter of principle. Many users have expensive data plans and if we don’t need to send something, we shouldn’t.</p><h4>The hard numbers</h4><p>With Chrome DevTools, I took a look at what was actually going on.</p><p>Using device emulation, I set the site to “low-end mobile”, which both throttles the connection to “slow 3G” and the CPU to “vacuum tube”.</p><p>The main part of the homepage, the hero banner, wasn’t readable for 6 seconds. Not as bad as I’d feared, frankly, but nowhere near good enough.</p><p>Our HTML payload is being reported as a whopping 400kb. I was suspicious of this, so I downloaded and measured the file — it is 72kb. WebPageTest reports the same (underlining a benefit of using multiple tools). Still, there’s more to this than meets the eye, and I believe there’s wins to be had here.</p><p>Something that hadn’t been flagged by an reporting tool was the sheer amount of time our main JS payload (225kb gzipped and minified!) took to download: <strong>18 seconds</strong>. Being a server-rendered site, you can still click on links and have a usable experience. But some things, like the alerts panel, would remain inoperable for that amount of time.</p><p>Part of the point of using React is the ability to reuse DOM, components and data for subsequent page loads. The main.js file is being thrown away if the user navigates away within that 18 second period. Which means any potential performance benefit we might derive from that capability is completely nuked, <em>and</em> we’ve wasted hundreds of kb of mobile data.</p><p>Finally, we make, in total, <strong>56 image requests</strong>.</p><p>All in all, for slow devices, this is potentially a fucking disaster.</p><h4>The users</h4><p>If this theory is true, then I <em>expect</em> to see a drastically higher bounce rate for users on mobile devices than on desktop.</p><p>Checking Google Analytics, the difference is a <strong>50% higher bounce rate</strong>. That’s not including the lost statistic for devices that don’t even get round to loading JavaScript, which I suspect, but can’t immediately prove, is also higher on mobile.</p><h3>Plan of attack</h3><p>This analysis leaves me with a bunch of different areas to investigate closer:</p><h4>1. Render-blocking CSS</h4><p>Both of Google’s reporting tools highlighted two render-blocking CSS assets. One, perhaps ironically, consists of <strong>Google Fonts Open Sans</strong> rules, a loading method recommended by Google itself. Maybe there’s a way of requesting this resource without blocking the page from loading.</p><p>The other asset is our <strong>global stylesheet</strong>. Conventional wisdom suggests this <em>needs</em> to be blocking. If you read my previous blog post on <a href="https://medium.com/drivetribe-engineering/why-were-slowly-migrating-to-styled-components-2f284d4b5d95">migrating to Styled Components</a> you know that we’re getting to a place where <em>only render-critical CSS is loaded.</em></p><p>As the homepage is brand-new, there shouldn’t be many legacy components kicking around that would require the global stylesheet to be render-blocking. We could be ready to take advantage of this.</p><h4>2. Time to first byte (TTFB)</h4><p>Our TTFB used to be near-instantaneous, but by all reports it’s now quite high. It’s a matter of debate whether this is a meaningful metric for users, as it doesn’t necessarily mean the page renders quicker. But, there <em>are</em> signs that it <a href="https://moz.com/blog/improving-search-rank-by-optimizing-your-time-to-first-byte">correlates to a higher PageRank</a>, making it a worthy subject of optimisation.</p><p>A high TTFB might suggest a delay with resolving API requests. Or maybe we’re calling too many endpoints. Are all requests happening in parallel? Do we even need to call all data dependencies from the server or can some be called later?</p><h4>3. Images and DOM outside the viewport</h4><p>We naively request and render all the DOM and images needed to render the entire page. However, the user only initially sees whatever’s in the viewport.</p><p>A better approach may be to deliver and render only the data and assets needed to render the initial viewport. Or to render everything but only request images when they appear in the viewport.</p><h4>4. HTML payload</h4><p>The typical approach to server-side rendering is to embed the data that the server used to render the page as an encoded object in the HTML payload itself.</p><p>This way, when the client JavaScript comes to render the same page, it 1) won’t have to make extra API calls and 2) will use the same data as the server so the checksums match.</p><p>The downside is a bigger HTML payload. Exactly how much is dependent on how much data you retrieve from your API. In our case, 55 of 72kb is all data, and it’s loaded <em>before the HTML itself</em>.</p><p>The thinking here was that we can send the data while the server is busy rendering the page. Originally, this did prove to be faster than sending the HTML first.</p><p>It’s worth revisting to ensure the ratio of data to HTML hasn’t shifted so much that this is no longer true, and double check it on slower devices where it could be the network connection, rather than the speed of the server, that’s the bottleneck.</p><p>We could also ensure that <em>only</em> the data necessary for the current page is sent. We already strip down the models returned from the API for data that we’ll need <em>in general</em>, and this can speed up subsequent page navigation.</p><p>For instance, if we have a feed full of posts, if a user clicks on one we don’t currently need to fetch that data again. But for that initial view, we <em>don’t</em> need all the data returned from the API.</p><h4>5. JS payload</h4><p>I remember thinking main.js was too large at 130kb, and “I’d better keep an eye on that.” We’ve seen how that turned out. I’ll be looking at reducing this by:</p><ul><li>Auditing what this bundle is made of and making sure no large third-party libraries have snuck in.</li><li>Splitting out a vendor JS file.</li><li>Ensuring Webpack is splitting the bundle as much as possible, even if modules are repeated across bundles.</li><li>Introducing build-time tooling that could potentially fail PRs if any one file gets too large.</li></ul><h3>Conclusion</h3><p>Using Google’s PageSpeed Insights, Lighthouse, WebPageTest and DevTools, we’ve identified five strong candidates for bagging ourselves some much-needed performance wins.</p><p>Considering websites are generally the fusion of CSS, HTML, JS, images and server-generation, I can’t think of an area where we <em>can’t</em> improve. Which means we should see big improvements in the coming weeks.</p><p>In subsequent posts, I’m going to investigate each of these potential areas for improvement. I’ll find a potential solution, implement it, and release it. I’ll compare performance before and after and hopefully we’ll discover where the time/effort ratio can yield worthwhile wins.</p><p><a href="https://medium.com/p/68f0fff588ec"><em>Read part 2: Render blocking CSS</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a776951e829a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/an-unravelling-tale-of-performance-part-1-analysis-a776951e829a">An Unravelling Tale of Performance, Part 1: Analysis</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why We’re (Slowly) Migrating to Styled Components]]></title>
            <link>https://medium.com/drivetribe-engineering/why-were-slowly-migrating-to-styled-components-2f284d4b5d95?source=rss----857fcd880bce---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f284d4b5d95</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[css-in-js]]></category>
            <category><![CDATA[css-modules]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matt Perry]]></dc:creator>
            <pubDate>Wed, 01 Nov 2017 17:01:08 GMT</pubDate>
            <atom:updated>2017-11-16T18:05:56.470Z</atom:updated>
            <content:encoded><![CDATA[<h4>We’re loving Styled Components. Here’s some whys (and why nots).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a28qkdjqsJvuXefxt0AcRQ.png" /></figure><p><a href="https://drivetribe.com/">DriveTribe</a> is transitioning from a monolithic CSS file generated with <a href="https://github.com/css-modules/css-modules">CSS Modules</a>, to a CSS-in-JS approach using <a href="https://www.styled-components.com/">Styled Components</a> (SC).</p><p>We’ve been at this for a couple months. Initially, progress was tentative and evaluative. Now, a PR isn’t passed if it touches an old component without porting it to SC.</p><p>So, I’m going to share some of our findings, and explain <em>why</em> our confidence in SC boomed in such a short space of time.</p><p>This <em>isn’t</em> a volley in the eye-rolling CSS-in-JS vs preprocessor war. It’s also not a stream of platitudes about why SC is the second coming. It’s just an explaination of why SC is a good, but not perfect, match for the culture at DriveTribe.</p><h3>Who we are</h3><p>First, it’s helpful to describe the nature of working in a front end team in a startup like DriveTribe, to help frame why SC is a good fit for us. You might recognise some, or all of these traits within your own team:</p><p><strong>We create features, often. </strong>We spin up new features at a breakneck pace to test ideas out with our users. This has the potential to inflate the codebase to the point that, even within a small team, is hard to maintain a full mental model of.</p><p><strong>We kill features, often.</strong> We’re quick to kill off features that don’t work, but cleanups aren’t always perfect. And sometime’s we’re not that quick, either.</p><p><strong>We iterate, rapidly.</strong> The features that do survive, the “idea tests”, are the quintessential eternal prototype. Sometimes there simply isn’t time to go back and brush up some gnarly hack, so the <em>simpler, cleaner, </em>and<em> more modular </em>that we can make that initial code, the better.</p><p><strong>We prefer functional, declarative code.</strong> It almost comes with the territory when you go all-in with React and Redux, but this style of code is very easy to <em>read</em><strong> </strong>and<strong> </strong><em>reason about</em>, so we err towards that style across the codebase.</p><h3>So what’s so effin great about Styled Components?</h3><p>With these traits in mind, let’s take a look at the benefits (and not-benefits) of SC that we’ve identified so far.</p><h4>1. Gradual implementation</h4><p>It was really important for us to be able to experiment with SC before making any commitment. The size of the codebase meant that a big bang approach would simply never be possible, from a time investment, design integrity, or pure human sanity point of view.</p><p>It’s easy to make just a single component with SC, or a series of components in a part of your site in order to stress-test its performance. You’ll quickly come to know if it’s right for your project.</p><p><strong>But… </strong>SC isn’t free. It brings with it a ~<strong>12kb overhead</strong>, which is frankly quite a bloody lot to load a sprinkling of CSS. Ultimately, if you’re loading 12kb of JavaScript for <em>any</em> reason, it needs to be integral. For that reason, you don’t want to be in this transitionary period for long.</p><h4>2. Semantic tags and clear logic</h4><p>Using semantic HTML tags like article and li correctly is critical for screen readers and bots to correctly parse our websites.</p><p>Typically attempts to make HTML semantic for <em>humans</em> centre on choosing descriptive, non-presentational class names:</p><pre>&lt;ul class=&quot;post-list&quot;&gt;<br>  &lt;li class=&quot;post highlighted&quot;&gt;&lt;/li&gt;<br>  &lt;li class=&quot;post&quot;&gt;&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>The code that generates this markup can look messy with <em>any</em> templating framework. To take the React &amp; CSS Modules approach, using <a href="https://github.com/JedWatson/classnames">Classnames</a> to handle the logic of which classes to apply, you can end up with code that looks like this:</p><pre>&lt;ul className={styles.postList}&gt;<br>  {posts.map(({ isHighlighted }) =&gt; {<br>    const className = classnames(styles.post, {<br>      [styles.highlighted]: isHighlighted<br>    });</pre><pre>    return (<br>      &lt;li className={className}&gt;&lt;/li&gt;<br>    );<br>  })}<br>&lt;/ul&gt;</pre><p>There are clearly ways of making this look better, for instance abstracting the list item to its own component. But, that classnames logic is still going to have to live somewhere, and adding extra presentational states becomes unwieldy.</p><p>There’s also nothing stopping styles.highlighted from being silently undefined, which has lead to presentational bugs. On the flip side, unused classes are compiled and sent to users.</p><p>Finally, this feels like a lot of implementation detail. I <em>shouldn’t have to care</em> that we arrive at our presentational state by conditionally concatenating classes, or even that we’re hooking into a class at all.</p><p>With Styled Components, our code looks like this:</p><pre>&lt;PostList&gt;<br>  {posts.map(({ isHighlighted }) =&gt; (<br>    &lt;PostItem isHighlighted={isHighlighted}&gt;&lt;/PostItem&gt;<br>  ))}<br>&lt;/PostList&gt;</pre><p>Semantically, PostList means more to me as a <em>human being</em> and a <em>developer</em> than ul.</p><p>If PostList or PostItem is undefined, this code will throw an error. Meanwhile unused components are ignored entirely thanks to Webpack’s tree-shaking capabilities.</p><p>And finally, the logic of isHighlighted is exposed in the CSS like this:</p><pre>export const PostItem = styled.li`<br>  /*...styles*/<br>  ${(props) =&gt; props.isHighlighted &amp;&amp; `animation-name: blink`}<br>`;</pre><p><em>I don’t care</em> that this logic leads to a new class being created. Incidentally, it does.</p><p><strong>But…</strong> This approach, of hiding tag names, can make it tougher to create valid HTML. For instance, li must be a direct child of ul or ol. This is clearly true in the first example, but isn’t as clear in the second.</p><p>This risk can be mitigated with naming conventions (like appending List and Item as above), but to some degree, it persists.</p><h4>3. No duplicate variables</h4><p>Invariably, there’s a time when you need a duplicate CSS variable in your JavaScript. It might be for a layout calculation, animation, or an interaction. It happens.</p><p>It happens rarely enough that you might even be tempted to store the variable locally in the component you’re using it in. And again, that inevitable second time.</p><p>It’s a fight you’ve already lost. You know the rest of this story. By storing all these variables in one place, JS, that nonsense stops.</p><p><strong>But… </strong>During the transitionary period, you’re maintaining mirror variables in both CSS and JS. In our case, this has luckily coincided with a transitionary period for our design language so the new stuff is in JS and the old stuff is in the CSS. YMMV.</p><h4>4. Module resolution</h4><p>Absolute paths are helpful for maintaining a flexible codebase. After configuring Webpack to support these, the SASS @import directive still didn’t respect them. Counting levels up a folder tree isn’t something we have to do any more.</p><h4>5. JavaScript</h4><p>With CSS Modules, we were also using SASS (which is lovely). They have different and slightly overlapping capabilities, so a few composes here and some @includes there, we were left with a bit of a mishmash.</p><p>These different directives and special rules live in the same file but they’re not interoperable. They’re also proprietry, and having to live and be parseable amongst pedestrian CSS they generally end up with weird syntax.</p><p>These are normal template literals outputting normal CSS. “Funny business” is handled with JS functions, many of which you may already use and be familiar with elsewhere on your site.</p><p>The only remaining domain knowledge is the Styled Components API, which is, yes, JS. You won’t be Googling “@mixin” again.</p><p><strong>But… </strong>SASS and LESS are <em>pre</em>processors. All this JS is just typical processing, bytes that you’re leaving for your user’s network to download and CPU to execute.</p><p>Theoretically, this leads to some level of reduced performance. However, we’ve run fairly intense chat rooms (1000s of messages per minute) with SC in place and they’ve been fine even on older processors. It is unlikely, but possible, that this has an impact outside of benchmarks.</p><h4>6. Removing the render-blocking request</h4><p>Server-side rendering (SSR) is, in my mind, a killer feature of React (and any other frameworks that support it).</p><p>It’s a massive win for performance, especially for users who live with poor-quality connections or slow devices. Used correctly, it enables people to use the website without the client JS ever loading.</p><p>It’s also a massive win for developers. Once you manage to switch your mental model of how the website hangs together, it’s easier to reason about a single codebase that becomes richer when it mounts, than it is to think about writing a HTML-generator in one language that has this weird extra runtime in JS that hooks in with brittle query selectors.</p><p>Even with SSR, the site still won’t render until the required CSS is downloaded and parsed. This extra network request is a <em>blocking request</em>. We can remove this final external dependency with SC:</p><pre>const html = renderToString(<br>  stylesheet.collectStyles(&lt;Site /&gt;)<br>);<br>const css = stylesheet.getStyleTags();</pre><p>With these two strings we can output a webpage that can be enjoyed by users as soon as the initial request is parsed. No render-blocking external dependencies required.</p><p>Crucially, <em>only</em> CSS required for the current render is inlined. This makes it trivial to <a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/">optimise the critical rendering path</a>.</p><p>By rendering <em>only</em> the components required for the initial view, and then asynchronously loading the data and components requried for the rest of the page, the user will only have to download the HTML and CSS neccessary for the first view. This is a massive win for the perceived speed of your site.</p><p>This isn’t a step we’ve taken yet, but the pieces are in place to do so in the near future.</p><p><strong>But… </strong>Like the spoon, for this one there is no but.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*aqltMWPAG2mTHxL7CX1A3A.jpeg" /></figure><p>This one’s just awesome.</p><h3>Conclusion</h3><p>Styled Components isn’t perfect, but for our usecase we have found it an improvement over CSS Modules.</p><p>It produces cleaner code, throws errors, consolidates our codebase, lets us reorganise components freely and can lead to big performance wins.</p><p>Though, many of these come with associated tradeoffs. There are probably plenty of pros and cons I’m not even aware of (let me know!)</p><p>Most people I’ve spoken to who dismiss it out of hand generally show the same visceral reaction that most of us had to JSX. The mere mention of CSS-in-JS can elicit head snaps so violent that I am left wondering whether I just said “Styled Components” or, actually, “go fuck yourself.”</p><p>I guess I’ll never know.</p><p>If your work environment sounds familiar to ours, I would recommend that, at the very least, you give it a real go with an open mind. Write a component or three, let them hang out with the rest of your code. If you choose a specific part of your site, code splitting will minimize the effect on your bundle.</p><p>Everything beyond that will happen naturally, if it’s the right fit.</p><p>DriveTribe is hiring Front End and React Native developers! <a href="http://hello.drivetribe.com/">Say hello</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f284d4b5d95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/drivetribe-engineering/why-were-slowly-migrating-to-styled-components-2f284d4b5d95">Why We’re (Slowly) Migrating to Styled Components</a> was originally published in <a href="https://medium.com/drivetribe-engineering">DriveTribe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>