<?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 Peter Hastie on Medium]]></title>
        <description><![CDATA[Stories by Peter Hastie on Medium]]></description>
        <link>https://medium.com/@phastie?source=rss-40f2db05ef50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SGC-sbr-a-UsJqaTV2dTKw.jpeg</url>
            <title>Stories by Peter Hastie on Medium</title>
            <link>https://medium.com/@phastie?source=rss-40f2db05ef50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:33:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phastie/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[Delicate sensibilities: techniques to block offensive usernames]]></title>
            <link>https://medium.com/bleacher-report-engineering/delicate-sensibilities-techniques-to-block-offensive-usernames-1dbdfdd1f994?source=rss-40f2db05ef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dbdfdd1f994</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[bleacherreport]]></category>
            <dc:creator><![CDATA[Peter Hastie]]></dc:creator>
            <pubDate>Tue, 05 Jun 2018 00:35:40 GMT</pubDate>
            <atom:updated>2018-06-05T00:35:40.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cl_z2QH676zmUYTVsipDQA.jpeg" /></figure><p>We’re making some big changes to the B/R app that we hope will make it a more interesting and useful place for people to spend time. Although Bleacher Report doesn’t require an account to read our content, we hope that people will create accounts to take advantage of the exciting new features we’ll be offering. In order to foster a vibrant community where everyone feels welcome, we’ve been doing some work on the backend to discourage spammy and offensive usernames during the signup process.</p><p>Over the years we’ve accumulated a frankly shocking list of the creatively offensive terms people have entered into our site. When users create a new account, the Elixir backend checks the string terms against this list to ensure they don’t contain any of these unwelcome words.</p><p>We can’t treat all profanity the same way, though, because of the <a href="https://en.wikipedia.org/wiki/Scunthorpe_problem">Scunthorpe problem</a>. Rather than an alias for a 19th-century pugilist, this describes the tendency of filters of this type to flag perfectly innocent words that happen to contain a substring from our list. We’ve tried to avoid this by running three separate comparisons.</p><ol><li>Check if the user term contains any substrings from the profanity list.</li><li>Check if the user term is exactly equal to a string in the exact profanity list, which contains mostly shorter words that are likely to be found in regular words and names.</li><li>Check if the user term contains any substrings from a separate list but allow certain exceptions that we’ve been made aware of through user feedback.</li></ol><p>In order to illustrate this without traumatizing the reader, I will use the lists from a more innocent time, from back when the site was simply “An Upstanding Victorian’s Report from the Bleachers.”</p><pre>{<br>  profanity = [<br>    &quot;arsenic&quot;,<br>    &quot;bloomers&quot;,<br>    &quot;bosom&quot;,<br>    &quot;bounder&quot;,<br>    &quot;fustilugs&quot;,<br>    &quot;suffrage&quot;,<br>    &quot;zounderkite&quot;<br>  ],<br>  exact_profanity = [<br>    &quot;cad&quot;,<br>    &quot;gin&quot;<br>  ],<br>  overridden_terms: {<br>    &quot;bottom&quot;: [&quot;winterbottom&quot;],<br>    &quot;free&quot;: [&quot;freeman&quot;]<br>  }<br>}</pre><p>Our SpamFilter module is a GenServer which loads the profanity list into state when it initializes, then each call to the GenServer uses String.contains?/2 to test for profanity within the user’s string. Since the second argument to this function can be a list of strings, we can check against the full list in one call. This function almost seems to be designed for this use case, but it’s not without its limitations.</p><p>One technique users employ to circumvent the filter is to replace letters with numbers. A proper cad might choose the username 4r53n1c or 3100mers to confound the filter. Rather than adding all the possible variations to the lists themselves, it makes sense to convert the numbers in the username back to letters and compare as normal. The problem in this example is that 1 is being used to represent both i and l, and 3 is being used to represent both B and e. Given that a username can have 16 characters, our worst-case username 1111111111111111 has 2¹⁶ permutations. That would mean calling String.contains?/2 65,536 times! Even for a less dramatic example, comparing against the full list of profanity words each time is inefficient.</p><p>A more appropriate data structure for the profanity words would be a <a href="https://en.wikipedia.org/wiki/Trie">trie</a>, a specialised tree that places each character of the word at a node. In our case a node can have up to 26 children, one for each alphabet character. Searching the trie means descending through the tree, comparing each node to the next character in the string until a leaf is found. This data structure is perfect for our purposes: We can do the hard work of building the trees once when the GenServer initializes; after that, each lookup has a worst-case run time bounded by the length of the user term and is only marginally affected by the number of terms in the list.</p><p>In Elixir we can represent the trie as a series of nested maps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4238ee99a30075c266e9b2ddfe1fc9cc/href">https://medium.com/media/4238ee99a30075c266e9b2ddfe1fc9cc/href</a></iframe><p>To check for the word bounder we would first check the b node at the top level, then check for o as a child of that node, continuing through each character until we see that the final character r is marked as a leaf, meaning we found a match. In contrast, we will not find a match for bouncer because once we’re at the b-&gt;o-&gt;u-&gt;n node we see that there is no key c, only d.</p><p>Building the tree requires just a small amount of recursive code. This example assumes that the list doesn’t contain any substrings of other words on the list. For example, suffragette shouldn’t be in the list because suffrage is present and will match both. This use case allows us to use a simplified trie where a node can either be a parent or a leaf, but not both.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/694b2c3feb300f367374d8e7f20ad8ce/href">https://medium.com/media/694b2c3feb300f367374d8e7f20ad8ce/href</a></iframe><p>The search code is similarly terse. At each node we attempt to fetch the value stored at the key corresponding to the current letter we’re matching. We call the search function recursively with that value as the next node. If the value was another map, we repeat the process for the next letter. If not, the function terminates, returning false if a :leaf atom was found, indicating our string matched a word from the list and is not valid. To test for substrings, as in the example below, we check each character in the string against the root of the tree; this is not necessary when checking for an exact match.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ba5d3761b1a66a7b17fc7d053baeaf7/href">https://medium.com/media/3ba5d3761b1a66a7b17fc7d053baeaf7/href</a></iframe><p>With these basics in place, implementing the new feature to handle the different translations of digits is a breeze. A new check_char clause for each digit to be translated can be added before the final clause; Elixir will pattern match the arguments to the appropriate clause. When 3 is encountered, we first check for the key b at the current node and follow that branch until a leaf is found. If no leaf is found, we return to the node we were at and do the same thing for the key e — we don’t need to reprocess the part of the string that we’ve already checked.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a806be13af96bb8ede9062cda8efcac/href">https://medium.com/media/3a806be13af96bb8ede9062cda8efcac/href</a></iframe><p>The chart below shows the time taken to filter 10,000 16-character usernames containing only alphabet characters against a profanity list containing 152 words. The benchmark uses Enum.filter/2 to filter the list of autogenerated usernames against the !String.contains?/2 and Trie.valid_word?/2 implementations in turn, yielding approximately 6,900 valid usernames in each run. On macOS running Elixir 1.5, the trie implementation is about 8 times faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*l68fffocHjFMFU8wy3jI8Q.png" /></figure><p>Hopefully these efficiency gains allow us to keep improving the filters while providing a smooth experience for new signups. The filter is unlikely to ever be perfect, though, and we will be relying on human moderators to remove any undesirable names that do get through. And if anyone feels that the filter is being too aggressive in rejecting their input, please reach out to us through the Send Feedback button in the app.</p><p><em>Header image courtesy of </em><a href="http://www.victorianweb.org/art/illustration/dumaurier/trilby/113.html"><em>Philip V Allingham</em></a><em>. Thanks to Pancham Mehrunkar for the implementation of the </em><em>check_char/2 translation clause.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dbdfdd1f994" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleacher-report-engineering/delicate-sensibilities-techniques-to-block-offensive-usernames-1dbdfdd1f994">Delicate sensibilities: techniques to block offensive usernames</a> was originally published in <a href="https://medium.com/bleacher-report-engineering">Bleacher Report Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asking the right question (or_where would we be without Ecto upgrades)]]></title>
            <link>https://medium.com/bleacher-report-engineering/asking-the-right-question-or-where-would-we-be-without-ecto-upgrades-f00a45da352c?source=rss-40f2db05ef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/f00a45da352c</guid>
            <category><![CDATA[bleacherreport]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[ecto]]></category>
            <dc:creator><![CDATA[Peter Hastie]]></dc:creator>
            <pubDate>Mon, 05 Dec 2016 18:21:52 GMT</pubDate>
            <atom:updated>2016-12-05T18:28:11.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoExmcQuZMTFFAItut9Myg.jpeg" /></figure><p>The most recent release of <a href="https://hex.pm/packages/ecto">Ecto</a>, version 2.1.0, includes a new query macro or_where. This adds the ability to dynamically build WHERE x OR y clauses of an arbitrary length. This might not sound like a major improvement, but for one of the services in <a href="http://bleacherreport.com/">Bleacher Report</a>’s data platform, it drastically simplified our code.</p><p>One of the limitations of Bleacher Report’s old data platform is that we had no way of matching up events sent from a user’s devices. If a user browses the site on their laptop, those events would be labelled differently from those sent from their Team Stream application. As we look to use these events to personalize a user’s Bleacher Report experience, consistency becomes more important.</p><p>To make this possible we created a very lightweight service called Portmeirion to dispense unique user IDs in response to the client sending over a set of identifiers, such as their device ID. If the identifiers have been seen before, Portmeirion will treat this as a request from an existing user and return the existing user id. Clients are expected to request a user ID before they send any events and to include that ID in all events they send.</p><p>As with all of our new user-facing services, Portmeirion is an <a href="http://elixir-lang.org/">Elixir</a> project built on <a href="http://www.phoenixframework.org/">Phoenix</a>. The service exposes an extremely lightweight API with just two endpoints: one for clients to request a user ID, another for clients to change the state of their user ID when a user logs in. The identification endpoint can accept a variety of identifiers to search for an existing ID for this user. These originally included login_id, device_id, and prism_id (a tracking cookie from our previous data platform), and we later added facebook_id. Some, all or none of these identifiers can be present in a request, and there is an informal hierarchy: If we can’t identify a user by login_id we will try their device_id and finally their prism_id.</p><p>My first attempt to match identifiers to a user made use of pattern-matched functions and short-circuiting logical OR operators. If there is no login_id present in the parameters, a call to find_user_by_login will match the definition that returns nil, causing the find_user_by_device function to be called. However, if login_id is present and a matching record is found, find_user_by_device will never be called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3109f5e245c6c1d17c8081cebeddb68/href">https://medium.com/media/f3109f5e245c6c1d17c8081cebeddb68/href</a></iframe><p>This initial implementation was easy to reason about, but each of the find_user_by_* functions makes a separate call to the database. We think most of our users are not logged in, so most calls to this endpoint will result in at least two database calls. I wanted to rewrite this as a single query, preserving the hierarchy by ordering the results with login_id at the top. In SQL, the query would have the following format and is even simpler if device_id is not present in the parameters as there is then no need to join the devices table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f60a886ca381b3b7bd8c92b57cb5a4f1/href">https://medium.com/media/f60a886ca381b3b7bd8c92b57cb5a4f1/href</a></iframe><p>However, this query is not simple to recreate with Ecto 2.0.1, the version installed with the current stable release of Phoenix, version 1.2. Ecto’s <a href="https://hexdocs.pm/ecto/Ecto.Query.html#where/3">where</a> macro can accept a list of parameters as we have here, but it will always combine these with AND rather than OR. To correctly build the where clause, we have to specify the OR manually. Some of our lookups may include login_id, device_id and prism_id, but others may include just login_id and prism_id or some other combination. Because we are explicitly defining the where clause to combine parameters with OR, we have to account for each combination of identifiers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d39c932bd9ef2f8107362f978c23d18/href">https://medium.com/media/4d39c932bd9ef2f8107362f978c23d18/href</a></iframe><p>I knew those seven where_clause functions would be a pain to maintain. When we added facebook_id as another parameter, I needed to find a better solution. Persisting with this approach would cause those seven functions to balloon to fifteen just to handle one more identifier. One optimization would be to handle all combinations of the same number of parameters in one function. For example, whether the parameters contain login_id and prism_id, or facebook_id and prism_id, they should be handled by one function that takes a list with two elements. The function would need to determine the field names at runtime based on the parameter keys. I chose to use Ecto <a href="https://hexdocs.pm/ecto/Ecto.Query.html#module-fragments">fragments</a> to build these clauses.</p><p>Fragments are a powerful feature of Ecto that allow us to inject SQL directly into our Ecto queries. Once I discovered these, I expected I would be able to compose my query string from an arbitrary number of parameters, removing the need for multiple where_clause functions entirely. However, fragments will not accept a string passed from a variable — the strings must be defined at compile time. This helps reduce the risk of introducing SQL injection vulnerabilities to the code. I was surprised by this, but I think it shows how thorough the Ecto team have been in designing for both flexibility and security.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/626758b2bc9d89b378800fca9625cec1/href">https://medium.com/media/626758b2bc9d89b378800fca9625cec1/href</a></iframe><p>So although fragments didn’t eliminate the need for multiple functions to handle lists of different length, by determining the fields and values at runtime I was able to design a set of functions that only expands linearly as we add more parameters. For each list size, two functions are needed as we query different tables if device_id is present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa22e01f6253a9e2c1e682037ec47a5d/href">https://medium.com/media/fa22e01f6253a9e2c1e682037ec47a5d/href</a></iframe><p>This solution is more succinct and, with fewer functions, is probably easier to maintain, but it is not easy to tell what is happening at a glance. As an alternative, I considered building a raw SQL string and executing this with Ecto.Adapters.SQL.query, but this increases the likelihood of introducing vulnerabilities and adds complexity to convert the result to the appropriate struct. I also saw some suggestions online that the problem can also be solved by writing a custom macro to generate the appropriate fragments.</p><p>In my search for solutions, I was very excited to hear that Ecto 2.1 adds support for these types of queries with the <a href="https://hexdocs.pm/ecto/2.1.0-rc.3/Ecto.Query.html#or_where/3">or_where</a> macro. Like the where macro, this can take a list of any length to build the where clause, but this time it will combine them with OR — exactly what I was originally hoping to do.</p><p>Ecto 2.1 is still at the release candidate stage, but hex.pm now lists this as the most current version. This is not true on hexdocs.pm, though, so be sure to include the version number in the URL when exploring the API: <a href="https://hexdocs.pm/ecto/2.1.0-rc.3/Ecto.html">https://hexdocs.pm/ecto/2.1.0-rc.3/Ecto.html</a>. In order to upgrade my project, I modified my mix.exs file to override the existing version of Ecto that comes with Phoenix 1.2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3daf469d3b621641a63410b76a565724/href">https://medium.com/media/3daf469d3b621641a63410b76a565724/href</a></iframe><p>Thanks to this amazing new feature, the final version of my query is also the simplest and will not need to change as we add more identifier fields to the users table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62e46234382fd74a1806798781a290e/href">https://medium.com/media/e62e46234382fd74a1806798781a290e/href</a></iframe><p>In the case where device_id is not present, you can see that it is possible to use or_where without an initial call to where. In the case where device_id is present, I had to move the device_id lookup to a separate where call, as the or_where macro attempts to find that field on the users table. This is one restriction that means that or_where is not a magic bullet for all complex queries of this nature, but it is nevertheless a welcome addition.</p><p>We have been running this version of the code, using Ecto 2.1.0-rc.3, in production for several weeks without issue. This change reduced our 50th percentile response time by several milliseconds, although whether this is directly related to the query rewrite or efficiency improvements in Ecto is not clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhkQaVrMGHRkV-oAEx4Wsg.png" /><figcaption>Red bar shows deploy of Ecto upgrade and or_where changes. Time units are microseconds.</figcaption></figure><p>Throughout this process I was very pleased to have a comprehensive test suite to ensure I wasn’t introducing any regressions with these multiple rounds of changes. I was also glad that we have kept Portmeirion’s dependencies up-to-date such that adding the latest version of Ecto required very few changes beyond the deprecation of cast/4 in favor of cast/3 and validate_required in the model changesets. Given how fast the Elixir ecosystem is growing, it can be a challenge to keep up with changes in your dependencies, but sometimes those changes are exactly what you need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f00a45da352c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleacher-report-engineering/asking-the-right-question-or-where-would-we-be-without-ecto-upgrades-f00a45da352c">Asking the right question (or_where would we be without Ecto upgrades)</a> was originally published in <a href="https://medium.com/bleacher-report-engineering">Bleacher Report Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brunch in a container: Phoenix frontend builds and Docker]]></title>
            <link>https://medium.com/bleacher-report-engineering/brunch-in-a-container-phoenix-frontend-builds-and-docker-bbf15e03585b?source=rss-40f2db05ef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbf15e03585b</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Peter Hastie]]></dc:creator>
            <pubDate>Tue, 20 Sep 2016 18:57:49 GMT</pubDate>
            <atom:updated>2016-09-23T16:33:44.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_kOU2m3jRxJ5GAUxbC73Q.jpeg" /></figure><p>In a <a href="https://dev.bleacherreport.com/starting-a-phoenix-project-with-docker-ab2a171fa2f4#.38m62nihu">previous post</a>, I detailed the steps required to set up a new Phoenix project in a Docker container. To keep things simple, I set up an API-only project, excluding the frontend build tools during the initial project setup. In this post I will show how to set up these tools within the Docker environment.</p><p>At Bleacher Report we have used Phoenix mainly to create fast API servers, focusing on the model and controller layers to build JSON objects. However, a lot of the current development on the Phoenix framework is focused on the view and frontend layers, making it particularly well suited for real-time interactive web applications supporting a large number of connected users. One area where this might be applicable at Bleacher Report is our writer tools, where we have to manage multiple editors making changes to a news stream simultaneously.</p><p>When I wrote my previous post, I encountered a number of issues when attempting to work with Phoenix’s frontend build pipeline on a Docker environment. These issues stemmed from limitations of <a href="https://docs.docker.com/machine/">docker-machine</a> which is built on top of <a href="https://www.virtualbox.org/">Virtual Box</a> and doesn’t forward inotify events to the container when a file is modified on the host. So if a file is edited in Sublime Text on the Mac host, that change won’t be detected by the build pipeline. In the past I have been able to work around this with <a href="https://github.com/sillypog/inotify-proxy">inotify-proxy</a>, a tool I built which ensures changes are detected within the container. This was not sufficient with Phoenix however, as the framework continues to serve a cached-version of the built file; this is true whether the change is made by triggering the pipeline or manually editing the built file.</p><p>Fortunately all of these issues are resolved with <a href="http://www.docker.com/products/docker#/mac">Docker for Mac</a>, the docker-machine replacement built on top of OSX’s own hypervisor framework rather than Virtual Box. Shared volumes work much more smoothly on this platform which is a huge boon for developing inside containers. I‘ve been running the beta version of this application for a month now without issues and I recommend making the switch. The one issue I have experienced is that compilation sometimes stalls when run in the container although not when building the image; modifying the run command in docker-compose to turn off multi-core features for development seems to fix this. Because we’re not using docker-compose in production, this only affects the development environment.</p><pre>command: elixir --erl &quot;-smp disable&quot; -S mix do ecto.migrate, phoenix.server</pre><p>The frontend build pipeline uses <a href="http://brunch.io/">brunch.io</a>, a javascript library that runs on <a href="https://nodejs.org/en/">Node.js</a>. Docker’s official Elixir image doesn’t come with Node preinstalled, so we will have to add that. The official Debian package for Node is quite old now, but fortunately <a href="https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions">Nodesource</a> provides an alternative package containing the latest version. We can modify the Dockerfile to add Node and install dependencies from npm during the image build step.</p><pre>FROM elixir:onbuild<br>MAINTAINER Peter Hastie &lt;<a href="/service/mailto:phastie@bleacherreport.com">phastie@bleacherreport.com</a>&gt;</pre><pre>RUN curl -sL <a href="https://deb.nodesource.com/setup_6.x">https://deb.nodesource.com/setup_6.x</a> | bash — &amp;&amp; \<br> apt-get install -y nodejs</pre><pre>ADD . /app<br>RUN mix local.hex — force<br>WORKDIR /app<br>ENV MIX_ENV prod<br>RUN mix do deps.get, compile</pre><pre>RUN npm install</pre><pre>EXPOSE 4000<br>CMD [“mix”, “do”, “ecto.migrate,”, “phoenix.server”]</pre><p>If we were to rebuild the image and run <em>docker-compose up</em> at this point we would get an error that <em>node_modules/brunch/bin/brunch</em> does not exist, even though the npm install step ran during our build. To fix this, we can change docker-compose.yml to expose the <em>node_modules</em> directory through a volume when we launch the container.</p><pre>web:<br>  build: .<br>  ports:<br>    — “49235:4000”<br>  links:<br>    — db:dockerdb<br>  volumes:<br>    — .:/app<br>    — /app/node_modules<br>  environment:<br>    - MIX_ENV=dev<br>  command: elixir --erl &quot;-smp disable&quot; -S mix do ecto.migrate, phoenix.server</pre><p>When you run this with <em>docker-compose up</em>, you may see an error in your log stream from the web container.</p><pre>[error] backend port not found: :inotifywait</pre><p>This error relates to the live reload feature. Phoenix will automatically reload the browser when javascript and css files are changed. This feature is great for developer productivity, but it relies on the inotify-tools package which we’ll have to add to our image at build time. The complete Dockerfile should now look like this.</p><pre>FROM elixir:onbuild<br>MAINTAINER Peter Hastie &lt;<a href="/service/mailto:phastie@bleacherreport.com">phastie@bleacherreport.com</a>&gt;</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y \<br> postgresql-client \<br> inotify-tools</pre><pre>RUN curl -sL <a href="https://deb.nodesource.com/setup_6.x">https://deb.nodesource.com/setup_6.x</a> | bash — &amp;&amp; \<br> apt-get install -y nodejs<br>ADD . /app<br>RUN mix local.hex — force<br>WORKDIR /app<br>ENV MIX_ENV prod<br>RUN mix do deps.get, compile<br>RUN npm install<br>EXPOSE 4000<br>CMD [“mix”, “phoenix.server”]</pre><p>We can confirm that the build pipeline and live reloading features are working by modifying <em>web/static/css/app.css</em>. I found it easiest to delete the current contents of the file and replace them with something simpler.</p><pre>h2 {<br>  color: #00FF00;<br>}</pre><p>Browsing to the landing page at localhost:49235 we now see a very stark page with green heading text saying “Welcome to Phoenix”. Edit the CSS color value and you should see the changes applied in the browser as soon as the file is saved, and the built file in <em>priv/static/css/app.css</em> will have been updated.</p><p>Although these steps should be sufficient to get you up and running in development, your configuration will probably change as you move towards production. In particular, you may wish to run the build pipeline in a separate container to avoid installing Node in the image by default, as you are unlikely to need this in your production containers. Having both the Elixir and Node versions defined in the Dockerfile certainly makes it easier to support multiple projects running on different versions of these platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbf15e03585b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleacher-report-engineering/brunch-in-a-container-phoenix-frontend-builds-and-docker-bbf15e03585b">Brunch in a container: Phoenix frontend builds and Docker</a> was originally published in <a href="https://medium.com/bleacher-report-engineering">Bleacher Report Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking optional block usage in Ruby]]></title>
            <link>https://medium.com/bleacher-report-engineering/benchmarking-optional-block-usage-in-ruby-890379fc28ba?source=rss-40f2db05ef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/890379fc28ba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Peter Hastie]]></dc:creator>
            <pubDate>Fri, 22 Jul 2016 22:57:31 GMT</pubDate>
            <atom:updated>2016-07-24T16:14:53.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YkxK6qIHbZVEty62lycfA.jpeg" /></figure><p>Thanks to an insightful code review from a coworker and Ruby’s benchmarking tools, I recently gained some insight into the different methods of invoking Ruby blocks.</p><p>I had created a pull request to modify a Ruby service that processes event logs, matching data field dimensions with appropriate foreign key values, allowing the data to be written to fact tables in our Redshift star-schema warehouse. The service, Pallet, stores copies of the dimension data in Redis and performs matches against this. This is faster than reading from Redshift and allows multiple Pallet workers using a shared store to update data without duplication.</p><p>When I first designed the system I had assumed that Redis would initially be empty, so I designed a read-through cache to populate Redis as values are read from the database. I didn’t want the Cache class to need to know the details of how to communicate with Redshift, so I passed this in as a block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f595e17070dfe9451b029ff81aa6b9c/href">https://medium.com/media/8f595e17070dfe9451b029ff81aa6b9c/href</a></iframe><p>After working with the service for a while I realised that it was easier to seed Redis with the small amount of initially known dimension data; since all new dimensions are added to the cache before being copied to the database, there was no longer a need for Pallet to read from Redshift at all. I removed the fallback block from the call to Cache.fetch, but I wanted to keep the Cache itself flexible, so I made it check for the presence of a block, calling it if present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c3df0455b5be16108a3d4057295577d/href">https://medium.com/media/0c3df0455b5be16108a3d4057295577d/href</a></iframe><p>Eddie Dombrowski (<a href="https://twitter.com/_thebrowski">@_thebrowski</a>) reviewed my pull request and pointed out that yield can be twice as fast as block.call and suggested pairing yield with a call to block_given? to handle this situation where the block is optional. This sounded like good advice, but performance metrics can quickly go out of date as the Ruby runtime advances so I didn’t want to make this change without testing it for myself. In addition, I like that the &amp;block syntax makes it explicit in the signature that the method works with a block and I didn’t want to lose that without good reason.</p><p>Ruby ships with a <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html">benchmark</a> module so I decided to use this to test Eddie’s claim. I set up a test to compare my method with Eddie’s method and a hybrid where the block is part of the method signature but is invoked with yield. What I found was that these methods performed quite differently depending on whether or not the block was actually present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1f400910d02482107ed8720474781d5/href">https://medium.com/media/f1f400910d02482107ed8720474781d5/href</a></iframe><p>One run of this test gave the following results on Ruby 2.1.5 running inside a Docker container on OSX, and subsequent repeat runs were similar.</p><pre>                     user       system     total    real<br>yield:               1.320000   0.000000   1.320000 (  1.322115)<br>block                5.580000   0.000000   5.580000 (  5.594383)<br>yieldblock           5.160000   0.000000   5.160000 (  5.169885)<br>yield no block:      1.050000   0.000000   1.050000 (  1.054659)<br>block no block       0.870000   0.000000   0.870000 (  0.876913)<br>yieldblock no block  0.850000   0.010000   0.860000 (  0.859577)</pre><p>The situation was even more pronounced than Eddie had warned — block.call was more than four times slower than yield when a block was given. However, when no block was passed, yield was slightly slower. The hybrid test suggests this is because the call to block_given? is slightly slower than testing for the presence of the block reference directly. As there is never a block passed in with the current version of the code, I left the code unchanged but added a note to use yield if other callers are added that do pass blocks. Thanks to Ruby’s easy to use benchmark module I was able to give Eddie a decent explanation for why I made that decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=890379fc28ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleacher-report-engineering/benchmarking-optional-block-usage-in-ruby-890379fc28ba">Benchmarking optional block usage in Ruby</a> was originally published in <a href="https://medium.com/bleacher-report-engineering">Bleacher Report Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting a Phoenix project with Docker]]></title>
            <link>https://medium.com/bleacher-report-engineering/starting-a-phoenix-project-with-docker-ab2a171fa2f4?source=rss-40f2db05ef50------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab2a171fa2f4</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Peter Hastie]]></dc:creator>
            <pubDate>Thu, 09 Jun 2016 18:46:34 GMT</pubDate>
            <atom:updated>2016-12-22T20:09:48.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6m4fCyNOAFpIsaGfe775Q.jpeg" /></figure><p>Over the last three years, the <a href="http://bleacherreport.com/">Bleacher Report</a> engineering team has been working to separate our Rails monolith into microservices. We now have 25 services in production, and this has relieved a lot of the bottlenecks on our development process. Our microservices have also brought performance and cost benefits as we are able to choose the most optimal technologies for the specific needs of that service. In many cases we have chosen <a href="http://elixir-lang.org/">Elixir</a>, a new language that runs on the Erlang virtual machine, perfect for high concurrency applications.</p><p>Running our microservices on <a href="https://www.docker.com/">Docker</a> makes the process of switching to a new technology much simpler. Our deployment process is the same whether we’re deploying an Elixir, Ruby, or Node application, allowing developers to take a more active role in setting up infrastructure and pushing code changes, reducing the load on the devops team. It also makes it much easier for developers to set up a new project on their machine, removing issues caused by differences in their local environment.</p><p>Here are the steps I take to set up a new project using Elixir’s <a href="http://www.phoenixframework.org/">Phoenix</a> web framework on Docker. These steps assume you have Docker running on your development machine.</p><h4>Starting from nothing</h4><p>To create an app called Example, we’ll need to download the Phoenix Mix archive and run the project generator. Thanks to Docker volumes, we can do this without installing the archive permanently. For each new project we create, we will be able to use the latest archive without having to consider what might have been installed previously.</p><p>Create and enter a new directory named <em>example</em>. Add a minimal Dockerfile to allow us to run elixir scripts.</p><pre>FROM elixir:onbuild<br>MAINTAINER Peter Hastie &lt;phastie@bleacherreport.com&gt;<br>ADD . /app<br>RUN mix local.hex --force<br>WORKDIR /app<br>EXPOSE 4000<br>CMD [“/bin/bash”]</pre><p>Build and run the Dockerfile.</p><pre>$ docker build --tag example .</pre><pre>$ docker run --interactive --tty --rm --volume $(pwd):/app example</pre><p>The volume argument to <em>docker run</em> creates a shared volume between the example directory on the host and the app directory in the container. When we run the Phoenix Mix archive in the next step, the files will be generated inside the container and will also be persisted to our <em>example</em> directory.</p><p>The run command should have left us at the bash prompt within the container. At this prompt, download and run the Phoenix Mix archive to create the project scaffold. The archive will be downloaded to a location outside the app directory, so it will not be persisted when the container is shutdown. However, the files that the mix task generates will be persisted, as they are added to the app directory.</p><pre>&gt; mix archive.install <a href="https://github.com/phoenixframework/archives/raw/master/phoenix_new.ez">https://github.com/phoenixframework/archives/raw/master/phoenix_new.ez</a></pre><pre>&gt; mix phoenix.new . --module Example --app example --no-brunch</pre><p>That should have added a lot of files to our example directory. We set the application name and module name explicitly, otherwise they will take the name of the container working directory, <em>app</em>. The no-brunch option excludes all of the frontend build pipeline; this won’t be needed on an api-only project. Update: I discuss the frontend setup <a href="https://dev.bleacherreport.com/brunch-in-a-container-phoenix-frontend-builds-and-docker-bbf15e03585b#.fhnbbnyqu">here</a>.</p><h4>Launching the server</h4><p>We should now be able to start the server and browse to the Phoenix welcome page for the project. It is possible to do this just by modifying the launch command for the container, but because we’ll want to launch the server by default it will be better to modify the image as well. Type <em>exit</em> to leave the container. It should be removed automatically because we launched it with the <em>rm</em> option. Change the last line in the Dockerfile as shown.</p><pre>CMD [“mix”, “phoenix.server”]</pre><p>Now rebuild the image and start a new container. This time we will map port 4000 in the container to one of the ports forwarded by the virtual machine.</p><pre>$ docker build --tag example .</pre><pre>$ docker run --interactive --tty --rm --volume /Users/peterhastie/workspace/elixir/example:/app --publish 49235:4000 example</pre><h4>Adding the database</h4><p>Running the database in a separate container has several advantages. It is similar to a production environment where the database will be running on a separate host. It also makes it very easy to recreate the database as needed, making it easier to experiment with schema changes.</p><p>Managing the application and database containers is made much easier by docker-compose. At Bleacher Report, we only use docker-compose on our development environments, and we check in our docker-compose.yml files to make it trivial for other team members to launch the whole application stack. Add this docker-compose.yml to the <em>example</em> directory.</p><pre>db:<br> image: kamui/postgresql<br> environment:<br> — POSTGRESQL_DB=phoenix<br> — POSTGRESQL_USER=postgres<br> — POSTGRESQL_PASS=postgres</pre><pre>web:<br> build: .<br> ports:<br> — “49235:4000”<br> links:<br> — db:dockerdb<br> volumes:<br> — .:/app</pre><p>Our application can now be launched by running <em>docker-compose up</em>. This will create two containers: <em>example_db_1</em> running the postgreSQL database and <em>example_web_1</em> running our Phoenix application. The database container will launch a new database named by the POSTGRESQL_DB environment variable we specified in docker-compose.yml, in this case “phoenix”. This means it is not necessary to run <em>mix ecto.create</em> as the database will already exist.</p><p>We will have to tell the application where to find the database. Because we linked the database container to the web container through the dockerdb alias, we can use automatically generated environment variables rather than hardcoded values. The database section of our config files can therefore be consistent between development and production environments. Modify config/dev.exs to include the following database configuration.</p><pre>config :example, Example.Repo,<br> adapter: Ecto.Adapters.Postgres,<br> username: System.get_env(“DOCKERDB_ENV_POSTGRESQL_USER”),<br> password: System.get_env(“DOCKERDB_ENV_POSTGRESQL_PASS”),<br> database: System.get_env(“DOCKERDB_ENV_POSTGRESQL_DB”),<br> hostname: System.get_env(“DOCKERDB_PORT_5432_TCP_ADDR”),<br> port: System.get_env(“DOCKERDB_PORT_5432_TCP_PORT”),<br> pool_size: 10</pre><p>The Ecto adapters for Postgres require the psql utility be installed, but it is not available by default in Docker’s official Elixir image. We can add it by modifying the Dockerfile, then rebuilding the image and relaunching the container.</p><pre>FROM elixir:onbuild<br>MAINTAINER Peter Hastie &lt;<a href="/service/mailto:phastie@bleacherreport.com">phastie@bleacherreport.com</a>&gt;<br>RUN apt-get update &amp;&amp; apt-get install --yes postgresql-client<br>ADD . /app<br>RUN mix local.hex --force<br>WORKDIR /app<br>EXPOSE 4000<br>CMD [“mix”, “phoenix.server”]</pre><p>We can now create some migrations by hand or via generators. To run the generators or migrations, we will need to access the shell inside the running container.</p><pre>$ docker exec --interactive --tty example_web_1 /bin/bash</pre><pre>&gt; mix phoenix.gen.model User users name:string</pre><pre>&gt; mix ecto.migrate</pre><p>We can check that these changes have been made in the database by connecting to it directly and running SQL queries.</p><pre>$ docker exec --interactive --tty example_db_1 psql phoenix --user postgres</pre><pre>&gt; \d users</pre><p>We can shutdown the containers by hitting ctrl-c on the tab in which we ran <em>docker-compose up</em>. We can then run <em>docker-compose rm</em> to remove the server and database containers, in which case all data in the database will be lost. If we want to retain that data, we can remove just the server container by running <em>docker rm example_web_1</em>.</p><p>We can ensure that newly created stacks or new code deploys always have an up-to-date database by running migrations when the container is launched. To do this, we can modify the Dockerfile to run multiple commands.</p><pre>CMD [“mix”, “do”, “ecto.migrate,”, “phoenix.server”]</pre><h4>Up and running</h4><p>You now have all of the basics in place to work on the application and you didn’t need to change anything on your system to get here. You can create as many microservices as you need, without ever having to worry about incompatibilities between language and framework versions. You will almost certainly want to make further changes to your Dockerfile as you share the project with other developers and start running the application on other infrastructure, and you may want to build off the more lightweight Elixir <a href="https://hub.docker.com/_/elixir/">base image</a> rather than the onbuild version.</p><p>Finding a good development workflow with Docker takes some time, and what works for one project or team might not be ideal for others. An ideal workflow is one that allows developers to feel as productive as possible, and it is certainly true that there are some hurdles to overcome when containerizing a new project. These initial downsides are more than made up for by enabling a consistent process for subsequent developers to install the project and to deploy the application to production environments. This early work pays huge dividends on teams working on multiple microservices.</p><p>Docker is still an evolving technology, and the tools are constantly improving. Everything shown here was run on <a href="https://www.docker.com/products/docker-machine">docker-machine</a> running on a Mac. I have found that there are some <a href="https://www.virtualbox.org/ticket/14234">significant</a> <a href="https://github.com/phoenixframework/phoenix/issues/1409">hurdles</a> to developing a project with frontend components on this setup, as Phoenix and Brunch have filesystem requirements that are not compatible with Virtual Box. The good news is that the upcoming <a href="https://blog.docker.com/2016/03/docker-for-mac-windows-beta/">Docker for Mac/Windows</a> may solve these issues.</p><p>Update: I describe my experiences setting up Phoenix for frontend development in containers <a href="https://dev.bleacherreport.com/brunch-in-a-container-phoenix-frontend-builds-and-docker-bbf15e03585b#.fhnbbnyqu">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab2a171fa2f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleacher-report-engineering/starting-a-phoenix-project-with-docker-ab2a171fa2f4">Starting a Phoenix project with Docker</a> was originally published in <a href="https://medium.com/bleacher-report-engineering">Bleacher Report Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>