<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Laurent Leconte on Medium]]></title>
        <description><![CDATA[Stories by Laurent Leconte on Medium]]></description>
        <link>https://medium.com/@laurent-leconte?source=rss-633ceb9d97f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5ocW0TC_yjJ6QiZO-qwqDQ.jpeg</url>
            <title>Stories by Laurent Leconte on Medium</title>
            <link>https://medium.com/@laurent-leconte?source=rss-633ceb9d97f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:58:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@laurent-leconte/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Hype Cycle of Side Projects]]></title>
            <link>https://laurent-leconte.medium.com/the-hype-cycle-of-side-projects-e94797835691?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e94797835691</guid>
            <category><![CDATA[hype-cycle]]></category>
            <category><![CDATA[side-project]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 06:31:38 GMT</pubDate>
            <atom:updated>2021-04-21T13:40:45.645Z</atom:updated>
            <content:encoded><![CDATA[<h4>About innovation, side projects and Mount Stupid.</h4><p><em>This article was originally published </em><a href="https://lau.rent/posts/hype-cycle-side-projects.html"><em>here</em></a><em>.</em></p><p>Fifteen months ago, I decided to learn OCaml by working through the 2019 Advent of Code problems and (painfully) blogging about it.</p><p>The first article was enthusiastic; the second one was glum. As I mulled what I was going to write for the third installment, it dawned on me that I was traveling a well-known trajectory. To wit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ME52yRRQeUaR4eZ9.jpg" /><figcaption>Innovation has its ups and downs</figcaption></figure><p>Garner’s hype cycle is a staple of the corporate innovation ecosystem. It thrives in solution provider white papers, “thought leadership” blog posts, and corporate R&amp;D seminars. You’ve certainly run into it at one time or another. If not, I envy you.</p><p>The hype cycle posits that all new technologies go through the same phases as they make their way from hot new stuff to boring old stuff.</p><p>The cycle begins with an <strong>innovation trigger</strong>, when a new technology enters the market and begins to find recognition. The initial excitement grows, and reaches a <strong>peak of inflated expectations</strong>. When the technology inevitably fails to live up to the hype, it falls into the <strong>through of disillusionment</strong>. As the technology matures, it climbs the <strong>slope of enlightenment</strong> and finally reaches the <strong>plateau of productivity</strong>.</p><h3>A side project’s hype cycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mn24WWBIPaVNeQvz.png" /><figcaption>The same for side projects, but even more so</figcaption></figure><p>It turns out that side projects (at least, my side projects) follow the same curve.</p><p>It all starts with an idea for a new side project. My imagination starts running loose; I mentally list all the features and the cool stuff I could fit in there. Before I know it, this innocent idea has turned into an <strong>overblown pipe dream</strong>.</p><p>Then I actually get started, and reality catches up to me: this project is going to be much harder than I expected. This is not something I can handle with a couple of hours of work each week; it’s going to require <em>real</em> work. My initial motivation plummets and I fall into the <strong>chasm of despair</strong>.</p><p>By now I have a much better idea of how much I was underestimating the complexity of the project; I lower my expectations accordingly. The initial enthusiasm is gone. Guilt becomes the prime motivation to push on: I have entered the phase of <strong>glacial progress</strong>.</p><p>This phase is often strewn with side quests, which sprout their own tiny hype cycles. An example: <em>Hey, I was really into learning OCaml but now it’s become painful and boring. I wonder why that is? Ooh, this idea of “side project hype cycle” sounds interesting! Let’s write a post about</em> *that* <em>instead of getting on with the initial project</em>.</p><p>(Fun fact: this particular side quest triggered its own side foray into how to make my writing clearer.)</p><p>Fitful progress, lowered expectations, occasional side quests and long periods of shutdown. Lather, rinse, repeat and after a few rounds I eventually reach the <strong>plateau of good enough</strong>. Time has played its part. It has eroded the initial goals of the project, watered down the guilt, distracted me with new ideas. The project stopped being fun a long time ago and I’ve achieved enough progress that I can stop with a clear conscience. So I shelve the project, never to touch it again.</p><p>Sound familiar?</p><h3>But wait, there’s more!</h3><p>I don’t claim that this is a very deep insight; I’m hardly the <a href="https://hugozap.com/posts/how-to-finish-your-side-project/">first</a> <a href="https://www.learningsomethingnew.com/how-to-finish-your-side-project">person</a> <a href="https://medium.com/typeforms-engineering-blog/how-to-finish-a-side-project-without-it-taking-over-your-life-169a069412d7">to</a> <a href="https://tomanagle.medium.com/i-finally-finished-a-side-project-1ee55a78f608">have</a> <a href="https://dev.to/kaylasween/how-to-finish-a-side-project-lo9">trouble</a> <a href="https://dev.to/samborick/it-doesn-t-matter-if-you-finish-your-side-project-43lb">finishing</a> <a href="https://code.likeagirl.io/how-to-finish-your-side-project-81d7d93dacea">side</a> <a href="https://thomas-sojka.tech/6-tips-to-finish-your-side-project.html">projects</a> (seriously, don’t read all those links! I barely skimmed the first two myself).</p><p>But the parallel to Gartner’s hype cycle is interesting; it suggests that this individual behavior more or less holds out in the aggregate. Sure, the drivers are different, or at least described differently; the guilt and stubbornness that push an individual project forward are recast as “strategic vision” or whatever. But the overall shape is the same.</p><p>And although I’ve described it through the lens of my personal projects, I’ve seen very similar trajectories in “real” projects at work (not <em>my </em>projects, of course. A <em>friend</em>’s project). The initial enthusiasm for a new product, driven by the promise of large market shares; the grand kick-off with the ExCom sponsor… And then the cold shower of the scoping phase and the initial work estimate; the versioning of features into v1 ( <em>we’ll give it our best shot</em>), v2 ( <em>mayyyybe…</em>), and v3 ( <em>never gonna happen</em>); the long slog to ship the v1, while the backlog grows and further arbitrages are made to stick to the initial schedule. The v2 that devolves into a v1.5, then a v1.1… Until finally the ExCom sponsor moves on to the next hot thing and the various stakeholders shuffle awkwardly away from the program, which is labeled a resounding success and shelved.</p><h3>It looks so easy from the top of Mount Stupid</h3><p>There’s a third curve that looks like the ones above, if you squint hard enough. It describes the Dunning-Kruger effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*i-u6EJXM2gbVdY7t.jpg" /><figcaption>Mount Stupid, courtesy of <a href="https://www.smbc-comics.com/comic/2011-12-28">SMBC</a></figcaption></figure><p>From <a href="https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect">Wikipedia</a>: the Dunning-Kruger effect is a cognitive bias in which people with low ability at a task overestimate their ability.</p><p>Very roughly, the less you know about a topic, the likelier you are to overestimate your ability. The effect also works the other way: competent people tend to underestimate their ability. Hence Mount Stupid, a summit of misplaced confidence and as-yet undiscovered incompetence.</p><p>The parallel with the hype cycle seems clear. When you embark on a new innovative project, you only have a vague idea of what the technology can do. You tend to overestimate what you can achieve and underestimate the problems you’ll discover along the way: Dunning-Kruger is taking you on a scenic trip to the peak of inflated expectations. It’s only after you gain some competence and domain knowledge (i.e. after the first few pitfalls) that you start to perceive how much you don’t know; you dial confidence all the way back, overcompensating for your previous cockiness, and plunge towards the through of disillusionment. It’s only once you’ve hit the high and low, calibrated your confidence so to speak, that you can hope to make sustainable progress.</p><h3>Where does this leave us?</h3><p>I must admit I don’t really have an ending for this post. It started, oh so long ago, as a jaded observation about my then-current side project. I thought it would make for a quick, witty post, maybe something that would pique the interest of HN (do you recognize the overblown pipe dream?).</p><p>But as I fleshed out the initial idea, I kept thinking there was something larger lurking behind.</p><p>I picked up and dropped off this draft multiple times over the past year, trying to tease something meaningful out of disparate concepts. I’m not convinced that I followed these ideas to their logical conclusion, nor even that they are related; we humans are good at recognizing patterns, sometimes where there are none.</p><p>Nevertheless, I’ve achieved enough progress that I can stop with a clear conscience. I’ve reached the plateau of good enough.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e94797835691" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Code 2019 — Lucky 14]]></title>
            <link>https://laurent-leconte.medium.com/advent-of-code-2019-lucky-14-71faf6a4a409?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/71faf6a4a409</guid>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ocaml]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 18:48:32 GMT</pubDate>
            <atom:updated>2020-07-13T18:48:32.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advent of Code 2019 — Lucky 14</h3><h4>Yes, I’m aware that my post titles have off-by-one errors.</h4><p>In my last article, I lamented that progress on the project had stalled. Well, writing that post was the impetus I needed to get back on the horse, or the camel as it were. Lo and behold, a few days later I solved day 14 of the Advent of Code, and what’s more : I enjoyed it. (and then, of course, it took me two months to publish this article).</p><p>Two reasons for this : better tools, and a fun problem.</p><h3>Better tools</h3><p>For work-related reasons, I recently spent some time getting WSL to suck less. I configured some basic stuff, installed or updated some packages, tweaked some settings. I bit the bullet and learned about .vimrc. The result: my WSL is now a usable Linux shell.</p><p>Along the way, I installed opam, and this unlocked some cool OCaml tools: merlin for auto-completion, and utop for a better REPL. Crucially, with a simple opam switch 4.10.0 I jumped to the latest Ocaml version, leaving behind Ubuntu’s slightly outdated 4.05 version. This gave me access to a language feature (to_seq) I wanted to use to solve the problem at hand. So, major step forward in the tooling department.</p><p>I still don’t have a decent OCaml IDE, but I’ve grown used to vim; Stockholm syndrome, probably.</p><h3>A fun problem</h3><p>Day 14 sounds suspiciously easy when you first read it. You’re provided with a list of reactions, which are recipes to generate chemical compounds from different input chemicals. All chemicals can ultimately be generated from a primordial input called “ORE”. Given all this, you are asked how many “ORE” inputs are required to produce one “FUEL” output.</p><p>Simple, right? You repeatedly substitute each chemical by its component inputs, until you’re only left with ORE. The trick is the order in which to do the substitutions: if you get it wrong, you’ll end up using more ORE than necessary. To get the correct quantity, you have to substitute each chemical exactly once.</p><p>Long story short, this requires performing a topological sort on a directed acyclic graph. (Fancy terms, right? Finding what words to Google was half the battle. I learned them when solving this problem, so don’t beat yourself up). This <a href="https://medium.com/@WindUpDurb/on-partial-ordering-total-ordering-and-the-topological-sort-9f9c0d0d812f">great article</a> covers the theory and gives not one but two algorithms for topological sort!</p><p>From there, it’s straightforward to code the solution.</p><p>I didn’t get too fancy with data structures; the entire solution is cobbled from hash tables. There’s certainly a more elegant way to build and traverse the DAG, but I couldn’t think of one. That’s ok. Hash tables don’t judge you when you write ugly code. They’re just glad to help.</p><p>To my amazement, my code gave the correct answer right away. Well, after I’d fixed all the syntax errors, obviously. So chalk this up as a net win for team side project! Day 15 requires interpreting keyboard presses, this is going to be a whole ‘nother can of worms to tackle.</p><h3>Addendum</h3><p>By the time I wrote the draft for this post and publication, I solved the first part of day 15. The solution was not as elaborate as it could be, but there’ll be time to improve the I/O routines if I end up reusing them for another problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71faf6a4a409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of code — the 13 days of Christmas]]></title>
            <link>https://laurent-leconte.medium.com/advent-of-code-the-13-days-of-christmas-ed4d61a1c9aa?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed4d61a1c9aa</guid>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Tue, 12 May 2020 06:53:37 GMT</pubDate>
            <atom:updated>2020-05-12T06:53:37.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advent of code — the 13 days of Christmas</h3><p>In the first article of this series, I prophesied that my initial enthusiasm for the project would soon burn out. Well, five months in, I’ve only solved 13 days of the advent of code. What can I say, I was right! To be fair, I’ve had a pretty full January and February, and, well, March and April haven’t been the best for just about everyone.</p><p>Anyway, I’m well and truly in the “glacial progress” phase of this little project. After a rather brutal start, I picked up enough OCaml to solve the first 10 problems or so. Now I’m fluent enough in the language to solve the new problems, but not fluent enough to solve them <em>the way I would like</em>.</p><p>This doesn’t provide enough incentive to learn more of the language, but it is sufficiently frustrating that working on new problems has turned into a chore. Hence, glacial progress.</p><p>So what OCaml look like now that I’ve learned enough to be competent (for Dunning-Kruger values of competence)?</p><h3>Batteries not included</h3><p>Coming from Python, the OCaml standard library feels austere, both in terms of features and expressiveness.</p><p>OCaml’s standard library is minimalist; you quickly need to reach for external libraries to carry out even fairly basic tasks. How basic? Well, here’s an apples-to-oranges (or in this case, camel-to-python) comparison: OCaml includes <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/index.html">70 modules</a> in the core library, whereas <a href="https://docs.python.org/3/library/">Python has 240</a>. You go <strong>a lot</strong> further with Python’s standard lib.</p><p>Then there’s the matter of OCaml’s sparseness compared to Python’s richer syntax. Obviously these things are subjective: one person’s expressiveness is another’s syntactic sugar. But for me Python strikes a nice balance between expressiveness and simplicity, and OCaml is decidedly on the “less is more” end of the scale. Here is what it takes to read a file using OCaml’s standard lib (as per the <a href="https://stackoverflow.com/questions/5774934/how-do-i-read-in-lines-from-a-text-file-in-ocaml">first answer in Stack Overflow</a>):</p><pre>let read_file filename =<br>  let lines = ref [] in<br>  let chan = open_in filename in<br>    try<br>      while true; do<br>        lines := input_line chan :: !lines<br>      done; !lines<br>    with End_of_file -&gt;<br>      close_in chan;<br>      List.rev !lines</pre><p>Compare this to Python’s with syntax:</p><pre>def read_file(filename):<br>    with open(filename) as f:<br>        return [l for l in f]</pre><p>You can also refer to <a href="https://medium.com/@laurent.leconte/advent-of-code-2019-its-always-day-1-f57312336695">last post</a>’s example on how to print an int list if you want to flog this particular dead camel a bit more.</p><p>The immediate consequence is that even trivial tasks are fairly involved compared to Python’s “batteries included” model. This in turn means that it’s not practical to write OCaml without using a supplemental library to complete the standard lib. Unfortunately, there’s more than one of these, so you need to spend some brain budget choosing your standard lib.</p><p>I’ve so far resisted using any 3rd-party libraries, mostly because I don’t want to have to figure out how to import them. But that often means reinventing the wheel (well, copy-pasting the wheel from Stack Overflow to be honest). For what it’s worth, if I had to use one I’d probably go with Jane Street’s <a href="https://ocaml.janestreet.com/ocaml-core/latest/doc/core/index.html">Core</a> library.</p><h3>Playing with matches</h3><p>One of my impetus for trying OCaml was the match syntax. It feels very natural; in fact, I use it a lot in pseudo-code. Match plays well with <a href="https://ocaml.org/learn/tutorials/data_types_and_matching.html#Variants-qualified-unions-and-enums">variant types</a> (another awesome feature) and it’s a natural fit for recursive functions.</p><p>Here is an almost-toy example of matching, from one of the first problems I solved.</p><pre>let rec digits = function<br>  | 0 -&gt; []<br>  | n -&gt; (n mod 10) :: digits (n / 10)</pre><p>This function turns a number into a list of digits. The match syntax | defines the two possible input cases:</p><ul><li>either a 0, in which case we return an empty list;</li><li>or any other number, from which we extract the leading digit, recurse on the remainder of the number and concatenate the results.</li></ul><p>OCaml’s interpreter does a splendid job detecting unmatched cases. This is one of the (rare) cases when the error messages are informative and useful. Consider the code below:</p><pre><em>(* equivalent to List.map List.tl but ignores empty lists and empty tails *)</em><br>let rec map_tl = function<br>  | []           -&gt; []<br>  | []::xs<br>  | (_::[])::xs  -&gt; map_tl xs<br>  | (_::xs)::xss -&gt; xs :: map_tl xss</pre><p>As the comment states, this method applies the tail function to all items of a list of list, skipping empty lists and singletons. How can we be sure that the match cases are exhaustive? Well, here’s what the interpreter tells me if I remove the second match ([]::xs, which handles empty lists):</p><pre>Warning 8: this pattern-matching is not exhaustive.<br>Here is an example of a case that is not matched:<br>[]::_</pre><p>A clear warning with a useful example to troubleshoot the problem. Ah, OCaml, if only all your error messages were as clear…</p><p>I like match so much that I often find myself rearranging arguments to write functions as a big match case on the last argument.</p><h3>Making a hash of dictionaries</h3><p>Maps are essential data structures. Python dictionaries in particular are the language’s workhorse. So it’s natural to reach for OCaml’s version, or in this case, version<strong>s</strong>: association lists, hash tables and maps all serve similar needs. So which should you use? ¯\_(ツ)_/¯</p><p>According to the <a href="https://ocaml.org/learn/tutorials/">official OCaml tutorial</a>, you should use Maps; it’s the first entry under “Data structures” and it’s even explicitly labeled “(Dictionaries)”. Maps are the hip, immutable, FP version of a dictionary. Map is a “functor”! How cool does this sound?</p><p>Well, as you can guess, maps sound too impressive to do any actual useful work. Hash tables are probably what you want 90% of the time. They’re the working man’s dict: mutable, easy to set up and with better performance in most use cases. I wish OCaml had taken the mutable concept all the way and added direct element access and modification to hash tables. Something like the array syntax (tbl.(key) and tbl.(key) &lt;- new_val) would be nice. And, of course, not pimping Map when what any normal programmer wants is a Hashtbl.</p><h3>Put that in your pipe!</h3><p>A <a href="https://stackoverflow.com/questions/16637015/is-there-an-infix-function-composition-operator-in-ocaml">perennial</a> <a href="https://stackoverflow.com/questions/4997661/composite-functions-in-ocaml">OCaml</a> <a href="http://caml.inria.fr/pub/old_caml_site/caml-list/0838.html">newbie</a> <a href="https://stackoverflow.com/questions/16120081/point-free-confused-about-where-to-put-parenthesis">question</a>: why is there no function composition?</p><p>Combining functions and using the resulting function, e.g. in a List.map, is a very common pattern. We are, after all, talking about <em>functional</em> programming. And yet there’s no elegant way to do it in OCaml.</p><p>Here’s a simple example to illustrate my point. Imagine you have an int list and you want to print it, one element per line. Since OCaml doesn’t have a method to print an int <em>and </em>a newline (ignoring Printf.printf for this example) , you need to combine print_endline and string_of_int. You would conceivably write this as:</p><pre>let _ = List.map (print_newline . string_of_int) l</pre><p>Where . (or whatever syntax) would denote function composition. But there’s no such operator in OCaml. You have to explicitly define the combined function like so:</p><pre><em>(* note that in the first line, the parentheses and the explicit argument are mandatory *)</em></pre><pre>let composed x = print_newline (string_of_int x)<br>let _ = List.map composed l</pre><p>I don’t know about you, but I find this disappointing.</p><p>However, there’s a nifty pipe operator, |&gt; , which alleviates some of the pain as long as you’re willing to reorganize the order of your functions. |&gt; takes the output of the left-side operation and passes it as the input to its right-side argument. Here it is in action:</p><pre>let max, spot = &quot;day10.dat&quot; <br>  |&gt; read_lines<br>  |&gt; points_from_input<br>  |&gt; count_all_visibles<br>  |&gt; max_of_list</pre><p>This code takes the string &quot;day10.dat&quot;, passes it to read_lines, then passes the result of that operation to points_from_input, and so on until the last function max_of_list.</p><p>Thi is much more readable than the “normal” way of chaining these functions:</p><pre><em>(* so many parentheses... *)</em><br>let max, spot = max_of_list (count_all_visibles (points_from_input (read_lines &quot;day10.dat&quot;)))</pre><p>I admit that at first I had a hangup about the pipe operator; passing the data from one function to another felt less “functional” than composing functions together. Now that I’ve gotten used to it, I can’t live without it.</p><h3>Will that be all?</h3><p>I have run out of puns for section titles, so I’ll stop here for today. Anyway, this blog post has been much too long in the writing and it’s past time I published it, incomplete as it is. I have a theory about my inability to make progress on this little adventure, which I’ve dubbed “the hype cycle of side project”. Stay tuned for more details in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed4d61a1c9aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Code 2019 — it’s always day 1]]></title>
            <link>https://laurent-leconte.medium.com/advent-of-code-2019-its-always-day-1-f57312336695?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f57312336695</guid>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 20:30:25 GMT</pubDate>
            <atom:updated>2019-12-17T20:31:21.089Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advent of Code 2019 — it’s always day 1</h3><p>If you missed <a href="https://medium.com/@laurent.leconte/advent-of-code-2019-re-learning-ocaml-cb8c9c860709">the first part</a> in this series, I’m currently learning OCaml by (slowly) making my way through the Advent of Code 2019.</p><p>Lao Tzu said that a journey of a thousand miles starts with a single step. In my case, the 25-day advent of code started with a very, very long, very, very repetitive first day. Here’s my OCaml Groundhog Day (OCaml enthusiasts, be warned: you’ll be yelling and cursing throughout this piece).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*8UYhdB6f9Z0FoKYlLyFdSw.jpeg" /><figcaption>I’d have gotten through the first day faster if I’d let this groundhog type for me</figcaption></figure><h3>Pitfall 1 : Installing OCaml on Windows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zAdWByfyAWmP_MbemZ3Kw.png" /><figcaption>Feeling lucky ? Three recommended solutions are probably two too many, especially since the first one is a dead link.</figcaption></figure><p>The first step was to get OCaml running on my PC. The OCaml installation page lists Windows after Linux, MacOS, OpenBSD and NetBSD ; in hindsight, not a good sign. The French installation page lists three solutions to install OCaml; the first link, the<em> “official Ocaml distribution”</em>, is no longer active 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nFxCXMk2EpD7-A34Do4bA.png" /><figcaption>We’re not off to a great start… The “official OCaml distribution” is no longer supported (to be fair, this link is not present on the English install page)</figcaption></figure><p>While the two other links look more credible, I didn’t want to take my chances with them, especially since they advertise “experimental” OPAM support and although I don’t exactly know what OPAM is, it sounds pretty useful. So I ended up installing OCaml on WSL (the Windows Subsystem for Linux — all the user-friendliness of Linux with the performance of Windows).</p><h3>Pitfall 2: double semi-colons</h3><p>After installing OCaml and taking the REPL for a spin, time to write a real program in a real editor or, failing that, vim. And this is where double semi-colons are waiting to trip you up.</p><p>In the interpreter, ;; is used to indicate the end of a statement and that the top-level should start doing its thing. Outside the REPL however, <a href="https://baturin.org/docs/ocaml-faq/">every</a> <a href="https://ocaml.org/learn/tutorials/structure_of_ocaml_programs.html#The-disappearance-of">tutorial</a> will tell you that double semi-colons are not necessary, and will point to the fact that <em>entire code bases </em>don’t use ;; <em>even once</em>. This affirmation is both technically correct and unnecessarily cruel. It’s like telling a toddler who just received her first bike that training wheels are not, in fact, necessary to ride a bike. “Look at Lance Amstrong! He didn’t win the Tour de France by using training wheels!”</p><p>It is indeed perfectly possible to write an OCaml program without using ;; once, but it takes a little while to get the hang of it. Personally, it took me about a week before I could reliably do without them. On that first day, I had to sprinkle those suckers every other line. Double semi-colons are a helpful beginner’s crutch and it is <em>very </em>frustrating to try to do without them. Especially since…</p><h3>Pitfall 3: “Error: Syntax error”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Kxaw45Hgct8C3onynbfozA.png" /><figcaption>I’ve lost count of the number of times I ran into this message</figcaption></figure><p>When you learn a new language, you’re going to make mistakes. Glaring, obvious mistakes, and more subtle ones. You’re counting on the compiler or the interpreter to tell you where and what you got wrong so that you can, hopefully, fix it and move on to the next mistake. And in this respect the OCaml interpreter is… underwhelming. The screenshot above says it all: the parser can’t be bothered to display an informative message, and won’t even print out the broken code! Nope, just “syntax error”. Go look up the code yourself.</p><p>The seasoned OCaml developers among you are no doubt smirking at this last sentence. That’s because they know what happens next: you open the file, and check line numbers, and count characters like a Neanderthal, and then you find out that characters 26–28 are, obviously, ;;. The actual syntax error is somewhere between the beginning of the last statement and those semi-colons — which is why you should add them liberally to your code when you don’t understand what’s breaking and you’re trying to debug it. Speaking of which:</p><h3>Pitfall 4: where’s my print() function?</h3><p>Debugging often amounts to adding a lot of print statements to figure out what’s going on in your program. In OCaml, printing out the content of variables is incredibly annoying to get right for such a basic use case. It’s not just that you need to choose between print_int, print_string, print_char and their ilk. These methods are actually only slightly useful to debug — I soon found myself grabbing for print_endline to get, you know, newlines between debug outputs. More importantly, printing out even slightly more complex structures quickly becomes a pain. Consider the iconic OCaml object, a list of ints; in <a href="https://stackoverflow.com/questions/9134929/print-a-list-in-ocaml">this StackOverflow question</a>, the validated solution, is, wait for it… to write a recursive print function. The most concise answer is this clunker:</p><p>print_string (String.concat &quot; &quot; (List.map string_of_int list))</p><p>Which is actually a pretty elegant solution! But there’s a lot of ways you can get it wrong and honestly, debugging your debug code is not fun. By contrast, Python’s print(list) is pretty hard to mess up.</p><p>(Before you get all righteous: I know about Printf.printf, which alleviates some of these issues. But if your most useful print function is in a module of its own, you’re doing it wrong).</p><h3>At last, it works!</h3><p>There’s only so many pitfalls you can run into before finally getting your code to work. So, eventually, I finished my first OCaml program. Here is my complete solution to the day 1 problem (input list elided for clarity, and without double semi-colons):</p><pre>let input = [149895; ...; 58085]</pre><pre>let required_fuel mass = max ((mass / 3) - 2) 0</pre><pre>(* apply a fuel function to a list of masses and sum the results *)<br>let sum_of_fuel fuel_function masses =<br>  List.fold_left (+) 0 (List.map fuel_function masses)</pre><pre>let () = print_endline (&quot;Part 1 &quot; ^ string_of_int (sum_of_fuel required_fuel input))</pre><pre>(* sum the values of f^k(x) from k = 1 until f^k(x) = 0 *)<br>let fixed_point_sum f x =<br>  let rec accumulate_till_zero acc x =<br>    let y = f x in<br>    if y = 0 then acc else accumulate_till_zero (acc + y) y in<br>  accumulate_till_zero 0 x<br>  <br>let complete_required_fuel = fixed_point_sum required_fuel</pre><pre>let () = print_endline (&quot;Part 2 &quot; ^ string_of_int (sum_of_fuel complete_required_fuel input))</pre><p>Despite all the tribulations to get there, I’m pretty happy with the final result. It feels idiomatic, and it makes good use of functional paradigms: there’s a map, a fold, tail recursion and function composition — all in only 12 lines of code 😁. Notice as well that the solution for part 2 is essentially the same as for part 1, but with a different fuel computing function.</p><h3>A final word</h3><p>If this entire article feels whiny, …well, it <em>is</em> whiny. But that’s because the promise of functional programming is to enable a purer, higher-level form of programming. To stick as close as possible to the Platonic ideal of data structures and algorithms. In a word, to be <a href="https://www.xkcd.com/224/">ideas manifest</a>. And when you get it to work, it’s mostly the case! (It certainly feels more natural to write algorithms in OCaml than in, say, Java). So I had high expectations when starting out, and accordingly severe frustration when I was stymied by such pedestrian issues as printing out a list of values.</p><p>This article is not about how stupid OCaml is for not supporting Windows. It’s about the impedance mismatch between the lofty promises of FP and the drudgery of learning any new language (even more so one which relies on ;; for debugging). Now that the worst of the learning curve is behind me, I promise that the next article will be more balanced!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f57312336695" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Code 2019— (re)learning OCaml]]></title>
            <link>https://laurent-leconte.medium.com/advent-of-code-2019-re-learning-ocaml-cb8c9c860709?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb8c9c860709</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[ocaml]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 22:04:58 GMT</pubDate>
            <atom:updated>2019-12-06T21:33:10.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tLonDeq0XFnB_PoRjmbmpw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@iaminbaltal?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Inbal Malca</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve been programming in Python (and, when I can’t avoid it, JavaScript) for the past several years. Before that, I was a Java certified programmer and before that, I committed some atrocious C/C++ code. And when I say ‘committed’, I don’t mean in the Git sense…</p><p>But before all this, before I typed my first public static void main(String[] args) or <em>(shudder)</em> malloc, I learned to program in Caml Light (OCaml’s predecessor — this was in 1997). The fact that I learned programming with Caml rather than say, Pascal or C, is due to the strong influence of the <a href="https://www.inria.fr/">INRIA</a> (the research institute behind Caml) in the French higher education system. And that’s a good thing! It makes much more sense to learn the basic concepts in a high-level, functional language than by messing with memory allocation. malloc will come soon enough.</p><p>Fast forward twenty years. Hacker News seems to put a lot of stock in this Functional Programming thing, and who am I to resist peer pressure? After reading a few books on the topic, I still don’t understand what a monad is but I’m yearning for curried functions and immutability. So I decided to pick up OCaml, hoping that I haven’t forgotten too much from my Caml Light days (spoiler: I’ve forgotten everything. Especially the messy parts).</p><p>What better way to learn a new language than by writing short, easy programs? That’s how I learned Python, by working on <a href="https://projecteuler.net/">Project Euler</a> problems after reading this <a href="https://www.xkcd.com/353/">xkcd comic</a> (check the alt-text — Randall is talking about the first Project Euler problems). So I’m currently working my way through the <a href="https://adventofcode.com/2019">Advent of Code,</a> and since I shouldn’t be the only one to suffer through this, I plan (hope) (well, I think it’d be cool) (okay I’ll probably give up in less than a week) to talk you through how that’s going.</p><p>Next up, how ridiculously long it took me to get through the first day. If you’d like to follow along, the puzzles are <a href="https://adventofcode.com/2019">here</a> and my code is <a href="https://github.com/laurent-leconte/advent-of-code-2019">here</a>. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb8c9c860709" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Okazoo, l’occasion a maintenant son assurance !]]></title>
            <link>https://medium.com/moonshot-internet/okazoo-loccasion-a-maintenant-son-assurance-83ecce166933?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/83ecce166933</guid>
            <category><![CDATA[insurance]]></category>
            <category><![CDATA[okazoo]]></category>
            <category><![CDATA[leboncoin]]></category>
            <category><![CDATA[smartphones]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 15:05:05 GMT</pubDate>
            <atom:updated>2019-11-22T15:05:05.021Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Okazoo, l’occasion a maintenant son assurance !</strong></h3><h4>Acheter son téléphone d’occasion, c’est bon pour la planète et le portefeuille, mais ça peut parfois réserver de mauvaises surprises…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T55zDXXa4S6wgrv7PYoyWg.png" /></figure><p>C’est pour répondre à cette problématique client que Moonshot-Internet, filiale du groupe Société Générale Assurances, a lancé <a href="https://app.moonshot-internet.com/okazoo-assurance/">l’assurance Okazoo,</a> destinée à protéger les<strong> </strong>smartphones d’occasion. Par exemple, si vous achetez votre téléphone d’occasion (iPhone, Samsung, Huawei…) sur <a href="http://www.leboncoin.fr/">leboncoin </a>et qu’il tombe en panne ou se casse dans les 3 mois suivant l’achat, Okazoo offre la réparation, le remplacement ou une indemnité financière au client. Pour souscrire <a href="https://app.moonshot-internet.com/okazoo-assurance/">c’est très simple</a> : il suffit d’indiquer les principales caractéristiques du téléphone, un prix personnalisé vous est proposé et en quelques étapes vous pouvez souscrire.</p><p>Une assurance unique, construite grâce aux utilisateurs du site leboncoin !</p><p>Nous aidons les Français à consommer « responsable » en privilégiant l’achat d’un téléphone d’occasion. Notre objectif est de supprimer les craintes liées à l’achat d’un mobile de seconde main grâce à notre garantie contre la panne et la casse. Il bénéficie d’une garantie… comme dans le neuf ! Enfin une assurance pour protéger les portables d’occasion 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83ecce166933" width="1" height="1" alt=""><hr><p><a href="https://medium.com/moonshot-internet/okazoo-loccasion-a-maintenant-son-assurance-83ecce166933">Okazoo, l’occasion a maintenant son assurance !</a> was originally published in <a href="https://medium.com/moonshot-internet">Moonshot Insurance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey into serverless, part 2]]></title>
            <link>https://medium.com/moonshot-internet/a-journey-into-serverless-part-2-96d39eb45db8?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/96d39eb45db8</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[innovationstartswithyou]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Wed, 24 Apr 2019 13:43:46 GMT</pubDate>
            <atom:updated>2019-04-24T13:52:09.282Z</atom:updated>
            <content:encoded><![CDATA[<h4>A look at our serverless toolbox</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t40_MeHpD55L892RmAGa_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/4dVDBMAho8c?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ricky Kharawala</a> on <a href="https://unsplash.com/search/photos/tools?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The <a href="https://medium.com/moonshot-internet/a-journey-into-serverless-af23e22e08b1">first part</a> of this series described how we gradually built up the CI/CD chain for our serverless APIs and what we learned along the way. However, we left out a lot of details about how the APIs are actually designed, and how we manage common operational topics such as testing, logging, etc. In this part of the series, we’ll be focusing on the tools we use to manage our serverless architecture. So, without further ado, here’s part ✌</p><h3>API architecture</h3><p>In part 1, I briefly mentioned that our API are built out of stock AWS components, mainly API gateway and Lambda functions. Now’s the time for a closer look.</p><p>Here is what a typical API stack looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*--_Tw-pkoWuB7yYILzQqFA.png" /><figcaption>The components of a typical API stack</figcaption></figure><p>The API gateway and Lambda functions, as well as the supporting IAM roles, are bundled in a CloudFormation stack which is deployed from scratch on each change (again, refer to <a href="https://medium.com/moonshot-internet/a-journey-into-serverless-af23e22e08b1">part 1</a> for a complete explanation of the how and why of the immutable approach).</p><p>The public URL of the API points to the currently active stack through a custom domain name mapping; in other words, moving to a new version or rolling back is simply changing a pointer to a different stack. Custom domain names can manage several path mappings, allowing us to expose different versions of an API simultaneously (e.g. /v1 and /v2 can point to 2 different stacks).</p><p>In addition to this stack, DynamoDB tables are used to store persistent data, and we make heavy use of the SSM parameter store both for sensitive information (e.g. API keys) or shared information (for instance, the ID of the currently active stack). Lambda functions call each other directly or use SNS to publish notifications.</p><h3>Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7aahOChZZxNfMInuGUN4w.jpeg" /><figcaption>This is what it feels like to run integration tests on micro-services ( Photo by <a href="https://unsplash.com/photos/3GZi6OpSDcY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nicolas Thomas</a> on <a href="https://unsplash.com/search/photos/testing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>)</figcaption></figure><p>Testing Lambda functions is complicated. Even more so when they act as glue between services, some of which are provided by third parties. How do you test locally? How do you test once you’ve deployed? Should you mock the services your Lambdas are calling, or call the real thing? What about writing to Dynamo, or posting to SNS?</p><p>On this topic, we followed the “different paths, same test” strategy described in <a href="https://hackernoon.com/yubls-road-to-serverless-part-2-testing-and-ci-cd-72b2e583fe64">this post</a>. During tests we call our Lambda functions in one of two different ways: either locally by calling the code directly, or remotely by calling the Lambda function through the API gateway (or through boto for Lambda functions which do not have a public endpoint). This switch is managed by an environment variable, and some helper code that abstracts the different ways to call a lambda function; the test code however is exactly the same for local and remote tests.</p><p>This allows us to write all tests as unit tests; they are run locally before deployment, and remotely, as integration tests, after deployment (but before the stack becomes active).</p><h4>To mock, or not to mock</h4><p>We call third-party services rather than mocking them, since a good deal of our code is about integrating with those services — so we want to catch integration issues or changes in the interface as early as possible. This approach works well in development and staging environments. However, calling third-party services in production creates “real” objects and transactions. We roll these transactions back at the end of the tests and/or isolate them on specific test accounts. But we’re still looking for a better way to manage the trade-off between the safety of systematic integration tests and the risk of creating fake transactions in production.</p><p>Another ongoing area of improvement is how to stub synchronous calls to other internal services. For integration tests this isn’t really an issue, since we want to make sure the platform as a whole works as expected. However, this makes local/unit tests more complex than they should be whenever a Lambda function calls another API: the called service has to be deployed and running on the developer’s account, and there’s some environment fiddling to get the same behavior as what happens in staging or production. And sometimes tests fail due to incorrect behavior in the called service, which is not always easy to track down in the logs. To resolve these issues, we’ve started to mock internal services so that we can have more isolated unit tests.</p><p>Our testing methodology is still a work in progress. The set-up outlined above worked really well when we had small APIs and they were mostly independent. It still holds up well for isolated or loosely coupled services; but as our platform grows and our services become more interconnected, we’re facing new challenges and reviewing how to best handle our unit and integration tests.</p><h3>Logging</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuZ_U9Yr4KuOuKNZSJysXQ.jpeg" /><figcaption>This is what searching through CloudTrail logs feels like (Photo by <a href="https://unsplash.com/photos/o4-YyGi5JBc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glen Noble</a> on <a href="https://unsplash.com/search/photos/log-stack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>)</figcaption></figure><p>Logging is like chocolate: when it is good, it is very, very good; and when it is bad, it is better than nothing. Yes, this is a shameless reboot of a saying originally about documentation and, well… not chocolate.</p><p>Logging is very straightforward in Lambda. You can use the standard logging library, or even just print to stdout, and the logs will end up in AWS’ logging solution Cloudwatch. Unfortunately, Cloudwatch falls in the “better than nothing” category, and comes reeeeally close to the “better off without it” tier. I won’t explain why Cloudwatch is not ideal to explore logs, especially when you have a lot of Lambda functions. If you’ve used it, you know why. And if you haven’t used it… Lucky you, I guess.</p><p>Our first approach to more robust log exploration was to deploy an ELK stack. This is very simple to do with the ELK service provided by Amazon. However, this solution had a few issues for us: it’s not managed; you have to add and manage your own authentication if you don’t want the world to read your logs; and it’s ridiculously easy to over-provision — when we tried it, the default template spun up 4 extra-large VMs (in each of our environments), leading to an invoice where our biggest spend was on *logging* 🤦‍♂️(leading, in turn, to adding billing alarms to our account).</p><h4>Enter Datadog</h4><p>We took a look at different logging/monitoring services and settled on Datadog. Datadog provides monitoring and alerting features which are well integrated with AWS, and since early 2018 has added log management to its features. This allows us to have a comprehensive monitoring dashboard and access to all of our logs in the same place.</p><p>We export our logs to Datadog using the standard log forwarding mechanism (a special Lambda function triggered by all Cloudwatch events). Our Lambda functions follow the naming convention &lt;stage&gt;-&lt;API name&gt;-&lt;Lambda function name&gt;-&lt;stack ID&gt;: adding a simple pattern matching rule to the ingestion pipeline automatically gives us filters on all these attributes. With the full-text search and temporal filters provided out of the box by Datadog, we can explore our logs to our heart’s content.</p><h4>Correlation helps root causation</h4><p>Even with all your logs in the same place and an easy way to sort and search them, it can still be a challenge to debug an issue, especially with a micro-service architecture where requests are passed from Lambda to Lambda. We solved this issue with correlation IDs, which are automatically inserted by AWS in the context of a new request and are passed along from service to service. Grabbing the correlation ID from the context and adding it to the logs makes it trivial to follow an interaction during its entire life cycle, even if it happens to go through several Lambda functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*LeRiuv6FoWFrR0klt4rKLQ.png" /><figcaption>Following a request as it goes through different Lambda functions (each color represents a different Lambda)</figcaption></figure><h3>Managing secrets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*XdGx4qDxRKFn6wJGNtWgMw.png" /><figcaption>How not to manage secrets (image stolen from <a href="https://blog.avira.com/de/passwortmanager-das-unbekannte-wesen/">this blog</a>)</figcaption></figure><p>Environment variables are a breeze to use with Lambda functions, and all serverless frameworks will allow you to configure and populate environment variables out of the box.</p><p>However, environment variables should not be used for everything, and especially not to hold sensitive information! They are usually handled in clear text, stored in configuration files and committed along with the code: there are a lot of ways for these values to leak, and you don’t want the world or even “just” everyone with read access to your Git repo to know the API keys for your payment provider…</p><p>AWS offers the SSM Parameter Store as a simple solution to hold key-value pairs securely. Values can be stored encrypted, with very fine-grained read and write access, making it ideal to manage sensitive information.</p><p>We use Parameter Store with a “namespace” strategy to manage variable scope: each variable name is prefixed either with &lt;API name&gt;_&lt;function name&gt;, &lt;API name&gt;_common or global depending on who can read its content (only a given function, all functions in the API, or everyone). This gives us tiered access rights without having to explicitly configure read rights for each variable.</p><p>Using Parameter Store rather than environment variables does have a performance cost, as the variable must be fetched and deciphered each time. To mitigate this, we use the ssm_cache Python library to cache values in memory, with a custom development to trigger cache invalidation as needed.</p><p>AWS has recently launched the Secrets Manager service, which looks like Parameter Store on steroids — we may move to this new service once we’ve had a chance to test it.</p><h3>Service discovery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsArn5e6HA-4m_hDkNZYuA.jpeg" /><figcaption>Wait, which version of the service should I call? (Photo by <a href="https://unsplash.com/photos/RFId0_7kep4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">N.</a> on <a href="https://unsplash.com/search/photos/n-treasure-hunt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>)</figcaption></figure><p>In the first part of this series, I mentioned that we build and deploy a new stack every time we make a change to an API. Each stack is given a unique name through the use of a commit tag and timestamp.</p><p>Only one stack is active at a time, but we may have several stacks of the same API deployed concurrently. In production, we will usually keep the previous version of each API in addition to the current one should we need to roll back. In staging, it’s common to have several versions around, as each pull request generates a new stack. This raises the question of how to keep track of the active stack.</p><p>The most common way to interact with a stack is through its public service endpoint, which, as described above, points to the active stack via a custom domain name: in this case, there’s no ambiguity in which stack is called. However, it’s also common to call Lambda functions directly. Lambdas can also be triggered by SNS notifications, or DynamoDB streams. In these cases how do we know which stack to use ?</p><p>Once again, SSM Parameter Store to the rescue! We store the active stack for each API in a global parameter, and update this parameter when we change the active stack. This effectively turns the active stack ID into a shared, centralized environment variable.</p><p>This information is used either by the calling Lambda function (to know which function to target), or by the called Lambda function (to determine if it’s active and therefore should react to SNS notifications and such).</p><h3>More serverless goodness</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FzMpCVDWIfMZ0WAqu_Eug.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/SmZWvAkKRVM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Schwartz</a> on <a href="https://unsplash.com/search/photos/candies?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Although the focus of this article is on how we build and host our APIs, this isn’t the only use case for which we’ve found serverless to be a good fit.</p><p>Our websites are hosted on S3 buckets + CloudFront. This set-up is a good fit for static websites, but also (with <a href="https://medium.com/@P_Lessing/single-page-apps-on-aws-part-1-hosting-a-website-on-s3-3c9871f126">a little tweaking</a>) for single page applications. In particular, we’ve built a <a href="https://app.moonshot-internet.com/">customer portal</a> on top of our subscription API, using vue.js for the client-side logic. This design pattern (a single page application backed by an API) works well when your website is basically a GUI to consume existing APIs, but can introduce needless complexity in other scenarios: for instance, when you don’t have an API to start with (and it wouldn’t make sense to build one), or when you don’t need a lot of client-side logic and interaction.</p><p>(Note also that although S3 + Cloudfront is a great way to quickly and cheaply host a website, you need to jump through some hoops to have more control over how your content is served — e.g. you have to set up a Lambda@Edge function <a href="https://aws.amazon.com/blogs/networking-and-content-delivery/adding-http-security-headers-using-lambdaedge-and-amazon-cloudfront/">to add security headers</a>)</p><p>So when we needed a simple back-office website to review complex claims, instead of going the SPA + API route we built a simple Flask app that we bundled in a Lambda function. With a few tweaks to our CI scripts, we were able to include this new application in our existing API deployment process, and <em>voilà</em>, a simple serverless back-office in a few days of work.</p><p>On the back-end, we’ve tested the new <a href="https://aws.amazon.com/blogs/compute/announcing-websocket-apis-in-amazon-api-gateway/">WebSocket API</a> feature from API Gateway, which we use to communicate with our claim-processing bot. It’s still early days for this feature (for instance, there was no initial CloudFormation support for it) but the ability to push notifications from the server to the client really simplifies workflows with long-running server processing, which don’t lend themselves well to traditional HTTP requests.</p><h4>Until next time…</h4><p>Well, this (temporarily) concludes the feedback from our journey into serverless. Our architecture is still very much a work in progress and we expect our tools and processes to keep evolving; for instance, we’ve started using Terraform for new services, and it will probably replace our CloudFormation / Ansible scripts at some point. We will also experiment with new serverless use cases as we develop new services and grow our IT plaform.</p><p>So stay tuned for further updates, and in the meantime if you’d like more details about specific topics drop us a note in the comments section 👇 !</p><p>The Moonshot-Internet IT team</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96d39eb45db8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/moonshot-internet/a-journey-into-serverless-part-2-96d39eb45db8">A journey into serverless, part 2</a> was originally published in <a href="https://medium.com/moonshot-internet">Moonshot Insurance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autopsy of a phishing attempt]]></title>
            <link>https://laurent-leconte.medium.com/autopsy-of-a-phishing-attempt-77aa61b4340a?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/77aa61b4340a</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[phishing]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Fri, 19 Oct 2018 16:56:04 GMT</pubDate>
            <atom:updated>2018-10-22T18:05:06.181Z</atom:updated>
            <content:encoded><![CDATA[<h4>In which I pretend to know stuff about security and email. And whine about Microsoft (although I didn’t mean to when I started to write this post).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAFNRRtbl6pwQMDAOewpZg.png" /><figcaption>Quick, let’s retrieve our messages before Something Bad happens.</figcaption></figure><p>Last week, one of my colleagues received an email that was, well… phishy (see what I did there?).</p><p>He had the right reflex and forwarded the email to the company’s CISO / CTO / general IT guy (i.e. me) rather than click on the link. It was quite obviously a phishing attempt, but I was curious about how this particular one was put together. So, down the rabbit hole I went!</p><h3>The bait</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEq5zPlaDpgZ9BpQvQwjMQ.png" /><figcaption>I can barely read this email. The syncing errors must be really bad (this is how the email is displayed in the Outlook client)</figcaption></figure><p>This investigation began with an email sent by <a href="/service/mailto:microsoft329e71ec88ae4615bbc36ab6ce41109e13@exchange.microsoft.com">microsoft32[…..]13@exchange.microsoft.com</a>, obviously a legit support email address, warning about syncing issues: recent emails couldn’t be delivered because of some passive aggressive server dropping emails. The message is really hard to read in Outlook, which kind of gives the trap away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAFNRRtbl6pwQMDAOewpZg.png" /><figcaption>This is a much more credible phishing email. Still some grammatical errors, though (this is how the message appears in the Outlook web app)</figcaption></figure><p>The same message viewed with Office 365 online (or whatever the cool kids are calling OWA these days) is, however, much more convincing. If it wasn’t for a few grammatical errors, and the weird email address, you could be tempted to click on the link. I don’t know if the Microsoft logo next to the sender is a default icon or if it’s added automatically because of the exchange.microsoft.com domain, but it certainly adds legitimacy to the whole thing.</p><h3>The link</h3><p>Ok, so far we have a pretty decent attempt to get an unsuspecting user to click on a link. With run of the mill phishing attempts, this is where it usually breaks down: they link to some weird looking domain that should send you away running when you see it, something like ms-online-security-support.com.cn. If there’s a sliver of a doubt that the domain may be legit, a WHOIS on the domain name can quickly dispel it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*6dYDhnHV_mKL0IezMLERIg.png" /><figcaption>The link is definitely dodgy, but points to an MS-owned domain.</figcaption></figure><p>In this email, however, the link points to <a href="https://stralab.z13.web.core.windows.net/">stralab.z13.web.core.windows.net</a>. In https, no less. While the sub-domain is definitely strange, the windows.net part is… unexpected. At first I thought it was a homograph attack, but checking the encoding confirms that it’s the real windows.net. Maybe domain squatting then ? Nope, a quick WHOIS shows that this domain name is owned by Microsoft.</p><p>Ar this stage, I admit that I initially thought the attackers had managed to get their content on a machine somewhere in MS-land which had been accidentally left open to the Internet. After some googling it turns out, much to my chagrin, that this isn’t some super-stealthy code injection on an MS-managed server. This is what <a href="https://azure.microsoft.com/fr-fr/blog/azure-storage-static-web-hosting-public-preview/">Azure static website hosting URLs look like</a>.</p><p>So, come to think of it, it is malicious code injection on an MS-managed server exposed to the Internet… But it’s paid for, so that probably makes it all right.</p><h3>The hook</h3><p>By this point I was genuinely curious about the rest of the phish. So I jumped to incognito mode, which is the equivalent of a <a href="https://xkcd.com/649/">static strap</a> for dodgy websites, and followed the link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WohIDCug0G1i5i2hegdmPQ.png" /><figcaption>This looks almost like the real thing! (<a href="http://www.office.com/login">click here</a> to compare — totally not a phishing attempt, I promise)</figcaption></figure><p>The link redirects to a pretty good imitation of the real Microsoft login page. Some details are off, like how the email address of the victim (which is passed through the link) is displayed, and an encoding issue next to the copyright sign. But we are greeted with a green padlock, so everything must be ok, right? And indeed, the certificate is legitimate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Z3wqjE4mAu9PeaFpWCBMg.png" /><figcaption>The dodgy page is secured by a genuine Microsoft certificate. Hurray for wildcards (and Azure static hosting)</figcaption></figure><p>Of course, all this is obvious if you know this is an Azure Storage static website (which I only found out later, so cut me some slack). My gripe is that the URL doesn’t really make this explicit, contrary to e.g. how S3 static hosting URLs look like (&lt;bucket_name&gt;.<strong>s3-website</strong>.&lt;region_name&gt;.<strong>amazonaws</strong>.com). I feel that putting “Azure” somewhere in the URL would make it more obvious.</p><h4>4K 4VR</h4><p>Before we look under the hood, a quick aside on the site appearance. Some details of the fake login page looked a little fuzzy on my 4K laptop screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*GwK0AHfqXpF3mDi8tNGBkQ.png" /><figcaption>Zoom on the fake login dialog. Notice the “Password” placeholder and the email address are sharper than the rest of the text</figcaption></figure><p>As you can see on the close-up above, some text elements, such as the “Password” placeholder, are sharper than others. This doesn’t show up if the page is viewed on a regular HD screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*i0jMnEzLQyKho6_ZHDI_Dw.png" /><figcaption>With regular HD, no discrepancies between the different text elements.</figcaption></figure><p>Also, while we’re looking up close at this dialog box, notice the “Back” and “Sign in” buttons are misaligned by one or two pixels.</p><h4>The code source</h4><p>Enough already with the screenshots and pixels, I hear you say. Show us the code! Well, there you go:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b474f503d9552bf6d723c6424ca0d885/href">https://medium.com/media/b474f503d9552bf6d723c6424ca0d885/href</a></iframe><p>Some fun stuff to note about the content of the page:</p><ul><li>an escaped “Sign in” title and “Password” placeholder —probably to avoid triggering automatic scans or AV/browser detection.</li><li>a password-masking library lifted from a sitepoint tutorial.</li><li>use of the microsoft CDN for the favicon — nicely done 😄</li><li>the entire page, including the form and the buttons, is a collage of png files served from Alibaba Cloud. This explains why it looks fuzzy on 4K screens and why the buttons are misaligned.</li><li>and of course, there’s some really smelly javascript at the bottom of the page. Let’s have a look!</li></ul><h3>The payload</h3><p>The javascript we’re interested in is obfuscated. Let’s start by unescaping it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/143b89187112342b2944660911beb7c3/href">https://medium.com/media/143b89187112342b2944660911beb7c3/href</a></iframe><p>The first eval defines the function j2daedb, and the second eval calls this function with an encrypted payload before writing the result in the document. The function itself splits the payload in two strings, an encrypted message and a key. It then deciphers the message by xoring it with the key.</p><p>Once more unto the breach, dear friends: let’s see what hides in this encrypted payload. In case you’re feeling both curious and lazy, here’s the key used for decryption: 6212839612778 (it doesn’t appear to mean anything, though).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3838faef350f0313c67a92a6b4214188/href">https://medium.com/media/3838faef350f0313c67a92a6b4214188/href</a></iframe><p>Well, now that we’ve gotten to the juicy core of this nugget of obfuscated badness, the payload is straightforward to analyze (and a bit disappointing, to be honest).</p><p>The twoToneButton event listener replaces the “Login” button by a “Loading…” image when clicked, giving the illusion that login is proceeding as usual. There’s some code for #submit and #pass which doesn’t appear to do anything other than identify enter key presses.</p><p>The main event is the sendmails function, which is called directly from the html. This function basically sends the email address and password to a remote server and waits for a response (in case you’re wondering, the remote URL was registered by Alibaba; it was purchased in July). If this response is &quot;donesend&quot;, the user is redirected to the real Microsoft login page. Otherwise, an error message is displayed and the user is invited to try again. I don’t know if the remote server simply stores the sent credentials or tries to login with them before acknowledging the request. But once again, a fair bit of effort was put in making the process inconspicuous.</p><h3>A closer look at the email</h3><p>Now that we’ve seen what happens when a victim clicks on the link and tries to login, let’s go back to how the email was built and how it was sent. First, a quick look at the body of the email (edited for brevity):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a409e5a1340b8edfb6a7e98337df6563/href">https://medium.com/media/a409e5a1340b8edfb6a7e98337df6563/href</a></iframe><p>The main thing to note is that the email content is interspersed by a lot of &lt;font id=&quot;xv&quot;&gt;zu0kI6zuzs3kI6&lt;/font&gt; elements, which looks like an old-school way to get past spam filters. As per the inline css, this should be displayed with font-size:0px , i.e. be invisible. Obviously, Outlook doesn’t follow the CSS standard, which explains why the email looks bad in the desktop client— and much more convincing in the web app.</p><p>This leaves one question: how did this email end up in a mailbox masquerading as a Microsoft support message? Let’s take a look at the email headers to find out. The relevant code is <a href="https://gist.github.com/laurent-leconte/e86c46b8ed7941800c19a11de8cf25e9">here</a> (posted as a link rather than inline, as it’s long and frankly ugly to look at). Making sense of email headers is somewhat of a black art, at least for me, but MxToolbox has a really nice tool for that; here’s how the headers look like in <a href="https://mxtoolbox.com/Public/Tools/EmailHeaders.aspx?huid=5d6d7a32-4589-4352-8e54-a40f7b2bf216">human-readable format</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-NHa102j-tzTwVDvvndVg.png" /><figcaption>The itinerary of the email from sender to victim</figcaption></figure><p>The email originates from an IP in Switzerland; the reverse lookup identifies it as a residential IP address from a Swisscom customer. Interestingly, this IP has already made it into a blacklist, although I wasn’t able to find out if this was before or after the email was sent.</p><p>The entry SMTP relay is controlled by bluewin.ch, which is a Swiss FAI bought by Swisscom a few years back. Taken together, this seems to point to a Swisscom customer’s computer having been compromised and being used, along with the customer’s email account, to send phishing emails.</p><p>From there, the email goes through the O365 SMTP servers without a hitch and lands in the victim’s mailbox. And the curious body formatting allows it to go through spam filters unscathed, as the headers show:</p><pre>X-Bluewin-Spam-Score: 0.00<br>[...]</pre><pre>X-Microsoft-Antispam: BCL:0;PCL:0;RULEID:(7020095)(4652040)(5600074)(711020)(4605076)(4614076)(1401234)(71702078);SRVR:DB6PR0701MB2151;<br>[...]</pre><pre>SpamDiagnosticOutput: 1:99<br>SpamDiagnosticMetadata: NSPM</pre><p>In the snippet above, “PCL” stands for Phishing Confidence Level. So, definitely not a spam or a phishing attempt.</p><p>Luckily, we have SPF and DKIM to protect us from fake sending domains! Right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5yccNzXxDNmrOyhTzf5lg.png" /><figcaption>SPF raises a soft fail, which doesn’t prevent O365 from serving the email.</figcaption></figure><p>No we don’t. SPF configuration for exchange.microsoft.com defaults to a soft fail if the sending address is not recognized, and Outlook doesn’t flag soft fails 😕</p><h3>Final thoughts</h3><p>So there you have it. I spent way too much time looking at this phishing attempt, and writing this post. It was fun to see how it was put together, and depressing to see how mundane the setup is. I was halfway expecting exotic vulns and the mark of an evil genius, and only found common exploits and plodding mediocrity.</p><h4>The good</h4><p>It’s not often that two wrongs make a right, but in this case Outlook failing to display the CSS properly foiled a phishing attempt 😁. Failing that, there’s always typos and grammatical errors to give the game away…</p><p>The effort put into using https and a legit domain name shows that education on “checking for the green padlock” is making headway, thanks in large part to browsers’ more aggressive warnings. Let’s keep it up.</p><h4>The bad</h4><p>This attempt shows how trivial it is to set up a halfway decent phishing website. A static hosting service, some screenshots, a bit of js and you’re done. This is essentially free, and there’s nothing stopping you from just creating a new account if your website gets pulled.</p><p>It also underlines just how easy it is to smuggle bad emails even through large, modern email services. It shouldn’t be this easy to pretend you’re from microsoft.com.</p><h4>The ugly</h4><p>It took more than a week for the phishing website to be pulled after I reported it through Microsoft’s abuse reporting tool. And this only happened after (or at the same time that) it was added to Chrome’s blacklist. So… Next time I’ll submit the URL directly to Chrome and see if this is more efficient.</p><p>Azure websites inheriting from a windows.net URL and SSL certificate… The potential for abuse seems high. People, at least those susceptible to fall for this type of scam, have come to recognize and trust the Windows / Microsoft name and this attack plays fully on that. It’s no coincidence that the phishing email was sent to an O365 email address. On the other hand, these same people are much less likely to trust an Azure URL.</p><p>Microsoft, maybe make the distinction between your online properties more explicit? Or at the very least please recognize that you’re serving potentially malicious code from your own domain name and, you know, <strong>maybe look into abuse reports promptly </strong>rather than, say, after a week. This is, ultimately, your reputation at stake.</p><h3>Post-scriptum</h3><p>This post may come across as Microsoft bashing. It’s not (well, maybe a little bit. Come on, who wouldn’t ?). But you know the old saw: with great power comes great responsibility. Microsoft is a trusted household name. Its attack surface is huge, between Azure and Office 365 and of course, Windows. On the other hand, they have made massive progress on security issues over the last few years, and I was frankly disappointed to see how long it took them to react to this issue. So here’s to hoping that I’m blown away (but in a good way) next time I report a security issue to them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77aa61b4340a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey into serverless]]></title>
            <link>https://medium.com/moonshot-internet/a-journey-into-serverless-af23e22e08b1?source=rss-633ceb9d97f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/af23e22e08b1</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[innovationstartswithyou]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Laurent Leconte]]></dc:creator>
            <pubDate>Wed, 12 Sep 2018 07:58:44 GMT</pubDate>
            <atom:updated>2019-05-20T19:13:41.310Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tools and processes for serverless in production</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzNN0AfoXcZAu0APaF6TcA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/qH36EgNjPJY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alex Siale</a> on <a href="https://unsplash.com/search/photos/winding-path?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A few months ago, we started work on <a href="http://moonshot-internet.com/">Moonshot Internet</a>’s IT platform. From the outset, we made a deliberate choice to leverage the serverless model and see how far we could go with it.</p><p>This article describes how we put this strategy in place, the different iterations we went through, what issues we faced and how we solved them (and what issues remain to be solved!). In other words, I’m going to talk about our process rather than just our current architecture, hence the title 😉.</p><p>Why the journey rather than the destination? This is an attempt to fill the void between the countless serverless tutorials (“Write your First Lambda !!!”) and more advanced articles such as <a href="https://theburningmonk.com/">Yan Cui</a>’s excellent series <a href="https://hackernoon.com/yubls-road-to-serverless-part-1-overview-ca348370acde">Yubl’s road to Serverless</a> (the other inspiration for this article’s title). Hopefully, describing our trials, failures and successes will help others struggling with the same questions.</p><p>The main focus in this article is on our APIs, which nicely illustrate the different topics and follow a very common serverless pattern:</p><ul><li>Route 53 and custom domains are used to route the requests;</li><li>API Gateway exposes the API;</li><li>Lambda functions are used for business logic and custom authentication;</li><li>Data storage is handled by DynamoDB.</li></ul><h3>In the beginning was the console</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gc3tOReZbiksK91T2PRr1g.jpeg" /><figcaption>Not this kind of console (source: www.apiaudio.com)</figcaption></figure><p>Our first step was to create the Lambda functions and API gateway manually, through the AWS console. While this is fine to explore the different configuration options and deploy a quick proof of concept, it doesn’t scale. The process is error-prone; packaging and deploying Lambda functions manually is a pain, and configuring API Gateway is needlessly complicated when you’re not familiar with the service. Even if you are, the terminology and arcane interface can still trip you up: I still don’t know off the top of my head the difference between Method Request and Integration Request… And where do you activate logs again? (answer: in the “Stages” sub-menu. Obviously. 🤔)</p><p>So, once we understood our initial workflow and were comfortable with the basic architecture, we started looking at ways to automate it.</p><h3>In comes Apex</h3><p>We looked at different frameworks and settled on <a href="http://apex.run/">Apex</a>. This framework was a good fit for our initial use case (make changes to a Lambda function, package it and deploy it) while not trying to do too much. Apex also manages environment variables and function settings, aliases, and can be extended via hooks — for instance, <a href="https://github.com/apex/apex/tree/master/_examples/python/functions/dependency">to install Python dependencies before the build step</a>.</p><p>So with Apex and a few shell scripts we now had a much more robust way to deploy our Lambda functions. We use BitBucket for version control, and BitBucket provides a CI/CD tool called <a href="https://bitbucket.org/product/features/pipelines">Pipelines</a>. Armed with our new deployment scripts, we could now deploy and test our Lambda functions with each commit (more on tests in a next article).</p><p>However, managing API Gateway was still highly manual.</p><h3>SAM to the rescue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*u-yZoj4I1xXHTGZoYrsiRQ.jpeg" /><figcaption>Not this Sam.</figcaption></figure><p>SAM is AWS’s <a href="https://github.com/awslabs/serverless-application-model">Serverless Application Model</a>. Simply put, it’s a super-set of the CloudFormation syntax which offers convenient shortcuts for the description and deployment of serverless apps. In particular, it can use Swagger files to configure API Gateway; not only the models and resources (although this is already a big win), but also the integration with Lambda functions and custom authenticators.</p><p>What this means in practice is that you can take your existing Swagger file, complete it with a few x-amazon-apigateway-* descriptors, and just like that your API is deployed and integrated with your Lambda functions with all the correct models and behaviors. No need to worry ever again about how to use the API console 🎉</p><p>Building on SAM, we built a complete CloudFormation template describing our API integration, the Lambda functions, as well as the associated IAM roles, log rules and so on. We now had a way to update our entire stack, and even rebuild it from scratch if the need arose. Infra as code!</p><p>It’s also around this time that we finally threw in the towel and isolated our staging and production platforms in dedicated AWS accounts. Previously we had kept them both in the same account, using Lambda aliases and API stages to distinguish them. But it was becoming increasingly complicated to reason about the release cycle, when to change aliases or which stage should point to which version. Security and keeping the contexts isolated was also a big pain. So we followed AWS best practices and set up a separate account for production, as well as giving each developer their own account. It’s not very expensive, since with a serverless architecture you only get billed for actual usage. And now that we could easily set up new environments by running our CloudFormation scripts, we went nuts 😁</p><h3>Getting containers on board</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kZO8kBIc4hQPRYS-Q47nQ.jpeg" /><figcaption>Not this kind of containers ( Photo by <a href="https://unsplash.com/photos/tjX_sniNzgQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">frank mckenna</a> on <a href="https://unsplash.com/search/photos/containers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>)</figcaption></figure><p>At this stage we only had one API, living in one repo, with all our deployment scripts and templates tucked away in a /infra directory. Then came the day when we started to work on a second API…</p><p>We graduated our CI code to its own repository and created a Docker image containing all the scripts and necessary tooling, while the configuration files stayed in the original repo.</p><p>Separating code from configuration allows us to easily replicate the set-up for new APIs. The Docker image provides a consistent environment whether we run the scripts locally, e.g. when testing on dev accounts, or through the CI server.</p><p>So, to recap. At this stage, about 3 months into building our platform,we used CloudFormation to deploy and update our API gateway and the associated AWS infrastructure (IAM roles, Lambda functions, etc). We deployed our Lambda functions, including their dependencies and environment variables, using Apex. Apex hooks and custom shell scripts were used to run tests before and after deployment. All these scripts and tools were packaged in a Docker image. All neat and tidy and working well… You’re guessing what comes next, right ?</p><h3>Let’s throw everything away and start again from scratch</h3><p>Well, we didn’t throw <em>everything</em> away, but we did make a lot of changes.</p><p>First, the why. Although we had built a functioning, complete set-up, we had a number of pain points that became obvious with use:</p><ul><li>We used different tooling to manage Lambda functions (Apex) and API Gateway (SAM / CloudFormation). This meant in practice that new versions of the Lambda functions were deployed automatically, but changes in the Swagger file required a manual action to upgrade the API Gateway configuration. Also, it prevented us from having a clean, simple rollback process.</li><li>We had a lot of custom shell scripts around Apex. This was a classic case of feature creep: as we added and automated new steps in the CI process, our scripts gradually became more complex and we eventually ended up with a lot of shell code that we were uncomfortable maintaining in the long run.</li><li>Our CloudFormation file was static, which meant copy-pasting whole sections each time we added a new Lambda function.</li></ul><p>Taken separately, we could live with each of these issues. But together, they suggested we should review our tooling choices.</p><p>The first step was to replace the shell scripts by Ansible playbooks, giving us a more modular and easier to maintain CI framework. Switching to Ansible also enabled us to use templates rather than static CloudFormation files; one line in the configuration file is now enough to create all the necessary resources for a new Lambda function. Finally, armed with our templating engine and existing playbooks, we extended the CloudFormation files to handle Lambda deployment as well. This allowed us to remove Apex from the stack and manage all our deployment steps through CloudFormation.</p><h3>Frozen stacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lxifywI10Jt7vTBO-g9xA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/MD6E2Sv__iA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Martin Sanchez</a> on <a href="https://unsplash.com/search/photos/frozen-stack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The more astute readers will have noticed that this latest setup doesn’t address one of the pain points mentioned above: the need for a simple way to roll back. And indeed, while having a single tool and set of playbooks makes it easier to deploy and roll back, it still takes a bit of time to build the CloudFormation package, upload it and run it. Furthermore, the new version can only be tested (in production) after it is live. So if there’s an issue that wasn’t detected in staging, it can potentially break the production platform before we have a chance to identify it.</p><p>To get around these issues we moved to an immutable model: every time we deploy, we create a completely new stack with a unique ID. Once the stack is deployed and tested, we divert the traffic to the new version. If we need to roll back, we can switch back to the previous version by simply changing which stack the custom domain name points to.</p><p>This setup completely removes the notion of “upgrading” an existing deployment: a stack lifecycle is simply deployment -&gt; activation -&gt; deletion. Deploying a new version means rebuilding the entire environment from scratch — no configuration drift, no manual upgrades to keep track of. If a stack builds and deploys in our staging environment, we’re very confident that it will build and deploy in production — the only possible issues come from objects outside of the stack, such as IAM roles for the CI server or persistent storage (DynamoDB tables and SSM Parameter Store in our case).</p><h3>Wrap-up</h3><p>Thanks for making it this far! Here’s a recap of what we learned on our journey (so far) into serverless:</p><ul><li>Infra as code rocks! Use a framework to describe your resources and build/upgrade your infra automatically.</li><li>A single framework/tooling chain is easier to manage than using a collection of tools (duh). We ended up rolling our own framework on top of AWS CloudFormation and Ansible, but do give a look at Serverless and Terraform first! (as to why we didn’t use Serverless ourselves, two words: <a href="https://github.com/serverless/serverless/issues/1847">Swagger</a> <a href="https://forum.serverless.com/t/having-swagger-native-to-serverless-framework/3965">support</a>).</li><li>Use separate AWS accounts for production and staging.</li><li>Actually, go ahead and create accounts for all your developers as well; infra as code makes it easy, and serverless makes it cheap.</li><li>Immutable infrastructure makes it easy to reason about the state of your stacks and how to upgrade. But it brings its own challenges, such as service discovery.</li></ul><h3>Next time…</h3><p>There’s a lot of stuff we haven’t talked about in this article but which are worth sharing. Stay tuned for a next article on some of the challenges we faced and how we solved them (or failed to): unit and integration tests; logging and alerting; managing environment variables — especially sensitive information such as API keys; how to get services to discover each other when every deployment gives them a new unique name…</p><p>Thanks for reading and until next time!</p><p>Update : the next installment is <a href="https://medium.com/moonshot-internet/a-journey-into-serverless-part-2-96d39eb45db8">available here</a></p><p>The Moonshot-Internet IT team</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af23e22e08b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/moonshot-internet/a-journey-into-serverless-af23e22e08b1">A journey into serverless</a> was originally published in <a href="https://medium.com/moonshot-internet">Moonshot Insurance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>