<?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[Rue Gilt Groupe Tech Blog - Medium]]></title>
        <description><![CDATA[Fine Code&#39;s Always in Style - Medium]]></description>
        <link>https://medium.com/rue-la-la-tech?source=rss----13f707e0d2fc---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Rue Gilt Groupe Tech Blog - Medium</title>
            <link>https://medium.com/rue-la-la-tech?source=rss----13f707e0d2fc---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:01:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/rue-la-la-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scala Short Take: Will it Fold?]]></title>
            <link>https://medium.com/rue-la-la-tech/scala-short-take-does-it-fold-c14222540917?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/c14222540917</guid>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[idioms]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 15:00:52 GMT</pubDate>
            <atom:updated>2018-08-29T13:11:29.818Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tale of procedural code made functional</h4><h3>Background</h3><p>For a reason that’s not important, we wanted to generate all versions of a multiword string (we’re Rue Gilt, so it’s a retail brand name).</p><p>Words, their initials, followed by “.”, space, or nothing at all. So “Jones New York” generates that string intact, through “J New.York” to “J N Y” and everything in between. We think there are 3³ * 2³ = 216 variations.</p><p>We were in a hurry so just wanted to knock something out that worked. We started with loops and quickly got into special cases and off-by-one errors. But we soldiered on regardless. The code looked like</p><pre>def extractFirstLetter(line: String) = {<br>  var words = line.split(&quot; &quot;)<br>  val fl = words.map(_(0).toString)<br>  words ++ fl</pre><pre>  for (i &lt;- 0 to fl.size - 1) {<br>    for (j &lt;- i + 1 to (fl.size)) {<br>      if (fl.slice(i, j).size &gt; 1)<br>        words = words :+ fl.slice(i, j).mkString(&quot;&quot;)<br>    }<br>  }</pre><pre>  words<br>}</pre><p>A few things we’re wondering</p><ul><li>Is it correct?</li><li>Could we explain it?</li><li>Why the var?</li><li>What does the words ++ fl do?</li><li>Can we make it for functional?</li></ul><h3>Let’s clean it up</h3><p>We think there’s a fold or reduce in there somewhere. There is. Here’s how, with the steps to derive it along the way.</p><p>First let’s make functions for things, including one that contains the for loop with a slight change to clean it up.</p><pre>def allCombos(remaining: Seq[String]): Seq[String] = {<br>    def safePrefix(word: String) = <br>      if (word.size == 0) &quot;&quot; else word.substring(0, 1)</pre><pre>  def variations(word: String) =<br>    Seq(word, word + &quot;.&quot;, word + &quot; &quot;, safePrefix(word))</pre><pre>  def expand(word: String, tail: Seq[String]) =<br>    for (w &lt;- variations(word); t &lt;- tail) yield Seq(w + t.mkString)<br>}</pre><p>(The lines of code wrap around, but we’re looking for a different kind of fold!) In any case this looks like a nice encapsulation of some of the operations we’ll probably need.</p><p>safePrefix gets the initial letter of a word if it exists, or &quot;&quot; if it doesn’t. variations uses this result and returns word with some suffixes. expand takes a word and returns all the word variations (in w) along with all the remaining combinations. We’re going to arrange to pass the current word (in, well word, which we totally should have called head) and the remaining words in the sequence tail. The for is just nested loops, and so a bit unsatisfactory, but we’ll get to that later.</p><p>Next task is to put these new functions together. We’ll make a function that traverses the list of source words in the input, peeling them off one at a time.</p><pre>remaining.size match {<br>  case 0 =&gt; Seq(&quot;&quot;)<br>  case _ =&gt; {<br>    val tail = allCombos(remaining.tail)<br>    <br>    expand(remaining.head, tail).flatten ++ tail<br>  }<br>}</pre><p>We made it messier because we have to check for an empty list. We can’t avoid putting somewhere: Either as we have it above or guarding the recursive call. And while the recursive call itself is OK to look at, all the tail and flatten tomfoolery is a bit much. And that would ruin our chances at being “<em>provably correct by inspection</em>” a thing we value highly at Rue Gilt Groupe.</p><p>In any case, now we call the entry point and print the results</p><pre>allCombos(words).foreach(println)</pre><pre>JonesNewYork<br>JonesNewYork.<br>JonesNewYork<br>JonesNewY</pre><p>It gives us what we want, along with duplicates, which we don’t quite understand. But we could easily throw them into a Set to dedup them.</p><h3>Now let’s get fold-y or reduce-y</h3><p>We’ll start with Seq(&quot;&quot;), a list of a single empty string. Then we’ll add all the word combinations for each source word as a prefix to all the previously created strings.</p><p>In other words, we keep expanding all the different possibilities so far with the variations of each word. And so on, until we’ve worked our way to the first word. Simple enough to say, but how do we implement it?</p><pre>val words = Seq(&quot;Jones&quot;, &quot;New&quot;, &quot;York&quot;)</pre><pre>def safePrefix(word: String) = <br>  if (word.size == 0) &quot;&quot; else word.head<br>def variations(word: String) = <br>  Seq(word, word + &quot;.&quot;, word + &quot; &quot;, <br>  safePrefix(word), safePrefix(word) + &quot;.&quot;)<br>def combine(word: String, tail: Seq[String]) = <br>  for (w &lt;- variations(word); t &lt;- tail) yield Seq(w + t.mkString)<br>def expand = <br>  (word: String, tail: Seq[String]) =&gt; combine(word, tail).flatten</pre><pre>val everything = words.foldRight(Seq(&quot;&quot;))(expand)</pre><pre>everything.foreach(println)</pre><p>That .foldRight expresses just the right thing: start with Seq(&quot;&quot;), and compose all the variations of each word to the right until we’ve done the last one (on the left).</p><p>So why .fold and not .reduce? Two reasons. .reduce does not work on empty lists because it requires at least one element, the head of the list. We don’t have an empty list (this time), but we want our code to be robust.</p><p>So we need .fold for that reason, which works because it takes a starting value. Note in .fold the function can produce a different type to the elements of the list, whereas .reduce variants can not: Everything must be the same type. This is another good reason to use .fold.</p><p>One other thing, there’s an ungainly .flatten in there, which is not only ugly but we feel sure can be done a better way.</p><h3>But is that enough?</h3><p>Not really, if we’re honest. There’s still a nested loop in there, even though the Scala syntax makes it expressive and compact.</p><p>Also, this blog post is about fold and reduce, so we need to go full beans on making that happen.</p><p>Start with some declarations, a bit cleaned up this time and more general.</p><pre>val words = Seq(&quot;Jones&quot;, &quot;New&quot;, &quot;York&quot;)</pre><pre>def safePrefix(word: String) = word.headOption.getOrElse(&#39; &#39;)<br>def suffixes(word: String) = Seq(word, word + &quot;.&quot;, word + &quot; &quot;)<br>def variations(word: String) = suffixes(word) ++ <br>      suffixes(safePrefix(word).toString)</pre><p>safePrefix now returns Char we got with .headOption. We have to convert this to a String somewhere. Not really sure of the best place. Now we have to figure out how to write a new combine() function that we can substitute for the old one.</p><p>We can do it in a one-liner, but this looks arguably cleaner, and so more likely to be correct and easier to explain.</p><pre>def combine(word: String, tail: Seq[String]): Seq[String] = {<br>  def concat(t: String) = tail.map(_ + t)</pre><pre>  variations(word).flatMap(concat)<br>}</pre><p>The _ + t is a bit mysterious until you know Scala. We could have written this as w =&gt; w + t, which you could argue is clearer. As a bonus, we removed the recursive call and made it recurrent. We don’t need the return type, but write Seq[String] for clarity. Good IDEs will show this if you hover over the function or value. In any case our driver code is still</p><pre>val everything = words.foldRight(Seq(&quot;&quot;))(combine)</pre><pre>everything.foreach(println)</pre><p>Which when we run it delivers the following and we’re done.</p><pre>YorkNewJones<br>York.NewJones<br>York NewJones<br>YNewJones<br>Y.NewJones<br>Y NewJones<br>...</pre><p>Wait what? The words and variations are in reverse order. What happened? And how do we fix it?</p><p>With the help of some println debugging code, we find the .foldRight(concat) is applied over the source words in the wrong order.</p><h3>We broke it. Can we fix it?</h3><p>Sure we can. Simply using a .foldLeft should do the trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yT_JeIXBy7Nacx3gD0E4wQ.png" /><figcaption>Converting foldRight to foldLeft isn’t as easy as we thought</figcaption></figure><p>Grrrr…. What’s going on. We look at the signature of .foldRight and it’s</p><pre>def foldRight[B](z: B)(op: (A, B) =&gt; B): B = ...</pre><p>meaning type we start with, B, a Seq[String], which is the second argument to op , the function combine in our case. And we return a B, Seq[String].</p><p>The function must work with the first argument of the type A, a String here. So it makes sense to us now that the words get appended in the <em>wrong</em> order, from the right.</p><p>Let’s see whether .foldLeft is the solution, appending source words in the correct order. Along the way, we can find the source of the error above.</p><p>The signature of .foldLeft is</p><pre>def foldLeft[B](z: B)(op: (B, A) =&gt; B): B = ...</pre><p>B is still Seq[String], the initial value and the return type of the .foldLeft. But the order of arguments to op is different. Why the complexity? Ignoring the specific implementation of op for a moment, let’s rewrite .foldRight as</p><pre>op(&quot;York&quot;, op(&quot;New&quot;, op(&quot;Jones&quot;, Seq(&quot;&quot;))))</pre><p>and .foldLeft as</p><pre>op(op(op(Seq(&quot;&quot;), &quot;Jones&quot;), &quot;New&quot;), &quot;York&quot;)</pre><p>The types of the arguments to op are reversed. An easy fix. Just change the signature of combine to</p><pre>def combine(tail: Seq[String], word: String): Seq[String] = ...</pre><h3>The upshot</h3><p>Was it worth it? We think so. We learned how to write iterative functional code to replace explicit loops. (It took considerably less time to do the work than write about it!) It’s easier to explain and “<em>prove correct by inspection”</em>, something we said we shoot for.</p><p>Also we removed the var, which is always really nice. var is a bad smell in code and we try to avoid it at all costs. Mutability encourages procedural code. We want functional.</p><p>Thanks for reading. There’ll be more on Scala in a bit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c14222540917" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/scala-short-take-does-it-fold-c14222540917">Scala Short Take: Will it Fold?</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Take: Scala Chops for Apache Spark]]></title>
            <link>https://medium.com/rue-la-la-tech/quick-take-scala-chops-for-apache-spark-4779600b7dcd?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/4779600b7dcd</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 14:04:24 GMT</pubDate>
            <atom:updated>2018-08-01T14:04:23.805Z</atom:updated>
            <content:encoded><![CDATA[<h4>More functional Spark using Scala idioms</h4><h3>Note</h3><p>This is the first in a series of stories on the same topic: Up your <a href="https://www.scala-lang.org/">Scala</a> game to write better <a href="https://spark.apache.org/">Apache Spark</a> code. We see a lot of good Data Scientists writing rather <a href="https://en.wikipedia.org/wiki/Procedural_programming">procedural, imperative code</a> where there are <a href="https://www.scala-exercises.org/fp_in_scala/getting_started_with_functional_programming">better alternatives</a> that are not well documented, at least for Data Scientists.</p><h3>Background</h3><p>The Rue Gilt Groupe Data Science Team writes Apache Spark mostly in Scala, but sometimes in Python, on the <a href="https://databricks.com/">Databricks platform</a>. We’re talking here about Scala, specifically some of Scala’s powerful functional features. Without care, Databricks notebooks can become procedural and messy. A fluency in these Scala features will improve your Spark code in the following ways:</p><ul><li><strong>Readability:</strong> Make it easier for you to write and others to read.</li><li><strong>Robustness:</strong> Remove fragile constructs.</li><li><strong>Performance:</strong> Make it faster.</li></ul><p>We’re using an example that came up recently where we wanted to union some datasets and it took longer than expected. It’s a simple thing, but the principles scale well. Below are our investigation and some results we hope you’ll find interesting.</p><h3>The issue</h3><p>We had four datasets with the same schema that we wanted to merge, or union, in Apache Spark as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19141f696543a682e895490f930b39ab/href">https://medium.com/media/19141f696543a682e895490f930b39ab/href</a></iframe><p>Our union code was simply a sequence of .unions like you’d expect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59cad950b71de920a1bc7dbb77f9bdcf/href">https://medium.com/media/59cad950b71de920a1bc7dbb77f9bdcf/href</a></iframe><p>which took about 20s. We include .filter($&quot;rating &gt; 0.1) so Spark can’t easily shortcut the count. Note that we use .count rather that display() because Databricks can use an implicit .limit(1000) to short-circuit things for display, which skews results. (You can .cache or .persist DataFrames to avoid reading the files again, which can slow down the initial load dramatically while speeding up subsequent operations.)</p><p>Our concerns with this approach were:</p><ol><li>The list of files was fragile because the path for each is long and must be the same.</li><li>You have to remember to add the DataFrame for any new files to the .union.</li><li>Performance was not predictable.</li></ol><blockquote>If you didn’t notice the deliberate bugs in each of the code snippets above, I think we’ve made our point about readability and robustness.</blockquote><p>Let’s replace a couple of things in the code to make it easier to spot these errors.</p><h3>Making it cleaner</h3><p>Two things stand out:</p><ol><li>The repetitive file paths.</li><li>The cumbersome union.</li></ol><p>To fix this, let’s collect the files in a List, map them to DataFrames, then union them in a function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eb66912c54854a4d5a43f073c1c3ea3/href">https://medium.com/media/3eb66912c54854a4d5a43f073c1c3ea3/href</a></iframe><p>Now our code is <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>: the file path and the union only appear once in the code. We could easily have put the union function inline with:</p><pre>.reduceLeft(_ union _)</pre><p>which many could argue is a bit idiosyncratic until you know about Scala’s trick with infix operators and how to use _ as a shortcut for parameters. Curiously, each _ above refers to a <em>different</em> parameter. But passing a function with a good name lets us write sentences in code that are clearer and therefore more likely to be a thing we like, <em>provably correct by inspection</em>.</p><h4>reduceLeft?</h4><p>Skip ahead if this is old hat.</p><p>reduceLeft takes the first element of a list. If there’s a second element, it applies the function, which is union in our case. Then it applies the function to this result and the third element, and so on. reduceLeft works fine with one element (it just doesn’t apply the function), but throws UnsupportedOperationException if the list is empty.</p><p>There are two ways to handle potentially empty lists:</p><ol><li>Use reduceLeftOption, which returns and Option[T], specifically None for the empty list and Some(t) if the list has values.</li><li>Use foldLeft.</li></ol><h4>reduce/fold? left/right? This is confusing!</h4><p>In general, left and right variants are interchangeable if the operators are commutative — that is, the order of parameters doesn’t matter. Both + and * are commutative (and so is union).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41e9317929becc64cfd91c5a9a3a3e31/href">https://medium.com/media/41e9317929becc64cfd91c5a9a3a3e31/href</a></iframe><p>As you see above, things get interesting for - and / because they are not commutative, and the order matters.</p><p>So what’s fold? Sometimes you want to start with an initial value or work with empty lists without Option tomfoolery. fold is just the ticket in this case, as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e37dc9ad29eddeef5d8367bddd95e770/href">https://medium.com/media/e37dc9ad29eddeef5d8367bddd95e770/href</a></iframe><p>Because fold always has an initial value, it works on empty lists just fine.</p><h3>Yes, but what about performance?</h3><p>We made our code more readable and robust, as promised. But does it go faster? No, not at all.</p><p>We can see this by doing a .explain. The plan is identical to the procedural code we started with.</p><p>Our fake example is only counting the number of rows in the union of all the DataFrames. So perhaps we can filter <em>before</em> the union like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b8e5eb11de4359502cd38428fce9d7d/href">https://medium.com/media/5b8e5eb11de4359502cd38428fce9d7d/href</a></iframe><p>And try it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Fv_jcnPsiTsmqmhFX5eIw.png" /><figcaption>Can’t seem to short-circuit the union this way</figcaption></figure><p>Nope.</p><p>Incidentally, if we really want to go for brevity, we can write the filtered count as:</p><pre>files.map(fromFile).map(_.filter($&quot;rating&quot; &gt; 0.1).count).sum</pre><p>Let’s look at the API reference for read.parquet. We can pass multiple files! So let’s try it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQMZ1IoFZPUsxh9_wyiP8A.png" /><figcaption>The Scala idiom “_*” expands a list to separate arguments</figcaption></figure><p>About the same. Makes no practical difference. Oh wait, .parquet takes a file <em>pattern</em>, .../group-*:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5r4WDSmWuYiqJG3EsQEn4Q.png" /><figcaption>Try passing a pattern to .parquet()</figcaption></figure><p>If anything, that’s taking a hair longer and would get messy if you didn’t want to read everything in a location.</p><h3>The upshot</h3><p>If having your cake is robust and reliable, then not eating it is not making it go faster. In this example, anyway. Sorry about that. Apache Spark is good at optimizing expressions that are equivalent regardless of how they’re written. And it simply can’t cheat the bandwidth required to read from AWS S3.</p><p>If we missed something, or you have a way to make this faster, please let us know in the comments.</p><h3>An aside on writing reduce* and fold* in terms of each other</h3><p>You might think fold and reduce are interchangeable. Well, they are, but maybe not as you might think at first. Take a look at this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68a721ac5c2e1bc553243429efb62f5c/href">https://medium.com/media/68a721ac5c2e1bc553243429efb62f5c/href</a></iframe><p>With +, a commutative operator, this works out perfectly. We pass the initial value for foldLeft to 0, which is a good start if you’re adding things up. (You’d use 1 for *.)</p><p>But with subtraction, -, things do not go as planned: reduceLeft and foldLeft are not equivalent. What’s going on? We decompose these into their arguments and operators as follows. list.reduceLeft is the same as the expression:</p><pre>1 - 7 - 5 - 2 = -13</pre><p>Whereas list.foldLeft(0) is equivalent to:</p><pre>0 - 1 - 7 - 5 - 2 = -15</pre><p>You can see how we construct the equivalent correct sequence of operations using the starting value of list.head and mapping over the remainder of the list, list.tail. (It does not work to convert the list to 0 +: list: we’re back to square one.)</p><p>You can see why this works by converting it back to reduceLeft with the components we used in the fold. list.head +: list.tail is by definition the identity transform on list. You can see exceptions as expected when we apply this to the empty list, Seq().</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4779600b7dcd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/quick-take-scala-chops-for-apache-spark-4779600b7dcd">Quick Take: Scala Chops for Apache Spark</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Rue La La Bulk Loads into DynamoDB]]></title>
            <link>https://medium.com/rue-la-la-tech/how-rue-la-la-bulk-loads-into-dynamodb-ad1469af578e?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad1469af578e</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Sun, 25 Mar 2018 15:21:27 GMT</pubDate>
            <atom:updated>2018-03-25T15:21:27.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we scale DynamoDB for bulk writes</h4><h3>The main story</h3><p>This article is about one aspect of a larger project we did at Rue La La. See the following for the big picture.</p><p><a href="https://medium.com/rue-la-la-tech/large-scale-data-science-apis-at-rue-la-la-9226ecffed04">Large-Scale Data Science APIs at Rue La La - Stephen Harrison - Medium</a></p><h3>Background</h3><p>Our Data Science API usage pattern is 100% <em>read</em>-dominated 23+ hours a day, and <em>write</em> dominated for short windows of about 20 mins, triggered by Databricks Apache Spark jobs writing data to S3. We bulk load our data in one big batch, usually in the wee hours. Then there are no writes at all until the next time the data science completes and we start the bulk load all over again. This is usually daily, but can be more often for up-to-date recommendations for changing flash sales.</p><h3>The upshot</h3><p>We can use DynamoDB autoscaling for <em>reads</em>. While the read traffic patterns are far from smooth because Rue La La is a flash sale site, changes in capacity typically occur over periods of minutes in the lead up to our usual sale times like 11am and 3pm. This is the target use case for DynamoDB auto-scaling. This is in contrast to bulk <em>writes</em>, where we’re either loading as fast as we can or not at all. This is most definitely not the target use case for DynamoDB auto-scaling. So for bulk writes we must scale DynamoDB capacity ourselves.</p><p>We stream DynamoDB writes from the data science jobs’ output in S3 with a small footprint custom importer running in AWS Batch, which runs Docker images. This importer adjusts provisioned write capacity directly before and after the import. We show you the code and configuration you’ll need to pull this off.</p><h3>The problem</h3><p>DynamoDB does not offer integrated bulk load directly. The <a href="http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-importexport-ddb.html">recommended approach</a> is to create an AWS Data Pipeline to import from S3. We found deal-breaker issues with this approach, including that Data Pipeline and EMR are finicky to set up, lag behind Spark updates, and do not provide sufficient—or often any—logging for key failures.</p><p>The example Data Pipeline scenarios read files from S3 and write the corresponding DynamoDB items. <a href="https://spark.apache.org/">Apache Spark</a> distributes the Dataset in memory across EC2 instances in a cluster. The cluster is large when the data is large. This makes perfect sense when you’re playing to Spark’s strengths by operating on the data. However, when writing to DynamoDB we only need a few items at a time to batch writes efficiently. Reading a whole Dataset into large-scale distributed memory, for example, is wasteful.</p><p>Import tasks must also map the input schema to the exact format of a DynamoDB Item. We do not assume Rue Data Science jobs know anything about how data is stored and delivered. In fact, we deliberately align the output format of Data Science tasks to the input schema, usually from our <a href="https://www.snowflake.net/">Snowflake</a> Data Warehouse. This removes surprises with naming of output columns.</p><p><a href="https://aws.amazon.com/glue/">AWS Glue</a> is promising, but does not directly support DynamoDB as an endpoint as of this writing.</p><h3>First we tried DynamoDB auto-scaling</h3><p>Writing data at scale to DynamoDB must be done with care to be correct and cost effective. We started by setting the provisioned capacity high in the <a href="http://airbnb.io/projects/airflow/">Airflow</a> tasks or scheduled <a href="https://docs.databricks.com/user-guide/notebooks/index.html">Databricks notebooks</a> for each API data import (25,000+ writes per second) until the import was complete. Then setting it back down to 1 when the importers completed. We sometimes forgot, which cost money, sometimes a lot, for write capacity we weren’t consuming. And sometimes the initial capacity increase failed, which caused the imports to take too long or just fail.</p><p>We started by writing CloudWatch alarms on write throttling to modulate capacity. We had some success with this approach. Then <a href="https://aws.amazon.com/blogs/aws/new-auto-scaling-for-amazon-dynamodb/">Amazon announced DynamoDB autoscaling</a>. It works for some important use cases where capacity demands increase gradually, but not for others like all-or-nothing bulk load.</p><p>There’s also an unpleasant side-effect you need to know about that was a deal-breaker for our use case. More on that shortly.</p><p>We had to pay particular attention to the following:</p><ul><li>The console UI does not expose two important properties of the autoscaling we found valuable: ScaleInCooldown and ScaleOutCooldown, which default to 0. These settings limit the rate of successive events for scale in and out, requesting a pause of at least the given number of seconds between changes. In order to give these parameters non-zero values you must use the SDK, the AWS CLI, or CloudFormation</li><li>Even with the cool-down parameters set to limit the <em>frequency</em> of capacity changes, we had little or no control over the <em>magnitude</em> of changes. Consequently, capacity was reduced to minimum even when there was just a pause in imports. This can happen, for example, because all data API importers share bounded compute clusters in AWS Batch and are competing for resources. We’re trying to limit the maximum size of these clusters since unchecked they’re a significant expense.</li><li>You’re only allowed four capacity decreases per table per day. So a transient decrease counts as one of these. And before you know it, you’re out of available decreases so must remember to decrease manually at the next window, currently after an additional two hours.</li><li><strong>But perhaps the worst surprise of all was that auto scaling only gets triggered when there’s traffic. </strong>So after we autoscale up with bulk imports we stay at the expensive high capacity when we abruptly stop importing and our traffic goes to zero. We have a nice solution to this issue, which we’ll publish shortly.</li></ul><h3>We ran a custom importer for each file in the dataset</h3><p>Our original design sent S3 events for each part... file in the Data Science export to the batch importer as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*DQGT_gPRVJBFBqWUcPxqUg.png" /><figcaption>We started with an AWS Batch Job per part file</figcaption></figure><p>This has the advantage that we could set arbitrary DynamoDB capacity and AWS Batch cluster size to maximize throughput. But we quickly found this apparent benefit was outweighed by the lack of sufficiently fine grained control over pipeline throughput. Consequently, some part... files were stalled waiting for AWS Batch cluster capacity, while others were running into DynamoDB write throttling constraints. Overall throughput suffered, data skew between related datasets was evident, and AWS Batch cluster sizes were often large and mostly dormant.</p><h3>The final version imports the whole dataset at once</h3><p>It seems obvious to us now, but this is the model that allows the greatest throughput with the fewest AWS resources. The code is a bit subtle in places. We’ll show you why and how we address the nuances.</p><p>We only send ans3:ObjectCreated event for a single sentinel file in each dataset. We picked the _committed... file written by Spark, which conveniently contains the manifest of data files in the dataset and is written at the end of the Spark export when they’re all available in S3 and stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*ArQNazs7p3E_8qQPpFHO7w.png" /><figcaption>One import AWS Batch Job per dataset is where we ended up</figcaption></figure><p>This single importer has to be a bit smarter now. First, it must unpack or discover the part... files to be imported. Next, it must set sufficient DynamoDB write capacity before any data is imported and wait for the provisioning to succeed. (Actually, even before that it must wait for any pending scaling on the table to complete or the request will fail. We ran into this during testing quite often.) But when it’s underway, the importer has full control over parallelism and throughput. We found it invaluable to expose a number of tuning parameters through environment variables in the importer as follows:</p><ol><li>JOB_CPUS and JOB_MEMORY tell the Lambda how to configure and launch the Dicker container for the AWS Batch job</li><li>THREAD_COUNT configures the concurrency of the importer</li><li>MAX_WRITE_CAPACITY and MIN_WRITE_CAPACITY define the DynamoDB target write capacity we need during and after the import respectively. (<em>Target</em> capacity is a key insight we learned early on. See details below why it’s ok not to even attempt to change capacity in some circumstances.)</li></ol><h3>You need a special InputStream for long-running S3 reads</h3><p>It’s easy to open an S3ObjectInputStream to a file in S3. But AWS S3 API reads are HTTP requests and those time out if you wait too long to complete a read, typically a few minutes. All our data science import jobs have long running reads.</p><p>So just opening an S3 file using the provided Java InputStream implementation is impractical, because all these files are large and reads for successive byte blocks could be infrequent while we wait for DynamoDB write capacity to spin up or other blocking DynamoDB operations. So you have to either read the whole file at once (impractical because of limited memory) or take a streaming approach.</p><p>We wrote a custom InputStream that reads sequential smaller byte blocks from S3, typically 1Mb. The implementation uses the underlying S3ObjectInputStream to access data in S3 without the need to keep a connection open for more than about 100ms. We read bytes from the S3 file, convert to lines, deserialize each JSON structure, convert to DynamoDB Items, and write the results to DynamoDB. This sounds complicated, but it’s a pretty straightforward data pipeline. We made it nicely threaded and non-blocking, because why not.</p><p>See the source for S3InputStream at the end of this story. (And if anyone can point us to a suitable abstract class that provides the common boilerplate, please let us know and we’ll fix it with pleaure. We should probably have made our own come to think of it.)</p><h3>Should I use DynamoDBMapper?</h3><p>No. Well maybe yes, if you can guarantee low volume and fixed columns. But definitely no for all other cases. DynamoDBMapper is positioned as a higher level interface for DynamoDB CRUD. It uses Java class annotations. Here are its pros and cons.</p><p>The DynamoDBMapper API will take a JavaIterable of instances of classes annotated with @DynamoDBDocument, and write micro-batches of 25 using the low level DynamoDB API. It handles capacity-related retries via a callback where you provide the retry interval, probably using Fibonacci back-off.</p><p>You might think that by passing an Iterable we’d be safe assuming the micro-batches were streaming. <strong>Unfortunately, </strong><strong>DynamoDBMapper dereferences the entire</strong><strong>Iterable to create all the micro-batches before writing the first one. </strong>So for data of any significant size, you’ll find your whole Iterable gets converted to an in-memoryList and you may run out of memory.</p><p>Since the @DynamoDBDocument annotation is applied to concrete Java classes, the bean properties are mapped to DynamoDB columns. You can map properties to columns with different names with optional binding names in the annotation, but you can’t (easily) use dynamic columns.</p><h3>Modulating DynamoDB write capacity effectively</h3><p>Out initial attempts at implementing effective scaling didn’t work because capacity control in Airflow our job scheduler, extrinsic to the importer. As it turns out, we were way too focused on separation of concerns. The issues we ran into were mainly concerned with synchronizing the timing of operations between Airflow and the importer. We could not guarantee proper synchronization between Airflow and the import tasks, so we did not always complete the corresponding capacity decreases, leading to AWS billing surprises. So we put the write capacity provisioning control in the importer itself. It works without issue now.</p><p>We have a pair of methods increaseWriteCapacity() and decreaseWriteCapacity() defined as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0933bedc2a6a1a0e672083a299c7f889/href">https://medium.com/media/0933bedc2a6a1a0e672083a299c7f889/href</a></iframe><p>It’s important that the common method, setWriteCapacity() must eliminate spurious requests to change capacity as follows</p><ol><li>If the capacity is already at least high (or low) enough, then ignore the request because honoring it will have the opposite effect.</li><li>If the capacity is already equal to the requested capacity, ignore that too, because same-value provisioning API requests throw an exception in the SDK. However, if you’re just changing the <em>write</em> capacity, for example, you have to copy the current <em>read</em> capacity and pass that in the request. You have to set both at the same time.</li></ol><p>Here’s the code for this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc8c1aceaeb3a1e389879d328c9d4263/href">https://medium.com/media/dc8c1aceaeb3a1e389879d328c9d4263/href</a></iframe><p>We use the provided predicate passed to setWriteCapacity() to filter out requests that would either fail or inadvertently change capacity in the opposite direction.</p><h3>Simple and efficient multithreading in the importer</h3><p>As we already noted, the importer 100% I/O bound: it’s always waiting for reads of byte blocks from S3 or writes of items to DynamoDB to complete.</p><p>Rather than add global throttling in the importer across threads, we did sometime much simpler. We matched the DynamoDB write capacity to the observed total throughput in the importer for a single thread, taking the speed we can read S3 into consideration. Then all we had to do was configure the number of threads to achieve optimum throughput.</p><p>We create a thread pool, Executors.newFixedThreadPool(IMPORT_THREADS), and schedule CompletableFutures in this bounded pool with</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c31ff00ad2428b5644ced6d52d4554c8/href">https://medium.com/media/c31ff00ad2428b5644ced6d52d4554c8/href</a></iframe><p>Then create all the CompletableFutures, one for each file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c46bc5910c8594b90752ac39b725ea4c/href">https://medium.com/media/c46bc5910c8594b90752ac39b725ea4c/href</a></iframe><p>Finally, wait for them all to finish and log a nice celebration with</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da5ad1289ac388c3c2a9f665a97668b/href">https://medium.com/media/0da5ad1289ac388c3c2a9f665a97668b/href</a></iframe><p>Apologies if this was old hat to you, but we found too many examples of threading made unnecessarily complex because they didn’t take advantage of some of the excellent support already available to you in the standard Java libraries.</p><p>We typically provision 10,000+ WCUs for a single DynamoDB table and match that to 4 threads in the importer consuming and converting the data in S3 files.</p><h3>In summary</h3><p>The Data Science team at Rue La La turned to DynamoDB for storing medium to large data backing APIs.</p><p>Bulk loading data into DynamoDB must be done with care. So must reading large files from S3. So must matching throughput and parallelism in the importer. The provided tools have some issues that required work-arounds.</p><p>We hope you have been able to see how we approached each of these issues. If you have questions, or have a better way to accomplish the same thing please let us know.</p><h3>Appendix A: Source for our bulletproof S3InputStream</h3><p>If you’re reading large S3 files, then this Java class is for you. We don’t time out and we don’t fill up memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e12586470980a6aa1b3e9f625a92ff18/href">https://medium.com/media/e12586470980a6aa1b3e9f625a92ff18/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1469af578e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/how-rue-la-la-bulk-loads-into-dynamodb-ad1469af578e">How Rue La La Bulk Loads into DynamoDB</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rich Data Science APIs at Rue La La]]></title>
            <link>https://medium.com/rue-la-la-tech/rich-data-science-apis-at-rue-la-la-3d44bd23b529?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d44bd23b529</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Fri, 23 Mar 2018 16:37:05 GMT</pubDate>
            <atom:updated>2018-03-25T15:14:22.803Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we store and retrieve large volume Data Science data at Rue La La</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*G_2VBAk6GIFKATorelw07g.png" /><figcaption>How to DynamoDB for rich API data?</figcaption></figure><h3>The main story</h3><p>This article is about one aspect of a larger project we did at Rue La La. See the following for the big picture.</p><p><a href="https://medium.com/rue-la-la-tech/large-scale-data-science-apis-at-rue-la-la-9226ecffed04">Large-Scale Data Science APIs at Rue La La - Stephen Harrison - Medium</a></p><h3>The upshot</h3><p>We call DynamoDB directly from API Gateway to support our data science APIs without an interstitial Lambda. Using a Lambda to map API requests and responses to a database has undesirable performance characteristics in some cases relating to the <a href="https://read.acloud.guru/cold-starting-lambdas-2c663055589e">cold start problem</a>.</p><p>DynamoDB’s storage format exposes type information and that wasn’t suitable to pass on to applications consuming the Data Science API. The API Gateway response mapping is an unforgiving place to parse out this type information, so we end up storing JSON blobs and returning those directly. It’s brilliantly fast but a bit quirky.</p><p>We store sparse matrices of 20,000,000,000+ elements in DynamoDB for recommendation APIs. We’ll show you our solution.</p><h3>Requests and responses</h3><p>You use <a href="http://velocity.apache.org/">Velocity</a> templates to map requests and responses in API Gateway, unlikely to be anyone’s favorite programming environment. So you have to write Velocity code to parse out the exposed DynamoDB type information if you go that route.</p><p>The template context <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html">contains</a> many details of the request, so you can use values from that context when you construct the mapped request and response. In addition to the context, a few simple utility functions are provided to manipulate JSON, URL, and base64 encodings.</p><p>Here’s a sample template to map a request in API Gateway to the DynamoDB GetItem REST endpoint. The URL endpoint in question is /v1/members/{member_id}/brands, which returns the list of brands we recommend for a member with a summary of the recommended styles in each. You can see how we get the name of the DynamoDB table from API Gateway stage variables and member_id from the request parameters, a path component in this case. member_id is defined as the HASH attribute on the DynamoDB table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41c7f141d19c14d3a6f703d29fd9a5c5/href">https://medium.com/media/41c7f141d19c14d3a6f703d29fd9a5c5/href</a></iframe><p>The table name is maintained in a stage variable rather than being hard-coded. It might be overkill, but the thinking here is that it allows us to switch it out in an emergency more easily. We’d be able to do that without redeploying, just updating the API Gateway configuration via the console or AWS CLI. We’ve never had to do that, but good to know.</p><p>The response mapping has to do a couple of things with the reply from DynamoDB. Disappointingly, DynamoDB does not return an HTTP 4xx status when an item is not found: it always returns a HTTP 200 with an empty response instead. So we have to check whether the response is empty and return valid JSON string []. Furthermore, API Gateway does not let you map HTTP status codes dynamically either. You’ll see the Velocity for this below. Fair warning: it’s pretty nasty.</p><h3>Storage layout</h3><p>The data we want to store looks something like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b3802934de73bbf7de631de627bbcd8/href">https://medium.com/media/8b3802934de73bbf7de631de627bbcd8/href</a></iframe><p>It’s a list of brand details: A member’s affinity to the brand with sample styles in that brand so we can display them on the site or mobile application.</p><p>However, you can’t store it that compactly in DynamoDB without some trickery. First, let’s see how DynamoDB stores non-trivial document structure. &quot;L&quot; for lists, &quot;N&quot; for numbers, &quot;S&quot; for strings, and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34cc386d90cc6821a631b426fae511d4/href">https://medium.com/media/34cc386d90cc6821a631b426fae511d4/href</a></iframe><p>You would need some significant <a href="http://jsonpath.com/">JSONPath</a> tomfoolery to extract just the list of styles we want, in this case[&quot;100123&quot;,&quot;100635&quot;,&quot;100845&quot;]. It’s possible, just a bit hard to get right and maintain.</p><p>Instead, let’s take advantage of the fact we always return the same brand data and overview styles intact without manipulation. At least in limited windows. So we store that whole structure as a JSON quoted string, and just unescape it in the API Gateway response mapping template on the way out. That means the DynamoDB Item for the above looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d385ffe256829804355115211896e5a0/href">https://medium.com/media/d385ffe256829804355115211896e5a0/href</a></iframe><p>Now we can reference the brand affinity string from the DynamoDB Item with the JSONPath$.Item.brands.S using the provided utility $input.json() in the API Gateway response mapping and parse the escaped JSON with $util.parseJson().</p><p>This is how we currently do it in production. We feel the consistent speed of the direct integration outweighs the inscrutability of the resulting Velocity templates. Just look at this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cbb62d7f5683db1d66d66afb8b2fcbc/href">https://medium.com/media/6cbb62d7f5683db1d66d66afb8b2fcbc/href</a></iframe><p>So while it’s a bit of a hack, we have to admit it’s compact, fast, and above all it works. The only JSON processing we’re doing is via a fixed JSONPath in the API Gateway response mapping, so there’s very little manipulation involved.</p><blockquote>API Gateway request and response mapping has many idiosyncrasies, but not working is not one of them.</blockquote><h3>Complex data</h3><p>The example above returns an overview of brands we think a given member likes at a point in time. This synopsis contains just a few styles for each brand and is used to render graphics in the mobile and web applications. It’s small enough we can return all the top brands and their summary styles in one API call.</p><p>There’s a companion API call, which returns <em>all</em> the styles for a given member and brand. There are often 1,000’s of styles on sale at any one time for a given brand, so returning all the brands and all their styles at once just to pull out the brands you want is impractical. The URL endpoint for the detail call is /v1/members/{member_id}/brands/{brand_id}.</p><h4>The obvious approach was too expensive</h4><p>Our original design for this API endpoint wrote items to DynamoDB with a HASH of member_id and RANGE of brand_id.</p><p>These tables had 100,000,000+ items, one for each member_id/brand_id combination. The lookup endpoint was still very fast. But while we can technically import that many rows daily, we were running into significant throttling bottlenecks waiting for DynamoDB write capacity to scale up that high. In addition, 100,000,000 writes a day is &gt; $1,000 a month. We have dozens of APIs, so that approach raised some eyebrows.</p><h4>A sparse matrix</h4><p>Instead, we switched our representation to make the brand_ids separate <em>columns</em> in each member’s DynamoDB Item, in effect creating a sparse matrix of members and brands.</p><p>We were concerned that having 10,000’s columns in a DynamoDB table—a vast majority of which were empty for each of millions of rows—would create some performance issues.</p><p>But our fears were completely unfounded. It works very well. Let’s take a look at how we organize the data in DynamoDB Items and how we modify the API Gateway response mapping template to pull this off.</p><h4>Storing sparse data</h4><p>We store the member_id as before, but now with columns for each brand_id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3521171ab1312fd636cc46d1b7838b51/href">https://medium.com/media/3521171ab1312fd636cc46d1b7838b51/href</a></iframe><p>We’re still storing the styles for a member’s brand as a JSON blob for fast retrieval and to simplify the response mapping.</p><h4>Enhanced request mapping</h4><p>Finally, we enhanced the request template in API Gateway to pass a <em>projection</em> of the brand column in the GetItem DynamoDB request so the return result from DynamoDB is limited to the styles for a specific brand. This means we’re not transferring more data than we need from DynamoDB to the API Gateway. In addition, we don’t have to do anything fancy in the response mapping to filter brands. These mapping templates are already plenty complex enough, so that’s a welcome simplification.</p><p>Here’s the updated request mapping template. The response temple remains essentially the same ugly mess as before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e32d19c2fb1f17b90ca02e794f9d0c33/href">https://medium.com/media/e32d19c2fb1f17b90ca02e794f9d0c33/href</a></iframe><p>We could not measure any significant performance penalty making this more complex call to DynamoDB, but we saw dramatic cost improvements because our import jobs were considerably less resource hungry.</p><h3>In summary</h3><p>We can use DynamoDB to store a 20,000,000,000+ element sparse matrix. We can still use the API Gateway request and response mapping templates to retrieve the data and so we can still omit the Lambda between API Gateway and DynamoDB.</p><p>Did we miss something? Is there a better way? Please let us know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d44bd23b529" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/rich-data-science-apis-at-rue-la-la-3d44bd23b529">Rich Data Science APIs at Rue La La</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large-Scale Data Science APIs at Rue La La]]></title>
            <link>https://medium.com/rue-la-la-tech/large-scale-data-science-apis-at-rue-la-la-9226ecffed04?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/9226ecffed04</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 20:58:44 GMT</pubDate>
            <atom:updated>2018-03-25T15:31:57.389Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cloud native and web scale</h4><p>The Data Science team at Rue La La writes code that delivers a variety of recommendations and other data about our Members. We mostly run Apache Spark Scala code on the excellent Databricks platform and write results to AWS S3 buckets. So far, so good. Nothing out of the ordinary. But the best architecture for the last step — making large volumes of data available via an API to our web and mobile platforms—was not obvious to us. There are options: Let’s explore.</p><p>This story looks at the choices we considered, explains what worked and what didn’t, and shows the final design in detail. The result is a set of large-scale APIs that have good performance with boundless scalability. It’s mostly about how we call DynamoDB directly from API Gateway to avoid Lambdas, and why that’s a good idea.</p><h3>Companion stories</h3><p>There are more detailed descriptions of a couple of interesting things we did in this project in the posts below.</p><ul><li><a href="https://medium.com/rue-la-la-tech/rich-data-science-apis-at-rue-la-la-3d44bd23b529">Rich Data Science APIs at Rue La La</a></li><li><a href="https://medium.com/rue-la-la-tech/how-rue-la-la-bulk-loads-into-dynamodb-ad1469af578e">How Rue La La Bulk Loads into DynamoDB</a></li></ul><h3>The upshot</h3><p>At the highest level, we ended up with this architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*aLeG3cJHmKP4zQlDToTHYg.png" /><figcaption>The Big Picture</figcaption></figure><ul><li>DynamoDB works well for storing 100,000,000+ items of data that can change frequently.</li><li>AWS API Gateway works well with a direct integration to DynamoDB, albeit with a couple of idiosyncrasies.</li><li>Custom importers are required to load data into DynamoDB at scale and AWS Batch proves an excellent way to run this code.</li><li>AWS CloudFormation served significantly better than the alternatives for bringing up repeatable stacks and CI/CD pipelines.</li></ul><h3>Background</h3><p>Q3 2017 saw the migration of Rue La La’s production software from our data center to Amazon Web Services. This first phase focused on discovery of legacy systems and migrating those systems largely intact. We want to continue this path, but in a more cloud-native direction—we’re not afraid to push the envelope in this next stage. Cloud native for us means as far away as practical from running a commercial application server, on hardware we own, in a data center colocation we rent. There may be better definitions, but if you’re doing any of those things, you’re probably not cloud native.</p><p>For this project we started with the following:</p><ul><li>The data is already available as output from our various data science jobs. We run Apache Spark Scala in Databricks and write data to large S3 files, each line of which is in the same JSON format.</li><li>10M+ items of API data are updated at least once a day from data science code running in Databricks <a href="https://docs.databricks.com/user-guide/notebooks/index.html">notebooks</a>.</li></ul><p>We have many Data Science API endpoints delivering different kinds of data about Rue La La <em>Members</em>, our flash-sale <em>Boutiques</em>, and products (or <em>styles</em>).</p><p>The example we’ll look at here is the API to deliver the <em>brands</em> that have a strong affinity to a given Member. We calculate this affinity using <a href="https://en.wikipedia.org/wiki/Collaborative_filtering">Collaborative Filtering</a> and other techniques.</p><h3>Requirements</h3><ul><li>Our web and mobile applications need to look up and render personalized Boutiques, brands, and styles for each Member when they log in. This is effectively a blocking call since although we can smooth out rendering the page while we’re retrieving the data, the recommendation section of the page is only actionable after they’re displayed.</li><li>The format of the data returned by the Data Science APIs may be different then the data written by Apache Spark. And in turn the data required to render pages or mobile app screens may be different again.</li><li>The API must be RESTful, secure enough, fast enough (average API call &lt; 50ms, 95% &lt; 150ms), and highly available (&gt; 99.99%).</li></ul><h3>Options for storing data</h3><p>We’ll meander around the architecture and technology, qualifying or discounting things as we go. This is probably not the exact path we took, but the result is the same. We’re just highlighting choices, failures, and reasoning.</p><h4>API reads directly from S3</h4><p>The data is already in Amazon’s S3. Can we deliver them from there via an API directly? We don’t have time to open a file on S3 and skip to the records we need. But perhaps we can read one of millions of small files with just the data we need. So what’s the quickest we can open, read, and unmarshal a file in S3 that contains a single JSON object? It’s about twice our total budget—300ms—in the best case. The other thing to note is that while S3 claims 11 9’s <em>durability</em>, it’s “designed for” 4 9’s <em>availability</em>. Practically speaking, we have witnessed several transient outages that have rendered otherwise highly available sites like GitHub unreachable, reportedly in part due to S3 outages. We did not feel it prudent to base our architecture on S3 availability.</p><p>We could do a few things to make this approach faster, including configuring API Gateway to cache results. But the services that deliver web pages and mobile data are already doing their own caching, and cascading caches always muddy the end-to-end TTL picture without careful initial implementation and strict control over maintaining TTL values. In any case, caching doesn’t help with the initial load from S3 and that takes too long.</p><h4>Store the data in a database</h4><p>Not such a radical idea. Amazon Web Services gives us a number of excellent options ranging from running our own database on an EC2 instance through managed services like AWS RDS running Oracle, PostgreSQL, and others, including running a managed NoSQL database, DynamoDB. We already have JSON document structure from the output of the data science Databricks jobs. So options like MongoDB and DynamoDB look appealing. We went with the AWS managed service, DynamoDB, and are pretty happy with the choice.</p><p>There are things you can’t do in DynamoDB that might be surprising at first, like quickly truncate a table to delete all the items. But you can always drop the table and recreate it. In practice we found that taking advantage of the feature that lets you set an expiration TTL on each DynamoDB item works well. That, combined with the fact that the common case completely replaces personalization data for a Member each day (and updates the TTL) avoids the need for explicit culling of old items. And no, you can’t postdate the expiration to delete items for DynamoDB immediately. It happens on a schedule we don’t control. Also, since updating the expiration TTL would cost a write anyway, you can’t come out ahead.</p><p>A note on updating existing DynamoDB items. The most efficient way to load data is to use thebatchWriteItem API call. But that bulk call can’t <em>update</em> existing items, only replace them. And then can only write small batches of 25 items at a time.</p><h3>Options for accessing data</h3><p>Ten years ago there’d be no discussion here other than which application server we could get good licensing terms for. It would quickly converge on something like SOAP endpoints in a JBoss cluster, with hardware load balancers, and so on.</p><p>But modern APIs are RESTful, JSON has replaced XML everywhere, and serverless is a thing now. By our definition above, this feels cloud native. So let’s go with that.</p><h4>We tried AWS Lambda, but…</h4><p>We originally tried using AWS Lambda with API Gateway as the access method for DynamoDB data. Almost all the example code shows how to do it this way. We implemented the Lambda using AWS Lab’s <a href="https://github.com/awslabs/aws-serverless-java-container">Serverless Java Container</a> runtime, the <a href="http://sparkjava.com/">Spark Java</a> variant (confusingly, a different Spark, not Apache Spark) because we really liked its brevity. This worked very well indeed. It had low end-to-end latency because the two key integrations in the pipeline—<em>API Gateway → AWS Lambda</em> and <em>AWS Lambda → DynamoDB</em>—were both typically ≪10ms each, for a total latency of about 30–40ms.</p><p>There was just one issue with this design and that turned into a deal-breaker: the “<a href="https://blog.newrelic.com/2017/01/11/aws-lambda-cold-start-optimization/">cold start problem</a>.” This had the effect of delivering API data fast <em>almost</em> all the time, but when it was slow it was 1.5 seconds or more.</p><p>In short, Lambdas run in reusable Docker containers. There are two cases where a supporting container can not be reused to execute a Lambda: scaling out requires new containers; and containers appear to be recycled every 10–15 minutes in any case. There are techniques for <a href="https://read.acloud.guru/how-to-keep-your-lambda-functions-warm-9d7e1aa6e2f0">keeping Lambdas warm</a> that send heartbeat requests, but this does not address the scale-out cold start. And if you think about it, there’s nothing to say the legitimate request isn’t the one that triggers the scaling out of a new Lambda instance, and thus be the one that gets the high latency.</p><p>In early testing with Lambdas we ran into cold start frequently enough that we not only noticed it, but could often predict it. We believe that would have resulted in a significant degradation in some Rue La La Members’ site experience. That’s a deal-breaker.</p><h4>Direct API Gateway integration</h4><p>We’re already using API Gateway to integrate with the Lambda. So why not try a <a href="https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-as-a-proxy-for-dynamodb/">direct integration with DynamoDB</a>?</p><p>This is the solution we ended up using. It’s a bit quirky, but really interesting. See this companion story about it.</p><p><a href="https://medium.com/rue-la-la-tech/rich-data-science-apis-at-rue-la-la-3d44bd23b529">Rich Data Science APIs at Rue La La</a></p><h3>Importing data</h3><p>Data is written to S3 buckets by Databricks jobs running Apache Spark Scala. These are files of JSON data partitioned into 100Mb+. There are other, more compact, storage formats like <a href="https://en.wikipedia.org/wiki/Apache_Parquet">Apache Parquet</a> with <a href="https://en.wikipedia.org/wiki/Snappy_(compression)">Snappy</a> compression, but they’re harder to read in a standalone program. We also considered and tried the <a href="https://github.com/awslabs/emr-dynamodb-connector">AWS EMR Connection for DynamoDB</a>, but found it baked in too much knowledge about its environment, did not support the version of Apache Spark we’re using, and was fragile even when we got it working. Anecdotally, AWS’s Elastic Map Reduce (EMR) does not appear to be receiving regular maintenance updates and EMR Data Pipeline can be difficult to get right and operationalize.</p><p>In our architecture, an AWS Lambda receives S3 events for each new file and creates an AWS Batch job for the ones it cares about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KtMxMf2TyML-7kvWTtnulw.png" /><figcaption>Lambda creates AWS Batch Jobs from S3 notifications</figcaption></figure><p>The batch jobs get queued and are allocated to existing AWS Batch clusters as resources become available. We configure clusters large enough to handle all import jobs simultaneously for a given environment, but that never happens in practice because data science jobs are naturally staggered. But good to know we can rerun everything at the same time in an emergency. Docker containers in AWS Batch start loading data from S3 to DynamoDB as soon there is capacity in the cluster. AWS Batch compute clusters are simply ECS clusters managed by AWS Batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*nwIQYtEtinEl-VY9DSUggA.png" /><figcaption>AWS Batch jobs load JSON data into DynamoDB</figcaption></figure><p>We iterated the importer architecture a couple of times before we converged on a design we liked as follows:</p><ul><li>The importer Docker image maps raw JSON from data science Databricks output into DynamoDB items. We are prepared to do some work here to make delivering the data from the API streamlined, specifically in the right format. This amounts to at least some field-name mapping and usually some small amount of data filtering and restructuring.</li><li>The Docker images run in 1Gb memory and only 1 CPU since they are completely I/O bound either waiting for data from S3 or write capacity on DynamoDB. This matches the CPU/memory ratio of many EC2 instance sizes available for running an AWS Batch cluster, including those we get by default with the special AWS Batch instance type optimal.</li><li>Scaling DynamoDB write capacity in the importer immediately before and after the import.</li><li>A custom InputStream for S3 files that does not make long-duration API calls to the S3 API to retrieve data. Instead, it implements the standard InputStream interface by performing lots of smaller reads on demand. See the appendix of this companion story for details.</li></ul><p><a href="https://medium.com/rue-la-la-tech/how-rue-la-la-bulk-loads-into-dynamodb-ad1469af578e">How Rue La La Bulk Loads into DynamoDB</a></p><h3>Current state</h3><p>We have a number of Data Science APIs in production and we’re adding to them regularly as new initiatives at Rue leverage the growing Data Science team. The pattern we established has proven very repeatable.</p><p>From a non-functional perspective, we’re happy with API security using built-in API keys. Consistently high throughput and low latency match requirements with room to spare. API Gateway’s request and response mapping is a little finicky but very fast once it’s correct. The ability to express a projection in DynamoDB requests means we can store sparse matrices of, for example, Member/brand affinity without loss of performance.</p><h4>Production performance</h4><p>Performance of API endpoints hovers around 18ms for simple cases, and up to 26ms for more complex DynamoDB projections. We assume HTTPS connection caching on the client if we’re to see client-side performance close to this. We see no issues handling thousands of concurrent requests, although read provisioning must be set in advance or allowed to auto-scale by ramping up load over a period of minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KdyAtRnbsbdqVUgeNcBhw.png" /><figcaption>A healthy Datadog API dashboard</figcaption></figure><h4>Non-functional requirements</h4><p>We looked at available options for securing access to our APIs. API Gateway endpoints in AWS are inherently public. We played with defining <a href="https://aws.amazon.com/cognito/">Cognito</a> users for authorizing API access. But that was cumbersome to administer and we did not appreciate the extra 10ms round-trip. Issuing client certificates would have been very secure, but again hard to administer.</p><p>We ended up using API Keys, which have these nice features:</p><ul><li>It’s simple to administer, including revoking access without a deployment.</li><li>It’s secure enough (keys are long, random strings).</li><li>Keys can be shared easily between related API Gateways in each QA and production environment via AWS API Gateway Usage Plans.</li><li>The REST API security is defined in Swagger to exactly match the HTTP header that API Gateway expects, x-api-key.</li><li>They are handled without measurable increased latency, we assume because valid keys are cached at the API Gateway.</li></ul><h3>In summary</h3><p>Rue La La turned on detailed personalization for Members by writing data science jobs that include predicting a Member’s affinity to brands and categories. Data changes every day because we’re a flash-sale site and products are only on sale for a few days.</p><p>DynamoDB proved an excellent place to store this data: 10,000,000s of data points for Members, brands, and product categories changing every day.</p><p>We did not use an AWS Lambda to pull data from DynamoDB because we liked being able to integrate directly with API Gateway. We had to write a custom data importer that behaved predictably under load, where multithreading and failures were under tight control.</p><p>We like the result: It’s a repeatable pattern and pretty much trouble-free. Let us know your thoughts in the comments. What did we miss? How could it be better?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9226ecffed04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/large-scale-data-science-apis-at-rue-la-la-9226ecffed04">Large-Scale Data Science APIs at Rue La La</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android CI With AWS CodeBuild]]></title>
            <link>https://medium.com/rue-la-la-tech/android-ci-with-aws-codebuild-ba5ff7a7293b?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/ba5ff7a7293b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Michael Scott]]></dc:creator>
            <pubDate>Mon, 23 Oct 2017 13:16:59 GMT</pubDate>
            <atom:updated>2017-10-23T13:16:58.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*GkcgMWrXSBvly2OpHOwVoQ.jpeg" /></figure><h4>A journey from Jenkins, server-based CI to the cloud</h4><p>Since Google I/O in May 2017, I had been pining to get the chance to use Kotlin in our Android app. I played around a little with Kotlin in Android Studio 2.3 and had implemented some simple classes, but ultimately found that I needed to migrate our development to Android Studio 3.0 to take full advantage of the native Kotlin support it offered.</p><p><em>(Side note: Android Studio &lt; 3.0 has problems bundling Kotlin classes into the APK, see my experience </em><a href="https://stackoverflow.com/questions/45922778/kotlin-activity-not-included-in-apk"><em>here</em></a><em>).</em></p><p>This also necessitated an upgrade of Gradle to 4.1, alongside the upgrade of the Gradle plugin to 3.0.0. This version of the plugin enables the new Android APK packaging tool aapt2 by default:</p><p><a href="https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#aapt2">Migrate to Android Plugin for Gradle 3.0.0 | Android Studio</a></p><p>Unfortunately our continuous integration build server did not like aapt2, because it requires the GNU core library glibc 2.14 or greater (ours was at 2.12). So I ended up with build errors like this:</p><pre>* What went wrong:<br>Execution failed for task &#39;:app:mergeDevDebugResources&#39;.<br>&gt; /tmp/aapt2_7440736682477326645/libc++.so: /lib64/libc.so.6: version `GLIBC_2.14&#39; not found (required by /tmp/aapt2_7440736682477326645/libc++.so)</pre><p>Although possible to fall back to aapt (ie disable aapt2), doing so would have missed the benefits of aapt2 and only be a stopgap solution. So I needed a way to get to our CI builds working again. Upgrading the build server itself would be time consuming and difficult; provisioning a new hardware build server was unlikely as we were migrating all our in-house server operations to the cloud.</p><h3>AWS CI Tools</h3><p>After briefly considering other non-hosted CI solutions such Travis and CircleCI, an architect colleague suggested taking a look at a couple of new tools provided by Amazon AWS: CodePipeline and CodeBuild.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*yMV4-DPjoq2nwUJOFNei1Q.png" /></figure><p>The beauty of this was that our company was already moving most of our server operations to the AWS cloud, so taking advantage of these tools would not require an upfront subscription, and in fact we would only pay for the minutes actually spent building the code.</p><p>So I created a CodePipeline project, specifying a Source step to hook up to our GitHub repository (this step would poll the repository for changes), and a Build step to execute the build of the source. There are additional steps for deploy and test, but for my purposes a source and build step were all I needed.</p><h3>AWS CodeBuild</h3><p>Although CodePipeline can support different build tools, I was interested in CodeBuild, which is a fully managed build service using docker containers to provide the necessary for build environment. They even offered Android container images, ready configured with the necessary SDK, build tools and gradle to support building an APK.</p><p>CodeBuild provides direct integration with GitHub, where our source code lives, and can store its built artifacts in an S3 bucket for later downloading.</p><p>For my initial attempt at a CodeBuild project for Android, I used an AWS-managed image based on Ubuntu, supporting Android/Java8 provided by Amazon themselves. After specifying the project source provider as GitHub with the necessary credentials to our repository, and my gradle build command, I was ready to go! Manually kicking off a build from the CodeBuild project launched the container, downloaded the source from GitHub, and ran my build commands.</p><p>All looked good… but this initial build failed because the AWS container was only configured with Android SDK and build tools up to Android 25, not Android 26 that I needed. It also only had gradle 2.14 pre-installed, whereas I needed at least 4.1 for the newest Android Studio build system.</p><p>Luckily AWS CodeBuild allows you to specify a custom image for a project, and thus began the long process of learning how to create my own docker image.</p><h4>Creating a Custom Docker Image</h4><p>Docker images are not generally created from scratch, they just extend other images. This greatly simplifies the process of creating new and more specialized images.</p><p>The Dockerfile used to create an image specifies FROM which image it extends, and I knew the Amazon AWS standard image was <em>almost</em> good enough, so it seemed a reasonable starting point:</p><pre>FROM aws/codebuild/android-8:latest</pre><p>I then just provided a series of commands to RUN which would install the additional versions of Gradle and the Android build tools to support my project build:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e83d1b850c0ab5265d5b367185e2b687/href">https://medium.com/media/e83d1b850c0ab5265d5b367185e2b687/href</a></iframe><p>To create the docker image with our updated SDK and build tools, we use the docker build command to execute the commands in the Dockerfile:</p><pre>docker build -t &lt;repository:tag&gt; &lt;path&gt;</pre><p>Repository is the name &amp; path where our image will be stored in a registry; tag is an optional identifier for this particular build, such as “version1.0” or “latest”, and path is the location of the Dockerfile. The image build process can take a little while the first time around because the FROM image has to be built from scratch; subsequent rebuilds are much quicker because the image is cached locally.</p><p>Docker images can be shared through a <em>registry, </em>the most popular of which is <a href="http://www.dockerhub.com/">dockerhub</a>. Use docker push command to store an image in a registry:</p><pre>docker push ruelala/android/build:latest</pre><p>Having done this, I was able to reference my new Android-26-enabled docker image from my CodeBuild project using a custom image id.</p><h4>CodeBuild Build Spec</h4><p>CodeBuild allows you to specify the commands to execute within a container either directly in the CodeBuild project configuration, or more usefully, in a build specification file buildspec.yml which CodeBuild will look for in the root directory of the source tree. The latter is the ideal approach, since the build steps are versioned and freely available to anyone with the access to the repository. That was the approach I took, creating a buildspec.yml and adding it to the root of our source tree in GitHub.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/487e9b4e0910d60b778446c3e9a3b384/href">https://medium.com/media/487e9b4e0910d60b778446c3e9a3b384/href</a></iframe><p>Pretty simple build steps — create the debug build, run the unit tests and then upload the built APK to our beta-test provider Crashlytics. The artifacts section describes the path where the output (our built APK) can be found for upload to S3</p><p>With the custom Docker image and buildspec in place, my CodeBuild project was ready to roll. CodePipeline recognized new pushes, and was executing CodeBuild runs as required:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*mq8hUKM7Jd_VQArGqxcaUg.png" /></figure><p>With a basic working CI Android build system, my attention turned to notifications. I wanted build notifications to be posted to a our android-build-notifications slack channel the way our old Jenkins build notifications were. That will be the subject of the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba5ff7a7293b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/android-ci-with-aws-codebuild-ba5ff7a7293b">Android CI With AWS CodeBuild</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technology != Architecture]]></title>
            <link>https://medium.com/rue-la-la-tech/technology-architecture-d7ca2e539fa8?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7ca2e539fa8</guid>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Fri, 20 Oct 2017 19:00:26 GMT</pubDate>
            <atom:updated>2017-10-18T14:14:58.101Z</atom:updated>
            <content:encoded><![CDATA[<h4>“Spring” is not a valid answer to “What’s your architecture?”</h4><p>Like many, I glom on to specific technologies, usually something new and shiny. The world just keeps giving me more and more awesome technology squirrels to look at. I’ve gotten pretty adept at fabricating the necessary architecture drivers to give me the desired technology implementation. This is so wrong. Now, some of the architecture drivers actually make complete sense. And all of them are recognizable and so they’re hard to refute, at least completely.</p><p>There are several things in play here, including “shiny new.” Docker is a great example. This is a solution to a specific problem and a really amazing one at that. But Docker should not even show up directly in an architecture diagram, while many of the things it addresses definitely should. I’m not even sure containers show up, because that tips your hand too much. What about micro services? Not sure either because isn’t that mostly about an implementation strategy?… This is getting at least confusing and probably annoying.</p><p>So let’s take a step back and think about what our architectures address, how we communicate them, and how we design and implement from them. Architectures show</p><ul><li>major moving parts and how they interact;</li><li>the smaller moving parts and how they can work independently;</li><li>how important nonfunctional requirements like security and scalability are implemented;</li><li>how external integrations are implemented.</li></ul><p>Really not much more. We should be able to validate the architecture with all our stakeholders, including</p><ul><li>Network Operations, who needs to confirm connectivity and security;</li><li>Developers, who need to create designs and implementations that render the architecture;</li><li>DevOps, who must be able to deploy and maintain the architecture;</li><li>QA, who needs easy access to internal components;</li><li>DBAs, who need to verify database access and design.</li></ul><p>We can see that things like Spring, Docker and Amazon Web Services are not in the mix at this point. Release engineering and DevOps can greatly influence the specific choices here. In fact, they may own them. They may also declare that an architecture does not make the grade for repeatable deployments, and so on.</p><p>At Rue, we live with legacy codebases from many turning points in Rue’s history and at least as many ways of doing similar things. An abundance of Oracle stored procedures is not the only choice now. Neither is generating a database schema that is compromised by the idiosyncrasies of a specific ORM. Our incremental approach to improving Rue’s architecture guarantees we will continue to run a mix of languages and architectural philosophies for some appreciable time to come. Many of these legacy components have implementation quirks as well as overarching architecture limitations. Our first inclination might be to “squirrel!” a specific technical deficiency, like logging, in a single component instead of fixing monitoring and maintainability for the whole system once and for all.</p><p>But what if we could also define architectures that had the feel of shiny new? Then we’d all be happy. Our CTO, Anthony, has specifically set us that challenge. Thinking about things that way, we can quickly start to identify opportunities.</p><ul><li>An architecture defined in terms of independent, composable components has some pretty remarkable properties like scalability. Wouldn’t it be shiny new to have a software system where the number of concurrent users is not a concern?</li><li>A data pipeline architecture defines components where the output of one component can directly become the input of the next, and so on. Our analytics platform is architected this way, and that lets us configure and specialize much more easily. I’m quite sure there’s shiny new in that too.</li><li>An architecture that emphasizes services rather than specific implementations allows us to replace pieces as we need without ruining anyone’s day. When we replace our creaky Order Management System, for example, we will make sure we capture core services first and direct traffic to that abstraction. Being able to relate parts of something as fundamental to Rue’s business as OMS without stopping the world will delight the business.</li></ul><p>There’s absolutely nothing new at all here in terms of patterns. It’s just a redoubled determination to keep things simple. Then the thrill comes from creating something that over-delivers business value just from being able to respond with “yep, we can do that.”</p><p>In this emerging architecture, we’ll be explicitly reaching out to collaborate in new ways with</p><ul><li>NetOps to leverage solutions that abstract away the distinctions between on-premise and PaaS;</li><li>DevOps on continuous delivery of independent components;</li><li>QA on making downstream environments indistinguishable from production;</li><li>Development on designs and implementations that make all this possible;</li><li>DBAs to create databases and schemas that match the business first, our ORMs second;</li><li>Business Owners to push audacious nonfunctional requirements.</li></ul><p>Let that be our shiny new.</p><p><em>Originally published at </em><a href="https://ruetech.io/2016/02/11/technology-architecture/"><em>ruetech.io</em></a><em> on February 11, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ca2e539fa8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/technology-architecture-d7ca2e539fa8">Technology != Architecture</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Functional in Java]]></title>
            <link>https://medium.com/rue-la-la-tech/how-to-functional-in-java-90d9e67289f6?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/90d9e67289f6</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Fri, 20 Oct 2017 19:00:08 GMT</pubDate>
            <atom:updated>2017-10-18T14:20:37.499Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ll show you how to get started using Java 8’s functional programming features. When you’re done, you’ll be able to read and write Java code that looks like</p><pre>private static &lt;T&gt; Map&lt;T, Long&gt; occurrences(final Stream&lt;T&gt; in) {<br>    return in.collect(groupingBy(x -&gt; x, counting()));<br>}</pre><p>Many of us are using tried-and-trusted imperative C#, Java, Python, and so on. There’s nothing wrong with those languages, of course. Amazing code is developed at Rue every day using them. Until Scala or Haskell are mainstream at your company, can you meet those languages halfway? This blog looks at Java 8’s functional enhancements and suggests places you can start to incorporate them.</p><p>Scala took a different approach to Java. So while Scala still runs on the Java VM, it was designed to marry functional and object-oriented at its core, so it’s a new language altogether. Some feel (including the author) this can give Scala code a more polished appearance than the same code in Java, even after functional features have been layered on. We’ll see. Finished Scala is often startlingly beautiful to look at, meeting the obligation of “provably correct by inspection” more often than most languages.</p><p>Does Java’s functional upgrade instantly make your code beautiful and easy to read? Of course it doesn’t. Not without care, in any case. So what do we have to do? Where do we start?</p><p>As you’re learning how to include Java 8’s new functional features, you’re probably going to start at the method level. Let’s try an example. Suppose we want to count the number of times each element appears in a List&lt;T&gt;. We’ll keep a Map&lt;T, Long&gt; with keys for each unique element and values for the number of times it occurs.</p><pre>private static Map&lt;String, Long&gt; counts(final List&lt;String&gt; in) {<br>  return new HashMap&lt;String, Long&gt;() {<br>    {<br>      for (final String s : in) {<br>         final Long value = get(s);<br>         <br>         put(s, value == null ? 1L : value + 1);<br>      }<br>    }<br>  };<br>}</pre><p>If we’re being completely honest, it’s a bit lame. Digging around, we notice that Java 8’s Map interface includes a new method, getOrDefault(), which lets us remove an explicit conditional. We’ll also make it generic because we’re exceptionally good at this kind of thing.</p><pre>private static &lt;T&gt; Map&lt;T, Long&gt; counts(final List&lt;T&gt; in) {<br>  return new HashMap&lt;T, Long&gt;() {<br>    {<br>      for (final T e : in) {<br>        final Long value = getOrDefault(e, 0L);</pre><pre>        put(e, value + 1);<br>      }<br>    }<br>  };<br>}</pre><p>It’s <em>still</em> lame. What happened? Well the issue is that although we’re using some new Java 8 features, we didn’t <em>think</em> about our problem in a functional way. So rather than just translate something from the old way, let’s explore another Java 8 feature, Streams. We find java.util.stream.Collectors.groupingBy and it feels like we’re getting warm. A few imports later, and we land on</p><pre>private static &lt;T&gt; Map&lt;T, Long&gt; counts(final Stream&lt;T&gt; in) {<br>  return in.collect(groupingBy(x -&gt; x, counting()));<br>}</pre><p>Much better. It reads like English left to right, which a lot of functional code tends to do. You can say <em>identity</em> for functional idioms like x -&gt; x or even better the thing it’s the identity of, in this case <em>key</em>. Try saying it out loud: “take the stream and collect the counts of the groups of keys.” Here’s the method in a micro test harness. It times counting the frequency of random integers in a Stream.</p><pre>package com.ruelala;<br><br>import static java.util.stream.Collectors.counting;<br>import static java.util.stream.Collectors.groupingBy;<br><br>import java.util.Map;<br>import java.util.Random;<br>import java.util.stream.Stream;<br><br>public class HowToFunctionalInJava {<br>  private static final Random R = new Random();<br>  private static final int N = 1 &lt;&lt; 26;<br><br>  public static void main(final String[] args) {<br>    final Stream&lt;Integer&gt; randomInts = R.ints(N, 0, 1000).boxed();<br>    final long start = System.currentTimeMillis();<br>    final Map&lt;Integer, Long&gt; counts = counts(randomInts);<br>    final long elapsed = System.currentTimeMillis() - start;<br><br>    System.out.println(N + &quot; in &quot; + elapsed + &quot;ms&quot;);<br>    System.out.println(counts);<br>  }<br><br>  private static &lt;T&gt; Map&lt;T, Long&gt; counts(final Stream&lt;T&gt; in) {<br>    return in.collect(groupingBy(x -&gt; x, counting()));<br>  }<br>}</pre><p>On my Mac laptop, the output is</p><pre>67108864 in 2445ms<br>{0=67493, 1=67284, 2=67167, 3=66703, 4=67240, 5=67653, 6=66953, 7=66922, 8=67060...</pre><p>That’s the frequency of over 67 million integer values counted in less than 2.5s, or about 27 million a second. It seems to be good enough for now. We just dipped our toe in Java 8’s functional features by looking at how to manipulate collections. Future blogs will take this a lot further. Until then, what could you do differently with code you’re working on? Write and let me know.</p><p>Functional programming takes off when you write in a language that’s designed that way. So here’s what a sudoku-board validator looks like in Scala. I tried to make it beautiful, but I’m sure there’s room for improvement. Even if you don’t know Scala, I’ll challenge you to read and understand it. The gist, anyway. Small functions with good names help make it flow. We’re basically setting things up for the isValid function. And by the time we get there, it seems almost too easy.</p><p>Can you make it clearer, faster, or prettier?</p><pre>case class Index(r: Int, c: Int)<br><br>object SudokuValidator extends App {<br>  val valid = (1 to 9).toSet<br>  val indexes = (0 to 8).toSet<br><br>  def rowOf(r: Int) = indexes.map(Index(r, _))<br>  def columnOf(c: Int) = indexes.map(Index(_, c))<br>  def blockOf(b: Int) = indexes.map(i =&gt; Index((b / 3) * 3 + i / 3, (b % 3) * 3 + i % 3))<br><br>  val allGroups = indexes.map(rowOf) ++ indexes.map(columnOf) ++ indexes.map(blockOf)<br><br>  def isValid(board: Seq[Seq[Int]]) = {<br>    def groupOf(group: Set[Index]) = group.map(i =&gt; board(i.r)(i.c))<br><br>    allGroups.map(groupOf).forall(valid.equals)<br>   }<br><br>   val badBoard = Seq(<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9),<br>     Seq(1, 2, 3, 4, 5, 6, 7, 8, 9))<br>   val goodBoard = Seq(<br>     Seq(9, 5, 3, 2, 1, 4, 7, 6, 8),<br>     Seq(2, 7, 6, 8, 5, 3, 4, 1, 9),<br>     Seq(8, 1, 4, 6, 7, 9, 2, 3, 5),<br>     Seq(7, 4, 8, 5, 3, 1, 6, 9, 2),<br>     Seq(6, 9, 1, 7, 4, 2, 5, 8, 3),<br>     Seq(5, 3, 2, 9, 6, 8, 1, 7, 4),<br>     Seq(1, 6, 9, 4, 8, 5, 3, 2, 7),<br>     Seq(3, 2, 5, 1, 9, 7, 8, 4, 6),<br>     Seq(4, 8, 7, 3, 2, 6, 9, 5, 1))<br><br>  val results = Seq(badBoard, goodBoard).map(isValid)<br><br>  println(results)<br>}</pre><p>We’ll talk about a Java version of this in another post. Until next time, have fun and stay functional.</p><p><em>Originally published at </em><a href="https://ruetech.io/2016/03/09/how-to-functional-in-java/"><em>ruetech.io</em></a><em> on March 9, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d9e67289f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/how-to-functional-in-java-90d9e67289f6">How to Functional in Java</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Java in Legacy Code at Rue]]></title>
            <link>https://medium.com/rue-la-la-tech/functional-java-in-legacy-code-at-rue-5544a73b1e0c?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/5544a73b1e0c</guid>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Fri, 20 Oct 2017 18:59:51 GMT</pubDate>
            <atom:updated>2017-10-20T19:11:53.715Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s continue where we left off last time. We’re going to implement a Java version of the sudoku-board validator so we can get a good feel for how Java 8 works. Then we’ll be able to evaluate it as a tool for improving our legacy codebase at Rue. Sometimes we get lucky and can write something new from scratch. Would Java 8 be a natural fit for that?</p><p>Java 8 has some functional features, so let’s see if we can use those to make something as pretty as the Scala version from last time. Spoiler alert: We can’t, but not just because of limitations with Java 8’s functional features. Can you guess what’s also missing?</p><p>There’s nothing obviously wrong with the structure of the Scala version, so we’ll start with a direct translation and clean it up later.</p><p>First, the Index data type. We cheat a little already because we’re assuming direct access to r and c is acceptable.</p><h4>Scala</h4><pre>case class Index(r: Int, c: Int)</pre><h4>Java 8</h4><pre>static class Index {<br>   private final int r;<br>   private final int c;<br>   public Index(int r, int c) {<br>     this.r = r;<br>     this.c = c;<br>   }<br>}</pre><p>Now for the constants that define a completed cell (1–9) and the index of cells in a row, column, or block (0–8).</p><h4>Scala</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0f1a9d2efbb6bebf10a96a38a9236ca/href">https://medium.com/media/c0f1a9d2efbb6bebf10a96a38a9236ca/href</a></iframe><h4>Java 8 (Lists)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0f1a9d2efbb6bebf10a96a38a9236ca/href">https://medium.com/media/c0f1a9d2efbb6bebf10a96a38a9236ca/href</a></iframe><p>So things aren’t looking so good. There’s a lot we’re lacking, most notably we’d like easy ways to declare integer ranges. We’ll find a nicer representation when we look at Streams in a bit.</p><p>Let’s define some basic functions to return the list of Index entries for each row, column, and block.</p><h4>Scala</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2c3250b7fc815752d440f118ab68e7c/href">https://medium.com/media/c2c3250b7fc815752d440f118ab68e7c/href</a></iframe><h4>Java 8 (Lists)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2edccd46711e50003bdb55d20e96e77e/href">https://medium.com/media/2edccd46711e50003bdb55d20e96e77e/href</a></iframe><p>At this point we could justifiably ask ourselves why on earth anyone would use Java 8, because it’s making everything so messy with very little obvious benefit. One of the clumsy things we’re doing is converting between List and Stream types in Java 8. There’s a map() method just like in Scala, but it doesn’t work directly on a List.</p><p>Let’s go back and make our original definitions more idiomatic using Streams where we can avoid the conversion at every step.</p><h4>Scala</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0adc39eb8f5f709843890e8352058213/href">https://medium.com/media/0adc39eb8f5f709843890e8352058213/href</a></iframe><h4>Java 8 (Streams)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e44fbb8474aeecd33c4c8587e01fb93/href">https://medium.com/media/8e44fbb8474aeecd33c4c8587e01fb93/href</a></iframe><p>This is starting to feel a bit more native. Each Stream can only be used once, so that’s why we’ve got a Supplier for a new one every time via its get() method. That’s like Iterator in old Java. Let’s rewrite rowOf, columnOf, and blockOf in this style.</p><h4>Java 8 (Streams)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50e595f813c944bbcd476572550fd8db/href">https://medium.com/media/50e595f813c944bbcd476572550fd8db/href</a></iframe><p>Now we can use these functions to create the Index structures for each row, column, and block. When we have these, we can concatenate them to make the list of all groups.</p><h4>Java 8 (Making All Groups)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b649e7fe12c1b57f46e027f9c120a6/href">https://medium.com/media/53b649e7fe12c1b57f46e027f9c120a6/href</a></iframe><p>The rows, columns, and blocks variables look really nice now. Perhaps Java 8 isn’t so bad after all. The allGroups value, however, probably needs some explanation. We’re doing two things: concatenating the Streams with</p><pre>Stream.of(rows, columns, blocks).flatMap(x -&gt; x)</pre><p>and converting the nested Streams to nested Lists with</p><pre>.map(s -&gt; s.collect(toList())).collect(toList())</pre><p>A feature common to many functional languages is idioms that don’t exactly roll off the tongue but are just the ticket.</p><p>While the use of our functions is looking good, the setup of the functions is really messy. We haven’t even started to convert the meat of the validator, the isValid function, and it’s already reaching readability limits. So why is that?</p><p>For a start, there are some really awkward interactions between Streams and Lists in Java 8. A significant advantage of Scala over Java 8 is <em>type inference</em>, which allows us to omit type declarations altogether. There are some exceptions, like recursion. But in general we can write code that’s terse without being unreadable. Java needs types, and while we could argue that the body of a particular function in Java 8</p><pre>r -&gt; indexes.get().map(c -&gt; new Index(r, c));</pre><p>isn’t much worse than</p><pre>indexes.map(c =&gt; Index(r, c))</pre><p>in Scala, the mandatory types make things messy.</p><p>Let’s leverage arguably the best feature of Java 8, lambdas, to remove some of the cumbersome boilerplate type declarations. We’re going to write our functions in line.</p><h4>Java 8 (Using Inline Functions)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f998c687010291aa0aadf22182eb893b/href">https://medium.com/media/f998c687010291aa0aadf22182eb893b/href</a></iframe><p>Compact, dense, a little hard to read, but I think this is about as good as it’s going to get. Let’s revisit our original question, whether we can use Java 8’s functional features to help refactor legacy Java code at Rue more effectively.</p><p>It turns out Java 8 has some limitations that make it hard to write clear functional code, even if that code is new. Trying to mimic a language that has a functional paradigm designed in from the beginning did not go that well in our example. Trying to layer Java 8’s features on top of legacy collections classes like List does not go that well either, because there are a lot of places where they simply don’t interoperate smoothly.</p><p>At Rue we use Java 8 in legacy code where it improves existing functionality without making it unreadable. In particular, we focus on applications of Streams that allow us to write lambdas in line. We have a bunch of helper methods that hide the explicit conversion of collections to Streams and back again, among other conveniences. And we always rely on good unit tests to make sure we didn’t break anything.</p><p>Here’s the complete Java class with those verbose functions collapsed into one-liners. I’d say it fails the test of “provably correct by inspection,” an important requirement of pull requests here at Rue.</p><h4>Java (One-Liner Anti-Patterns)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03b861219e45d4818c662cf6ec8fb349/href">https://medium.com/media/03b861219e45d4818c662cf6ec8fb349/href</a></iframe><p>We failed because in our effort to get rid of those verbose function type declarations, we made code that’s too hard to understand. So while the total number of statements went down a bit, the readability went down a lot. That’s a bad trade.</p><p>As a compromise, we create just enough functions with their irksomely wordy type declarations to make the bodies of other functions more readable. This is the version most likely to pass pull request code review at Rue.</p><h4>Java (Final Version for Pull Request)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18288a8b7ab46ea51509c7a735051459/href">https://medium.com/media/18288a8b7ab46ea51509c7a735051459/href</a></iframe><p>Can you make our final Java 8 code better? Comment with your suggestions if you can. Are you using Java 8 in your legacy Java code? Let us know that too.</p><p><em>Originally published at </em><a href="https://ruetech.io/2016/05/04/functional-java-in-legacy-code-at-rue/"><em>ruetech.io</em></a><em> on May 4, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5544a73b1e0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/functional-java-in-legacy-code-at-rue-5544a73b1e0c">Functional Java in Legacy Code at Rue</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What about Go? Can it Functional?]]></title>
            <link>https://medium.com/rue-la-la-tech/what-about-go-can-it-functional-f332ccf0f5c6?source=rss----13f707e0d2fc---4</link>
            <guid isPermaLink="false">https://medium.com/p/f332ccf0f5c6</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Stephen Harrison]]></dc:creator>
            <pubDate>Fri, 20 Oct 2017 18:59:27 GMT</pubDate>
            <atom:updated>2017-10-23T13:22:05.894Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go isn’t a functional language like Scala, but it has functions that are first-class types. Let’s see what we can do with it. You can still enjoy this post with exactly no Go experience. We’ll walk you through the key concepts and any unusual syntax.</h4><p>Previous posts examined Java 8’s functional additions and compared a short example written in Java 8 with the same one written in idiomatic Scala, a functional language designed from the ground up.</p><p>We concluded that while you can create functional code in Java 8, it’s not nearly as succinct as its Scala equivalent. But it turned out the reason has almost nothing to do with Java 8’s functional features: It’s because it doesn’t have <em>type inference</em>, meaning you have to declare types for the local variables. That can get really verbose, and the resulting code is often ungainly.</p><p>Significant in all of this is that this author found Java 8 functional code harder to write than the equivalent in Scala. The lack of type inference means that your code must compile to get the right feedback on the types in the sequence of assignments in your functional code. Ironically, it’s often that flow of types you’re trying to get help with. The Scala IDE (eclipse with specialized plug-ins) has some nice features that include showing the types of assignments it has worked out for us as tooltips. This allows a more iterative approach to finding the right sequence of operations, a natural way to program many people like. Specifically, when you can’t have that it gets in the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*ndZA71yh_2LREPm6." /></figure><p>So much for Scala. What about Go? It’s got the advantage of type inference but is not truly functional. How does that look? Don’t worry if you’re not a Go expert yet. We’ll help you out with any unfamiliar syntax so you can follow along just fine.</p><p>We’re going to use our running example, the Sudoku-board validator. Thanks to <a href="https://www.linkedin.com/in/mkorablin/">Misha Korablin</a> for the suggestion.</p><p>First, let’s work out some types we’re going to use. We need the row and column coordinates into the board, Index. Then we need nine of those to describe a complete row, column, or block, Group. Here are example Groups for a row, column, and block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*e7qvkXn68NfSUfkfaJ0i6Q.png" /></figure><p>In Go, the array index goes before the type. That’s not the only thing in Go that’s a bit odd on first look. Last, we need a two-dimensional array for the board values. Go has unsigned numbers, like uint, so we use those. In Go, you can create named types as a shorthand. You can say type Index struct{ r, c int } for each declaration in turn, or you can group them as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/222ae4cc3d491870c10f188ef0d2d415/href">https://medium.com/media/222ae4cc3d491870c10f188ef0d2d415/href</a></iframe><p>We need some functions to create groups of Index values for each row, column, and block. Let’s start with a row.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4f0c992b671d72451164d038ac3474/href">https://medium.com/media/ed4f0c992b671d72451164d038ac3474/href</a></iframe><p>Note how Go has nice for-loop semantics with range, and that constructors are compact Index{r, c} and provided. Also, we can see that types are written consistently after variables, parameters, and functions. Now, we could replicate this function for the equivalent columnOf and blockOf. If we’re honest, that would be lame in any case, but especially for a story about functional programming.</p><p>As stated earlier, Go is not a functional language, but we can use its functions to encapsulate the loops that create groups. Each Group has a major and minor input—named a and i, respectively—which map to the corresponding row and column. For rowOf it’s easy: Index{a, i}. For columns we simply switch the major and minor indexes for Index{i, a}. The complicated one, the blocks, are Index{a/3*3 + i/3, a%3*3 + i%3}.</p><p>Wrapping this up in a function looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9461c7522057509f141655543ced1eb/href">https://medium.com/media/c9461c7522057509f141655543ced1eb/href</a></iframe><p>We can create a named type shorthand for this function, Indexer, as</p><pre>type Indexer func(int, int) Index</pre><p>and now write the general-purpose function to generate groups that uses it as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a6e853081b24cce59f37547657a63b8/href">https://medium.com/media/2a6e853081b24cce59f37547657a63b8/href</a></iframe><p>Finally we can collect all the groups for each row, column, and block with the function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d42f5979e3ae1c566c2defbe1fd763c/href">https://medium.com/media/2d42f5979e3ae1c566c2defbe1fd763c/href</a></iframe><p>We call this by passing in the generator functions, which in turn get passed to the previous function. We can pass in the rowIndexer function like this</p><pre>var rows = allOf(rowIndexer)</pre><p>or we can pass the function in-line like this for more idiomatic Go.</p><pre>var rows = allOf(func(a, i int) Index { return Index{a, i} })</pre><p>Speaking of idiomatic, Go usually deals with <em>slices</em> of arrays, not the arrays themselves. A slice in Go is a view on an array. A majority of library code deals with slices, so we should too. The allOf function does this as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dca87a4d66f6138160a53c7cd35e5e1c/href">https://medium.com/media/dca87a4d66f6138160a53c7cd35e5e1c/href</a></iframe><p>make is a built-in function for creating slices and := is a convenient shorthand for declaration and assignment. It’s starting to come together now. We need a function to check that the board values in any group are valid. Go doesn’t really have sets (you usually end up using a map and ignore the values). So we define the output of the function that gets the values in a group as [9]bool: If the cells in a group contain exactly one of each of the numbers 1 through 9, that slice will be 9 true values. All other combinations let us know the group is invalid. We don’t have to count the occurrences of each number because any duplicate value means that another element must be missing and therefore false. Here’s that function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/532cfe32eb6586456910ee520ed7e6f2/href">https://medium.com/media/532cfe32eb6586456910ee520ed7e6f2/href</a></iframe><p>A couple of new things to look out for here. First, we declare that the function valuesFrom belongs to Board. You can use any name you like for the type the function belongs to, including this, self, me and so on. But Go’s tools will complain you’re not being very helpful using these generic names. Also, for...range loops can have two control variables: the index over the range and the element at that index, respectively. If you don’t need the element, you can omit that variable. If you don’t need the index, you can use a _.</p><p>This all culminates in a isValid function that makes sure all the row, column, and block groups have exactly the numbers 1 to 9.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8897a5561c4f82a61fdc433616331a97/href">https://medium.com/media/8897a5561c4f82a61fdc433616331a97/href</a></iframe><p>Here’s the final version of the Sudoku-board validator in Go, with a few lose ends tidied up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d43f708a6a798adabf90a7c0da1ccfe1/href">https://medium.com/media/d43f708a6a798adabf90a7c0da1ccfe1/href</a></iframe><p>So what did we learn?</p><p>We saw that because Scala is functional and has type inference, you can write terse code that preserves legibility. Java 8’s functional features can be handy and expressive, but we saw how Java 8’s lack of type inference made the code harder to read and anecdotally harder to write.</p><p>What Go lacks in functional features it makes up for in type inference. In addition, Go has some really nice programming features like expressive for loops and compact object creation.</p><p>Your verdict? Comment below and let us know. Did we skew the results or miss something? Let us know that too.</p><h3>Postscript</h3><p>Here are a couple more things we like about Go: small and fast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd853b208cb9291d2d9b92bc47ba7e20/href">https://medium.com/media/fd853b208cb9291d2d9b92bc47ba7e20/href</a></iframe><p><em>Originally published at </em><a href="https://ruetech.io/2016/06/02/what-about-go-can-it-functional/"><em>ruetech.io</em></a><em> on June 2, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f332ccf0f5c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rue-la-la-tech/what-about-go-can-it-functional-f332ccf0f5c6">What about Go? Can it Functional?</a> was originally published in <a href="https://medium.com/rue-la-la-tech">Rue Gilt Groupe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>