<?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 Zachary Anker on Medium]]></title>
        <description><![CDATA[Stories by Zachary Anker on Medium]]></description>
        <link>https://medium.com/@zanker?source=rss-a29cf9bf448c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*s6MS67LEr3zHiXoe.</url>
            <title>Stories by Zachary Anker on Medium</title>
            <link>https://medium.com/@zanker?source=rss-a29cf9bf448c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:21:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zanker/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[Finding a Ruby bug with GDB]]></title>
            <link>https://medium.com/@zanker/finding-a-ruby-bug-with-gdb-56d6b321bc86?source=rss-a29cf9bf448c------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d6b321bc86</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zachary Anker]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 19:42:36 GMT</pubDate>
            <atom:updated>2018-01-26T02:20:17.021Z</atom:updated>
            <content:encoded><![CDATA[<p>While I was at Square, a coworker reported a bug to my team, and I’ve been meaning to write it up for a few months. <a href="https://github.com/nerdrew">Andrew Lazarus</a> deserves credit as well, since we worked together on debugging this over a few days.</p><p>This issue still exists in Ruby 2.5.0, and can be found as far back as Ruby 2.0.0. If you just want a summary of the bug, see <a href="https://bugs.ruby-lang.org/issues/13882">ruby-lang#13882</a>.</p><p>Someone reported they were seeing old Puma (a HTTP web server) processes hanging around after their app was deployed. Easy enough to confirm, SSH into the server, and run ps -fu foo</p><pre>% 20:42 &lt;zanker:~&gt; ps -fu foo<br>UID         PID   PPID  C STIME TTY          TIME CMD<br>33333      5105      1  0 Aug15 ?        00:00:05 puma: cluster worker 2: 61264 [foo_aaaaaa]<br>33333     26644      1  0 Jun29 ?        00:02:12 puma: cluster worker 0: 26639 [foo_bbbbbb]<br>33333     42796      1  0 Sep07 ?        00:05:43 puma: cluster worker 1: 53755 [foo_dddddd]<br>33333     59085      1  0 Aug29 ?        00:03:44 puma: cluster worker 2: 76064 [foo_eeeeee]</pre><p>Truncated for brevity, but multiple Puma workers with different SHAs (the foo_##### part) should never happen, especially not with start times (the STIME column) that are weeks old.</p><p>Given the age of the process, it wasn’t feasible to track down exceptions or logs, and we’re not even sure what we want was recorded properly. We started off by trying to replicate it, but deploying a few times yielded no results.</p><p>Since the parent process id (PPID column) is 1, we know these are orphaned processes and can be more aggressive in our debugging by attaching GDB and looking around.</p><p>Picking one of the processes at random, we run: cd foo_aaaaaa/ &amp;&amp; gdb ruby/bin/ruby 5105 . GDB was looking for a Ruby bin path that didn’t exist, and this way we get the symbols data in GDB. Symbols are important since it gives us the file/line number in Ruby’s C code to look at.</p><p>GDB is treating our process as a very complicated C program, since we want to get access to the Ruby state we need to run:</p><pre>define r_eval<br>  call (void)rb_p((unsigned long)rb_eval_string_protect(&quot;File.open(&#39;/tmp/caller.out&#39;, &#39;a&#39;) { |f| begin; f.write $arg0; f.write(&#39;\n&#39;); rescue =&gt; ex; f.write ex.inspect; f.write(&#39;\n&#39;); end }&quot;,(int*)0))<br>end</pre><p>This creates a GDB function which calls the Ruby VM to eval a string and dump the data to a file, even if we make a typo. Now we can run Ruby code, such as r_eval Process.pid and look at /tmp/caller.out to see the end result.</p><p>Threads are a good place to start to get an idea of the current state of the process, we can run, r_eval Thread.list.inspect:</p><pre>[<br>  #&lt;Thread:0x007fd99d4a2260@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 sleep_forever&gt;,<br>  #&lt;Thread:0x007fd99d4a2148@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 sleep_forever&gt;<br>]</pre><p>Weird! The process should have at least 5 threads running. We can look at what the thread is currently doing by running r_eval Thread.list.first.send(:caller).inspect:</p><pre>[<br>  &quot;eval:1:in `open&#39;&quot;, &quot;eval:1:in `block (2 levels) in spawn_thread&#39;&quot;,<br>  &quot;foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:106:in `sleep&#39;&quot;,<br>  &quot;foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:106:in `wait&#39;&quot;,<br>  &quot;foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:106:in `block (2 levels) in spawn_thread&#39;&quot;,<br>  &quot;foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:90:in `synchronize&#39;&quot;,<br>  &quot;foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:90:in `block in spawn_thread&#39;&quot;<br>]</pre><p>(Rerun it a few times to see if the thread is doing something else.)</p><p>Checking out the code for <a href="https://github.com/puma/puma/blob/v3.9.1/lib/puma/thread_pool.rb#L104-L107">thread_pool.rb</a> shows it’s waiting on not_empty.wait mutex, which is Puma sleeping until it gets a HTTP request to process.</p><p>Since Puma manages the startup/shutdown lifecycle, we move onto looking at Puma’s internal state withr_eval Thread.current[:puma_server].instance_variable_get(:@status).inspect which tells us it’s in the run state. From looking at the code, we see it should be stop if it were trying to shutdown.</p><p>For thoroughness, we can dump Puma’s thread pool with r_eval Thread.current[:puma_server].instance_variable_get(:@thread_pool).instance_variable_get(:@workers).inspect which leads to:</p><pre>[<br>  #&lt;Thread:0x007fd99d4a23a0@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 dead&gt;,<br>  #&lt;Thread:0x007fd99d4a2260@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 sleep_forever&gt;,<br>  #&lt;Thread:0x007fd99d4a2148@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 sleep_forever&gt;,<br>  #&lt;Thread:0x007fd99d4a2008@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 dead&gt;,<br>  #&lt;Thread:0x007fd99d4a1ec8@puma 005@foo_aaaaaa/bundle/ruby/2.4.0/gems/puma-3.9.1/lib/puma/thread_pool.rb:74 dead&gt;<br>]</pre><p>What. Puma has a reaper thread that is responsible for removing dead threads to make room for new ones… except that reaper thread is dead since it wasn’t in Thread.list.</p><p>Given everything we’ve found, it seems likely that Puma was attempting to shutdown, but was interrupted partway — perhaps by magic, maybe solar.</p><p>Back to GDB, we can run thread apply all backtrace which gives us the backtrace of all the running threads from the C perspective:</p><pre>Thread 1 (Thread 0x6f187658c83e (LWP 279882)):<br>#0  0x00000033d940b68c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0<br>#1  0x00007f9cb9847959 in native_cond_wait (cond=&lt;value optimized out&gt;, mutex=&lt;value optimized out&gt;) at thread_pthread.c:343<br>#2  0x00007f9cb98515b8 in native_sleep (th=0xb18d521b551d, timeout_tv=0x0) at thread_pthread.c:1147<br>#3  0x00007f9cb9851e34 in rb_thread_terminate_all () at thread.c:494<br>#4  0x00007f9cb9742466 in ruby_cleanup (ex=6) at eval.c:186<br>#5  0x00007f9cb9742725 in ruby_run_node (n=0xd368e9e61fd1) at eval.c:300<br>#6  0x00000000004008eb in main (argc=2, argv=0xe1f78525fd22) at main.c:36</pre><p>Looks promising! Pulling up the Ruby C for rb_thread_terminate_all:</p><pre>while (vm_living_thread_num(vm) &gt; 1) {<br>    /*<br>     * Thread exiting routine in thread_start_func_2 notify<br>     * me when the last sub-thread exit.<br>     */<br>    sleeping = 1;<br>    native_sleep(th, 0);<br>    RUBY_VM_CHECK_INTS_BLOCKING(th);<br>    sleeping = 0;<br>}</pre><p>We now know that at least one thread fails to exit, which creates an infinite loop and prevents the process from exiting gracefully. That doesn’t really help us a lot, because we didn’t think that was possible! As a hail mary, we went back to looking at the Ruby process itself.</p><p>By default, app exceptions and logs are reported using a background thread. Since that thread is killed at exit, maybe something got stuck in the queue that can give us better insight.</p><p>Omitting the relevant snippet, as it’s internal code, but the exception message wasThreadError: can&#39;t alloc thread and the stack trace pointed to ruby-kafka’s <a href="https://github.com/zendesk/ruby-kafka/blob/2c528704cf2154969bb675c999e568932672beac/lib/kafka/async_producer.rb#L146-L152">async_producer.rb</a> file.</p><p>Since we’ve not run into that exception before, it’s back to the Ruby C code:</p><pre>static VALUE<br>thread_s_new(int argc, VALUE *argv, VALUE klass)<br>{<br>    rb_thread_t *th;<br>    VALUE thread = rb_thread_alloc(klass);</pre><pre>if (GET_VM()-&gt;main_thread-&gt;status == THREAD_KILLED)<br>  rb_raise(rb_eThreadError, &quot;can&#39;t alloc thread&quot;);</pre><p>The error only comes up if you call Thread.new while the main VM thread is dead/dying. Makes sense, we don’t want to start a new thread during shutdown. Verifying against other orphaned processes shows they contain similar exceptions.</p><p>My personal guess was the ThreadError exception is corrupting the Ruby VM internal state on a thread, which prevents the thread from cleanly exiting. Since we’re unable to replicate it, we’ve nothing to go on beyond debugging after the fact.</p><p>From further digging, we found Ruby provides a THREAD_DEBUG option to give more low level debug info on threads… unfortunately you have to recompile Ruby to get it.</p><p>Before we tried deploying a debug version of Ruby, Andrew had the idea of looking into how ensure works. He figured out that the bug can be replicated with:</p><pre>Thread.new do<br>  loop do<br>    puts &quot;Loop start&quot;</pre><pre>    begin<br>      begin<br>        sleep<br>      ensure<br>        raise<br>      end<br>    rescue =&gt; e<br>      p e<br>    end<br>  end<br>end</pre><pre>sleep 1<br>exit</pre><p>After that, everything else was easy. We can recompile Ruby locally with THREAD_DEBUG to confirm that rb_threadptr_to_kill is being called. This is called by Ruby to mark a thread as exiting, and looks like:</p><pre>static void<br>rb_threadptr_to_kill(rb_thread_t *th)<br>{<br>    rb_threadptr_pending_interrupt_clear(th);<br>    th-&gt;status = THREAD_RUNNABLE;<br>    th-&gt;to_kill = 1;<br>    th-&gt;errinfo = INT2FIX(TAG_FATAL);<br>    TH_JUMP_TAG(th, TAG_FATAL);<br>}</pre><p>errinfo is a VALUE field that contains anything from a meta tag (such as TAG_FATAL) to the exception object if the thread had an exception. The majority of the state handling in threads is keyed off errinfo. We open up GDB on a stuck process, and run:</p><pre>(gdb) p ruby_current_thread-&gt;to_kill<br>$2 = 1<br>(gdb) p ruby_current_thread-&gt;status<br>$3 = THREAD_STOPPED<br>(gdb) p ruby_current_thread-&gt;errinfo<br>$4 = 8<br>(gdb)</pre><p>(0x08 is the value for nil in Ruby)</p><p>All of the stuck threads have the to_kill field set, but no errinfo , which confirms the initial theory that exceptions were causing the thread to lose the kill state.</p><p>Tying everything together, we now know the following has to happen:</p><ol><li>The thread needs to contain an infinite loop</li><li>The loop needs to include a begin rescue block</li><li>Within the begin block it needs another begin with an ensure</li><li>An exception has to happen within the embeddedensure, which is then rescued by the top level rescue</li></ol><p>The top level rescue is causing the Ruby VM to think the thread is “safe” and doesn’t have to be killed due to an exception. Unfortunately, this happens during shutdown which means the Ruby VM forgets that it needs to shutdown, and the infinite loop continues, and orphans the process.</p><p>The short-term fix is to ensure the relevant code using ruby-kafka never raises an exception. The long term fix requires fixing Ruby, which was reported in <a href="https://bugs.ruby-lang.org/issues/13882">ruby-lang#13882</a> and hopefully it’ll be fixed soon.</p><p>—</p><p>After the fact, Andrew figured out a better way of doing r_eval that goes to the GDB process stdout to avoid tailing a file.</p><p>Instead, when you sudo you run: sudo -iu &lt;user&gt; script -q /dev/null <br>And then you run GDB using: gdb -ex ‘set $tty=”’$(tty)’”’ -p &lt;pid&gt; <br>Finally, you define r_eval using:</p><pre>define r_eval<br>  eval &quot;call (unsigned long)rb_eval_string_protect(\&quot;File.open(&#39;%s&#39;, &#39;a&#39;) { |f| begin; f.puts $arg0; rescue =&gt; ex; f.puts ex.inspect; end }\&quot;,(int*)0)&quot;, $tty<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d6b321bc86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ruby VM and How Apps Break (Part 2)]]></title>
            <link>https://medium.com/@zanker/the-ruby-vm-and-how-apps-break-part-2-e8b4620ad50d?source=rss-a29cf9bf448c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b4620ad50d</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Zachary Anker]]></dc:creator>
            <pubDate>Wed, 25 Oct 2017 21:54:51 GMT</pubDate>
            <atom:updated>2017-10-30T21:44:16.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YdLu6Cr-8fYEL1BY6Qt2IQ.png" /></figure><p>See <a href="https://medium.com/@zanker/ruby-vm-and-how-apps-break-part-1-81a309384f39">Global Interpreter Lock, Threads, Lies and Metrics</a> for the first part of this. I’ll be covering how Ruby’s Incremental Generational Garbage Collector works in MRI 2.4.2, and how it can break your app.</p><p>In reality, Ruby’s GC is a lot more complicated than I’m outlining here. It has a lot of techniques built in to keep compatibility across versions and maintain performance. I’ll be outlining the gist of how it works, because it’s the relevant parts when trying to understand what GC metrics mean, and why your app is broken.</p><p>I’ve included a “Further Reading” section if you want to go deeper into how the garbage collector works in Ruby.</p><h3>Heaps, Pages and Slots</h3><p>Ruby allocates two heaps, one called eden which contains all pages that contain at least one alive object, and tomb which contains empty pages.</p><p>A heap contains a linked list of pages. Each page is 16KB, and on a 64-bit OS a slot takes 40 bytes, so a single page can hold around 408 slots. Within a page, it has a linked list of allocated and free slots.</p><p>A slot contains the type of object (string, boolean, integer, etc) and the value of the object. In some situations, such as strings above ~23 bytes, the value of the object is stored outside of the slot, and the slot stores a reference to the memory.</p><p>Depending on the size of the Ruby object, the entire value of the object is stored within the slot. In some scenarios, such as large strings, the string will be stored outside of the slot. A slot is still used to maintain a reference to the memory</p><p>For the sake of brevity, I’m skipping over the linked list to track pages for mark/sweep, as it’s not relevant to the explanation. Visually, the Ruby heaps look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XModTx-lv25YNu4q55NR9g.png" /><figcaption>In a real process, there’s quite a lot more pages and slots.</figcaption></figure><h3>Mark and Sweep</h3><p>At its core, Ruby uses a mark-and-sweep algorithm. If you want to go down the rabbit hole, Wikipedia has an <a href="https://en.wikipedia.org/wiki/Tracing_garbage_collection">article on it</a>.</p><p>The algorithm is straight forward, we start with a page from the eden heap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YtrfcgenpvWDiutb8QTiiQ.png" /></figure><p>The Ruby VM then walks the slots within the page checking if it has any references, and marks them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ldlyoXfbpSYVTn6Gl6DKZw.png" /><figcaption>Marked slots are in green. White ones are unreferenced.</figcaption></figure><p>Once the mark phase completes, the sweep runs which frees any unmarked (white) slots and moves them to the free slots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Azmh9jMfoxrvNdjhiFljYQ.png" /><figcaption>Only one slot was unreferenced.</figcaption></figure><p>Repeat until your process exits.</p><p>In Ruby 1.9.3, this was further improved to do a mark-and-sweep, then lazily run sweeps to reduce the pause time during GC.</p><h3>Generational Garbage Collector</h3><p>The main problem with the basic mark-and-sweep algorithm is it requires you to walk every object to ensure it’s still referenced. A Rails process for example, will allocate a lot of objects during boot that will never be garbage collected, and then allocate short lived objects to handle requests.</p><p>To improve performance, Ruby 2.1 added generational GC. This is semantically similar to the one in the JVM, but Ruby only has two buckets, NewGen and OldGen.</p><p>Newly created objects are put into NewGen, and if they survive 3 GCs are promoted to OldGen. Now instead of walking every object, Ruby walks the NewGen bucket during a minor GC, and both NewGen and OldGen during a major GC.</p><h3>Incremental Garbage Collector</h3><p>The generational garbage collector improved things, but it’s still not perfect. Ruby 2.2 added a full incremental garbage collector, which will lazily mark objects allowing it to mark a subset of slots at a time, and then lazily sweep them.</p><p>Instead of spending 100ms on a full mark-and-sweep, you could spend 5ms on a mark and 5ms on a sweep, repeated 10 times. The overall time spent on GC is still the same, but you have more predictable pauses in your app.</p><h3>How Apps Break the GC</h3><p>Given all this, there are a few ways you can break a process.</p><p>Most GC issues come down to allocating objects too aggressively in a single request, which forces Ruby to run more major GCs. It’s easy to identify when looking at metrics, since you will see a spike in major GCs.</p><p>Because GC (even incremental GC) in Ruby requires stopping the world, you run into the same issues outlined in <a href="https://medium.com/@zanker/ruby-vm-and-how-apps-break-part-1-81a309384f39">part 1</a> around thread contention. If you see a large amount of time spent in GC, you can’t trust your timing metrics anymore.</p><p>Your timing metrics being thrown off makes it harder to sort out where the memory leak was introduce. Sometimes, you can use the metrics if you go far enough back and find the sweet spot where it slows down but before it goes into a GC death spiral. Otherwise, you have to rely on diffing new vs old code.</p><p>Typically, when looking at code to determine where the problem started, I look at code that talks to a SQL database. Anything from a N+1 query due to missing eager loads, to loading tens of thousands of ActiveRecord objects, or doing map(&amp;:id) instead of pluck(:id). Those tend to be the common mistakes that lead to GC thrashing.</p><h3>Memory Fragmentation</h3><p>While Ruby eventually frees up pages (and thus memory) in the Tomb Heap, getting a page into the Tomb Heap requires all slots in the page to be freed. What if we have two pages that look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GH7pYk6HHFcmln-8rT1svg.png" /></figure><p>Ideally, the Ruby VM would compact it into a single page that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*p234YInIMP-VK6eaG8WyQw.png" /></figure><p>Which would allow page 2 to be moved to the Tomb Heap and free up memory. The Ruby VM can only free up a page if all the slots in it are free, it does not compact partially full pages. If you repeat the process enough, you can end up with a slow leak in memory.</p><p>In general, this is a rare issue. I’ve only seen it come up a handful of times, and it was because the app had requests that allocated a variably large chunk of memory, that was then freed up immediately after.</p><p>The fix was to use a different allocator, and reduce the GC_HEAP_GROWTH_FACTOR value, which reduced the exponential growth of the heap. Although this is no longer necessary with Ruby 2.4.2, because it now allocates based on a goal ratio, and GC_HEAP_GROWTH_FACTOR defaults to 1.0.</p><h3>jemalloc</h3><p>jemalloc is magical. It’s built with the aim of reducing memory fragmentation in multi-threaded programs, which uses multiple arenas to allocate memory rather than a shared one.</p><p>We had moved all of Square’s big Ruby apps to jemalloc, and it reduced memory usage by around 20% to 30% depending on the app, as well as a minor improvement to GC time.</p><p>There are other alternative allocators, such as <a href="http://goog-perftools.sourceforge.net/doc/tcmalloc.html">tcmalloc</a>. I’ve heard of good results with using that, but haven’t personally tried it. I always recommend swapping out malloc with (at least) jemalloc for a Ruby app given how easy it is to do.</p><h3>GC Tuning</h3><p>Historically, tuning your GC was a necessity because Ruby defaults were inappropriate for Rails app, and the GC was immature. As of Ruby 2.4, I’ve been recommending people don’t tweak the GC by default.</p><p>What I’ve usually seen happen, is someone tries to configure 8 GC options, a year later Ruby has made improvements, their app has changed, and the GC settings are no longer appropriate and hurt more then help.</p><p>One exception to this is the RUBY_GC_HEAP_INIT_SLOT ENV variable, which was called RUBY_HEAP_MIN_SLOTS until Ruby 2.1. The option controls how many slots (and thus, pages) should be allocated at boot time. As of Ruby 2.4, it defaults to 10,000.</p><p>A typical Rails app will use <em>at least</em> a hundred thousand slots, and I’ve seen even basic ones use 800,000+. This leads to the GC spending more time allocating slots as your app boots up.</p><p>It’s an easy option to tune, and short of deleting large chunks of code, doesn’t hurt you if it becomes out of date. Easiest way to figure out a default value is to open a Rails/irb console, run GC.stat[:heap_live_slot] , and set that as your RUBY_GC_HEAP_INIT_SLOT .</p><p>The heap_live_slot metric is how many slots are still in use and survived GC.</p><h3>Further Reading</h3><p>Aaron Patterson’s <a href="https://tenderlovemaking.com/2017/09/27/visualizing-your-ruby-heap.html">Visualizing Your Ruby Heap</a> goes in depth with how memory is aligned and allocated, as well as general visualization tricks.</p><p>Koichi Sasada, who wrote the generational GC used in Ruby 2.1, wrote <a href="https://blog.heroku.com/incremental-gc">Incremental Garbage Collection</a>, which covers how incremental GC was implemented to maintain compatibility with C libraries.</p><p>Jason Evans <a href="https://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf">paper on jemalloc</a> goes into further detail of how it works</p><p>Hopefully this was an educational read. Let me know if you think I missed something, or you’re interested in learning more and I can write a follow up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b4620ad50d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ruby VM and How Apps Break (Part 1)]]></title>
            <link>https://medium.com/@zanker/ruby-vm-and-how-apps-break-part-1-81a309384f39?source=rss-a29cf9bf448c------2</link>
            <guid isPermaLink="false">https://medium.com/p/81a309384f39</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zachary Anker]]></dc:creator>
            <pubDate>Sun, 22 Oct 2017 07:35:53 GMT</pubDate>
            <atom:updated>2017-10-30T21:13:49.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7Kmu6PeiKf4Maa6slY9PhQ.png" /></figure><p>While I was at Square, I helped debug a lot of Ruby apps, and learned a few tricks for narrowing down what was wrong by looking at the Ruby VM.</p><p>This is the first of two posts, with this one covering the Global Interpreter Lock, thread contention, and why app metrics can lie to you. The second part will cover how Ruby’s Garbage Collector works, and why your app can slowly fragment memory despite your code not having any memory leaks.</p><p>Everything covered here is against MRI 2.4.2, I don’t know of any changes in MRI 2.5.0 that will invalidate anything here. If you’re using JRuby, then none of this applies to you, as that uses the JVM.</p><h3>Global Interpreter/VM Lock</h3><p>The <a href="https://en.wikipedia.org/wiki/Global_interpreter_lock">Global Interpreter Lock</a> (GIL), also known as the Global VM Lock (GVL) within Ruby, forces Ruby apps to run concurrently. Ruby uses a GVL because it simplifies the VM internals, since you don’t have to deal with thread safety, and also allows for greater compatibility with C libraries that aren’t thread safe.</p><p>As a refresher on concurrency vs parallelism. Concurrency is having multiple threads that are alive, but only a single one is executing at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwL-ud0Jz4OcBIcmdi7Cag.png" /><figcaption>The actual order threads run in will vary based on the OS scheduler, and the code being run.</figcaption></figure><p>Whereas parallelism can have multiple threads that are executing simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYBmxBMtSBOKnKNQTPgD7w.png" /></figure><p>Internally, Ruby acquires the GVL, runs Thread #1 until the scheduler decides to pause it, releases the GVL, then reacquires it to run Thread #2, and so on. Whenever you call sleep or IO.select (which ultimately calls sleep), the GVL is released, and another thread can run.</p><p>Ruby 3 has a proposal for adding true parallelism through Guilds, but Ruby 3 is a few years out still. Olivier Lacan <a href="http://olivierlacan.com/posts/concurrency-in-ruby-3-with-guilds/">explains more on Guilds</a> if you want to learn more.</p><h3>Thread Contention</h3><p>Because of the GVL, each thread has to compete for execution time within a single Ruby process. When using a threaded web server, such as <a href="https://github.com/puma/puma">Puma</a>, this can lead to unpredictable performance. For example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1f67008bfef7fbbeeb11db5a822c19f/href">https://medium.com/media/f1f67008bfef7fbbeeb11db5a822c19f/href</a></iframe><p>When monitoring response times, you would see Thread #2 start to take longer to respond, when in reality Thread #1 is causing the problems. Because Thread #1 is a tight loop, the Ruby VM doesn’t have easy places to pause the thread, like you would during an IO operation. This will lead to Thread #2 taking longer to respond, even if nothing is wrong with that code.</p><p>Short of modifying the Ruby VM itself, I’m not aware of a blessed way to measure thread contention. I settled on using a thread which sleeps for 1 second, and then measures how long we were slept over that second.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81ace03abc054142577b6c9f273a8076/href">https://medium.com/media/81ace03abc054142577b6c9f273a8076/href</a></iframe><p>The reported time is then how much time was “stolen” from our thread. If it’s only a few milliseconds, nothing to worry about, but if it’s spiking to 100s of milliseconds, then we know something is overloading the Ruby VM.</p><p>In general, thread contention issues come down to doing too much in Ruby land in a single process. The only fix is to do less, whether it’s running more processes and less threads, or optimizing your code.</p><p>One memorable case of this causing issues, was one of the gems Square used for reporting exceptions had some performance issues. Exceptions were infrequent enough that it didn’t cause a problem originally.</p><p>One day a bug made it to production which caused an exception, and was triggered frequently enough to cause thread contention issues. After that, the app went into a death spiral with requests queuing up that it would never process in time, and had to be restarted.</p><p>Also a good example for why you should ensure your app servers <a href="https://medium.com/square-corner-blog/faster-app-recovery-with-bounded-queues-d546820a0abc">quickly reject requests when overloaded</a>.</p><h3>Lies and Metrics</h3><p>Any kind of monitoring tool, such as NewRelic or DataDog instruments your Ruby app with a snippet like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eec5eaf64f1a04e554ef91416b26d54/href">https://medium.com/media/6eec5eaf64f1a04e554ef91416b26d54/href</a></iframe><p>Because Ruby runs concurrently, any kind of timing metrics will be thrown off when thread contention happens. Here’s an annotated example of a timing metric being thrown off:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5500bb0307cccb68b24934c6e2651f45/href">https://medium.com/media/5500bb0307cccb68b24934c6e2651f45/href</a></iframe><p>It’s important to always check metrics from multiple sources, rather than relying solely on what the app is reporting.</p><h3>Why Use Threads?</h3><p>Your typical app is a business logic wrapper around a database and a set of web services. If you have 30 processes and half of your time is spent waiting on an IO call, then all 30 processes spend half of their time sleeping.</p><p>With threads, you could run 15 processes with 2 threads and drop your memory usage by half. Or you could run 5 processes with 6 threads to further reduce memory usage.</p><p>Since threads are competing for resources, you can’t just configure your app to use 100 threads to serve requests. You would slow down your app during heavy load. The exact ratio of processes to threads varies on the app, and is something you can only find with experimenting.</p><h3>Next up, Garbage Collection</h3><p>In the last part, we’re going to cover how Ruby’s Incremental Generational Garbage Collector works, and why it requires so many words to describe. <a href="https://medium.com/@zanker/the-ruby-vm-and-how-apps-break-part-2-e8b4620ad50d">Check it out here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81a309384f39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster App Recovery With Bounded Queues]]></title>
            <link>https://medium.com/square-corner-blog/faster-app-recovery-with-bounded-queues-d546820a0abc?source=rss-a29cf9bf448c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d546820a0abc</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Zachary Anker]]></dc:creator>
            <pubDate>Wed, 21 Jun 2017 18:08:07 GMT</pubDate>
            <atom:updated>2019-04-18T22:13:15.583Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Heads up, we’ve moved! If you’d like to continue keeping up with the latest technical content from Square please visit us at our new home <a href="https://developer.squareup.com/blog">https://developer.squareup.com/blog</a></blockquote><p>A problem we’ve encountered in the past is when a Ruby app becomes unresponsive due to downstream issues. After the issue is resolved, the app continues to be unresponsive or very slow to process requests. While a restarts clear it up immediately, but the less manual steps we have to take to recover an app, the better.</p><p>Because testing on production is bad, we need a simple way of replicating this locally.</p><h3>Replication</h3><p>At Square, our Ruby apps use <a href="https://www.nginx.com/">NGINX</a> and <a href="https://github.com/puma/puma">Puma</a> to serve requests. We write out a simple <a href="https://gist.github.com/zanker/e0ca717bcc9cd11859872c2c73505758">server side test case</a>, which we can run by using nginx -v ./nginx.conf and puma -C puma.rb. Then we set up the client side test case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff2219c211dfdf62f9b48eb2b998be0/href">https://medium.com/media/fff2219c211dfdf62f9b48eb2b998be0/href</a></iframe><p>Now we have a test endpoint, which sleeps for 5 seconds before responding, and the benchmark which makes 10 requests. With our initial configuration, the benchmark looks like:</p><pre>Starting…<br>[0] 200 - 4.13 seconds elapsed<br>[1] 200 - 9.13 seconds elapsed<br>[2] 200 - 14.13 seconds elapsed<br>[3] 200 - 19.13 seconds elapsed<br>[4] 200 - 24.14 seconds elapsed<br>[5] 200 - 29.14 seconds elapsed<br>[6] 504 - 29.70 seconds elapsed<br>[7] 504 - 29.80 seconds elapsed<br>[8] 504 - 29.90 seconds elapsed<br>[9] 504 - 30 seconds elapsed<br>Took 30.0102 total, avg of 21.9242 in thread time, max 30, min 4.13</pre><p>Requests #0 through #5 returned HTTP 200 Success and #6 through #9 returned HTTP 504 Gateway Timeout. This is expected since our test case for NGINX has proxy_read_timeout 30s set, and Puma is configured to process one request at a time, it takes about 30 seconds to process the first 6 requests, and the remaining 4 timeout in NGINX.</p><p>Comparing the Puma logs, we see that Puma saw 10 requests, all of which returned HTTP 200s, NGINX saw the same as the client, 6 requests with HTTP 200 and 4 with HTTP 504.</p><p>This is one of those fun gotchas. The client spent 30 seconds waiting for responses, but the server took 50 seconds to process it. Here’s what’s going on:</p><pre>00:00 — [A] Client sends request A to Server<br>00:01 — [A] NGINX buffers the HTTP request into memory and sends it to Puma<br>00:01 — [A] Puma accepts the connection, reads the request into memory and queues it<br>00:03 — [B] Client times out, sends request B to Server<br>00:04 — [B] NGINX buffers the HTTP request into memory and sends it to Puma<br>00:04 — [B] Puma accepts the connection, reads the request into memory and queues it<br>00:05 — [A] Puma starts processing the request, and responds with it to NGINX<br>00:06 — [A] NGINX throws the response away since the client closed the connection for A<br>00:06 — [B] Puma starts processing the request, responds with it to NGINX<br>00:07 — [B] Client receives the response for B</pre><p>Even better is if the client has automated retries. If a client has a timeout of 500ms on the endpoint /api/v1/update-user, and that endpoint now takes 1,000ms, the server has to spend 1,000ms of processing time for every 500ms the client spends. If the client retries 3 times, your server now spends 3,000ms for every 1,500ms the client spends.</p><p>Especially in a microservice architecture, that one endpoint could call another service, which calls another and so on. We’d quickly end up DoSing ourselves, and making an outage worse than it was originally due to requests being backlogged.</p><p>Ideally, our app is configured to reject requests when it’s overloaded. It prevents the above scenario of cascading failures, and means the app can recover without having to restart and flush out all the long running requests.</p><p>In this case, we have a few levers we can tweak. We’ll start with the obvious one, which is Puma.</p><h3>Restricting Requests In Puma</h3><p>Digging through the Puma code, we found that by default, Puma has an unbounded queue, and accepts a connection from the socket then queues it up for processing in server.rb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce079efe7df9d1430674bfddab9feaec/href">https://medium.com/media/ce079efe7df9d1430674bfddab9feaec/href</a></iframe><p>Double-checking the thread_pool.rb in Puma, we find:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f690172f199f181ff1e903dc4a86a5f1/href">https://medium.com/media/f690172f199f181ff1e903dc4a86a5f1/href</a></iframe><p>The variable @todo is an unbounded array which stores the HTTP requests in memory until a thread is available to process. If our app is unable to keep up, we could have a queue with hundreds/thousands of requests that timed out a long time ago. The app may eventually catch up, but we don’t want to wait 10 minutes for it to recover if 95% of the requests it is processing timed out already.</p><p>Looking at the code though for server.rb, the pool.wait_until_not_full unless queue_requests option looked promising. Turns out, it’s an option that does exactly what we want! We can make Puma only accept connections when it has a thread available to do so.</p><p>As a note, Puma 3.9.0, which was released at the start of June 2017, now <em>only</em> accepts a connection if it can immediately process it. The timing was unrelated to our digging into it, and was a happy coincidence.</p><p>After all that, we add queue_requests false to our Puma configuration and rerun the test… and get exactly the same results. Puma processed 10 requests, and the benchmark saw 6 successes and 4 failures.</p><p>From prior experience in working with sockets, we know that eventually a TCP socket ends up using the syscall <a href="https://linux.die.net/man/2/listen">listen</a> (in Linux). Looking at the documentation, we see the backlog argument which “defines the maximum length to which the queue of pending connections for sockfd may grow”.</p><h3>Queues All The Way Down</h3><p>One of the core parts of TCP is buffering. When clients send HTTP requests, they don’t first connect, wait for the server to accept, and send the HTTP request. They attempt to send off everything at once and parts of the request will sit in buffers between the client and the server until the server accepts the connection or times out.</p><p>Good for performance, not so when we want predictable request queuing. At this point, we pinged Evan Miller, a fellow Square engineer, on the semantics of backlog and queues, which led to learning that Linux has a backlog for post-handshake sockets (the backlog we’re looking at) and then also a pre-handshake socket. This gets into semantics of how TCP works, which I won’t cover here but <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment">Wikipedia</a> has an article explaining the handshake process.</p><p>Because we’re putting NGINX in front of Puma, we actually have four additional queues: one pre and post handshake in Puma, and another in NGINX. Looking at our server configuration and the documentation, we found the max backlog is 128 for the post-handshake queue.</p><p>We configured Puma to use a backlog of 2x what a single instance could process. For example, if one of our smaller apps can handle 10 requests simultaneously, we set the backlog to 20. Given there are multiple TCP queues, this isn’t perfect, but it helps narrow the funnel of where requests can queue up.</p><p>We’ve done what we can for the Puma side, but we still haven’t looked at NGINX.</p><h3>Restricting Requests in NGINX</h3><p>After chatting with other engineers, they mentioned <a href="http://nginx.org/en/docs/http/ngx_http_upstream_module.html#server">max_conns</a>, a NGINX option that became available in 1.11.5 (the paid version had it earlier).</p><p>The documentation looked promising, “limits the maximum number of simultaneous active connections to the proxied server”, though it has some caveats further down noting it can exceed the limit due to keep alive connections.</p><p>We used the same defaults we settled on for the backlog: each instance can queue up to 2x the requests it can handle at once. For our test, the server handles 1 request at a time, and we set max_conns=3. Rerun the test, and we see:</p><pre>Starting…<br>[0] 200 - 4.13<br>[1] 200 - 9.14<br>[2] 200 - 14.14<br>[3] 502 - 0.01<br>[4] 502 - 0<br>[5] 502 - 0<br>[6] 502 - 0<br>[7] 502 - 0<br>[8] 502 - 0<br>[9] 502 - 0<br>Took 14.14 total, avg of 2.74 in thread time, max 14.14, min 0</pre><p>Puma logs only show 3 requests, and nginx rejected the other 7 because we exceeded the maximum number of connections.</p><h3>Summary</h3><p>Queues are fun, and trying to ensure everything between the client and the server is complicated. The NGINX max_conns option is good enough for most cases, and has the added advantage of rejecting requests before it hits the Ruby apps. The TCP backlog and nginx queuing changes are an extra layer of protection, and reduce the chance of long-lived requests hiding out in a queue between NGINX and Puma.</p><p>With these changes, we’re expecting to see more deterministic failure modes when apps slow down due to downstream issues. Instead of queuing up more requests than the app can realistically process, they’ll start responding with errors more quickly.</p><p>These aren’t perfect, but the faster an individual host goes unhealthy, the faster it can be taken out of rotation and given a chance of catching up and becoming healthy again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d546820a0abc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/square-corner-blog/faster-app-recovery-with-bounded-queues-d546820a0abc">Faster App Recovery With Bounded Queues</a> was originally published in <a href="https://medium.com/square-corner-blog">Square Corner Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing ruby-protobuf deserialization by 50%]]></title>
            <link>https://medium.com/@zanker/optimizing-ruby-protobuf-deserialization-by-50-d54ffccb60c8?source=rss-a29cf9bf448c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d54ffccb60c8</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Zachary Anker]]></dc:creator>
            <pubDate>Fri, 09 Jun 2017 21:54:51 GMT</pubDate>
            <atom:updated>2018-01-23T04:11:28.350Z</atom:updated>
            <content:encoded><![CDATA[<p>(This is a repost on Medium of something I wrote at the end of 2015 while at Square)</p><p>I’m on a team colloquially called “WebScale” at Square, which deals with extracting legacy payments data from our monorail. One of our recent tasks has been the rollout of a new internal service to search for payments on Square. We mostly use protobuf as our data transport, and a single payment proto is about 1,500–2,000 bytes when serialized and returns up to 500 records per request.</p><p>Once rollout of the new service started, a few requests from a Ruby MRI 2.2.3 client went from 250ms to 1,600ms on. We already have metrics around time spent in RPC requests, so we took a guess that protobuf deserialization was the culprit.</p><p>To verify our guess, we used <a href="https://github.com/ruby-prof/ruby-prof">ruby-prof</a> to profile code in Ruby (in this case, the <a href="https://github.com/ruby-protobuf/protobuf">protobuf</a> gem). RubyProf is a helpful tool for profiling MRI code, and here’s how we used it to find hotspots.</p><p>Our test case:</p><pre>require &#39;protobuf&#39;<br>require &#39;ruby-prof&#39;</pre><pre><em># Just so we don&#39;t get spammed when testing</em><br>Protobuf<strong>.</strong>print_deprecation_warnings <strong>=</strong> <strong>false</strong></pre><pre><em># Construct a proto that mimics the size of our production responses</em><br>encoded <strong>=</strong> RecordResponse<strong>.</strong>new(<br>  payment: 500<strong>.</strong>times<strong>.</strong>map <strong>do</strong> <strong>|</strong>i<strong>|</strong><br>    Record<strong>.</strong>new( <strong>.</strong>.<strong>.</strong>test data<strong>.</strong>.<strong>.</strong> )<br>  <strong>end</strong><br>)<strong>.</strong>encode</pre><pre>result <strong>=</strong> RubyProf<strong>.</strong>profile <strong>do</strong><br>  RecordResponse<strong>.</strong>decode(encoded)<br><strong>end</strong></pre><pre>printer <strong>=</strong> RubyProf<strong>::</strong>FlatPrinter<strong>.</strong>new(result)<br>printer<strong>.</strong>print(<br>  STDOUT,<br>  <em># Only want to focus on hotspots right now</em><br>  min_percent: 1<br>)</pre><p>RubyProf supports various ways of <a href="https://github.com/ruby-prof/ruby-prof#printers">printing</a> a report. I picked FlatPrinter by using the scientific method of it appearing “first on the list”. For the sake of brevity, I’m only showing methods that took more than 1% of the total run time:</p><pre>Measure Mode: wall_time<br>Thread ID: 70093065552380<br>Fiber ID: 70093084071700<br>Total: 4.599523<br>Sort by: self_time</pre><pre>%self      total      self      wait     child     calls  name<br> 16.25      0.748     0.748     0.000     0.000  2031000   Protobuf::Enum#to_i<br> 15.35      1.454     0.706     0.000     0.748    30000   Array#select<br>  7.30      0.745     0.336     0.000     0.410   140000   &lt;Class::Protobuf::Decoder&gt;#read_varint<br>  3.44      0.176     0.158     0.000     0.018    94000   Kernel#respond_to?<br>  3.32      1.156     0.152     0.000     1.003    72000   &lt;Class::Protobuf::Decoder&gt;#read_field<br>  2.44      0.508     0.112     0.000     0.396    72000   &lt;Class::Protobuf::Decoder&gt;#read_key<br>  2.26      0.298     0.104     0.000     0.194    72000   Protobuf::Message::Fields::ClassMethods#get_field<br>  2.00      0.159     0.092     0.000     0.067   166500   IO::generic_readable#readbyte<br>  1.76      0.124     0.081     0.000     0.043   171500   Numeric#nonzero?<br>  1.66      0.076     0.076     0.000     0.000   410500   Fixnum#&amp;<br>  1.58      0.073     0.073     0.000     0.000   144000   Protobuf::Field::BaseField#repeated?<br>  1.48      0.068     0.068     0.000     0.000    69000   Protobuf::Field::BaseField#setter<br>  1.46      0.067     0.067     0.000     0.000   166500   StringIO#getbyte<br>  1.19      0.055     0.055     0.000     0.000     1500   Kernel#caller<br>  1.17      0.054     0.054     0.000     0.000    72000   Protobuf::Message::Fields::ClassMethods#field_store<br>  1.05      0.087     0.048     0.000     0.039    72000   Protobuf::Field::BaseField#packed?<br>  1.00      0.137     0.046     0.000     0.091    36003   Class#new</pre><p>Continuing with the scientific method of “first on the list”, we’ll dig into <a href="https://raw.githubusercontent.com/ruby-protobuf/protobuf/4cbb1f7cb98bb5a63875f4fc0cdf0c8109feffa7/lib/protobuf/enum.rb">Protobuf::Enum</a>. There are a few uses of to_i in that class, but the one that stands out is:</p><pre><em># Public: Get an array of Enum objects with the given tag.</em><br><em>#</em><br><em># tag - An object that responds to to_i.</em><br><em>#</em><br><em># Examples</em><br><em>#</em><br><em>#   class StateMachine &lt; ::Protobuf::Enum</em><br><em>#     set_option :allow_alias</em><br><em>#     define :ON, 1</em><br><em>#     define :STARTED, 1</em><br><em>#     define :OFF, 2</em><br><em>#   end</em><br><em>#</em><br><em>#   StateMachine.enums_for_tag(1) #=&gt; [ #&lt;StateMachine::ON=1&gt;, #&lt;StateMachine::STARTED=1&gt; ]</em><br><em>#   StateMachine.enums_for_tag(2) #=&gt; [ #&lt;StateMachine::OFF=2&gt; ]</em><br><em>#</em><br><em># Returns an array with zero or more Enum objects or nil.</em><br><em>#</em><br><strong>def</strong> <strong>self.enums_for_tag</strong>(tag)<br>  enums<strong>.</strong>select <strong>do</strong> <strong>|</strong>enum<strong>|</strong><br>    enum<strong>.</strong>to_i <strong>==</strong> tag<strong>.</strong>to_i<br>  <strong>end</strong><br><strong>end</strong></pre><p>The code has great documentation on how the method works, which makes things easy. We use a lot of enums in our protos, and looking around the <a href="https://raw.githubusercontent.com/ruby-protobuf/protobuf/4cbb1f7cb98bb5a63875f4fc0cdf0c8109feffa7/lib/protobuf/enum.rb">Protobuf::Enum</a> class it’s clear enums_for_tag is called frequently (in enum_for_tag and fetch). Looking at the all_tags and values methods, we know it’s safe to cache enum data. In this case, it’s a straightforward optimization of O(n) -&gt; O(1). We can only map int -&gt; enum because you can <a href="https://developers.google.com/protocol-buffers/docs/proto?hl=en#enum">alias enums</a>. That’s fine for this case though.</p><p>The full changes are at the end, but the gist is:</p><pre><strong>def</strong> <strong>self.mapped_enums</strong><br>  @mapped_enums <strong>||=</strong> enums<strong>.</strong>each_with_object({}) <strong>do</strong> <strong>|</strong>enum, hash<strong>|</strong><br>    list <strong>=</strong> hash<strong>[</strong>enum<strong>.</strong>to_i<strong>]</strong> <strong>||=</strong> <strong>[]</strong><br>    list <strong>&lt;&lt;</strong> enum<br>  <strong>end</strong><br><strong>end</strong></pre><pre><strong>def</strong> <strong>self.enums_for_tag</strong>(tag)<br>  mapped_enums<strong>[</strong>tag<strong>.</strong>to_i<strong>]</strong> <strong>||</strong> <strong>[]</strong><br><strong>end</strong></pre><p>And then rerun it in RubyProf</p><pre>Measure Mode: wall_time<br>Thread ID: 70271059223040<br>Fiber ID: 70271070182440<br>Total: 3.308983<br>Sort by: self_time</pre><pre>%self      total      self      wait     child     calls  name<br> 10.16      0.736     0.336     0.000     0.400   140000   &lt;Class::Protobuf::Decoder&gt;#read_varint<br>  4.92      0.182     0.163     0.000     0.019    94000   Kernel#respond_to?<br>  4.62      1.148     0.153     0.000     0.995    72000   &lt;Class::Protobuf::Decoder&gt;#read_field<br>  3.33      0.501     0.110     0.000     0.391    72000   &lt;Class::Protobuf::Decoder&gt;#read_key<br>  3.25      0.308     0.108     0.000     0.201    72000   Protobuf::Message::Fields::ClassMethods#get_field<br>  2.70      0.156     0.089     0.000     0.066   166500   IO::generic_readable#readbyte<br>  2.37      0.078     0.078     0.000     0.000   410500   Fixnum#&amp;<br>  2.34      0.119     0.077     0.000     0.042   171500   Numeric#nonzero?</pre><p>Much better! The total time listed in RubyProf is accurate in percentage saved (~25%), but the total time is higher because RubyProf hooks into Ruby to profile everything. Without RubyProf, we saw requests from the Ruby MRI 2.2.3 client drop from 1,000ms to around 750ms.</p><p>Since 750ms is still too long, we’ll take a look at the next slowest callsite <a href="https://github.com/ruby-protobuf/protobuf/blob/58ca57e2aac6d5f9860e64534d5ef2d23c934ed2/lib/protobuf/decoder.rb">Protobuf::Decoder</a> and the read_varint method.</p><pre><em># Read varint integer value from +stream+.</em><br><strong>def</strong> <strong>self.read_varint</strong>(stream)<br>  value <strong>=</strong> index <strong>=</strong> 0<br>  <strong>begin</strong><br>    byte <strong>=</strong> stream<strong>.</strong>readbyte<br>    value <strong>|=</strong> (byte <strong>&amp;</strong> 0x7f) <strong>&lt;&lt;</strong> (7 <strong>*</strong> index)<br>    index <strong>+=</strong> 1<br>  <strong>end</strong> <strong>while</strong> (byte <strong>&amp;</strong> 0x80)<strong>.</strong>nonzero?<br>  value<br><strong>end</strong></pre><p>The code is simple enough that any optimizations will be marginal at best. Ruby is just too slow for the amount of calls we’re making, which makes this a candidate for rewriting the method in C.</p><p>It turns out, the authors of the ruby-protocol-buffers gem (a different ruby protobuf gem from the one we use), released a gem called <a href="https://github.com/liquidm/varint/blob/master/ext/varint/varint.c">varint</a> which does exactly what we need.</p><p>Normally, you wouldn’t want to replace Ruby with C. It locks you into using MRI, and adds a bigger maintenance burden. Since the Ruby version is simple enough, shouldn’t change, and is already used by another gem it’s easy enough to test.</p><p>We add a simple monkeypatch to our test case:</p><pre><strong>module</strong> Protobuf<br>  <strong>class</strong> <strong>FastVarint</strong><br>    <strong>extend</strong> <strong>::</strong>Varint<br>  <strong>end</strong></pre><pre><strong>  class</strong> <strong>Decoder</strong><br>    <strong>def</strong> <strong>self.read_varint</strong>(stream)<br>      FastVarint<strong>.</strong>decode(stream)<br>    <strong>end</strong><br>  <strong>end</strong><br><strong>end</strong></pre><p>Rerun RubyProf</p><pre>Measure Mode: wall_time<br>Thread ID: 70126242488840<br>Fiber ID: 70126246561280<br>Total: 2.722766<br>Sort by: self_time</pre><pre>%self      total      self      wait     child     calls  name<br>  5.65      0.676     0.154     0.000     0.522    72000   &lt;Class::Protobuf::Decoder&gt;#read_field<br>  5.64      0.172     0.154     0.000     0.018    94000   Kernel#respond_to?<br>  4.55      0.283     0.124     0.000     0.159    72000   &lt;Class::Protobuf::Decoder&gt;#read_key<br>  4.04      0.302     0.110     0.000     0.192    72000   Protobuf::Message::Fields::ClassMethods#get_field<br>  3.48      0.250     0.095     0.000     0.156   140000   &lt;Class::Protobuf::Decoder&gt;#read_varint<br>  3.13      0.156     0.085     0.000     0.070   140000   Varint#decode<br>  2.86      0.078     0.078     0.000     0.000   144000   Protobuf::Field::BaseField#repeated?<br>  2.58      0.070     0.070     0.000     0.000   166500   StringIO#getbyte<br>  2.49      0.068     0.068     0.000     0.000    69000   Protobuf::Field::BaseField#setter<br>  2.10      0.058     0.057     0.000     0.000     1500   Kernel#caller</pre><p>We got a 18% optimization by cheating and having C do it instead. Even with all these improvements, our decoding time is around 600ms still.</p><p>Moving on, we take another look at <a href="https://github.com/ruby-protobuf/protobuf/blob/58ca57e2aac6d5f9860e64534d5ef2d23c934ed2/lib/protobuf/decoder.rb">Protobuf::Decoder</a>. Unfortunately the read_field and read_key methods are too simple for any real optimization. Kernel#respond_to? is used in too many places for safety, such as returning nil if to_i doesn’t exist rather than erroring.</p><p>That really just leaves us with <a href="https://github.com/ruby-protobuf/protobuf/blob/71fd6ae9185c53764dd665da7e45e8fbb73853da/lib/protobuf/message/fields.rb">Protobuf::Message::Fields::ClassMethods</a>, since we don’t want to optimize 50 callsites for a few milliseconds each. Looking at get_field, we see:</p><pre><strong>def</strong> <strong>get_field</strong>(name_or_tag, allow_extension <strong>=</strong> <strong>false</strong>)<br>  name_or_tag <strong>=</strong> name_or_tag<strong>.</strong>to_sym <strong>if</strong> name_or_tag<strong>.</strong>respond_to?(:to_sym)<br>  field <strong>=</strong> field_store<strong>[</strong>name_or_tag<strong>]</strong></pre><pre><strong>if</strong> field <strong>&amp;&amp;</strong> (allow_extension <strong>||</strong> <strong>!</strong>field<strong>.</strong>extension?)<br>    field<br>  <strong>else</strong><br>    <strong>nil</strong><br>  <strong>end</strong><br><strong>end</strong></pre><p>Looking at the RubyProf trace above, we already know that respond_to? is called 94,000 times total. After adding some debugging to count calls, it turns out get_field accounts for 72,000 (75%) of the calls to respond_to?, and it only calls to_sym 2,000 times. Or to put it another way, only 2.7% of our respond_to? calls are useful.</p><p>Instead of calling respond_to? and to_sym, we can cache a map of string field -&gt; field to turn it into two O(1) lookups. The get_field method then looks like:</p><pre><strong>def</strong> <strong>get_field</strong>(name_or_tag, allow_extension <strong>=</strong> <strong>false</strong>)<br>  field <strong>=</strong> field_store<strong>[</strong>name_or_tag<strong>]</strong> <strong>||</strong> str_field_store<strong>[</strong>name_or_tag<strong>]</strong></pre><pre><strong>if</strong> field <strong>&amp;&amp;</strong> (allow_extension <strong>||</strong> <strong>!</strong>field<strong>.</strong>extension?)<br>    field<br>  <strong>else</strong><br>    <strong>nil</strong><br>  <strong>end</strong><br><strong>end</strong></pre><p>One last rerun of RubyProf</p><pre>Measure Mode: wall_time<br>Thread ID: 70107917574660<br>Fiber ID: 70107924939720<br>Total: 2.428846<br>Sort by: self_time</pre><pre>%self      total      self      wait     child     calls  name<br>  6.12      0.666     0.155     0.000     0.511    72000   &lt;Class::Protobuf::Decoder&gt;#read_field<br>  4.70      0.277     0.119     0.000     0.158    72000   &lt;Class::Protobuf::Decoder&gt;#read_key<br>  3.70      0.248     0.094     0.000     0.154   140000   &lt;Class::Protobuf::Decoder&gt;#read_varint<br>  3.39      0.132     0.086     0.000     0.046    72000   Protobuf::Message::Fields::ClassMethods#get_field<br>  3.39      0.154     0.086     0.000     0.068   140000   Varint#decode<br>  2.96      0.075     0.075     0.000     0.000   144000   Protobuf::Field::BaseField#repeated?<br>  2.70      0.068     0.068     0.000     0.000   166500   StringIO#getbyte<br>  2.60      0.066     0.066     0.000     0.000    69000   Protobuf::Field::BaseField#setter</pre><p>This gives us another 12% improvement, and Kernel#respond_to? drops to 22,000 calls (1.29% of self%). Overall, we optimized deserialization by 50%, and it only took a few hours of investigating with RubyProf.</p><p>RubyProf is a great tool, and you can get even more details using a GraphPrinter or CallTreePrinter which can be used with <a href="http://kcachegrind.sourceforge.net/">KCachegrind</a>. For our case, FlatPrinter was simple, and the code was easy enough to trace through to narrow down what to optimize. Examples of various printers in RubyProf can be found <a href="https://github.com/ruby-prof/ruby-prof/tree/master/examples">on the repo</a>.</p><p>We shipped all of the changes upstream into the <a href="https://rubygems.org/gems/protobuf">protobuf</a> gem. You can see the exact changes that were made in the <a href="https://github.com/ruby-protobuf/protobuf/pull/269">varint</a>, <a href="https://github.com/ruby-protobuf/protobuf/pull/267">get_field/get_extension_field</a>, and <a href="https://github.com/ruby-protobuf/protobuf/pull/264">enum</a> optimization PRs. If you’re using the protobuf gem, v3.5.5 and higher with the <a href="https://rubygems.org/gems/varint">varint</a> gem (MRI only) installed will give you the full set of optimizations.</p><p>In the future, we’re going to look at moving to <a href="https://github.com/google/protobuf/tree/master/ruby">protobuf3</a>. The Ruby gem is in alpha, but it’s built off Google’s first party <a href="https://github.com/google/protobuf">C++</a> library. In benchmarks against the optimizations above, Google’s implementation is about <a href="https://gist.github.com/zanker/6002476f5a957d79d279">7x faster</a> than ruby-protobuf.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d54ffccb60c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>