<?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 Jon San Miguel on Medium]]></title>
        <description><![CDATA[Stories by Jon San Miguel on Medium]]></description>
        <link>https://medium.com/@j.s.m?source=rss-9029162d1a48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vWrINUnsVjhSgHcV16Lsew.jpeg</url>
            <title>Stories by Jon San Miguel on Medium</title>
            <link>https://medium.com/@j.s.m?source=rss-9029162d1a48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:36:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@j.s.m/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[Turning My Techie Guilt Into Action]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/the-bold-italic/coming-to-terms-with-the-guilt-of-being-a-techie-turning-my-privilege-into-action-62aa3b9bf972?source=rss-9029162d1a48------2"><img src="https://cdn-images-1.medium.com/max/2400/1*k0XJ1VsRBuLs2oyauo8u5g.jpeg" width="2400"></a></p><p class="medium-feed-snippet">I want to use my privileges as a software engineer to actually make the world a better place</p><p class="medium-feed-link"><a href="https://medium.com/the-bold-italic/coming-to-terms-with-the-guilt-of-being-a-techie-turning-my-privilege-into-action-62aa3b9bf972?source=rss-9029162d1a48------2">Continue reading on The Bold Italic »</a></p></div>]]></description>
            <link>https://medium.com/the-bold-italic/coming-to-terms-with-the-guilt-of-being-a-techie-turning-my-privilege-into-action-62aa3b9bf972?source=rss-9029162d1a48------2</link>
            <guid isPermaLink="false">https://medium.com/p/62aa3b9bf972</guid>
            <category><![CDATA[tech-industry]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[san-francisco]]></category>
            <dc:creator><![CDATA[Jon San Miguel]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 19:43:31 GMT</pubDate>
            <atom:updated>2020-09-03T16:47:00.242Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Chapter in the Life of Go’s Compiler]]></title>
            <link>https://medium.com/samsara-engineering/a-chapter-in-the-life-of-gos-compiler-c89b9db74617?source=rss-9029162d1a48------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89b9db74617</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jon San Miguel]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 00:23:39 GMT</pubDate>
            <atom:updated>2021-04-20T18:14:03.078Z</atom:updated>
            <content:encoded><![CDATA[<p>Samsara had a large presence at last year’s Strange Loop. We set up a sponsor table where we got to meet some amazing developers and I had the opportunity to give <a href="https://youtu.be/BTY1LgGnLik">one of the talks</a>. In this blog post I’ll be diving into some interesting things I learned about Go’s compiler while I was working towards making our deploys faster.</p><h3>Intro</h3><p>At Samsara we use Go to power our Industrial IoT platform. When I say we use Go, I mean we <em>really</em> use it. A lot. For everything. I’m talking:</p><ul><li>Backend services</li><li><a href="https://github.com/samsarahq/thunder">Our GraphQL implementation</a></li><li>Firmware that runs on our devices</li><li>Feature flags</li><li>Managing users &amp; teams for things like github/aws/pagerduty/permissions</li><li>Generating Terraform files to codify the infrastructure that powers our services</li><li>Generating protobufs</li><li>Generating sql queries</li><li>Generating generators for sql queries</li><li>… and more</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/0*g0gbNLNQ7n-8Rfqg.png" /></figure><h3>Deterministic Deploys</h3><p>We also used Go to write our deployment orchestration. In trying to improve our deploy speed, one of the projects we worked on was making our deployments byte-for-byte deterministic. This helps with our deploys by:</p><ol><li>Reducing time spent moving docker layers across the network</li><li>Enables no-op deploys for unchanged microservices</li></ol><ul><li>Since we use a monorepo, changes to the repo trigger deploys for all services. Any way we can avoid doing a full deploy saves us time.</li><li>Saving on shutdown and startup time</li><li>Less downtime on singleton services. Services that we can only run one of at a time have a period of downtime until the new one comes up. The less this happens the better.</li><li>Prevention of initialization outages. Some outages are caused by things like config loading, bootup, etc. Minimizing startups allows services to run even in the event of a failure of any initialization dependencies.</li></ul><p>These both led to a big improvement for us in deploy speed &amp; reliability.</p><p>To get there, we had to:</p><ol><li>Make Golang compiles deterministic</li><li>Make Docker builds deterministic</li><li>Reduce large dependency graphs</li></ol><p>Golang has had some support for deterministic compiles since its 1.0, but for some reason our Go binaries were changing even when compiling the same code. While I was investigating why this was happening, I found an issue mentioning that the compiler’s determinism broke in Go 1.8beta. <strong>In this post, I’ll be diving into the developments that led to this regression in deterministic Golang compilation.</strong></p><blockquote><a href="https://youtu.be/BTY1LgGnLik"><em>To hear on a high level about everything else we did for this project, watch the live talk I presented at the Strange Loop conference in St. Louis!</em></a></blockquote><h3>Static Single-Assignment Form (SSA)</h3><p>Go 1.7 introduced a new compiler backend based on static single-assignment form (also known as SSA).</p><p>SSA is a compiler design principle around structuring the intermediate representation so that every variable is assigned exactly once. In compilers the intermediate representation is the data structure or code used internally by a compiler or virtual machine to represent source code. Using SSA enables the Go compiler to:</p><ol><li>Use some compiler optimizations it otherwise couldn’t have</li><li>Improve the performance of other compiler optimizations</li></ol><p>Both of which lead to better performance for our Go code.</p><p>To read more about SSA I’d recommend reading the slides from one of <a href="https://www.cs.cmu.edu/~fp/courses/15411-f08/lectures/09-ssa.pdf">Carnegie Mellon’s lectures</a>.</p><h3>Performance Regression</h3><p>While the SSA implementation was supposed to lead to better performance, it actually ended up degrading performance for a specific set of operations. Two divide operations ended up with about a 15% increase over the pre 1.7 compiler backend.</p><p>You can see the Github issue for this <a href="https://github.com/golang/go/issues/16061">here</a>.</p><p>The commit message for the fix says:</p><pre>When allocating registers, before kicking out the existing value,<br>copy it to a spare register if there is one. So later use of this<br>value can be found in register instead of reload from spill. This<br>is very helpful for instructions of which the input and/or output<br>can only be in specific registers, e.g. DIV on x86, MUL/DIV on<br>MIPS.</pre><p>Let’s break this down.</p><blockquote><em>When allocating registers</em></blockquote><p>Computer CPUs contain “registers,” which are used by the CPU to store data. Registers are the fastest place for CPUs to store data (faster than L1 Cache, RAM, &amp; SSDs), and the CPU can only have a limited amount of them.</p><p>When a computer process needs to do an operation, such as division, it will often use registers to store the input and/or output of that operation.</p><blockquote><em>before kicking out the existing value, copy it to a spare register if there is one.</em></blockquote><p>If an operation needs to load data into a register before it can happen, it will need to move any existing data in that register somewhere else. Since there aren’t many registers, the compiler can choose to move it into RAM. Rather than just moving it to RAM, this change makes it try to move it to another register instead. This, however, makes the compiler more complex as it now has to deal with understanding which registers are holding data that is being actively used as well as clean them up after they no longer are.</p><blockquote><em>So later use of this value can be found in register instead of reload from spill.</em></blockquote><p>If we happen to need the data that was previously in the register, we can now read it from the register instead of from the “spill,” which is a term for data that has been moved from the register to RAM.</p><blockquote><em>This is very helpful for instructions of which the input and/or output can only be in specific registers, e.g. DIV on x86, MUL/DIV on MIPS.</em></blockquote><p>While some CPU operations can refer directly to a value in RAM, some, like the DIV (division) operation on x86 (a specific Intel CPU architecture), need to have those values in a specific register. If the value is currently in RAM instead of a register, it needs to first copy that value out of RAM into the register. Accessing RAM is much slower than accessing a register, which leads to the 15% performance loss we see.</p><h3>Determinism Regression</h3><p>In addition to adding logic to copy registers instead of kicking them out to the spill, there needs to be logic to remove these copies if they end up never being used. While this fixed the performance regression, it also caused Go compiles to no longer be deterministic.</p><p>You can see the Github issue here: <a href="https://github.com/golang/go/issues/17288">https://github.com/golang/go/issues/17288</a></p><p>The following is a snippet from the code that was added to fix the previous performance regression. Can you spot the issue?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KH5R_VLjra_NwwJM" /></figure><p>The first thing to understand here is what s.copies is.</p><pre>// a set of copies we generated to move things around, and<br>// whether it is used in shuffle. Unused copies will be deleted. copies map[*Value]bool</pre><p>But what is a Value?</p><pre>// A Value represents a value in the SSA representation of the program.<br>// The ID and Type fields must not be modified. The remainder may be modified<br>// if they preserve the value of the Value (e.g. changing a (mul 2 x) to an (add x x)).<br>type Value struct {<br>  ...<br>  // Arguments of this value<br>  Args []*Value<br>  ...<br>}</pre><p>You can see that s.copies is a map of SSA values and c.Args is a slice of other Values that are used as arguments to that value.</p><p>Going back to the code snippet, when freeing an unused register copy, we also decrement Uses for the first Argument.</p><p>What if c.Args[0] is actually a register copy itself?</p><h3>The Fix</h3><p>Hopefully you might have an idea of what’s happening now, so let’s take a look at the fix.</p><p>One user in the issue thread asked an important question.</p><blockquote><em>Do we make copies of copies? Is it possible that copy A is the only use of copy B, and depending on whether we visit A before B will influence whether we’re able to eliminate B?</em></blockquote><p>He then implemented the following change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aq-EYu3hNvY2nTUW" /></figure><p>Rather than iterating through s.copies only once, we keep iterating through it until progress is false. progress will be true unless we don’t delete any copies in that iteration.</p><p>When calling c.Args[0].Uses — we may actually be freeing up another register copy, making it unused as well. Without the continued loop, this code can fail to erase an unused copy.</p><p>To illustrate this, let’s go through an example. Say we have two register copies, A and B. A is unused, whereas B is used but only as an argument to A. Let’s walk through two scenarios where the copies slice is ordered differently.</p><h3>Scenario 1</h3><pre>s.copies = [A, B]<br>NOTHING -&gt; A -&gt; B (NOTHING uses A, but A uses B)</pre><p>If we run through the code on the first iteration, we will determine that A is unused and erase it, leaving us with the following.</p><pre>s.copies = [B]<br>NOTHING -&gt; B (NOTHING uses B)</pre><p>Continuing on to B as part of the iteration, we determine that B is unused and erase it, leaving us with the following.</p><pre>s.copies = []<br>NOTHING -&gt; (All copies have been erased)</pre><h3>Scenario 2</h3><pre>s.copies = [B, A]<br>NOTHING -&gt; A -&gt; B (NOTHING uses A, but A uses B)</pre><p>If we run through the code on the first iteration, we will determine that B is still being used, and ignore it, leaving us with the same state.</p><pre>s.copies = [B, A]<br>NOTHING -&gt; A -&gt; B (NOTHING uses A, but A uses B)</pre><p>If we then continue on to A as part of the iteration, we will determine that A is unused and erase it, leaving us with the following.</p><pre>s.copies = [B]<br>NOTHING -&gt; B (NOTHING uses B)</pre><p>You can see that we end up with different states, causing our broken determinism.</p><h3>Fixed Scenario 2</h3><p>Let’s now add the fix to the equation and continue with the 2nd scenario. We are currently at the following state.</p><pre>s.copies = [B]<br>NOTHING -&gt; B (NOTHING uses B)</pre><p>By running the entire algorithm again, we will see that B is unused and erase it, leaving us with the same state as the 1st scenario.</p><pre>s.copies = []<br>NOTHING -&gt; (All copies have been erased)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*xxhvVSdTxttL_4nj" /></figure><p>This fix was merged in 1.8beta1, and you can see the issue <a href="https://github.com/golang/go/issues/17288">here</a>.</p><h3>Getting to Deterministic Builds</h3><p>Since we were already on go1.10, it didn’t seem that this exact bug should have affected us, but I was wondering if it could have been re-introduced in another way.</p><p>It turned out, however, that the reason our compiles were non-deterministic was that Golang’s host linker includes a randomly generated build ID in its binaries.</p><p>To get around this, we ended up compiling our binaries with this not well-documented flag:</p><pre>ldflags=”-linkmode=internal&quot;</pre><p>to use Golang’s internal linker, which does not include the build ID in the binary.</p><h3><em>Working @ Samsara</em></h3><p><em>At Samsara, we take pride in solving challenging problems and building the right solution, even if it means we might need to do a bit of digging.</em></p><p><em>Samsara is only about 5 years old, which means we are use a lot of the latest technology. We’ve also scaled to over 100 Billion sensor data points collected yearly, which means we run into some interesting challenges that most other companies haven’t seen. If you’d like to help solve them, </em><a href="https://grnh.se/40ca09bf1"><em>check out our open positions</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89b9db74617" width="1" height="1" alt=""><hr><p><a href="https://medium.com/samsara-engineering/a-chapter-in-the-life-of-gos-compiler-c89b9db74617">A Chapter in the Life of Go’s Compiler</a> was originally published in <a href="https://medium.com/samsara-engineering">Samsara R&amp;D</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Rake Multitask]]></title>
            <link>https://medium.com/@j.s.m/optimizing-rake-multitask-fece36a16c8f?source=rss-9029162d1a48------2</link>
            <guid isPermaLink="false">https://medium.com/p/fece36a16c8f</guid>
            <category><![CDATA[rake]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jon San Miguel]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 02:14:38 GMT</pubDate>
            <atom:updated>2018-09-28T17:46:01.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In a <a href="https://medium.com/engineers-optimizely/behind-the-scenes-rake-multitask-6a11058bc754">previous article</a>, I talked about how rake implements promises for better threading when running tasks concurrently.</p><p>Today, I’m going to talk about a small but very interesting optimization I made to speed things up.</p><h3>Numbers</h3><p>First let’s do some math</p><p>Given 12 tasks that each take about 1 second, how quickly should all of these complete when given N number of threads?</p><p>The answer is: 12s/N</p><p>Given proper division of labor, and efficient use of labor, this is what we should see.</p><p>Let’s write down some examples of N.</p><ul><li>N:6 = 2seconds</li><li>N:4 = 3seconds</li><li>N:3 = 4seconds</li><li>N:2 = 6seconds</li></ul><h3>Back to the Real World</h3><p>Now, timings are never going to be exact, given various overhead from the language, the cpu, etc. But it should be close.</p><p>What happens in Rake?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*Ru5rnERKp9yw38eyU_GMEg.png" /><figcaption>Test Rakefile</figcaption></figure><p>Running the test code, let’s see what happens by configuring rake with different threadpool sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*ruSLTWdO6V9vzG0i2w6ALw.png" /></figure><ul><li>N:6 = 2 seconds (Actual: ~3 seconds)</li><li>N:4 = 3 seconds (Actual: ~4 seconds)</li><li>N:3 = 4 seconds (Actual: ~6 seconds)</li><li>N:2 = 6 seconds (Actual: ~12 seconds)</li></ul><p>Not we’re expecting right? When using Ruby::Thread, we get the results we’re expecting, so what’s going on in the Promise code that makes this happen?</p><p>While I was working at Optimizely, we ran into this when we were using Rake to concurrently fetch package dependencies. I started diving into the Rake source (which is how I was able to write my previous blog post) to figure this out.</p><p>I eventually started looking into this line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T00cUE5bZ1uXAQ9jS1ZpzA.png" /><figcaption><a href="https://github.com/ruby/rake/blob/v12.3.1/lib/rake/task.rb#L250">https://github.com/ruby/rake/blob/v12.3.1/lib/rake/task.rb#L250</a></figcaption></figure><h3>The Fix</h3><p>From my previous post:</p><blockquote><em>When we use Promise.value, it has 3 paths instead:</em></blockquote><blockquote><em>- If it is not finished executing and a Thread is currently executing it — wait for the promise to finish</em></blockquote><blockquote><strong><em>- If it is not finished executing and a Thread is not currently executing it — the main Thread will pick up the work</em></strong></blockquote><blockquote><em>- If it is finished executing — receive the return value</em></blockquote><p>The bolded path is the one we want to take a deeper look at. Thinking about it, I eventually decided to try this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*G76Dq7cySCVfswIhpt_FAw.png" /></figure><p>Let’s see what the results are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*xp_UigZxFuDKPCxJKgJ_2w.png" /></figure><ul><li>N:6 = 2 seconds (Actual: ~2 seconds)</li><li>N:4 = 3 seconds (Actual: ~3 seconds)</li><li>N:3 = 4 seconds (Actual: ~4 seconds)</li><li>N:2 = 6 seconds (Actual: ~6 seconds)</li></ul><p>Now we’re pretty much getting the results we want. But why does this work?</p><h3>Explanation</h3><p>The explanation for this goes down into how thread scheduling typically works for most operating systems.</p><pre>Since Linux 2.6.23, the default scheduler is CFS, the &quot;Completely<br>       Fair Scheduler&quot;.  The CFS scheduler replaced the earlier &quot;O(1)&quot;<br>       scheduler.</pre><p>You can read into this more here: <a href="https://en.wikipedia.org/wiki/Completely_Fair_Scheduler">https://en.wikipedia.org/wiki/Completely_Fair_Scheduler</a></p><p>But the note to takeaway is that “The leftmost node of the scheduling tree is chosen”.</p><ul><li>Tasks created earlier will have a higher chance of being picked up by the Threadpool.</li><li>By reversing the order the parent task will have a higher chance of picking up the promise, rather than having to wait for it to finish.</li><li>When it has to wait for the promise to finish, it will actually sacrifice it’s thread, so that the Threadpool can use it to pick up another task.</li><li>This causes a thread to have to context switch, which can be an expensive operation when running many smaller tasks.</li><li>By minimizing the amount of thread context switches, we get better performance!</li></ul><h3>TL;DR</h3><p>Thread context switches are expensive, iterating through promises in reverse minimizes them.</p><p>Thanks for reading! You can see the PR I’ve submitted here: <a href="https://github.com/ruby/rake/pull/273">https://github.com/ruby/rake/pull/273</a></p><p>Also shoutout to Optimizely, for having been a wonderful place to work, and the company I’m at now, Samsara, for being awesome as well :) Both are hiring!</p><p><a href="https://www.samsara.com/careers">Careers at Samsara</a></p><p><a href="https://www.optimizely.com/careers/">https://www.optimizely.com/careers/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fece36a16c8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes: Rake Multitask]]></title>
            <link>https://medium.com/engineers-optimizely/behind-the-scenes-rake-multitask-6a11058bc754?source=rss-9029162d1a48------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a11058bc754</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rake]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Jon San Miguel]]></dc:creator>
            <pubDate>Thu, 15 Dec 2016 01:03:45 GMT</pubDate>
            <atom:updated>2016-12-15T22:56:21.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/903/0*IabR8zWulgIiHCcI." /></figure><h3>Introduction</h3><p>At Optimizely, we use the open source tool <a href="https://github.com/ruby/rake">Rake</a> quite heavily. While trying to figure out how to execute blocks of code in parallel, I ended up reading into the Rake::ThreadPool class, which is pretty interesting.</p><p>What I came up with was this: <a href="https://github.com/optimizely/rake-opt-parallel">https://github.com/optimizely/rake-opt-parallel</a>. Check out the README to see what it does!</p><p>But, let’s get back to the interesting part.</p><h3>Rake Tasks &amp; Multitasks</h3><p>First, let’s take a look at some rake code.</p><pre>task main: [:sub1, :sub2]</pre><pre>task :sub1 do<br>  puts ‘Subtask 1’<br>end</pre><pre>task :sub2 do<br>  puts ‘Subtask 2’<br>end</pre><p>Here, there’s a task called “main” that defines two prerequisites to be run: sub1 and sub2. When calling “rake main”, the output should look like</p><pre>Subtask 1<br>Subtask 2</pre><p>But instead of using the #task method to define main, you can also use #multitask like so</p><pre>multitask main: [:sub1, :sub2]</pre><p>This would call the prerequisites in parallel, meaning each task would execute concurrently.</p><p>Sidenote: since they are running concurrently, the output could be jumbled.</p><p>To understand how this works, let’s talk about Ruby’s Thread, which is what is used behind the scenes. Time to dive in.</p><h3>Ruby Threading</h3><pre>threads = 3.times.map do |i|<br>  Thread.new do<br>    1+1 # Just some random calculation<br>    puts “Thread #{i} done”<br>  end<br>end</pre><pre>threads.each do |t|<br>  t.join<br>end</pre><p>Each thread is a pthread managed by ruby. What we’re doing here is we’re creating 3 of them, and saving them all into an array. Afterwards, we go through all of them and call Thread#join, which waits until the thread has finished execution, effectively blocking the main code from continuing and exiting until all the threads have finished.</p><p>We should see something like the following:</p><pre>Thread 0 done<br>Thread 2 done<br>Thread 1 done</pre><p>There are two important things to note here:</p><ol><li>Although there’s only 3 blocks of work to be done, we have a total of 4 threads, the 3 we created, as well as the main thread.</li><li>The main thread is essentially unused while the other threads are executing</li></ol><p>Rake does a few tricks to get around these issues</p><h3>Rake::Threadpool</h3><p>Rake creates a Threadpool at initialization, which creates and manages threads. The number of threads it creates is based on the number of CPUs available, but can be overwritten with a flag.</p><pre># Rake source<br>@thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.suggested_thread_count-1)</pre><p>The threads are created an initialization and never disposed of, just reused. Also, you can see here that whatever thread count is requested, it subtracts one from the ThreadPool size. For example if the application requests 8 threads, it actually creates a ThreadPool with a size of 7.</p><p>This is possible because of Rake’s idea of “Promises”</p><h3>Rake::Promise</h3><p>A promise is a block of work to be done. When we were creating threads in my previous example, we were telling the threads what to do when we created them. Rake instead essentially creates threads that are idle, and waiting on work to be done. It thinks of the work to be done, and the Thread that actually does it as separate entities.</p><p>To see how this works, we’ll take a look at the Rake::Task definition.</p><pre>209 # Invoke all the prerequisites of a task.<br>210 def invoke_prerequisites(task_args, invocation_chain) # :nodoc:<br>211   if application.options.always_multitask<br>212     invoke_prerequisites_concurrently(task_args, invocation_chain)<br>213   else<br>214     prerequisite_tasks.each { |p|<br>215       prereq_args = task_args.new_scope(p.arg_names)<br>216       p.invoke_with_call_chain(prereq_args, invocation_chain)<br>217     }<br>218   end<br>219 end<br>220<br>221 # Invoke all the prerequisites of a task in parallel.<br>222 def invoke_prerequisites_concurrently(task_args, invocation_chain)# :nodoc:<br>223   futures = prerequisite_tasks.map do |p|<br>224     prereq_args = task_args.new_scope(p.arg_names)<br>225     application.thread_pool.future(p) do |r|<br>226       r.invoke_with_call_chain(prereq_args, invocation_chain)<br>227     end<br>228   end<br>229   futures.each(&amp;:value)<br>230 end</pre><p>When a task is called, the prerequisites are invoked. In the case of a normal task, you can see in line 214 that it just iterates through each prerequisite, and invokes it sequentially. However, in the case of a multitask, it defers to the #invoke_prerequisites_concurrently, which maps each prerequisite to a “future” using the thread_pool. A future is an instance of a Promise, which rake uses interchangeably (I’m not sure why they use two names, but trust me, they’re the same thing).</p><p>If you compare this to the Thread code we wrote, it looks very similar. For each block of work, map it, then iterate through them. The key difference is that when we iterate through them, we called #join on the threads, and with the futures/promises, we’re calling #value.</p><p>Recalling what Thread.join does:</p><ol><li>If it is not finished executing — wait for the Thread to finish,</li><li>If it is finished executing — receive the return value,</li></ol><p>When we use Promise.value, it has 3 paths instead:</p><ol><li>If it is not finished executing and a Thread is currently executing it — wait for the promise to finish</li><li>If it is not finished executing and a Thread is not currently executing it — the main Thread will pick up the work</li><li>If it is finished executing — receive the return value</li></ol><p>By separating the work, and the worker, it allows the opportunity for a new path, having the thread that is calling futures.each(&amp;:value) to possibly pick up the work itself, instead of just waiting for each piece of work to finish.</p><h3>Why is this useful?</h3><p>I’m sure you’re thinking, “Having one extra thread isn’t really a noticeable performance gain”. Let me tell you, you’re absolutely right. But it’s pretty cool right?</p><p>Just kidding, Promises are actually very useful.</p><p>One thing to consider is when rake is executing a tree of nested tasks.</p><pre>multitask main: [:a1, :a2]</pre><pre>multitask a1: [:b1, :b2]<br>multitask a2: [:b3, :b4]</pre><pre>multitask b1:[ :c1, :c2]<br>multitask b2:[ :c3, :c4]<br>multitask b3:[ :c5, :c6]<br>multitask b4:[ :c7, :c8]</pre><pre># This part is pseudocode, but you get what I mean<br>task c1…c8 do<br>  something<br>end</pre><p>Here we’re executing a task, that has a tree of prerequisites, with most of them just calling other tasks. If we wanted to have tasks c1..c8 execute at the same time and we were using normal Thread.join logic, each multitask would have it’s own Thread dedicated to just waiting for it’s children to finish. That’s a total of 15 threads for 8 tasks! Nearly a 50% increase in this case.</p><p>Using Rake::Promise, since a thread doesn’t need to be used for waiting on it’s children, we would only need the 8 threads for the 8 tasks.</p><p>Another thing to consider, even if the number of threads used by each were equivalent, is the cost of thread context switching. If a parent thread calls #value on a promise, it has the chance of picking up the work instead of waiting. Which means it can keep going instead of switching threads by waiting. Each thread context switch is CPU time that is wasted. While this may not matter much with large workloads, it can make a noticeable difference when running many small workloads. I’ll be talking more on this in a later blog post!</p><p>Anyways, I hope you enjoyed going on this adventure with me. If you have any questions, feel free to contact me at <a href="/service/mailto:jsm@optimizely.com">jsm@optimizely.com</a></p><p>Also, we’re hiring! Check out our <a href="https://www.optimizely.com/careers/">careers page</a> for openings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a11058bc754" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineers-optimizely/behind-the-scenes-rake-multitask-6a11058bc754">Behind the Scenes: Rake Multitask</a> was originally published in <a href="https://medium.com/engineers-optimizely">Engineers @ Optimizely</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>