<?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[Stories by Brandon Doran on Medium]]></title>
        <description><![CDATA[Stories by Brandon Doran on Medium]]></description>
        <link>https://medium.com/@brandondoran?source=rss-ebe43075cc3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*f00XpbhTkNNfWqHI.jpg</url>
            <title>Stories by Brandon Doran on Medium</title>
            <link>https://medium.com/@brandondoran?source=rss-ebe43075cc3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:11:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brandondoran/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Caching Assets Long Term with Webpack]]></title>
            <link>https://medium.com/connect-the-dots/caching-assets-long-term-with-webpack-5ad24a4c39bd?source=rss-ebe43075cc3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad24a4c39bd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Brandon Doran]]></dc:creator>
            <pubDate>Thu, 01 Sep 2016 17:33:22 GMT</pubDate>
            <atom:updated>2016-09-01T19:07:16.230Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently converted a <a href="http://gulpjs.com/">Gulp</a> + <a href="http://browserify.org/">Browserify</a> build for a large production app over to Webpack. While there were many pitfalls and a few failed production deploys along the way, it all came together in the end. One of the biggest sources of frustration was getting long term asset caching to work.</p><p>Long term asset caching is accomplished by adding a content hash to the filename of each public asset. This hash should only change when the content of the file changes. This enables browsers to download the assets on the user’s first visit and cache them for future visits. The file(s) will only need to be downloaded again if filename, and thus the file content has changed.</p><p>The first, successful long term caching setup I arrived at involved a combination of <a href="https://github.com/diurnalist/chunk-manifest-webpack-plugin">chunk-manifest-webpack-plugin</a> and <a href="https://github.com/erm0l0v/webpack-md5-hash">webpack-md5-hash</a> plugins. <a href="https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.fui0m6cct">Here</a> is great blog post on getting that to work. When upgrading to Webpack 2 beta, I was unable to get chunk-manifest-webpack-plugin to work due to some changes in the webpack api. Rather than use a <a href="https://github.com/brandondoran/chunk-manifest-webpack-plugin">fork</a> of the plugin I decided to pursue other approaches and ended up finding a more straight forward way. I’ve created a <a href="https://github.com/brandondoran/react-webpack-tutorial">repo on GitHub</a> to demonstrate how to accomplish long term caching on top of a React app. The awesome <a href="https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html">create-react-app</a> project was used to generate the base app. Generally, you’re only concerned with long term caching for production so this post will ignore the dev build and only focus on production.</p><h3><strong>Splitting the Bundle</strong></h3><p>A related optimization is splitting the Javascript bundle into separate vendor and application chunks. The vendor chunk will contain npm packages such as React, Angular, lodash, etc. The application chunk is just your app code. The idea is that vendor should change less frequently and in many cases is going to be larger than your app chunk. So if the vendor is separated out, returning users can use the cached version.</p><p>If we run <strong>npm run build</strong>, we get a single .js asset that includes a hash in the filename:</p><pre>File sizes after gzip:<br><br>  46.58 KB  build/static/js/main.fa1ac7bc.js<br>  289 B     build/static/css/main.9a0fe4f1.css</pre><p>This hash will change whenever the code for our app changes or if we install/uninstall packages from npm. The hash is the result of using [chunkhash] for <em>filename</em> and <em>chunkFilename</em> in the webpack config output:</p><pre>output: {<br>  path: paths.appBuild,<br>  filename: ‘static/js/[name].[chunkhash:8].js’,<br>  chunkFilename: ‘static/js/[name].[chunkhash:8].chunk.js’,<br>  publicPath: publicPath<br>}</pre><p>To split our bundle into separate vendor and app chunks, lets first create a vendor.js file that exports an array of vendor module names. The reason for this it just to be DRY. Since we’ll need to do this in both our development and production builds, having one file that is required by development and production configs is more maintainable.</p><pre>// config/vendor.js</pre><pre>module.exports = [<br>  &#39;react&#39;,<br>  &#39;react-dom&#39;<br>];</pre><p>Next, add the CommonChunksPlugin to our webpack config:</p><pre>new webpack.optimize.CommonsChunkPlugin({<br>  names: [&#39;vendor&#39;],<br>  minChunks: Infinity<br>})</pre><p>Finally, change the entry point in our webpack config to be an object with vendor and app keys instead of an array:</p><pre>var vendor = require (&#39;./vendor&#39;);</pre><pre>...</pre><pre>entry: {<br>  vendor // Use ES6 object literal property value shorthand<br>  app: [path.join(paths.appSrc, &#39;index&#39;)]<br>}</pre><p>Running <strong>npm run build</strong> will now generate separate app and vendor chunks:</p><pre>File sizes after gzip:<br><br>  46.28 KB  build/static/js/vendor.f3034dda.js<br>  944 B     build/static/js/app.9fa6cb3f.js<br>  289 B     build/static/css/app.9a0fe4f1.css</pre><h3><strong>Extracting Webpack Runtime</strong></h3><p>At first glance, this looks great. However, when we make a change to our app code we expect the app chunk’s hash to change but the vendor chuynk should stay the same. This is not the case. But why could that be? The answer lies inside the vendor chunk. If we peak into this file we’ll find the culprit:</p><pre>{ 1: “app” }[e] || e) + “.” + { 1: “9fa6cb3f” }[e] + “.chunk.js</pre><p>The vendor chunk is our entry point and therefore includes the webpack runtime, which maps chunk ids to chunk hashes. So whenever any module changes, the side affect is that entry point’s hash will change to0. This invalidates our cached vendor chunk every time we make a change to our app.</p><p>To solve this, we can extract the webpack runtime into a separate manifest chunk. Here is the one line change to our webpack config:</p><pre>new webpack.optimize.CommonsChunkPlugin({<br>  names: [&#39;vendor&#39;, &#39;manifest&#39;], // add manifest chunk<br>  minChunks: Infinity<br>}),</pre><p>Now the build output becomes:</p><pre>File sizes after gzip:<br><br>  45.8 KB  build/static/js/vendor.c5e4b74b.js<br>  945 B    build/static/js/app.ba4d0d56.js<br>  715 B    build/static/js/manifest.26d5bd51.js<br>  289 B    build/static/css/app.9a0fe4f1.css</pre><p>Let’s change some app code and rebuild and check the output:</p><pre>File sizes after gzip:<br><br>  45.8 KB  build/static/js/vendor.c5e4b74b.js<br>  948 B    build/static/js/app.db92bf79.js<br>  716 B    build/static/js/manifest.e7800a99.js<br>  289 B    build/static/css/app.9a0fe4f1.css</pre><p>Success! The app chunk’s hash changed and the vendor asset hash did not change. Also, our manifest asset changed, as you would expect. Since create-react-app uses <a href="https://github.com/ampedandwired/html-webpack-plugin">html-webpack-plugin</a>, the manifest automatically gets injected into our html. We now have long term caching working!</p><h3>Inlining manifest.js</h3><p>The manifest.js file is very small once minified and compressed, but it is still an additional network request the browser has to make. We can optimize further by inlining this small file in a script tag in our html. We can use <a href="https://github.com/szrenwei/inline-manifest-webpack-plugin">inline-manifest-webpack-plugin</a> to accomplish the inlining.</p><p>Add the plugin to our webpack config:</p><pre>var InlineManifestWebpackPlugin = require(&#39;inline-manifest-webpack-plugin&#39;);</pre><pre>...</pre><pre>new InlineManifestWebpackPlugin({ name: &#39;webpackManifest&#39; })</pre><p>We’ll also need to rename create-react-app’s index.html template to index.ejs and add the following line to it:</p><pre>&lt;%= htmlWebpackPlugin.files.webpackManifest %&gt;</pre><h3>Deterministic Builds</h3><p>It would seem we’re in good shape for long term caching in production now. But there’s still one more problem. Webpack, by default, assigns modules integer ids, based on order. So when modules are changed, all ids could change, invalidating the cache. Luckily, there is a way to prevent ids from changing. We can configure webpack to choose ids in a deterministic way by using NamedModulesPlugin. This just takes one addition to the plugins array in webpack config:</p><pre>new webpack.NamedModulesPlugin()</pre><p>A couple of points to keep in mind with this plugin:</p><ul><li>Because filenames are longer than ids, file sizes will be larger, although it’s very minimal after gzip.</li><li>File paths of modules are leaked, which could be a security issue.</li></ul><h3>HTTP Cache Headers</h3><p>All the work configuring webpack for long term caching is useless without setting the proper HTTP Cache-Control header for our assets on the server side. <a href="https://jakearchibald.com/2016/caching-best-practices/">Here</a> is some more reading on HTTP caching patterns. Because we are using filenames that include a hash that changes whenever the file contents change, we can consider the assets to be immutable content. Therefore we can use a long max-age for Cache-Control. Here is an example where max-age of is set for 1 year:</p><pre>Cache-Control: public,max-age=31536000</pre><h3>Final Thoughts</h3><p>Webpack is an amazing and powerful tool! The concepts and configuration can seem complex at first. But learning the tool is well worth the time. Webpack has an <a href="https://medium.com/webpack/webpack-its-getting-real-92c60fca1db1#.1k4puoth5">awesome core team</a> and docs are continuing to improve. Since introducing webpack at <a href="https://www.thredup.com/">thredUP.com</a>, we’ve been able to optimize our Javascript assets, not mention improving our build leading to a better developer experience. I’m looking forward to sharing some more tips we’ve learning along the way.</p><h4>Reference</h4><ul><li>Checkout the <a href="https://github.com/brandondoran/react-webpack-tutorial">github</a> repo for the full, working a app.</li><li><a href="https://medium.com/webpack/webpack-its-getting-real-92c60fca1db1#.k8pbvdud0">webpack: It’s getting real</a> by <a href="https://medium.com/@sokra?source=post_header_lockup">Tobias Koppers</a></li><li><a href="http://survivejs.com/webpack/building-with-webpack/splitting-bundles/">Bundle Splitting</a> by <a href="https://disqus.com/home/forums/survivejs/">SurviveJS</a></li><li><a href="https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.7rf7zr5kc">Long-term caching of static assets with Webpack</a> by <a href="https://medium.com/@okonetchnikov?source=post_header_lockup">Andrey Okonetchnikov</a></li><li><a href="https://jakearchibald.com/2016/caching-best-practices/">Caching Best Practices</a> by Jake Archibald</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad24a4c39bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/connect-the-dots/caching-assets-long-term-with-webpack-5ad24a4c39bd">Caching Assets Long Term with Webpack</a> was originally published in <a href="https://medium.com/connect-the-dots">Inside thredUP</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing queries in RethinkDB]]></title>
            <link>https://medium.com/connect-the-dots/optimizing-queries-in-rethinkdb-584d7f660cb?source=rss-ebe43075cc3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/584d7f660cb</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[rethinkdb]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Brandon Doran]]></dc:creator>
            <pubDate>Tue, 02 Feb 2016 16:15:13 GMT</pubDate>
            <atom:updated>2016-02-05T00:56:05.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://www.flickr.com/photos/brandondoran/5257202290"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMin0F_MzKtRLfzFd0pzWw.jpeg" /></a></figure><h3>Optimizing Queries in RethinkDB</h3><p>Anyone who’s been writing code for a couple of years has likely heard the quote “premature optimization is the root of all evil”. The idea is that it’s better to design and implement a clean solution that gets the job done, then benchmark and optimize later. While this is great advice, there comes the time, hopefully before going into production, when you need to address your applications performance. In this post I’ll be explaining how to optimize a query in <a href="http://rethinkdb.com/">RethinkDB</a>.</p><h4>RethinkDB</h4><p>At <a href="https://www.thredup.com/">ThredUP</a> we use an API backed by RethinkDB to power our shop web UI. RethinkDB is a realtime JSON database that, at least on the surface, has some resemblance to other NoSQL databases such as MongoDB. One difference is the RethinkDB query language called ReQL. With ReQL you build up queries on the client using your language of choice (JavaScript, Ruby, Python, and Java are supported) using a functional style syntax. When writing a ReQL query in application code, it looks and feels like a normal function but then once the code executes, the query runs on the database server. In this blog post, I’ll be using JavaScript for code samples. The RethinkDB JavaScript driver has both a promise based and callback based API. I’ll be using the promise API. The code samples assume you’ve configured RethinkDB and have an open connection referenced by the variable <em>conn</em>.</p><h4>Primary Keys</h4><p>RethinkDB tables have a primary key field, which you can specify at the time the table is created. The primary key must be unique just like in any other type of database. If not specified, RethinkDB will automatically create a primary key field named id, which is a UUID string. The <em>get</em> method in the RethinkDB api is used to efficiently query by the primary key. This method takes the primary key value and returns a single document. For example, if you have a table of blog posts you could retrieve a single document by it’s id using a query like this:</p><pre>r.table.get(&#39;00c0a336-b9dc-4e76-9392-23eec6839ce7&#39;).run(conn);</pre><h4>Queries on Non-Primary Keys</h4><p>More often than not you need to query based on one or more fields that are not primary keys. If we want to look up blog posts by author, the <em>get</em> method doesn’t work because it only returns a single document and there may be many posts by a given author. A simple way to do this is to use the <em>filter</em> method, which takes a object literal “predicate” and returns any document for which it is true. For example, to query for blog posts by a given author:</p><pre>r.table(&#39;posts&#39;).filter({ author: &#39;Kendra Mertz&#39; })<br> .run(conn)<br> .then(cursor =&gt; cursor.toArray())<br> .then(posts =&gt; console.log(posts));</pre><h4>Extending the Blog Posts Example</h4><p>Suppose we add tagging capability to our blog posts by adding a tags field, which is an array of strings. Now we want to look up all posts from a certain author <em>and</em> having a certain tag. The easiest way to do this is to change the query to use the row command along with eq and contains operators:</p><pre>r.table(&#39;posts&#39;).filter(<br> r.row(&#39;author&#39;).eq(&#39;Kendra Mertz&#39;).and(<br> r.row(&#39;tags&#39;).contains(&#39;cat&#39;))<br>).run(conn);</pre><p>Even more powerful and arguably more readable way to achieve the same functionality is to use an anonymous function as the argument to filter:</p><pre>r.table(&#39;posts&#39;).filter(<br>  post =&gt; r.and(post(&#39;author&#39;).eq(&#39;Kendra Mertz&#39;),<br>  post(&#39;tags&#39;).contains(&#39;cat&#39;))<br>).run(conn);</pre><p>These two queries return the correct results, however it can be made much more efficient. But in order to do so, we’ll need a secondary index. It turns out the <em>filter</em> method does not actually uses indexes at all.</p><h4>Secondary Indexes</h4><p>There are three types of secondary indexes:</p><ol><li><strong>Simple</strong>: on a single field</li><li><strong>Multi</strong>: on an array field</li><li><strong>Compound</strong>: combination of two or more fields</li></ol><p>To optimize our filter query we only need a simple index on author. We can create it like so:</p><pre>r.table(&#39;posts&#39;).indexCreate(&#39;author&#39;)<br> .run(conn)<br> .then(result =&gt; console.log(&#39;index created&#39;))<br> .catch(err) =&gt; console.error(err));</pre><p>Now instead of using filter, we can use the <em>getAll</em> method, specifying the index . Here’s an example, ignoring the tags criteria for now:</p><pre>r.table(&#39;posts&#39;)<br> .getAll(&#39;Kendra Mertz&#39;, { index: &#39;author&#39; })<br> .run(conn);</pre><p>Now to include tags in our query we just chain the filter command:</p><pre>r.table(&#39;posts&#39;)<br> .getAll(&#39;Kendra Mertz&#39;, { index: &#39;author&#39; })<br> .filter(r.row(&#39;tags&#39;).contains(&#39;cat&#39;))<br> .run(conn);</pre><p>This gives correct results but there is a much more efficient way to implement this query. Your first thought might be to create a new multi secondary index on the tags field. However, this will not help performance because, as we learned above, filter does not use indexes at all. To make this query more efficient we need to use an index mapping function like so:</p><pre>indexCreate(&#39;authorTags&#39;,<br>  (post) =&gt; post(&#39;tags&#39;).map(tag =&gt; [ post(&#39;author&#39;), &#39;tag&#39; ]),<br>  { multi: true }<br>).run(conn);</pre><p>Then the we can remove the filter and contains from our query and use the newly created index in a getAll:</p><pre>r.table(&#39;posts&#39;)<br> .getAll([&#39;Kendra Mertz&#39;, &#39;cat&#39;], { index: &#39;authorTags&#39; })<br> .run(conn);</pre><h4>Benchmarking</h4><p>In Node.js development a quick and dirty way to benchmark performance is just to measure the wall clock time by using <em>console.time</em> and <em>timeEnd</em>:</p><pre>console.time(&#39;get posts&#39;);<br>r.table(&#39;posts&#39;)<br> .getAll([&#39;Kendra Mertz&#39;, &#39;cats&#39;], { index: &#39;authorTags&#39; })<br> .run(conn)<br> .then(() =&gt; {<br>    console.timeEnd(&#39;get posts&#39;);<br>  });</pre><pre>// get posts: .8765ms</pre><p>Node core’s <a href="https://nodejs.org/api/process.html#process_process_hrtime"><em>process.hrtime</em></a> can be used instead if you need high resolution time (nanoseconds). This technique is great for getting a rough idea of performance, but sometimes you may need more statistically sound benchmarking. This is probably not something you want to take on yourself. Fortunately, John Dalton, creator of <a href="https://lodash.com/">lodash</a>, built the fantastic <a href="https://benchmarkjs.com/">benchmark.js</a> library. I created a <a href="https://github.com/brandondoran/rethinkdb-index-tuning">repo on github</a> to benchmark the RethinkDB queries from this article using benchmark.js. The repo sets up a test database with a single table containing 1000 blog posts, creates three different indexes, and benchmarks four different queries. The results, including ops/sec and mean run time, are logged to the terminal. The results show how significantly performance can be optimized by using the right index and RethinkDB query.</p><h4>Results</h4><ul><li>The two queries using filter perform nearly identical and clock in around <strong>95 ops/sec</strong> with <strong>10 ms</strong> mean run times.</li><li>getAll with filter chained we get a big improvement of <strong>620 ops/sec</strong> and <strong>1.61 ms</strong> mean run time.</li><li>mapped multi index is nearly twice as fast, clocking in at <strong>1,173 ops/sec</strong> and a <strong>.84</strong> mean run time.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584d7f660cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/connect-the-dots/optimizing-queries-in-rethinkdb-584d7f660cb">Optimizing queries in RethinkDB</a> was originally published in <a href="https://medium.com/connect-the-dots">Inside thredUP</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>