<?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 Alex Tan on Medium]]></title>
        <description><![CDATA[Stories by Alex Tan on Medium]]></description>
        <link>https://medium.com/@alextan?source=rss-305369a04efe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4GHAZQIHif47B1bO.jpg</url>
            <title>Stories by Alex Tan on Medium</title>
            <link>https://medium.com/@alextan?source=rss-305369a04efe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:12:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alextan/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 Outbox Pattern]]></title>
            <link>https://alextan.medium.com/the-outbox-pattern-ba88247c070?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba88247c070</guid>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Thu, 07 Jan 2021 15:19:28 GMT</pubDate>
            <atom:updated>2021-01-07T15:42:06.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDxCSVBD2clQBsHtIHDxaA.jpeg" /></figure><h3>The Assignment</h3><p>Let’s say you are tasked to write a service that handles user registration. Upon registration, two emails will be sent out — one welcome email, and another for confirming the email. How would you design it?</p><h3>Dissecting the Problem</h3><p>Surely it’s not difficult. All we need is just one register function that persists the user, and sends email right? You might be tempted to do so:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252F%25252F%252520Sends%252520emails%252520immediately%252520after%252520creating%252520the%252520user.%25250Afunction%252520register%2528name%25252C%252520email%25252C%252520password%2529%252520%25257B%25250A%252520%252520const%252520user%252520%25253D%252520await%252520createUser%2528name%25252C%252520email%25252C%252520password%2529%25250A%25250A%252520%252520%25252F%25252F%252520BAD%25250A%252520%252520await%252520sendWelcomeEmail%2528user%2529%25250A%252520%252520await%252520sendConfirmationEmail%2528user%2529%25250A%25250A%252520%252520return%252520user%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%25252528171%2525252C%2B184%2525252C%2B195%2525252C%2B1%25252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%25252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%2525252F%2525252F%25252520Sends%25252520emails%25252520immediately%25252520after%25252520creating%25252520the%25252520user.%2525250Afunction%25252520register%252528name%2525252C%25252520email%2525252C%25252520password%252529%25252520%2525257B%2525250A%25252520%25252520const%25252520user%25252520%2525253D%25252520await%25252520createUser%252528name%2525252C%25252520email%2525252C%25252520password%252529%2525250A%2525250A%25252520%25252520%2525252F%2525252F%25252520BAD%2525250A%25252520%25252520await%25252520sendWelcomeEmail%252528user%252529%2525250A%25252520%25252520await%25252520sendConfirmationEmail%252528user%252529%2525250A%2525250A%25252520%25252520return%25252520user%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a0fb0768d6bf61e98f4f0c7dfc5b7c/href">https://medium.com/media/95a0fb0768d6bf61e98f4f0c7dfc5b7c/href</a></iframe><p>While the solution is straightforward, it lacks the following:</p><ul><li><strong>reliability</strong>: If the first email fails to send, how do we retry it? If the second fails, how do we retry it without double-sending the first.</li><li><strong>extensibility</strong>: What if we have additional requirements after the user is created? Adding new lines of code means more room for failure in between.</li></ul><p>In short, we want to be able to repeat the delivery of the email, but at the same time deliver it only once.</p><h3>Investigating Alternatives</h3><h4>Create the user, and then publish the event</h4><p>Here’s another variation, but in the context of event-driven design where an event is published to consumers:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dasync%252520function%252520register%2528name%25252C%252520email%25252C%252520password%2529%252520%25257B%25250A%252520%252520const%252520user%252520%25253D%252520await%252520createUser%2528name%25252C%252520email%25252C%252520password%2529%25250A%252520%252520const%252520event%252520%25253D%252520new%252520UserRegisteredEvent%2528user.id%25252C%252520user.name%25252C%252520user.email%2529%25250A%25250A%252520%252520%25252F%25252F%252520BAD%25250A%252520%252520await%252520publish%2528event%2529%25250A%25250A%252520%252520return%252520user%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%25252528171%2525252C%2B184%2525252C%2B195%2525252C%2B1%25252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%25252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dasync%25252520function%25252520register%252528name%2525252C%25252520email%2525252C%25252520password%252529%25252520%2525257B%2525250A%25252520%25252520const%25252520user%25252520%2525253D%25252520await%25252520createUser%252528name%2525252C%25252520email%2525252C%25252520password%252529%2525250A%25252520%25252520const%25252520event%25252520%2525253D%25252520new%25252520UserRegisteredEvent%252528user.id%2525252C%25252520user.name%2525252C%25252520user.email%252529%2525250A%2525250A%25252520%25252520%2525252F%2525252F%25252520BAD%2525250A%25252520%25252520await%25252520publish%252528event%252529%2525250A%2525250A%25252520%25252520return%25252520user%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f20be52190b94ec0ebbbc2aa454a98/href">https://medium.com/media/40f20be52190b94ec0ebbbc2aa454a98/href</a></iframe><p>However, many things can still go wrong here:</p><ol><li>The server crashed or restarted.</li><li>The message broker may not be available, crashed, or restarted.</li><li>The code that publishes the event failed due to an error.</li></ol><p>All of this leads to the fact that a user may be created, but the message could not be delivered and is lost.</p><h4>Publish the event first, then create the user</h4><p>Reversing the steps (publishing the event, and then creating the user) would not help either:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dasync%252520function%252520register%2528name%25252C%252520email%25252C%252520password%2529%252520%25257B%25250A%252520%252520%25252F%25252F%252520BAD%25250A%252520%252520const%252520userId%252520%25253D%252520uuid.v4%2528%2529%25250A%252520%252520const%252520event%252520%25253D%252520new%252520UserRegisteredEvent%2528userId%25252C%252520name%25252C%252520email%2529%25250A%252520%252520await%252520publish%2528event%2529%25250A%25250A%252520%252520const%252520user%252520%25253D%252520await%252520createUser%2528userId%25252C%252520name%25252C%252520email%25252C%252520password%2529%25250A%252520%252520return%252520user%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%25252528171%2525252C%2B184%2525252C%2B195%2525252C%2B1%25252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%25252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dasync%25252520function%25252520register%252528name%2525252C%25252520email%2525252C%25252520password%252529%25252520%2525257B%2525250A%25252520%25252520%2525252F%2525252F%25252520BAD%2525250A%25252520%25252520const%25252520userId%25252520%2525253D%25252520uuid.v4%252528%252529%2525250A%25252520%25252520const%25252520event%25252520%2525253D%25252520new%25252520UserRegisteredEvent%252528userId%2525252C%25252520name%2525252C%25252520email%252529%2525250A%25252520%25252520await%25252520publish%252528event%252529%2525250A%2525250A%25252520%25252520const%25252520user%25252520%2525253D%25252520await%25252520createUser%252528userId%2525252C%25252520name%2525252C%25252520email%2525252C%25252520password%252529%2525250A%25252520%25252520return%25252520user%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bf43d028f553c1c777f3bceb6b4dedc/href">https://medium.com/media/0bf43d028f553c1c777f3bceb6b4dedc/href</a></iframe><p>Now we need to deal with the following problems:</p><ol><li>Incomplete information like user id. We can generate one on the client-side, but there’s no guarantee it is unique in the database.</li><li>Publishing the event might be successful, but the creation of the user in the database might fail, leaving the system in an incomplete state. The published event would not be able to query the user later.</li></ol><h4>Create the user and publish it in a transaction</h4><p>Putting the operation in a transaction, hoping that the whole operation would be reverted if the publishing fails does not help either:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgbdKNwvXSv-crrRtvtlmQ.png" /></figure><p>It is easy to imagine that the operation above is executed serially, but it is not. This is always a trap, especially when dealing with external infrastructure.</p><ol><li>If the event is published successfully and is picked up by a worker before the transaction is committed, the worker might not be able to query the user for processing. Sure, we can retry them, but at the cost of false-positive errors.</li><li>If the publish takes a long time, the transaction will be open for a long time, slowing performance.</li><li>Complexity increases in the scenario where there are more intermediate steps and multiple events to be published.</li></ol><h4>Implementing the Outbox Pattern</h4><p>The <strong>Outbox Pattern</strong> solves the problem above by persisting the event in the same transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhGEvS6K-M7fNtOC1zc1Rg.png" /></figure><p>With this, both operations are atomic — they succeed together, or fail as a whole. To publish the event, we have another function running in the background that will periodically pull the unprocessed events from the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nv3Yy_D8GM5WyT__TaNlug.png" /></figure><p>Basically, the pool does the following:</p><ol><li>query unpublished/unhandled events</li><li>publish/handle that event</li><li>delete the events from the table</li><li>repeat at every interval</li></ol><h4>How about database trigger?</h4><p>Basically, this step can be further simplified by creating a trigger that will be executed on <em>INSERT</em>, <em>UPDATE,</em> or <em>DELETE</em>. Assuming we have the following tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vlmtvrZnJQPV8T6JqEBaQ.png" /></figure><p>We can create a trigger that persists the event upon creation (the pg_notify is a bonus implementation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvA-Z-QbUzekNJdHG5Zriw.png" /></figure><p>For each table that we want to attach the trigger to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKcNFYpPe9d85vrHJNAOYg.png" /></figure><p>Testing it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXqwFgb1iXnrTyHN5g-Z8Q.png" /></figure><p>However, it is not as flexible as performing the creation of an event in the transaction due to the following reasons:</p><ol><li>We can’t be granular with the event type, and representing the event as CRUD makes it hard when it comes to handling the event processing later.</li><li>Triggers are less visible, compared to writing application code. Not all developers have access to creating triggers too.</li><li>We now need to maintain triggers (adding, deleting, etc) for multiple tables (it’s not maintainable).</li><li>The trigger assumes the event created is tied to the existing table, but it might not always be true. Say if we created an `Order` and wanted to send a user an email, but the event requires data from multiple tables, then we will have to query it later, at the risk of data changes. It would be safer to persist all those information as an event to be processed in the first place.</li><li>We might one to publish multiple events in a single transaction if there are more operations involved.</li></ol><h4>Granularity of events</h4><p>Back to the problem statement above — when the user registers for a new account, we want to perform the following:</p><ol><li>Send welcome email</li><li>Send confirmation email</li></ol><p>In other words, we have two event handlers for a single event UserRegisteredEvent. Keeping them idempotent and ensuring one-time delivery is tricky in this situation. In this case, we should actually split it into two events, WelcomeEmailRequested, ConfirmationEmailRequestedEvent respectively. This will ensure that there is only 1:1 mapping of the event to an event handler which simplifies the processing.</p><p>This idea is similar to having a queue of tasks, and processing them individually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vj6FsCrvIDFVR18AFah7Tg.png" /></figure><p>As opposed to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96-IOsCpj4V0F59vhCpeYA.png" /></figure><p>Of course, we can cache the steps in between, but caching introduce a few problems:</p><ul><li>how long to cache the intermediate steps?</li><li>in-memory cache does not persist if a server restart</li><li>distributed cache adds another dependency, as well as the complexity</li></ul><p>By creating more granular events, we can also parallelize the processing further.</p><p>In other words, the proposed solution would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUg8Rcc8ykFXFaUl-k_7Nw.png" /></figure><h4>Batch vs Stream Processing</h4><p>Above we demonstrated how to perform batch operations by pooling. Alternatively, we can also perform stream processing, by using listen/notify.</p><p>The differences are as follow:</p><ul><li><strong>batch</strong>: we perform the operations in bulk. This is usually for processes that do not require real-time delivery.</li><li><strong>stream</strong>: we perform the operation close to real-time, on individual events.</li></ul><p>The pool function is essentially a batch operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADv78T8ctMesvWBj_xc5fw.png" /></figure><p>By processing the listen/notify, we can stream the event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRApdCGOYttBOENCvzU0hw.png" /></figure><p>Our stream function handles only a single event at a time, and removing them from the database once completed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJcYfzEsqkJ1wlql63cAaQ.png" /></figure><p>If the server restarts, we can always retry it by running the stream periodically to pick up on old events:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3DsetInterval%2528stream%25252C%2525205_000%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3DsetInterval%252528stream%2525252C%252525205_000%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c0328ca623d710c1e9224563d22c041/href">https://medium.com/media/0c0328ca623d710c1e9224563d22c041/href</a></iframe><p>Parallelizing it is easy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dasync%252520function%252520batchStream%2528n%252520%25253D%25252010%2529%252520%25257B%25250A%252520%252520for%252520await%252520%2528let%252520i%252520%25253D%2525200%25253B%252520i%252520%25253C%252520n%25253B%252520i%25252B%25252B%2529%252520%25257B%25250A%252520%252520%252520%252520await%252520stream%2528%2529%25250A%252520%252520%25257D%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dshades-of-purple%26wt%3Dnone%26l%3Djavascript%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dasync%25252520function%25252520batchStream%252528n%25252520%2525253D%2525252010%252529%25252520%2525257B%2525250A%25252520%25252520for%25252520await%25252520%252528let%25252520i%25252520%2525253D%252525200%2525253B%25252520i%25252520%2525253C%25252520n%2525253B%25252520i%2525252B%2525252B%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520await%25252520stream%252528%252529%2525250A%25252520%25252520%2525257D%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecc37ed844824e43a25bb4e607bce925/href">https://medium.com/media/ecc37ed844824e43a25bb4e607bce925/href</a></iframe><p>I hope you find this topic interesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba88247c070" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Makefile 101]]></title>
            <link>https://alextan.medium.com/makefile-101-56ba4590025b?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ba4590025b</guid>
            <category><![CDATA[makefile]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 15:35:44 GMT</pubDate>
            <atom:updated>2020-06-08T05:21:40.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMl9_cwDJG82kApvAB6n3Q.png" /><figcaption>Makefile 101</figcaption></figure><h3>Makefile 101: Useful tips and tricks</h3><p>Here are some useful tips on using Makefile and how to optimize them:</p><h4>Creating a Makefile</h4><p>In order to work with Makefile , we need to create one first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGyuyC1yeF63dkWbxy8suw.png" /></figure><h4>Hello World</h4><p>Let’s start with a basic command. Add this to your Makefile :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kFjfXAU1wYvJ5Vy8mr8KA.png" /></figure><p>Then run make greet . Hurray, you ran your first Makefile command!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMLqzuYBTPe_jBABjWBo8Q.png" /><figcaption>Hello World</figcaption></figure><h4>Chaining Commands</h4><p>Makefile commands can be chained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scbuXq-LIl08etxJfwz1Yw.png" /><figcaption>Chaining Makefile commands</figcaption></figure><p>Running this will produce the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lU4BiFkdyQDWUv988cJr8w.png" /><figcaption>Executing chained commands</figcaption></figure><p>This is especially useful when you have multiple steps involved, e.g. building and deploying a container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG3n3Lr1RtRzo2v5Zqr_-Q.png" /><figcaption>A more complex example of chaining commands with Makefile</figcaption></figure><h4>Suppressing command output</h4><p>To suppress the command being executed, add @ before the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4bKphn7aMMK55UyRMBjIQ.png" /><figcaption>Suppressing command output</figcaption></figure><p>Note the difference between @echo hello command andecho bye command when running $ make greet :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6ACMgenyZT7UeBwY3fAdg.png" /></figure><h4>Using Environment Variables</h4><p>You can pass environment variables into Makefile when running the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X12SnwRx1WJnlVaED1idhQ.png" /><figcaption>Using Environment Variables</figcaption></figure><p>Let’s see what will happen when we run the command while passing in the environment variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rvbPfmnB-8d37Z01EqKKA.png" /><figcaption>Passing environment variables in command</figcaption></figure><p>This is useful if you need to use Makefile to configure builds for certain environment, e.g. ENV=prod make build.</p><h4>Loading environment variables from file</h4><p>Makefile can also load environment variables from .env file. We will touch more on how to load different .env files ( .env.staging, .env.production ) next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FceLKPdEwqP4zPRtKPyFA.png" /><figcaption>Including .env file in Makefile</figcaption></figure><p>If you want to make it optional, add the minus sign before include. Otherwise, an error will occur if the .env file does not exist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EGiH-GBeUSZGJu7q8VEVg.png" /><figcaption>Making .env file optional</figcaption></figure><p>The export will export all available environment variables in the Makefile.</p><blockquote><em>You can include as many </em><em>.env files as you want, the order matters though</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATyolO-YI83_NNt2s38XhA.png" /><figcaption>Including multiple .env files</figcaption></figure><h4>Loading enviroment variables dynamically</h4><p>You can also load environment variables dynamically based on the current environment. The example below assumes that you use the ENV environment variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbRpJzHai2yVy4fkaEfO_g.png" /><figcaption>Including .env files based on existing ENV</figcaption></figure><p>Run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7kRnRqPEch5bLDUQd3gUA.png" /><figcaption>Toggling different environment when running Makefile command</figcaption></figure><h4>Environment guards</h4><p>Say if we only want to ensure that certain command can only be run in certain environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HkRstBRsEjD06BBQf0VOg.png" /><figcaption>Setting up guards for environment variables</figcaption></figure><p>Run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKTDEoZEErVFo9TMpL9-rg.png" /><figcaption>Guard for different environment</figcaption></figure><h4>You can make a CLI with your Makefile</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqSvZFD7EnyfXIoe18P9pg.png" /></figure><p>Just run make without any commands, it will print the command and the description.</p><h4>Useful variables</h4><p>Here are the common variables that might be useful when you are working with Makefiles. Note that to run the shell command, it has to be within the brackets and prefixed with shell, e.g. $(shell git rev-parse HEAD) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBAsM0KzgL5TvKm-a-oMHA.png" /><figcaption>Useful Makefile variables</figcaption></figure><h4>Using dynamic variables in command</h4><p>Sometimes you just want to get dynamic values from your command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTskQzp3l75a6MaNk17bEw.png" /><figcaption>Getting dynamic value from command</figcaption></figure><h4>Modular Makefiles</h4><p>You can separate your Makefiles into smaller Makefiles. This promote reusability, while keeping your Makefile small. Say you have the following Makefiles:</p><p>In database/Makefile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u37MmS62L7sL91geFLPsUQ.png" /><figcaption>database/Makefile</figcaption></figure><p>In docker/Makefile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWVupkiv_WnQdXfnBCc_5w.png" /><figcaption>docker/Makefile</figcaption></figure><p>You can now include them in your main Makefile at the root of your project directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcZs_BqR807wVGdSDO_qhw.png" /><figcaption>Main Makefile</figcaption></figure><p>And you can run all the commands that are available in docker/Makefile and database/Makefile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqldtPrnFgpSVmZMCx_NyQ.png" /><figcaption>Running all commands from combined Makefile</figcaption></figure><p>The only disadvantage is that the naming of the command cannot be the same.</p><p>Hope you find this tips useful! You can also find the README for this article here in my Github Repo: <a href="https://github.com/alextanhongpin/.makefiles/">https://github.com/alextanhongpin/.makefiles/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ba4590025b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservice Health Endpoint]]></title>
            <link>https://alextan.medium.com/microservice-health-endpoint-7bf25310f000?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf25310f000</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[health-endpoint]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 08:06:05 GMT</pubDate>
            <atom:updated>2019-10-06T08:06:05.749Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Health Endpoint 👨‍⚕️</h3><p>Consider the following scenarios:</p><ul><li>You are working on an integration of an API, and you are given an API endpoint, https://api.abc.com/. Now, they did not provide sufficient information on the endpoint, so you figured you will have to take a look at the repository and read the code (assuming it’s a different team from the same company). But you have no clue on how to get there.</li><li>Someone reported a bug in the response API — you took charge of finding and fixing the bug. Your teammate shared that he has fixed the bug and had committed it to the repository. Now both of you are wondering, has the fixed been deployed to production?</li></ul><p>Wouldn’t it be better if our microservice is self-describing, and provide sufficient information that allows us to deal with the scenario above?</p><p>You go to the health endpoint and see the following:</p><pre>GET /health HTTP/1.1<br>{<br> &quot;repo&quot;: &quot;abc/api&quot;,<br> &quot;revision&quot;: &quot;2963648&quot;,<br> &quot;version&quot;: &quot;1.2.0&quot;,<br> &quot;deployed_at&quot;: &quot;Wed Oct 02 2019 14:19:52 GMT+0000 (Coordinated Universal Time)&quot;,<br> &quot;uptime&quot;: &quot;4 days&quot;<br>}</pre><p>Now, you know which git repository to look at, which isabc/api. Also, you can check the last git revision as well as the version that is deployed to the current environment. From the uptime, you now know that no one has deployed the code in the last 4 days. With that, you have more insights into the services that are currently running.</p><h4>What is a health endpoint?</h4><p>Typically, the health endpoint is exposed for the load balancer to check the status of the server before sending requests to it. If the load-balancer detects that a particular server is unhealthy, they would replace the server with a healthy one by spinning a new instance. Above, we are using the same endpoint to provide basic information on the server.</p><h4>Basic API Server Information</h4><p>There are several other information that we could return. Here is an explanation on the response that we returned above, and some other possible additions:</p><ul><li><strong>uptime</strong>: how long has the server been alive, to indicate when the deployment was last done. Human readable relative time.</li><li><strong>deployed_at</strong>: last deployment time, which is the date the server starts running.</li><li><strong>version</strong>: what is the current version of the system</li><li><strong>revision</strong>: the git hash of the system</li><li><strong>build_type</strong>: The type of build, e.g. docker, binary</li><li><strong>build_date</strong>: The date the build was made, especially useful for docker.</li><li><strong>language</strong>: The version of the language used, e.g. go version 1.10, note that this might introduce security risk if the particular version has security vulnerabilities.</li><li><strong>environment</strong>: e.g. staging, production, etc. Normally this can be derived from the subdomain (staging.abc.api for staging, abc.api for production).</li></ul><p>Are you using this too for your team? What do you think can be improved on this? 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf25310f000" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker and Go 1.11 modules]]></title>
            <link>https://alextan.medium.com/docker-and-go-1-11-modules-a96fcad262df?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96fcad262df</guid>
            <category><![CDATA[go-modules]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 17:51:00 GMT</pubDate>
            <atom:updated>2018-09-09T06:51:31.656Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a simple guide on how to <em>dockerize</em> a golang binary in go1.11 with the vendor directories. By default go command will completely ignore vendor directories. But enabling the build using the vendor directory would speed up build a lot, especially when running inside Docker, as you do not need to fetch the dependencies anymore.</p><p>View the guide here:</p><p><a href="https://github.com/alextanhongpin/go-modules">alextanhongpin/go-modules</a></p><p>Another guide for gRPC:</p><p><a href="https://github.com/alextanhongpin/go-grpc-modules">alextanhongpin/go-grpc-modules</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96fcad262df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Circuit Breaker in Microservices]]></title>
            <link>https://alextan.medium.com/circuit-breaker-in-microservices-d32068fb568e?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d32068fb568e</guid>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 15:05:12 GMT</pubDate>
            <atom:updated>2018-08-23T15:08:15.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0a7Kyynwa7Qd5SFAjsO8OQ.jpeg" /></figure><p>I have seen a lot of presentation on circuit-breakers - on how successful it was when Company X or Company Y applied it in services. Yet, I have always asked myself this question — is circuit breaker really practical in an auto-scaling environment? That question was never really answered by those who presented it, and a lot of examples were demonstrated on a single node that was run locally.</p><p>I may be wrong, but there are two ways to apply circuit-breaker to your application — <strong>application level</strong> (a.k.a thick client, placing all the logics on your application, typical in monolith application) or <strong>infrastructure level</strong> (think Linkerd2, Envoy, Traefik etc).</p><p>For <strong>application level</strong>, you would normally use existing solutions such as <a href="https://github.com/Netflix/Hystrix/wiki/How-it-Works"><em>Hystrix</em></a> and attach it as a middleware. But this can be limiting, since it is hard to find equivalent libraries in other languages (Hystrix is Java-based). The go’s equivalent for example, <a href="https://github.com/afex/hystrix-go">hystrix-go</a> does not have a dashboard comparable to Java’s Hystrix. And what if you need a library for Rust? Tough luck. Microservices are supposed to be heterogenous.</p><p>Let’s imagine if we have such application with circuit-breaker baked in, and we scaled it so that we have 10 instances behind a load balancer. If you are distributing 1000 requests evenly among this 10 instances, such that each would receive 100 requests, what would happen when one of them trip? It would most likely <em>reject</em> incoming requests. But the desired outcome would be to stop sending requests altogether to that instance (correct me if I am wrong). Since the state of the circuit-breaker is <em>local </em>with respect to the application, there’s no way to prevent sending the requests to the application. So each instance would still be receiving 100 requests, one would reject all requests until it recovered.</p><p>By placing the circuit-breaker in the <strong>infrastructure</strong>-level, we could achieve what is called <em>latency-aware</em> load-balancing. Services that exceeds certain error threshold would not receive requests until they recovered as the requests are distributed evenly to other healthy services. Also, by moving the logic outside of the application, it becomes much easier to configure the circuit-breaker for your applications. Any microservices written in any languages can share the same configuration without adding a single line of code. Most modern service mesh has circuit-breaker capabilities baked-in, as well as other features (retry, gRPC-load balancing etc, rate-limit) and a centralized dashboard for monitoring.</p><p>That is my two cents on circuit-breakers in an auto-scaling environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d32068fb568e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC Load Balancing with Nginx]]></title>
            <link>https://alextan.medium.com/grpc-load-balancing-with-nginx-673d5d4df708?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/673d5d4df708</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nginx-grpc]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 14:24:06 GMT</pubDate>
            <atom:updated>2018-04-11T14:24:06.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Nginx recent release finally has native support for gRPC. It is a nice addition to existing tools such as Linkerd, Traefik, Envoy etc, but with much simpler configuration. 😄If you have tried Linkerd (which has an awesome dashboard!), you would definitely have agreed.</p><p>To test it out, we have a simple gRPC Echo service that will ingeniously return the text that is receives.</p><p>Our <em>docker-compose.yml </em>file would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6QSSeHMdqRD8-QFWn2B8g.png" /><figcaption>docker-compose.yml</figcaption></figure><p>We have two gRPC servers running, a client and nginx.</p><p>The <em>nginx.conf</em> is rather simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGUjw8GMQ01dqVpLhLHGAA.png" /><figcaption>nginx.conf</figcaption></figure><p>Running <em>docker-compose up -d </em>will give us the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCc3x_uwL8TGYE50Kl0sGQ.png" /><figcaption>gRPC client logs</figcaption></figure><p>As you can see, the client manage to call the servers with different hostnames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkYAKYA7v6vmUV8b3-5Fvg.png" /><figcaption>nginx logs</figcaption></figure><p>You can find the full repository here: <a href="https://github.com/alextanhongpin/grpc-nginx-docker">https://github.com/alextanhongpin/grpc-nginx-docker</a></p><p>😄 Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=673d5d4df708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 things I learnt about Go]]></title>
            <link>https://alextan.medium.com/10-things-i-learnt-about-go-6c208247d995?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c208247d995</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Sat, 09 Sep 2017 01:14:41 GMT</pubDate>
            <atom:updated>2017-09-09T01:35:39.261Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. There’s no round function for numbers</h3><p>If you want to round numbers in go, you have to implement it yourself, that is, until <a href="https://github.com/golang/go/issues/20100">go 1.10</a> is released.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2c88445539ec515fcdb49e6b15c620a/href">https://medium.com/media/b2c88445539ec515fcdb49e6b15c620a/href</a></iframe><h3>2. There’s no reverse string function</h3><p>Again, it’s weird that go lacks something as simple as a reverse string function. But there are times when you actually need it. Here&#39;s how you can do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f9b7982fd655d1d1fb439e588ad86e8/href">https://medium.com/media/7f9b7982fd655d1d1fb439e588ad86e8/href</a></iframe><h3>3. Writing to a JSON file</h3><p>Marshalling is the process of converting domain objects to a serialized format, such as json. In order to write a golang struct to a json file, you need to marshal it first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d60b0cb00b5b7fd7b95e24273faaf173/href">https://medium.com/media/d60b0cb00b5b7fd7b95e24273faaf173/href</a></iframe><p>If you set pretty to true, it will be saved in a more readable format. This is how our output json will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be7a83f2bced125275738ec3f9b80eb/href">https://medium.com/media/9be7a83f2bced125275738ec3f9b80eb/href</a></iframe><h3>4. Loading a JSON file</h3><p>Unmarshalling is the process of converting domain objects from a serialized format, such as json. To load the json file to our golang struct, we have to unmarshal the json data:</p><p><a href="https://gist.github.com/alextanhongpin/12ca8509a51e9d11b26460aa2daa0b2c.js">https://gist.github.com/alextanhongpin/12ca8509a51e9d11b26460aa2daa0b2c.js</a></p><p>This is the json file we are loading:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d815fab3e5235f6302160b5a4fe724b7/href">https://medium.com/media/d815fab3e5235f6302160b5a4fe724b7/href</a></iframe><h3>5. Mapping map to structs</h3><p>In case you need to map golang map to structs, there is a library for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03efd4f9f9df12f841115f45d1f6f159/href">https://medium.com/media/03efd4f9f9df12f841115f45d1f6f159/href</a></iframe><h3>6. Shadowing fields</h3><p>There are times where you want to hide certain fields from the golang struct before returning it as a json response, but not with the json:&quot;-&quot; approach. The example below shows how you remove the <em>password</em> field from the original struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/966d42588aa7818a205c5a22eeaab877/href">https://medium.com/media/966d42588aa7818a205c5a22eeaab877/href</a></iframe><h3>7. Composing struct</h3><p>When returning a json response, you might want to return fields from other structs, but want to avoid creating too many of them. One way to achieve this is by composition - you compose a new struct by embedding other structs and you choose to exclude the fields too through <strong>shadowing</strong> (see previous example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/338d18ea4bfc46b2d6de073b51de500f/href">https://medium.com/media/338d18ea4bfc46b2d6de073b51de500f/href</a></iframe><h3>8. Overwriting tag names</h3><p>The name of the fields returned in the json is based on the json tag in your struct. You can overwrite them if you want your json response to have different field name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6706b7b483e0fecf1c3f371c56e32fa9/href">https://medium.com/media/6706b7b483e0fecf1c3f371c56e32fa9/href</a></iframe><h3>9. Concatenating arrays</h3><p>It’s probably wasn’t that obvious, but concatenating array can be easily done as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff70e6223fd1dcfbbb5557ae66f297c6/href">https://medium.com/media/ff70e6223fd1dcfbbb5557ae66f297c6/href</a></iframe><p>Note that both arrays must be of the same type. Appending a string array to an int array will result in an error.</p><h3>10. It’s fast</h3><p>Here’s a benchmark of a “hello world” request using <a href="https://github.com/wg/wrk">wrk</a>. View the full report below:</p><p>1 threads and 1 connections:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bd12bc36703133a8e4735fb7ace0daf/href">https://medium.com/media/7bd12bc36703133a8e4735fb7ace0daf/href</a></iframe><p>Similar test carried out with 10 threads and 10 connections:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7eecfabc2204c1e089d74dbfe60c329/href">https://medium.com/media/e7eecfabc2204c1e089d74dbfe60c329/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c208247d995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Stage Docker build for Go]]></title>
            <link>https://alextan.medium.com/multi-stage-docker-build-for-go-311680e02e9b?source=rss-305369a04efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/311680e02e9b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[multi-stage-builds]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Alex Tan]]></dc:creator>
            <pubDate>Mon, 04 Sep 2017 05:06:47 GMT</pubDate>
            <atom:updated>2017-09-04T05:06:47.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>Dockerize your golang app easily with the new multi-stage builds from Docker 17.05. Reduce deployment steps and produce smaller, optimized builds.</p><h3>Audience:</h3><ul><li>You want to know how to Dockerize your Golang app</li><li>You want your Docker image to be as small as possible</li><li>You want to know how multi-stage docker build works and the pros</li></ul><h3>References:</h3><ul><li>The example can be found in the Github repo <a href="https://github.com/alextanhongpin/go-docker-multi-stage-build">here</a></li></ul><h3>Highlights</h3><ul><li>You will first build a docker image using only the Docker golang base image, and observe the outcome. For simplicity, our program will just output <strong>”hello, go”</strong></li><li>Then, you will learn how to build a more optimized docker image, but requires separate commands</li><li>Finally, we will demonstrate how multi-stage build can simplify our process</li></ul><h3>Guide</h3><h3>Setup</h3><p>You need to have golang and a minimum version of docker 17.05 installed in order to run this demo. You can check the version of your dependencies as shown below: Validating <strong>go</strong> version: <a href="https://gist.github.com/5e74c2ee01840a350ef720e7db5346d5">https://gist.github.com/5e74c2ee01840a350ef720e7db5346d5</a></p><p>Validating <strong>Docker</strong> version: <a href="https://gist.github.com/36417cafdeda115742b0fdde99361c0e">https://gist.github.com/36417cafdeda115742b0fdde99361c0e</a></p><h3>The golang program</h3><p>The main.go contains our application logic. It does nothing but print Hello, go!. <a href="https://gist.github.com/f3f011ab9f1567f766c394d5812c3ac3">https://gist.github.com/f3f011ab9f1567f766c394d5812c3ac3</a></p><p>Now that we have our application, let’s dockerize it!</p><h3>Method 1: Using the Golang image</h3><p>The steps in Dockerfile.00 is as follow:</p><ol><li>We select the golang:1.9 image</li><li>We create a workdir called hello-world</li><li>We copy the file into the following directory</li><li>We get all the dependencies required by our application</li><li>We compile our application to produce a static binary called app</li><li>We run our binary <a href="https://gist.github.com/e05ad186f077213da49b5253f00a32eb">https://gist.github.com/e05ad186f077213da49b5253f00a32eb</a></li></ol><p>Let’s build an image called alextanhongpin/hello-world-00 out of it. You can use your Github username instead when building the image. <a href="https://gist.github.com/5257c56e80e3587806c36a7afb41c90b">https://gist.github.com/5257c56e80e3587806c36a7afb41c90b</a></p><p>We will run our docker image to validate that it is working: <a href="https://gist.github.com/04f18d7ebd5f32d5a9f3c5d61d8ccf8a">https://gist.github.com/04f18d7ebd5f32d5a9f3c5d61d8ccf8a</a></p><p>Let’s take a look at the image size that is produced: <a href="https://gist.github.com/aeae060a1d869dc74aa71e2374fdeb86">https://gist.github.com/aeae060a1d869dc74aa71e2374fdeb86</a></p><p>We have a 729MB image for a simple Hello, go!! What can we do to minimize it? That brings us to next step…</p><h3>Method 2: Build locally</h3><p>The reduce the size, we can try to compile our main.go locally and copy the executable to an alpine image — the size should be smaller since it contains only our executable, but without the <strong>go runtime</strong>. Let’s compile our main.go: <a href="https://gist.github.com/b0a0887082b43d104b42164c6aca378d">https://gist.github.com/b0a0887082b43d104b42164c6aca378d</a></p><p>Dockerfile.01 contains the step to build our second image: <a href="https://gist.github.com/9bbd19a6dfb4f7bdf5e97d157142e38d">https://gist.github.com/9bbd19a6dfb4f7bdf5e97d157142e38d</a></p><p>All it does is copy our compiled binary to an <strong>alpine</strong> image. We will build the image with the following command: <a href="https://gist.github.com/93ddcb0bfec31964a52e347f778e4d9b">https://gist.github.com/93ddcb0bfec31964a52e347f778e4d9b</a></p><p>Let’s validate it again as we did before and view the change in the size: <a href="https://gist.github.com/7bfdd2df17150aac0f79af12d8f28ced">https://gist.github.com/7bfdd2df17150aac0f79af12d8f28ced</a></p><p>Let’s take a look at the image size: <a href="https://gist.github.com/57b7a974f5650e4ae796b43d77aba22d">https://gist.github.com/57b7a974f5650e4ae796b43d77aba22d</a></p><p>We can see that the size has reduced dramatically from 729MB to 6.55MB. This however, involves two different step — compiling the binary locally and create a docker image. The next section will demonstrate how you can reduce this to a single step.</p><h3>Method 3: Using multi-stage build</h3><p>Multi-stage buil is a new feature in Docker 17.05 and allows you to optimize your Dockerfiles. With it, we can reduce our build into a single step. This is how our Dockerfile will look like: <a href="https://gist.github.com/a730a9bc81d798de806b827191a14379">https://gist.github.com/a730a9bc81d798de806b827191a14379</a></p><p>Let’s build and observe the magic: <a href="https://gist.github.com/7327de52ef39e5eeff4df0b73a0d4a36">https://gist.github.com/7327de52ef39e5eeff4df0b73a0d4a36</a></p><p><a href="https://gist.github.com/2a1285794fd911404692f187c3cb7156">https://gist.github.com/2a1285794fd911404692f187c3cb7156</a></p><p>You can now build your golang image in a single step. The output is shown below: <a href="https://gist.github.com/77dde3e92d1ad6a39ce2092881fa8e93">https://gist.github.com/77dde3e92d1ad6a39ce2092881fa8e93</a></p><p><em>Originally published at </em><a href="https://gist.github.com/8bc1b6301b939dcf0314b7136061b813"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311680e02e9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>