<?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 Jacob Lerche on Medium]]></title>
        <description><![CDATA[Stories by Jacob Lerche on Medium]]></description>
        <link>https://medium.com/@jacob.lerche?source=rss-478253f0a94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VtYgH5CdaL4RsJNVFZy7zw.jpeg</url>
            <title>Stories by Jacob Lerche on Medium</title>
            <link>https://medium.com/@jacob.lerche?source=rss-478253f0a94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacob.lerche/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[Writing Rust NIFs for your Elixir code with the Rustler package]]></title>
            <link>https://medium.com/@jacob.lerche/writing-rust-nifs-for-your-elixir-code-with-the-rustler-package-d884a7c0dbe3?source=rss-478253f0a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/d884a7c0dbe3</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Jacob Lerche]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 01:54:27 GMT</pubDate>
            <atom:updated>2018-09-28T01:54:27.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Elixir is a language that has positioned itself as suitable for high concurrency workloads. It does so by running on the Erlang VM (BEAM), which is well known for its implementation of the actor model. Actors are realized as BEAM processes which are lightweight compared to OS threads, but most importantly they have their own stack and heap which share nothing with other processes. Communication requires message passing semantics, which in practice means copying values around.</p><p>Process execution is handled by the schedulers of which BEAM will usually spawn a number equal to the number of logical cores on the system. The schedulers have a queue in which processes are sent to for execution scheduling. Each process runs for a certain number of <em>reductions</em> before being rescheduled. Reductions are a somewhat obfuscated term in the Erlang docs, but the number that is frequently quoted is 2000 reductions is roughly &lt;1ms, which is also the time slice a process runs for before rescheduling. This preemptive behavior is what gives BEAM its low latency and soft real-time capabilities.</p><p>What this means is that a process needs to be able to be interrupted more or less at any point in its code. Achieving this requires trading off in other areas, and these will tend to manifest themselves in CPU heavy computation. Which isn’t to say that BEAM is slow, it sits pretty comfortably ahead of languages like Ruby and Python, but will lag behind languages like Java and Go. Of course even then, BEAM will do really well if it can take advantage of its strengths like binary pattern matching for example.</p><p>Nevertheless, there will be times where code will run slow and Erlang/Elixir optimizations will only go so far. BEAM has several ways to interface with foreign code, the fastest way being with a Native Implemented Function (NIF) whose API expects them to be written in C. But speaking frankly, the last time I worked with C involved a lengthy debugging session that boiled down to the lack of type safety, so I’d rather not have to repeat that experience. It’s for this reason that Rust is such a compelling language. It has a robust type system with type inference, pattern matching, and many <a href="https://www.rust-lang.org/en-US/">more features</a>. That and it has a C compatible ABI.</p><p>This is where the <a href="https://github.com/hansihe/rustler">Rustler</a> project comes in. In its own words it provides a safe bridge for writing Erlang NIFs. One of its safety guarantees is catching panics before they reach the C code. One of the nice things about Rust is that if the code compiles, you can be reasonably sure you won’t run into a wide range of memory safety related bugs, among others.</p><p>Rustler provides a Hex package as well as a Cargo crate (Rust’s package management system). To get started, create a new mix project and add rustler to the dependencies</p><pre>defp deps do<br>    [<br>      {:rustler, &quot;~&gt; 0.16.0&quot;}<br>    ]<br>end<br></pre><p>And then run mix deps.get to grab the dependencies. Rustler then provides a mix task we can invoke, mix rustler.new. Here’s what that looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbb8656d3d8fa4a4ba1e9c16a7896108/href">https://medium.com/media/fbb8656d3d8fa4a4ba1e9c16a7896108/href</a></iframe><p>There are two interactive prompts, the first one asks for the Elixir module in which to load the NIF. Note that if your base project module name is Foo and the module in which you wish to load the NIF is Foo.NifModule then that is what you need to put in the prompt. I point it out because I made that mistake previously. The second prompt asks for the name of the crate it will generate. Leaving it blank will have it default to a name that will probably work just fine.</p><p>Once it is done running, we can see that it created a directory called native with a generated Rust project located in it. The generated README tells us to make some changes to our mix.exs. The full listing is as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/223d9dd3d99db143097a5f657bc07db0/href">https://medium.com/media/223d9dd3d99db143097a5f657bc07db0/href</a></iframe><p>The additions are straightforward, we have a rustler_crates keyword in the mix project, and an entry for Rustler in Mix.compilers. The value of MIX_ENV will dictate how our crate is compiled, debug or release. The README gives us a boilerplate module example to load the NIFs into BEAM</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86eefa3baa7d3723185896a00aab5e22/href">https://medium.com/media/86eefa3baa7d3723185896a00aab5e22/href</a></iframe><p>Note that the generated boilerplate has use Rustler, otp_app: [otp app], crate: &quot;niftest&quot; so we need to remember to substitute with the actual atom for our OTP app. As explained by the comment, the function is a fallback to guard against the case where the NIF is not loaded. The add function has a corresponding Rust implementation when Rustler generated the crate for us. Before we take a look at the Rust code, let’s try the NIF out in a quick iex session</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4339670c8536c5075663255db28c300/href">https://medium.com/media/c4339670c8536c5075663255db28c300/href</a></iframe><p>and indeed 1+2=3.</p><p>Now let’s take a look at what the lib.rs file that Rustler generated for us looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86c86e68e59112c01c70e22cb22be39d/href">https://medium.com/media/86c86e68e59112c01c70e22cb22be39d/href</a></iframe><p>After the usual imports at the top of the file, we see two macro calls. The first defines atoms that we want to use, the second exports a Rust function and registers it to a name that will be used to call it in the Elixir code with its arity. The Option as the third argument in the exports is of type Option&lt;fn(env: &amp;Env, load_info: Term) -&gt; bool&gt; and if it’s Some will execute when the NIF is first loaded by BEAM. Here, it is None so nothing will be executed upon loading.</p><p>The Rust function is where we get into the substantive part. We see that it is decorated with a lifetime parameter, specifically this is because no value may live longer than env, which is an opaque data type defined in the Erlang NIF API. Each Rust function that is to be exported as a NIF will have the same signature, it will take an argument of type Env&lt;&#39;a&gt; and one of type &amp;[Term&lt;&#39;a&gt;]. The latter will contain all the arguments used when calling from Elixir. The return type will always be NifResult&lt;Term&lt;&#39;a&gt;&gt; where NifResult is an alias for Result.</p><p>The body is fairly straightforward to read, but I want to point out the pattern. When extracting the value from a Term we need to decode it into a variable with a type annotation. When we return data, we need to encode it. The returned data here is Rust tuple with an atom in the first slot, and the sum of the two arguments in the second slot, encoded into a Term and wrapped in an Ok() to satisfy the function signature.</p><p>When we encoded a Rust tuple we got an Elixir tuple when we called the NIF. The conclusion here is that Rust types will more or less correspond to similar Elixir types. Let’s give it a shot with some simple examples</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9956d72e132c2b0f9410876bb79a480/href">https://medium.com/media/e9956d72e132c2b0f9410876bb79a480/href</a></iframe><p>and the corresponding guards</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b153bc2d90645c3ac0379a0539be654f/href">https://medium.com/media/b153bc2d90645c3ac0379a0539be654f/href</a></iframe><p>and a quick iex -S mixsession shows</p><pre>iex(1)&gt; Rustnif.NifTest.return_string()<br>&quot;Hello world!&quot;<br>iex(2)&gt; Rustnif.NifTest.return_list()<br>[1, 2, 3, 4]</pre><p>So far so good, but what about maps? Let’s try with another simple function like this (don’t forget to register it in the rustler_export_nifs! macro and Elixir module)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e14537f7a57dcbe12ab5877f1e1badd/href">https://medium.com/media/2e14537f7a57dcbe12ab5877f1e1badd/href</a></iframe><p>If we try to compile, this is the error we get</p><pre>error[E0599]: no method named `encode` found for type `std::collections::HashMap&lt;std::string::String, {integer}&gt;` in the current scope<br>  --&gt; src/lib.rs:46:12<br>   |<br>46 |     Ok(map.encode(env))<br>   |            ^^^^^^</pre><p>which we could have seen coming if we checked the <a href="https://docs.rs/rustler/0.18.0/rustler/types/trait.Encoder.html">Rustler documentation</a>. The Encoder trait is not implemented for Rust’s HashMap.</p><p>We’re not quite <em>completely</em> out of luck, <a href="https://docs.rs/rustler/0.18.0/rustler/struct.Term.html#method.map_new">there technically is a way to return a map if we really want to</a>. We can call it like this, let map = rustler::types::map::map_new(env). And now we can call encode on map. But this is essentially a Rust representation of an Erlang map, and probably much less efficient than Rust’s HashMap.</p><p>The reason for mentioning this is that there is a real possibility for non-trivial overhead to manifest itself when serializing data between Erlang and C/Rust and back again, depending on the type and size of the data. There is also a tiny overhead associated with running a NIF on a dirty scheduler.</p><p>Speaking of dirty NIFs, I would be remiss if I did not include an example showing how to mark a NIF as such. Here is an example showing how to do so, it is done entirely in the rustler_export_nifs! macro</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ebfedda706008823a70725baaa8e43/href">https://medium.com/media/d3ebfedda706008823a70725baaa8e43/href</a></iframe><p>and the other flag is DirtyIo, which are defined as follows</p><pre>pub enum SchedulerFlags {<br>    Normal = 0,<br>    DirtyCpu = 1,<br>    DirtyIo = 2,<br>}</pre><p>The examples above are a small sample of what is possible. For a more comprehensive list, I recommend the <a href="https://github.com/hansihe/rustler/tree/master/rustler_tests">test directory in the repository</a>. For example, you can return an Option and the value will get unwrapped when it is called inside Elixir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d884a7c0dbe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using constant pools to speed up your Elixir code]]></title>
            <link>https://medium.com/@jacob.lerche/using-constant-pools-to-speed-up-your-elixir-code-c527d533c941?source=rss-478253f0a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/c527d533c941</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Jacob Lerche]]></dc:creator>
            <pubDate>Wed, 22 Nov 2017 21:35:14 GMT</pubDate>
            <atom:updated>2017-11-22T21:35:14.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BveNxR6PettAS98SNHAlQ.jpeg" /><figcaption>A nice picture of a pool.</figcaption></figure><h3>Introduction</h3><p>Writing code in Elixir that is optimized for speed can sometimes be challenging due to the nature of the Erlang runtime environment’s (BEAM) concurrency model. Instead of using OS threads like, say, Java and other languages, BEAM provides its own abstraction in the form of processes implemented in the runtime environment itself. These processes have their own stack and heap, but more importantly they share nothing with other processes. Communication between processes is done via message passing. In practice what this means is that any message, which is just an Erlang term, that is sent to another process must be copied to the destination’s heap.</p><p>For the most part, this limitation is fine. A lot of the time, a message that gets passed will be small enough, usually something like :ok or {:ok, result} where result is any term. Of course, result could be of arbitrary size, and that is where the problem could start to appear.</p><h3>A naive GenServer constant store</h3><p>To get a feel for the problem, let us start with a contrived scenario: we wish to store some data to be available to other processes. We will naively do so with a GenServer like in the following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e286ca43f89612b19437a329f35e67/href">https://medium.com/media/d1e286ca43f89612b19437a329f35e67/href</a></iframe><p>Now every process that wishes to access the data can do so by calling Store.get/0. The immediate problem with this is that processes go through the messages in their mailbox one at a time. This means that reads are effectively serialized by the host process, which is less than ideal when you have thousands of processes trying to read the data.</p><h3>ETS tables as a first optimization</h3><p>Erlang Term Storage (ETS) is an in-memory data store with some modest concurrency guarantees, namely that updates to single objects are both atomic and isolated. What this means is that any update to an object either succeeds or fails without effect, and no other processes will see intermediate results of the update. An ETS table is created from within a process and is stored off-heap. The process maintains ownership and the table persists until its owner process dies.</p><p>The default behavior is that the owner process is the only one that can write to the table, but any other process may read from it. This is a nice way of solving the sequential read problem with the pure GenServer implementation from before. A naive ETS store might look like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a87d937243121a895b3b2e545ef838e2/href">https://medium.com/media/a87d937243121a895b3b2e545ef838e2/href</a></iframe><p>Other processes may access the data via :ets.lookup(:store, :key).</p><p>There is still a slight problem though. The data in the ETS table is indeed stored off-heap, but any read from a process requires the data to be copied into the process space. So if the size was so prohibitively large that copying it between processes incurred a performance penalty then we are mostly back where we started.</p><h3>Module constant pools</h3><p>Constant Erlang terms are also called literals and are treated in a somewhat special manner. Per the Erlang docs <a href="http://erlang.org/doc/efficiency_guide/processes.html">efficiency guide</a> in section 8.2, the literals are stored in that module’s pool. These pools are heaps in their own right, but may actually be referenced directly from other processes without being copied. This implementation detail can be quite useful for alleviating memory pressure issues. So we can solve both process read access and data copying problems in our scenario with the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c671c0da9ea6dd4fb768a427741cba/href">https://medium.com/media/44c671c0da9ea6dd4fb768a427741cba/href</a></iframe><p>This is all well and good, but how often will this scenario ever play out? The vast majority of the time, the data will be dynamic in nature and not something that can be baked into the code. So what we really need here is a way to be able to dynamically set the data as a literal in a module during runtime. This is something that can be accomplished with a simple macro.</p><pre>defmodule StoreSetter do<br>  defmacro set(val) do<br>    quote do<br>      defmodule Store do<br>        def get() do<br>          unquote(val)<br>        end<br>      end<br>    end<br>  end<br>end</pre><p>There is a little bit going on here so let’s take a little bit of time to understand it. The keyword defmacro defines a macro called set which we will end up calling like a regular function. The quote keyword instructs the compiler to store everything in its block as data, which in this case is the module definition of Store with its get function. It then transforms the block of code into its internal abstract syntax tree representation which is a nested tree of 3-tuples. This representation is then injected back into the compile tree. Now unquote here lets us evaluate a code block, in this case the term we want to set in the store, but defers execution until the code generated by the quote block is executed.</p><p>So that was a quick and dirty rundown of Elixir macros. For more check out the official docs and Chris McCord’s <a href="https://pragprog.com/book/cmelixir/metaprogramming-elixir">excellent book</a>. Let’s try it out in iex.</p><pre>iex(1)&gt; c &quot;naive_dynamic_module.ex&quot;<br>[StoreSetter]<br>iex(2)&gt; require StoreSetter<br>StoreSetter<br>iex(3)&gt; StoreSetter.set([:foo])<br>{:module, Store,<br> &lt;&lt;70, 79, 82, 49, 0, 0, 3, 140, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 82,<br>   0, 0, 0, 8, 12, 69, 108, 105, 120, 105, 114, 46, 83, 116, 111, 114, 101, 8,<br>   95, 95, 105, 110, 102, 111, 95, 95, 9, ...&gt;&gt;, {:get, 0}}<br>iex(4)&gt; Store.get<br>[:foo]</pre><p>So far so good, when we call StoreSetter.set/1 with a term we generate a new module called Store and we can retrieve the value we set by calling Store.get. Now, what if we were to set a new value in the store?</p><pre>iex(5)&gt; StoreSetter.set([:foo, :bar])<br>warning: redefining module Store (current version defined in memory)<br>  iex:5</pre><pre>{:module, Store,<br> &lt;&lt;70, 79, 82, 49, 0, 0, 3, 152, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 82,<br>   0, 0, 0, 8, 12, 69, 108, 105, 120, 105, 114, 46, 83, 116, 111, 114, 101, 8,<br>   95, 95, 105, 110, 102, 111, 95, 95, 9, ...&gt;&gt;, {:get, 0}}<br>iex(6)&gt; Store.get<br>[:foo, :bar]</pre><p>It still works as expected, but we get that pesky warning. To get rid of it, we need to first remove the module from the loaded modules in the runtime. This is easily done thanks to the :code module as it is core to BEAM’s hot code upgrade feature. Let’s continue in our iex session.</p><pre>iex(7)&gt; :code.purge(Store)<br>false<br>iex(8)&gt; :code.delete(Store)<br>true<br>iex(9)&gt; StoreSetter.set([:foo, :bar, :baz])<br>{:module, Store,<br> &lt;&lt;70, 79, 82, 49, 0, 0, 3, 156, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 82,<br>   0, 0, 0, 8, 12, 69, 108, 105, 120, 105, 114, 46, 83, 116, 111, 114, 101, 8,<br>   95, 95, 105, 110, 102, 111, 95, 95, 9, ...&gt;&gt;, {:get, 0}}</pre><p>We no longer get the warning, and we have the ability to allocate data in a special read-only heap that can be read by any process without copying the data. As a special note, OTP 20 included an optimization such that literals are no longer copied when sending messages, which makes this technique even more powerful.</p><p>A few months ago, Discord’s CTO wrote a <a href="https://blog.discordapp.com/scaling-elixir-f9b8e1e7c29b">blog post</a> that gave a very nice high level overview of the Elixir powered portion of their backend. Discord is a distributed chat app backed by a ring data structure created using consistent hashing. They were experiencing slow reads and even slower lookups in the ring. One of their optimization attempts involved storing the ring in ETS. Even though ETS has sophisticated pattern matching to limit the size of the data that would eventually be copied back to the calling process, the size of the ring was still prohibitively large. They quoted 17.5 seconds for looking up values. Eventually they discovered an Erlang library called <a href="https://github.com/mochi/mochiweb/blob/master/src/mochiglobal.erl">mochiglobal</a> which abstracts away the previous technique into a nice API. Discord ported it to Elixir under the name <a href="https://github.com/discordapp/fastglobal">fastglobal</a>. Now that their ring was stored in a constant pool, their lookup time decreased to 0.3 microseconds. The downside is that compiling and loading a module with a large amount of data can take some time. In Discord’s case they reported up to one second. Therefore, this technique should only really be used if the amount of reads vastly outnumber the amount of writes, and this difference is known.</p><p>If you want to learn more about how to implement this technique, colloquially known sometimes as the “compile module hack”, I would highly recommend going through Discord’s fastglobal library to understand how it is implemented. Do note that they use erlang syntax to build up their modules while here I used a macro.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c527d533c941" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>