<?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 Talha M on Medium]]></title>
        <description><![CDATA[Stories by Talha M on Medium]]></description>
        <link>https://medium.com/@talham7391?source=rss-aeb11c1cc00b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3RyrzMtN98IuiVVFVVvIhw.jpeg</url>
            <title>Stories by Talha M on Medium</title>
            <link>https://medium.com/@talham7391?source=rss-aeb11c1cc00b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:41:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@talham7391/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[Animate Your Landing Page with Alpine.js]]></title>
            <link>https://medium.com/@talham7391/animate-your-landing-page-with-alpine-js-0cc2910114f9?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc2910114f9</guid>
            <category><![CDATA[landing-pages]]></category>
            <category><![CDATA[alpinejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 23:12:05 GMT</pubDate>
            <atom:updated>2024-12-01T23:12:05.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Animation Preview" src="https://cdn-images-1.medium.com/max/640/1*A4Y0QpWb9DKXihf3kpoRig.gif" /><figcaption>Animation Preview</figcaption></figure><h3>Step 1 — Dependencies</h3><p>Add Alpine.js to your &lt;head&gt; tag in your html file:</p><pre>&lt;script defer src=&quot;https://cdn.jsdelivr.net/npm/alpinejs@3.14.3/dist/cdn.min.js&quot;&gt;&lt;/script&gt;</pre><h3>Step 2 — Setup</h3><p>Create a new script tag and write a custom Alpine.js directive. Directives allow us to reuse our fade animation:</p><pre>&lt;script&gt;<br>  document.addEventListener(&quot;alpine:init&quot;, () =&gt; {<br>    Alpine.directive(&quot;reveal&quot;, (el) =&gt; {<br>      // custom code goes here<br>      console.log(&quot;test&quot;)<br>    })<br>  })<br>&lt;/script&gt;</pre><p>Apply the directive to the element you’d like to animate:</p><pre>&lt;div x-data x-reveal&gt;<br>  &lt;img src=&quot;...&quot;/&gt;<br>&lt;/div&gt;</pre><p>Note, the x-reveal attribute only works when the x-data attribute is present.</p><p>We also need to add some CSS to hide the element on page load. We’ll unhide the element using our directive later on:</p><pre>[x-reveal] {<br>  position: relative;<br>  top: 50px;<br>  opacity: 0;<br>}</pre><h3>Step 3— Code</h3><p>Try reloading the page to ensure everything is setup properly. Your element should be invisible, and you should see a log statement in your console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*4MRj3vnuZ0nn7zIGou1SNw.png" /></figure><p>Now we’ll write the code the reveals the element:</p><pre>&lt;script&gt;<br>  document.addEventListener(&quot;alpine:init&quot;, () =&gt; {<br>    Alpine.directive(&quot;reveal&quot;, (el, {}, { cleanup }) =&gt; {<br>      const callback = () =&gt; {<br>        // Check if the element is within 70% of the screen<br>        const position = el.offsetTop - window.scrollY<br>        const threshold = window.scrollY + window.innerHeight * 0.7<br>        const reveal = position &lt; threshold<br><br>        // Ignore if the element doesn&#39;t reach the threshold<br>        if (!reveal) {<br>          return<br>        }<br><br>        // Add css classes to set the opacity to 100 and the offset to 0<br>        // We also use a 0.2 second delay<br>        setTimeout(() =&gt; {<br>          el.classList.add(<br>            &quot;!opacity-100&quot;,<br>            &quot;!top-0&quot;,<br>            &quot;transition-all&quot;,<br>            &quot;duration-300&quot;,<br>          )<br>        }, 200)<br>      }<br><br>      setTimeout(() =&gt; callback(), 0)<br><br>      // Setup to reveal the element when the user scrolls<br>      window.addEventListener(&quot;scroll&quot;, callback)<br>      cleanup(() =&gt; {<br>        window.removeEventListener(&quot;scroll&quot;, callback)<br>      })<br>    })<br>  })<br>&lt;/script&gt;</pre><h4>Notes</h4><ul><li>I’m using a 70% threshold, but it can be adjusted if you’d like the element to fade in sooner or later.</li><li>!opacity-100 is a tailwindcss class. If you’re not using tailwind you can also modify the element styles manually via el.styles.</li></ul><h3>Final Result</h3><figure><img alt="Animation Preview" src="https://cdn-images-1.medium.com/max/640/1*A4Y0QpWb9DKXihf3kpoRig.gif" /></figure><p>If you have any questions, message me on X @ <a href="https://x.com/talhamtech">talhamtech</a></p><p>And here’s the website if you’re curious: <a href="https://declutter.work/">declutter.work</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc2910114f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Graph Based Access Control?]]></title>
            <link>https://medium.com/@talham7391/what-is-graph-based-access-control-76f097cee23f?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/76f097cee23f</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[gbac]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Sun, 29 May 2022 18:58:09 GMT</pubDate>
            <atom:updated>2022-05-30T22:47:32.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAYoJkqJ4AF3IJ5ocv8-eA.png" /></figure><p>The 2 most common access control paradigms are RBAC and ABAC.</p><p><strong>RBAC</strong> — Role based access control.</p><p><strong>ABAC</strong> — Attribute based access control.</p><p>Organizations will employ both paradigms depending on their application maturity and use cases. However, under certain circumstances, RBAC and ABAC start to fail. That’s when an organization may consider adopting a GBAC system (and why we’ve built <a href="https://graphbac.com/?source=whatisgbac">graphbac</a>).</p><p><strong>GBAC</strong> — Graph based access control.</p><p>Every access control paradigm has an underlying data model. GBAC systems are built using the graph data model, giving developers access to efficient traversal algorithms. For this reason, GBAC systems work extremely well when applications need to exercise access control on highly nested data.</p><h3>Example of GBAC</h3><p>Facebook is an excellent example of graph based access control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0kX6jNcm9UNeCP2X" /></figure><p>At the time of writing, users on Facebook have the following options to control who they receive friend requests from:</p><ul><li>Everyone</li><li>Friends of friends</li></ul><p>If you’ve selected the “Friends of friends” option, Facebook’s access control system will hide the “Send Friend Request” button from complete strangers.</p><p>Facebook is able to offer the preceding feature because all users become nodes on a graph related to one another via “friend” relationships. The access control system uses the graph to service requests.</p><h3>Do I need to use GBAC?</h3><p>Access control systems are meant to answer questions:</p><ul><li>Can Bob access a private document created by Lisa?</li></ul><p>Every access control system runs code to find the answer. That code can be isolated to a service, it can be sprinkled throughout the codebase, it can be delegated as a query to the database, etc… RBAC / ABAC / GBAC are theoretical paradigms; the code is the application of the paradigm, usually deemed the “Authorization Service” or “Authorization System”.</p><p>Paradigm applications will work across 3 verticals to come up with an answer:</p><ul><li>Classification (e.g. Bob is a Manager)</li><li>Business Logic (e.g. A newManager may access private documents after 3 months of probation)</li><li>Relationships (e.g. A Manager should have access to all documents created by a reporting Employee)</li></ul><p>Generally speaking, each access control paradigm has varying levels of competency in each vertical:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wn9p1eucKIWIiwgDub6nKQ.png" /></figure><p>If the paradigm you decide to adopt doesn’t support a vertical that’s central to the types of authorization questions you plan on asking, its up to your software / developers to build out the missing functionality.</p><p>Suppose you’ve employed an RBAC system for user account management. The product owner discovers a new business use case:</p><blockquote>After 5 failed login attempts, users must wait 24 hours before they can make another login attempt.</blockquote><p>Unfortunately, the RBAC system doesn’t support business logic, so it cannot answer the following question:</p><ul><li>Is user X authorized to login?</li></ul><p>The only option is to support “Business Logic” in your application code even though it’s something that concerns authorization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbabe3d7221056438d704b51fa59dbc4/href">https://medium.com/media/cbabe3d7221056438d704b51fa59dbc4/href</a></iframe><p>In an effort to support a business use case, we’ve broken the single responsibility principle and our authorization system is no longer encapsulated. Of course, had we employed a ABAC system, our authorization logic would remain isolated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46b949d6dff033a7b8669a9486a0bc27/href">https://medium.com/media/46b949d6dff033a7b8669a9486a0bc27/href</a></iframe><p>Similarly, there are authorization questions that force developers to support “Relationships” with respect to authorization in the application code, resulting in the same outcomes described above.</p><p>For example, the product owner discovers yet another use case:</p><blockquote>If a user is deactivated, they may be reactivated by anyone the user directly or indirectly reports to. (Assistant Manager, Manager, Senior Manager, etc…)</blockquote><p>Supporting the preceding use case will warrant more than just breaking encapsulation. Most applications use either SQL databases, key-value stores, or document stores, all of which aren’t designed for relationship traversal. The business must now bare the cost of poor authorization performance. A problem that’s exasperated as use cases grow in count and complexity.</p><p>After choosing the wrong paradigm, organizations will continue to support complex use cases by modifying the application code.</p><p>Theres comes a time when supporting additional use cases becomes too expensive for the business and too painful for the developers. After lengthy deliberation, everyone decides to invest in a costly, error-prone migration to a new authorization system that uses a different access control paradigm.</p><p>Many engineering departments have fallen victim to the preceding inevitability. It’s important to understand what questions you plan on asking your authorization system today and what questions you might ask in the future in order to choose the paradigm that’s right for your business.</p><p>We’ve listed example use cases that are well served by GBAC to help you assess if your application makes relationship based authorization queries:</p><h4>Document Sharing</h4><blockquote>A user that’s given access to a folder should be given access to all descending documents.</blockquote><h4>Corporate Structures</h4><blockquote>A district manager should have the same authority as all reporting managers; A manager should have the same authority as all reporting employees.</blockquote><h4>Social Networking</h4><blockquote>A user should be able to view posts created by friends or friends of friends.</blockquote><h3>Summary</h3><ul><li>GBAC is great for serving authorization requests that rely on deeply nested data.</li><li>To choose the access control paradigm that’s right for your business, consider the authorization questions you plan on asking. If the questions rely on business logic, use ABAC. If the questions rely on relationships or nested data, use GBAC. If simple classification is enough, use RBAC.</li><li>If it’s painful to modify or extend your current authorization system, it may be a sign you’ve chosen the wrong paradigm.</li><li>If developers find themselves building functionality to supplement the shortcomings of your authorization system, it may be a sign you’ve chosen the wrong paradigm.</li><li>If your application is experiencing poor authorization performance, it may a sign you’ve chosen the wrong paradigm.</li><li>Strongly consider adopting GBAC for use cases that depend on relationships between people or relationship between objects. Example domains include (but aren’t limited to) document sharing, corporate structures, and social networking.</li></ul><p>If you’re looking for a GBAC solution, check out <a href="https://graphbac.com/?source=whatisgbac">graphbac</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76f097cee23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Help Developers Sleep at Night]]></title>
            <link>https://medium.com/better-programming/how-i-help-developers-sleep-at-night-69cb70a9f018?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/69cb70a9f018</guid>
            <category><![CDATA[progamming]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 21:01:15 GMT</pubDate>
            <atom:updated>2020-11-07T19:28:14.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Case Study on Dealing with a Noisy Load Balancer Alarm</h3><h4>How to diagnose and resolve load balancer issues</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SqZN0A-OU-xiRgUf" /><figcaption>Photo by <a href="https://unsplash.com/@yokeboy?utm_source=medium&amp;utm_medium=referral">Yeo Khee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>To deliver a highly available application, it’s standard practice to set up alarms that get triggered if something goes wrong. Alarms may be triggered by:</p><ul><li>An instance with high CPU or memory usage</li><li>Exceptions or non-zero exit codes</li><li>A high number of HTTP error status codes</li></ul><p>Good alarms are actionable; otherwise, important issues may be masked by seemingly unimportant alerts and get swept under the rug. Alarms that are alerted often under irrelevant circumstances are considered <em>noisy</em>. To reduce the cognitive load on developers and first responders, it’s important irrelevant circumstances don’t spawn alerts.</p><p>As of late, our AWS application load balancer has been generating a lot of 504 and 502 error codes which have triggered an alarm a handful of times. We didn’t see any smoking guns during our investigation, and everything seemed to be fine. We realized this alarm had become noisy.</p><p>In this article, I’ll talk about the steps we took to bring the alarm back to a healthy state. Who’ll benefit from this article:</p><ul><li>People interested in network configurations for REST services</li><li>Developers that lack experience with infrastructure and want exposure. This exercise is an excellent example of the kind of work developers on platform, DevOps, and site reliability teams do.</li></ul><h3>Terminology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*RPmt6232JmLd1NBYEICGdw.png" /><figcaption>A load balancer reverse proxying to multiple servers (Image source: Author)</figcaption></figure><p><strong>Load balancer </strong>— A load balancer is an architectural component that distributes requests amongst a group of servers so that no one server is overwhelmed.</p><p><strong>Upstream service</strong> — An upstream service refers to one or more servers that are running the same business logic. In the diagram above, Servers A, B, and C form an upstream service (from the perspective of the load balancer).</p><h3>The Reaction</h3><p>The process is started with an ELB_5XX alarm notification from PagerDuty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB83B4l_PLae0_K9F1pUaw.png" /><figcaption>Slack notification triggered by our PagerDuty integration</figcaption></figure><p>Before we resolve the issue, we need to see if there are any immediate steps we can take to reduce the level of service degradation experienced by users. We’ve written “run books” for different failure scenarios that help us expedite the process. The link to the appropriate run book is included in the description of the triggered alarm. The first responder simply needs to follow the run book, which usually has the following structure:</p><ul><li>Are upstream servers experiencing high CPU or memory usage? If so, increase the number of servers to cope with the load.</li><li>Is only one upstream server experiencing high CPU or memory usage? If so, kill that server and replace it with a new one.</li><li>Check upstream logs. Are the alarms originating from the same server? If so, kill that server and replace it with a new one.</li><li>And so on…</li></ul><p>A few things to note about run books:</p><ul><li>The instructions are extremely simple.</li><li>The steps are sequential and easily followed.</li><li>They are designed to help first responders systematically resolve the issue.</li></ul><p>In our case, the associated run book didn’t result in a resolution, and our dashboards didn’t show any error/warning signs. During our investigation, the alarm auto-resolved, and the 502 errors went away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMIoF34nfOGnopvD2iV00w.png" /><figcaption>5XX error count from our elastic load balancer</figcaption></figure><p>Before we do a deeper dive into the issue, we need to determine the impact of the errors and give constant status updates to stakeholders. In our case, less than 0.5% of requests resulted in 502 errors.</p><h3>The Discovery</h3><p>Now that we’ve updated stakeholders, it’s time to investigate and resolve the issue. I temporarily increased the threshold for the alarm to make sure it doesn’t trigger during our investigation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SlrcIKxuvaxpshWNl_rRg.png" /><figcaption>Github PR to change the threshold which triggers the alarm</figcaption></figure><p>There are many reasons why a load balancer would throw 5XX errors:</p><ul><li>One (or many) upstream servers have become unresponsive.</li><li>There’s a transient network issue that’s disrupting upstream connections.</li><li>An upstream service responds with non-compatible/corrupt data.</li></ul><p>AWS has many articles that explain <a href="https://aws.amazon.com/premiumsupport/knowledge-center/http-5xx-errors-s3/">how to troubleshoot ELB 5XX errors</a>. Our job is to systematically check and eliminate possible failure modes. The easiest way to uncover the root cause is to query the ELB (elastic load balancer) access logs and analyze the results:</p><ul><li><a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#enable-access-logging">AWS ELBs can be configured to deposit their access logs into an S3 bucket</a>. An access log file simply contains a list of all requests made to the ELB.</li><li><a href="https://docs.aws.amazon.com/athena/latest/ug/application-load-balancer-logs.html">We can load the log files into AWS Athena and use SQL to comb through the logs.</a> (Using Athena makes it extremely easy to narrow down possible failure modes, as we’ll see.)</li></ul><p>First, we index relevant log files in Athena:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a83ee19b234b2034015fac0a4dfd291/href">https://medium.com/media/4a83ee19b234b2034015fac0a4dfd291/href</a></iframe><p>Let’s check if the 5XX errors are resulting from the same upstream server. We can do this by grouping the requests by their target IP. We should see only a handful of IP addresses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e375556b7303b45eaad243d9e56b8233/href">https://medium.com/media/e375556b7303b45eaad243d9e56b8233/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*9XJbZ1sqCy2CjPBffVVolg.png" /><figcaption>Results from the query.</figcaption></figure><p>The query result includes many different IP addresses, so we know the error isn’t originating from one upstream server. Here are some other queries we can use to help with our investigation:</p><p>Determining the response time of requests which resulted in a 5XX:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f897f985fe62458bb5d33eb4a17155e/href">https://medium.com/media/5f897f985fe62458bb5d33eb4a17155e/href</a></iframe><ul><li>If the target processing time is 0, it means the ELB is having trouble establishing a connection with upstream services.</li><li>If the target processing time is almost 60s (the default ELB timeout) then upstream services are not responding fast enough. In this case, you’ll need to investigate why upstream services are taking so long to respond or increase the ELB target response timeout.</li></ul><p>Grouping the requests based on client IP:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4983ef3f5f081e635895679f94db41d/href">https://medium.com/media/e4983ef3f5f081e635895679f94db41d/href</a></iframe><ul><li>If all erroneous requests were generated from a handful of clients, it may be the case that those clients are experiencing issues with their internet connection.</li></ul><p>Grouping requests using HTTP verbs and URLs to discover slow endpoints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc293bfd49dcc5b5ce81f0afadb5649/href">https://medium.com/media/3fc293bfd49dcc5b5ce81f0afadb5649/href</a></iframe><p><strong>Note:</strong> We’ve indexed the Athena table for our ELB logs by the year, month, and day. Using a date-based index is absolutely crucial because we’re able to load and query log files in the timeframe we’re interested in. These isolated queries have the following benefits:</p><ul><li>Our queries are faster because we’re processing a subset of the log files.</li><li>Athena charges by the amount of data processed; processing a subset of log files means we spend less per query.</li></ul><p>If you want to avoid spending money on queries, another way to comb through log files is to download the relevant log files and write a script that parses and filters the requests.</p><h3>Reducing the Noise</h3><p>After thoroughly querying the ELB access logs, we saw all our 5XX requests had a response processing time of 60 seconds (i.e., the ELB waited 60 seconds for an upstream server to respond). Upstream servers weren’t responding fast enough, which resulted in the ELB throwing a 5XX. We tested our upstream servers to figure out why they were responding so slowly, and we found they weren’t actually responding slowly at all.</p><p>After doing some research, we discovered the problem was an inconsistent network configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*xukDTzhWlK6Gz0Txi8_biQ.png" /><figcaption>Open connections between the load balancer and upstream servers</figcaption></figure><p>When the ELB forwards a request to an upstream server, a connection is established and data is subsequently transmitted and received over that connection. Establishing a connection is slow and expensive; to avoid opening a new connection for every request, our ELB and upstream servers were using the same connection to handle several requests (known as <a href="https://en.wikipedia.org/wiki/HTTP_persistent_connection"><em>keep-alive connections</em></a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*vVbFdjByPicj77b_n-da3Q.png" /><figcaption>The load balancer maintaining a connection with no receiving server</figcaption></figure><p>Our upstream servers were configured to close these connections after some time to free up resources. Due to a race condition, our ELB would sometimes think these connections were still open. The ELB would try sending data over this “ghost” connection, and the request would timeout since there’s nothing there that will respond.</p><p>To fix this issue, we made sure our upstream server had a larger keep-alive timeout than our ELB’s idle connection timeout, insuring the ELB doesn’t maintain any ghost connections. After making this change, we stopped received periodic alerts and our alarm was once again healthy.</p><h3><strong>Conclusion</strong></h3><p>Once an alarm is resolved, there are some metrics we consider when evaluating the significance of an alert:</p><ul><li>Number/percentage of users affected</li><li>Duration of degraded user experience</li><li>The monetary cost of the event</li></ul><p>If the alarm was triggered despite no disruption on the preceding factors, then you may have a noisy alarm, and in our case, we did. Our users weren’t significantly impacted, we were in an “alarm” state for less than a minute, and the alert auto resolved.</p><p>Let’s recap why we want to make sure this alarm never triggers under insignificant circumstances again:</p><ul><li>We need to reduce the cognitive load for our developers.</li><li>Actionable alerts shouldn’t be hidden under a blanket of noisy alarms.</li><li>First responders shouldn’t be disturbed with an alert after business hours.</li></ul><p>In some cases, refactoring the alarm to be less noisy simply means to raise/lower the alerting threshold. In others, you may have to do a deeper dive and adjust server/network configurations.</p><h4>Closing remarks</h4><ul><li>Whether you’re using Athena, CloudWatch, or custom Python/C scripts, teams should conduct ELB diagnosis drills every couple of months. Having a practiced workflow for investigating and resolving issues is extremely valuable in critical situations.</li><li>Some ELB 5XX errors result from an AWS outage. It’s best to <a href="https://en.wikipedia.org/wiki/Timeboxing">timebox</a> investigations and open an AWS support ticket if you’re not able to arrive at a root cause. AWS specialists will be able to tell you if the issue was on their end.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69cb70a9f018" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-i-help-developers-sleep-at-night-69cb70a9f018">How I Help Developers Sleep at Night</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Python: Dependency Injection vs. Mocking]]></title>
            <link>https://medium.com/better-programming/testing-in-python-dependency-injection-vs-mocking-5e542783cb20?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e542783cb20</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 18:18:14 GMT</pubDate>
            <atom:updated>2020-04-22T18:18:14.113Z</atom:updated>
            <content:encoded><![CDATA[<h4>When should you use dependency injection? When should you use mocking?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*45-3UO529G5czUB7" /><figcaption>Photo by <a href="https://unsplash.com/@helloquence?utm_source=medium&amp;utm_medium=referral">Helloquence</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>One of the things I love about Python is its testing facilities. When you need to mock interactions with external dependencies, you may choose to:</p><ul><li>Use dependency injection to replace the dependency with a test double.</li><li>Use Python’s <a href="https://mock.readthedocs.io/en/latest/">mock</a> library to hijack the actual function call.</li><li>Test against a fake server with mock responses.</li></ul><p>With all these testing strategies available to us, it may not be clear which strategy to use. In this article, I’ll talk about when it makes sense to choose mocks over dependency injection and vice versa.</p><h3>The Code</h3><p>Let’s look at some code to illustrate the difference between mocking and dependency injection. Suppose I was testing code that called the Inventory service. The Inventory service keeps track of the items a user holds. Here’s the client we use to interact with the Inventory service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b43c86aa1cd1f16a2dc315f76b5ee56e/href">https://medium.com/media/b43c86aa1cd1f16a2dc315f76b5ee56e/href</a></iframe><p>The code under test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea6981bb16f70f562b23dbf345c6db73/href">https://medium.com/media/ea6981bb16f70f562b23dbf345c6db73/href</a></iframe><h4>A valid test using the mock approach</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d9d793d68261f4f03234cab26e1bb7/href">https://medium.com/media/25d9d793d68261f4f03234cab26e1bb7/href</a></iframe><p>Although this isn’t a tutorial on how to use the mock library, I’ll walk through the code to establish context:</p><ul><li>We don’t want to call the Inventory service, so we’ve patched the get_items and add_item functions.</li><li>We’ve set the return value of the call to the Inventory service to what we expect it’ll return.</li></ul><h4>A valid test using dependency injection</h4><p>Before we can use dependency injection, we need to establish a production/test environment and a way to choose the code that runs in each environment. Let’s change our client:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5636e8f43fae3738017781f4518eebd2/href">https://medium.com/media/5636e8f43fae3738017781f4518eebd2/href</a></iframe><p><em>Disclaimer: This code is enough to illustrate the concept. You’ll need a more sophisticated setup for a production codebase.</em></p><p>We’ve defined two concrete classes. If we aren’t in the prod environment, we’ll use the InventoryMock class that holds data in memory. There’s no longer a need to use the mock library. Our new test looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7160a09858f3fc7cd8f99a840c215277/href">https://medium.com/media/7160a09858f3fc7cd8f99a840c215277/href</a></iframe><h3>What Should I Use?</h3><p>Both strategies enable us to test our code without calling the Inventory service. Here are some things I consider when choosing which strategy is most appropriate:</p><h4>Scope/Cost</h4><p>Depending on the state of your code, one strategy will be cheaper than the other. If you need to mock a handful of use cases, it may be easier/faster to patch the functions instead of creating a mock class. If your codebase already has infrastructure and tooling to support dependency injection, then writing a simple mock class may be simpler than patching.</p><p>You should also consider the future consequences of the approach you adopt. If the interaction you’re mocking is subject to change, then consider choosing the approach that&#39;s fastest to modify.</p><h4>Economies of scale</h4><p>Dependency injection is a way to scale the mocking approach. If a lot of use cases are relying on the interaction you’d like to mock, then it makes sense to invest in dependency injection. Systems that lend themselves easily to dependency injection:</p><ul><li>An authentication/authorization service.</li><li>Logging solutions that are responsible for distributed tracing and tracking metrics.</li><li>Commonly used infrastructure, like caches and message brokers.</li></ul><p>These systems are commonly used throughout the codebase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzAMP5D4iSNP-QM9kiq2hQ.png" /></figure><p>This is where dependency injection shines — having to patch every interaction would be a pain. If the system in question is used across multiple repositories, then you can go one step further and formalize the dependency injection classes into a client library.</p><h3>Closing Thoughts</h3><p>Dependency injection and mocking are both commendable approaches for testing external dependencies. Dependency injection takes more work to set up, but it’s well-positioned for high-frequency usage. A mocking/patching approach is fast/easy, but it begins to turn into technical debt as dependency usage increases/changes. A couple of other things to keep in mind:</p><ul><li>Consistency: If the code uses dependency injection (or patching) to mock interactions, there’s no reason to deviate unless there are serious advantages.</li><li>Competence: If engineers are well-versed with Python’s mock library and don’t have experience with object-oriented-style dependency injection (or vice versa), the quantitative benefits of migrating to dependency injection may not outweigh the qualitative harm.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e542783cb20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/testing-in-python-dependency-injection-vs-mocking-5e542783cb20">Testing in Python: Dependency Injection vs. Mocking</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signs of Failing Service-Oriented Architecture]]></title>
            <link>https://medium.com/better-programming/signs-of-failing-service-oriented-architecture-fd405c58f75b?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd405c58f75b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 17:27:58 GMT</pubDate>
            <atom:updated>2020-04-15T17:27:58.944Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop building a distributed monolith</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LJ3V40k3vf-Pq66-" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve come across articles where developers talk about their organization shifting to service-oriented architecture (SOA), failing, and migrating back to monolithic development. Of course, there’s nothing wrong with that. A large aspect of our job is to try something, see if it works, and scrap it if it doesn’t. SOA isn’t for everybody. If it’s not for your company, then stick with the monolith. But if it is, then you have to do it right!</p><p>Working with large and singular codebases for years shapes our opinions and biases on how things ought to be done. If we unconsciously stick with the same habits when working with services, we may not realize areas in which we’re failing. In this article, I’ll talk about the dangers of applying monolithic practices in an SOA world.</p><h3>1. Highly Coupled Data and Architecture</h3><p>To succeed in an SOA world, it’s important to avoid highly coupled data and architecture. Each service should be built around a thought-out, forward-looking abstraction. Services should be, to a degree, self-contained — ideally, they don’t know of the existence of any services. There are certain cases where it becomes easy to create highly coupled services:</p><ul><li>We build ad hoc services to support ad hoc use cases.</li><li>It may be expensive to create a good abstraction. A coupled service is the path of least resistance for the organization.</li><li>Some products have a central data model. If we let the data model dictate the abstraction we define, our service ends up being coupled to some degree.</li></ul><p>If we don’t scrutinize the abstractions we create, we may end up with a highly coupled service ecosystem. Here are some coupled dependency structures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-u-Xct-E5qkSi-kww-M6g.png" /><figcaption>Photo by the author.</figcaption></figure><ul><li>Left: Service A calls Service B knowing it will call Service C. It then queries Service C for the result.</li><li>Right: Service A depends on B, which depends on C, which depends on A. We have a cycle in our dependency graph.</li></ul><p>In these structures, you’re essentially developing a distributed monolith. At some point, you’ll run into the following issues:</p><ul><li>You’ll need to update two services at the same time but won’t know which one to update first, as they both depend on each other. You’ll get around this by introducing a non-breaking backward-compatible change in one service, updating it, then updating the second service before removing dead code from both services. Yeah… not pretty.</li><li>A simple user flow may span multiple services. If there’s an issue, it can only be diagnosed by someone who has contextual knowledge of multiple services.</li></ul><p>A “bad” dependency structure hints at a distributed monolith — all the pains of working with the monolith with none of the benefits of working with services. Furthermore, highly coupled services usually pave the way and welcome more of the same. In other words, if you don’t address the issue, things get worse as your service ecosystem grows.</p><h4>Data coupling</h4><p>When your data is highly coupled across services, you’ll need to invest in keeping the data in sync using synchronous API calls and asynchronous tasks. These sync processes may also take the form of a <a href="https://microservices.io/patterns/data/saga.html">SAGA</a>. In any case, you’ll have to:</p><ul><li>Invest heavily in infrastructure and testing to make sure data is synced properly.</li><li>Educate developers on the process so that they don’t accidentally introduce a change resulting in data sync issues.</li><li>With enough data points being synced across multiple services, developers are bound to make a mistake — and a potentially catastrophic mistake at that.</li><li>Invest in visibility and instrumentation to make sure you’re alerted when the sync process breaks. When it does break, which it likely will, you’ll have to diagnose the issue and resolve it. Both can be very expensive depending on the rigidity of your system.</li></ul><p>If, however, you’re able to build a service ecosystem with little/no data coupling, you avoid having to jump through these hoops.</p><h4>Next steps</h4><p>What should you do if you find yourself in this situation? Of course, there’s no one-size-fits-all solution. Here are some ideas to help you get started:</p><ul><li>Firstly, if the services are stable and they’re not being changed, leave the system alone. It&#39;s working, and you don’t want to be the one to break it because you were “enlightened.”</li><li>If your current architecture is causing problems, the first thing I would do is analyze the monetary cost of maintaining the current system, the cost associated with migrating to a better system, and the cost savings the new system would procure. This is a hard exercise, but you’d be surprised how far you can get using metrics like <a href="https://en.wikipedia.org/wiki/Lead_time">lead time</a>, number of bugs/outages, number of users affected, etc. Once you’ve done a thorough analysis, you may realize that migration isn’t necessary. If, however, the analysis strengthens your resolve to migrate the system, use your analysis to get buy-in from management.</li><li>In many cases, it’s unrealistic to change the current system. The organization can’t afford a slower pace to carry out the migration, it may be too expensive, etc. That’s OK. You can still make sure systems are designed properly moving forward.</li></ul><h3>2. Monolithic Development Habits</h3><p>Communication structures, teams, operations, deployments, and processes all look different in an SOA world. The tools we’ve gathered over years of monolithic development aren’t necessarily the ones to use when working with services. Old tools/habits need to be replaced by their SOA equivalents if developers (and the organization) are to succeed with SOA.</p><h4>Local development</h4><p>When working with a monolith, we run most (if not all) infrastructure on our local machine. Developers, at one point or another, have run into the “it doesn’t work on my machine” problem. Organizations invest in bootstrap solutions to avoid this problem and make developers productive as soon as possible. Most solutions are centered around making the infrastructure easier to run on your local machine.</p><p>Running everything on your local machine doesn’t scale when you start working with multiple services.</p><ul><li>In most cases, dev machines aren’t powerful enough to run the necessary services during feature development. You may get away with running a handful of large services, but there will come a time when your machine won’t keep up.</li><li>Running services locally means developers have to know how to run (and potentially deploy) a service they don’t own. Ideally, service owners shouldn’t need to worry about any service outside their ownership.</li></ul><p>Investing in solutions that make it easy to run multiple services locally is the monolithic mindset, and approaching service development the same way hints at a distributed monolith. I’ll leave some resources at the end of the article on how other companies approach local service development, but here’s what those solutions typically look like:</p><ul><li>Mocking interactions with other services using dependency injection and client libraries.</li><li>Running some of your infrastructure in the cloud, running some of it locally, and plugging your local infrastructure into your cloud infrastructure.</li></ul><h4>End-to-end testing</h4><p>There are two forms of end-to-end testing:</p><ul><li>Automated tests, which are usually run in CI/CD pipelines.</li><li>Manual tests, which developers do before checking in their code and while they’re doing code reviews.</li></ul><p>End-to-end testing in a monolithic codebase is somewhat straightforward. After setting up the appropriate data/state, you’re able to test the new user flow on your local machine.</p><p>Even if we write good unit/integration tests that verify the correctness of code, manually testing everything on our local machines during QA increases our confidence. As your service ecosystem grows, features and use cases will be backed by multiple services and it will be infeasible to test everything locally:</p><ul><li>Setting the appropriate state may take a long time.</li><li>It may be hard to mock interactions with non-trivial systems (message brokers, asynchronous job queues, etc.).</li><li>Your machine isn’t capable of running the required infrastructure.</li></ul><p>End-to-end testing looks much different in SOA. Pursuing a solution that makes it easy to do end-to-end tests locally is expensive and doesn’t scale.</p><p>SOA is popular because of its promise to quicken iterations. If you’re spending a considerable amount of time testing your changes locally, you’re not positioning yourself to take advantage of SOA. At some point, you’ll need to let go of the psychological safety of testing everything locally.</p><p>Your testing strategy depends on the local development solution you’ll adopt. Here are some ways to release code without having tested user flow locally:</p><ul><li>Hiding new features behind <a href="https://launchdarkly.com/">feature flippers</a>, allowing you to test user flow in production before enabling the feature for everyone.</li><li>Canary deployments, shadow deployments, red/black deployments, etc.</li><li>Stress testing new changes in staging before rolling out to production.</li></ul><p>Of course, the psychological safety you surrender by dropping local testing can be procured in other ways:</p><ul><li>Thorough and well-thought-out instrumentation/observability.</li><li>Alarms, workbooks, and rollback procedures to help you recover from failures.</li></ul><p>I’ve listed testing/deployment strategy resources at the end of the article.</p><h4>Debugging</h4><p>On the flip side of the same coin, if your testing strategy needs to change, so does your debugging strategy.</p><p>In monoliths, a stack trace is enough to get us started. A stack trace points us in the right direction and we follow the cookie crumbs until we reach the problem. Stack traces and traditional debugging tools are usually enough to debug issues in SOA, but they’re useless for certain classes of issues:</p><ul><li>Transient network errors.</li><li>Data sync issues across multiple services.</li><li>Incorrect configurations — connection timeouts, read/write timeouts, number of workers, scaling configurations, etc.</li></ul><p>Although you’ll still comb through code to find the issue, your debugging toolbox should also include:</p><ul><li>Scripts to download and filter access logs for different systems in your ecosystem.</li><li>Distributed tracing to help you understand the lifecycle of a single user request.</li><li>Dashboards with CPU, memory, and P99 metrics to catch issues that don’t result in stack traces.</li><li>Load simulation strategies that replicate a production environment.</li></ul><h3>Conclusion</h3><p>It’s surprisingly easy to develop a distributed monolithic in SOA. We need to avoid applying monolithic development habits to our services. Here are some of the symptoms to be mindful of:</p><ul><li>Highly coupled data and/or architecture.</li><li>A poor local dev strategy for working with multiple services.</li><li>A poor testing strategy that involves testing everything locally.</li><li>Dated debugging tools that aren’t capable of diagnosing network and cross-service issues.</li></ul><p>Monolithic development isn’t bad. It’s just different. A lot of companies have invested in shifting to SOA without realizing they’d have been much better off investing in monolithic development. Whether you stick with the monolith or take the services route, just make sure to avoid building a distributed monolith — the worst of both worlds.</p><h3>Resources</h3><ul><li><a href="https://dzone.com/articles/development-environments-for-microservices">Development Environments for Microservices</a></li><li><a href="https://www.martinfowler.com/articles/feature-toggles.html">Feature Flags</a></li><li><a href="https://blog.risingstack.com/the-future-of-microservices-monitoring-and-instrumentation/">Microservice Instrumentation</a></li><li><a href="https://dzone.com/articles/making-your-microservices-resilient-and-fault-tole-1">Proactive Failure Prevention</a></li><li><a href="https://www.infoq.com/presentations/microservices-failure-modes/">Managing Failure Modes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd405c58f75b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/signs-of-failing-service-oriented-architecture-fd405c58f75b">Signs of Failing Service-Oriented Architecture</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Leverage a Boilerplate Service in Service-Oriented Architecture]]></title>
            <link>https://medium.com/better-programming/the-usefulness-of-a-boilerplate-service-14ba7fc5e1e1?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ba7fc5e1e1</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 18:05:17 GMT</pubDate>
            <atom:updated>2020-04-08T18:29:11.295Z</atom:updated>
            <content:encoded><![CDATA[<h4>How boilerplate code helps developers and the organization succeed in a service-oriented world</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DxkP2yk6spXFlBG9" /><figcaption>Photo by <a href="https://unsplash.com/@danist07?utm_source=medium&amp;utm_medium=referral">贝莉儿 DANIST</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>Most people don’t give boilerplate code a second thought. I mean… it’s boilerplate. The sole reason it exists is so you don’t need to think about it.</p><p>That was my perception of boilerplate as well, so almost a year ago when I started working as a platform developer, you could imagine my <em>excitement</em> when I learned that most of my efforts would go towards improving our boilerplate offering. Fast-forward to today, and my perspective has totally changed — so much so that I feel compelled to write an article about it.</p><h3>Motivation</h3><p>Why do I care about boilerplate now? Over time, I’ve seen the impact a good boilerplate offering has on the organization. It’s much more than a tool to improve the developer experience.</p><p>The shift towards service-oriented architecture (SOA) is challenging. Companies adopt SOA because of its promise to enable “fast iterations,” but the architecture alone isn’t going to get you there.</p><ul><li>Traditional monolithic development practices don’t work in the SOA world.</li><li>Developers need to start owning their infrastructure.</li><li>End-to-end testing looks much different. Developers will have to part with the psychological safety of testing everything on their local machine.</li></ul><p>A shift towards SOA doesn’t exclusively warrant a change in architecture. It warrants a paradigm shift where developers need a new way to develop and a new way to communicate.</p><p>This is my longwinded way of saying, “SOA is hard… really hard, and you need all the help you can get to do it properly.” That’s where boilerplate comes in. Boilerplate is an excellent medium to help facilitate the paradigm shift you’ll need to scale your service ecosystem.</p><p>In this article, I’ll talk about the decisions we’ve made in our boilerplate offering to address different issues.</p><h3>A Boilerplate Service</h3><p>The platform team I work on offers a “boilerplate service.” It’s meant to be the gold standard for services across our organization. It acts as a starting point that other teams use to develop new services. It provides:</p><ul><li>All the infrastructure needed to launch a service in production.</li><li>Scripts to help developers run tests, generate documentation, deploy their service, and create personal dev environments.</li><li>A complete CI/CD pipeline (i.e. linting, testing, deploying, Slack notifications, etc.).</li></ul><p>Here’s a rough directory structure to help you get a better idea:</p><pre>boilerplate-service/<br>    infrastructure/<br>        config/<br>            ...<br>        template.yml<br>    docs/<br>        index.md<br>        ...<br>    scripts/<br>        setup.sh<br>        ...<br>    src/<br>        ...<br>    tests/<br>    README.md<br>    Dockerfile<br>    Jenkinsfile<br>    ...</pre><p>Teams use boilerplate tools when they&#39;re either forced to or they see enough value in the generated code to justify the time spent discovering and learning the tool. We hope we’ve provided enough value in our offering to align our adoption with the latter. However, along with the developer, a boilerplate offering can help the organization as well.</p><p>If the time it takes to develop a boilerplate tool is less than the cumulative time it takes to write the corresponding code, then organizations should invest in a boilerplate offering (if it’s the highest-value gain action at the time).</p><p>Yet boilerplate can accomplish a lot more than just saving time:</p><ul><li>Baking in best practices (routing setup, CPU and memory alarms, etc.) helps increase the competency of your service ecosystem.</li><li>Including developer tools helps improve the local development experience and developer productivity.</li></ul><p>Let’s dig a little deeper and see how our boilerplate service is helping us in our transition to an SOA.</p><h3>The Ejection</h3><p>The first thing teams need to do when starting a new service is eject from the boilerplate service template. Tools like create-react-app and gradle-init have a seamless/self-service ejection process. You provide the name of the project, some versioning information, and it generates the appropriate boilerplate code.</p><p>We, however, opted for an involved ejection process. Here’s a rough outline of the steps service owners follow to start a new service:</p><ol><li>Clone our boilerplate-service repository.</li><li>Update references to boilerplate-service to their service’s name.</li><li>Configure integrations with their team information (e.g. Slack, email).</li></ol><p>A few months ago, we made our ejection process self-service, but up until that point, we consciously chose not to automate the ejection. Why?</p><h4>Reason #1: Operational concerns</h4><p>At the time, our SOA ecosystem had rudimentary tooling/instrumentation and our organization didn’t have substantial experience operating more than a handful of services. To de-risk the organization, we designed an involved ejection process, which by extension meant a long ejection process.</p><p>What this meant for teams:</p><ul><li>Service owners were forced to comb through the code and learn more about the infrastructure they now owned.</li><li>Teams were incentivized to create fewer services. Ad hoc services for ad hoc use cases weren’t justified by the time required to create them.</li></ul><p>What this meant for the organization:</p><ul><li>Outages were easier to debug since it’s easier to reason about a system with a handful of services.</li><li>We could adopt an iterative approach to flesh out our SOA offerings. The handful of services operating in production were enough to tie into our feedback loop, help us run experiments, and learn from our failures.</li></ul><h4>Reason #2: Scrutiny</h4><p>Our service ecosystem is young. We want new services to undergo rigorous scrutiny, as they will set the tone for forthcoming services. A complicated ejection process means first-time service owners have to pair with someone on our team during ejection. Pairing sessions gave us the chance to:</p><ul><li>Vet the service and make sure it’s conceived around well-thought-out, forward-looking abstractions.</li><li>Promote best practices and align the organization.</li></ul><p>Once our service ecosystem matured and we surpassed a threshold of operational competency, we made our boilerplate service ejection as simple as eject &lt;service_name&gt;.</p><h3>Bubbling Change</h3><p>We’re early in our SOA journey. There’s a lot we don’t know and we’re figuring things out as we go. We do research and run experiments to figure out what works, what doesn’t work, and what we’re missing. For example, one thing we’re exploring is how we should handle <a href="https://dzone.com/articles/development-environments-for-microservices">service-to-service dependency and local development</a>:</p><ul><li>Should local services plug into services in the sandbox environment?</li><li>Should all services provide an in-memory client library for other services to use during testing/local development?</li><li>Should we run all the required services locally?</li><li>Etc.</li></ul><p>Once we know what works for us, we modify our boilerplate service so that our learnings are reflected in upcoming services. However, we need a way to propagate changes to existing services. Take <a href="https://microservices.io/patterns/observability/distributed-tracing.html">distributed tracing</a> — it doesn’t work unless all services are using the same tracing solution.</p><p>It’s important for “updates” to be fast and seamless. Service owners won’t mind doing the update and our team won’t have to wait long for all services to receive the change. Here’s how we propagate changes in our boilerplate service:</p><p>There are three “components” to a service:</p><ol><li>Code/files that the service owner is responsible for. Any change we introduce won’t touch these files (e.g. things like application code, infrastructure files, documentation, etc.).</li><li>Local dev tools developers use to interact with services and the service ecosystem.</li><li>Tooling and instrumentation services used in production.</li></ol><h4>Scaffolding library</h4><p>The scaffolding library addresses item #2. It’s a dependency for all of our services. It’s responsible for anything/everything that aids in the development of your service:</p><ul><li>Deploying the service to the cloud (either in staging, production, or a custom environment).</li><li>Running tests, linting, generating documentation, etc.</li><li>Allowing services to plug into our message broker solution (and vice versa).</li></ul><p>How we use the scaffolding library to propagate changes (and other things we love about it):</p><ul><li>When we introduce a change, we release a new version of the scaffolding library and service owners simply have to update to the latest version.</li><li>Developers are able to get up and running with an unfamiliar service very quickly since the tools needed to interact with the service are the same.</li><li>By using the commands exposed by the scaffolding library, we can write one CI/CD pipeline that works for every service.</li></ul><h4>Runtime library</h4><p>Our runtime library addresses item #3. It includes any code needed at runtime and shares the same “easy updates” property as our scaffolding library. Some of the things it’s responsible for:</p><ul><li>An “infrastructure” Django app that helps with things like health checks.</li><li>Logging utilities to help us tag logs and enable distributed tracing.</li><li>Helper functions to tie into different systems within our organization.</li></ul><h4>Notes</h4><ul><li>I would be lying if I said this system was conceived by design. Some of it was intuition, but most of it was trial and error.</li><li>We can only enjoy the benefits of our scaffolding/runtime libraries because we take a disciplined approach to updates. We avoid introducing breaking changes and we make sure service owners are keeping up to date with the latest versions of the library.</li><li>Having a system that enables fast and easy change propagation allows us to take advantage of the talent we have in our organization. We hold weekly meetings with our service owners to get feedback on our SOA offerings. When service owners identify a gap in their service, they tell us their solution and we generalize it before rolling it out to all services. A seemingly small change bubbles up to have a large impact on our organization.</li></ul><h3>Summary</h3><p>Our journey towards SOA has been bumpy, and we’re using a boilerplate service to help smooth out those bumps as best as we can. We’ve designed our ejection and change propagation processes to help us:</p><ul><li>Make sure new services don’t compromise the stability of our ecosystem.</li><li>Promote best practices and different methodologies to help developers succeed in an SOA world.</li><li>Adopt an iterative approach for developing our SOA offerings. What works for one company might not work for another, and an iterative approach helps us find what works for us.</li><li>Make up for the lack of SOA expertise by leveraging the talents of all developers in our organization.</li></ul><p>There other aspects of the boilerplate service I want to talk about. However, some of those ideas are half-baked. I know of their merit through intuition and experience, but it’s hard to solidify them into actionable practice. I’ll list them below. Hopefully, you can draw inspiration from these ideas:</p><ul><li>All code your boilerplate generates should be relevant. If it isn’t relevant, it should be abstracted away or structured so that the developer never touches it. On the flip side of that coin, if it is relevant, it should be explicit and present even if it can be abstracted away.</li><li>We began with an involved ejection process. It worked out well for us, but obviously it won’t work well for all cases. Suppose we were offering a boilerplate lambda in place of a boilerplate service. Even if our boilerplate lambda was chock-full of tooling, an involved ejection process wouldn’t be a good idea since lambdas usually serve ad hoc use cases.</li><li>I guess this one’s more philosophical: Just like communication structures that work for startups don’t work for large companies, practices that work for monolithic development (a few codebases) don’t work for SOA (many codebases). In these cases, we need a new structure to help cope with scale. Boilerplate helps us put that structure in place.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ba7fc5e1e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/the-usefulness-of-a-boilerplate-service-14ba7fc5e1e1">How to Leverage a Boilerplate Service in Service-Oriented Architecture</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for Your Next Interview Coding Challenge]]></title>
            <link>https://levelup.gitconnected.com/tips-for-your-next-coding-challenge-7c1c90c121d0?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c1c90c121d0</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-interviews]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[interview-tips]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 00:20:24 GMT</pubDate>
            <atom:updated>2020-03-24T18:42:08.686Z</atom:updated>
            <content:encoded><![CDATA[<p>A software development job is gated behind many doors. The first door unlocks by successfully completing the coding challenges they throw your way. In this article, I’ll give you some keys to completing these challenges which I’ve acquired from my own experience. Hopefully, one of these keys helps you unlock a door of your own.</p><h3>Prologue — Coding Challenge &amp; The Interview</h3><p>Coding challenges can make interviewing a very bipolar experience; either they go really well or they go really not well. Having done maybe almost 50 interviews, both as the interviewer and the candidate, I can tell you that need not be the case. The right/wrong nature of a challenge fools us into thinking our interview was either a pass or a fail.</p><p>The challenge is only part of the process. There are other qualities such as communication, personality, culture-fit, growth potential, etc. that are as important as your technical abilities. I’ve seen geniuses denied an offer because they weren’t a good culture fit, or they would’ve been difficult to work with, etc. So don’t worry, you won’t live/die by your ability to complete coding challenges.</p><p>Having said that, there’s a certain threshold of technical proficiency you need to exceed and coding challenges help interviewers gauge whether or not you’re ready for the job you’ve applied for. You may have an excellent understanding of how to structure quality code but sadly, we must communicate our technical proficiency through coding challenges. I’m going to try to help you communicate in the language of “coding challenges” just a little bit better.</p><h3>3 Major Keys</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VManFSVjbS8zzgHC" /><figcaption>Photo by <a href="https://unsplash.com/@bergerteam?utm_source=medium&amp;utm_medium=referral">Florian Berger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we get into the keys, let&#39;s get some of the foundational stuff and prep work out of the way:</p><ul><li>You need to understand how to analyze the time and space complexity of an algorithm.</li><li>Review your data structures and algorithms. Especially ones you think aren’t relevant (because in my experience those are <em>always</em> the ones that show up in the interview…)</li><li>Make sure you’re proficient with at least one programming language. Interviews can be very stressful. You don’t want the language which should be helping you ace the challenge be the reason you didn’t.</li><li>Do practice problems online. There are many websites like <a href="https://leetcode.com/">LeetCode</a>, <a href="https://www.hackerrank.com/">HackerRank</a> that have an abundance of practice material.</li></ul><p>There are many other ways to prep, but I’m sure you already know that. You came here for the good stuff… well, here it is!</p><h3>Lateral Thinking</h3><p>Some questions are “cleverly” designed to test your <a href="https://en.wikipedia.org/wiki/Lateral_thinking">lateral thinking</a>. How many different perspectives can you attack a problem from? Usually, your first interpretation of the problem will lead to the most inefficient solution. When your interviewer asks you to “do better”, it’s time to shift those lateral thinking gears into place.</p><p>Lateral thinking is all about breaking through any “perceived” limitations. I can’t teach you how to do that, otherwise, we’d all be geniuses. What I <em>can</em> do is teach you how to conjure an environment that fosters lateral thinking.</p><p>The secret is — you’re not supposed to do anything… your conscious mind that is. After looking at the problem, digesting it, your subconscious mind will start spitting ideas at you. Ideas that seemingly come from nowhere. Your job is to evaluate and explore the merits of those ideas. Eventually, a ting of inspiration will help you arrive at the solution.</p><p>Unnecessary thoughts distract your mind and hinder your ability to think. Thoughts like:</p><ul><li>What if I can’t get this solution? Will I fail the interview?</li><li>How much time do I have left? How am I going to solve this in 7 minutes?</li></ul><p>These thoughts act as a gateway into a downward spiral, which ends in panic. Dispell these thoughts from your mind and focus on the question. Don’t let these useless thoughts take up precious thought-generating real estate, real estate that should be allocated to solving the question.</p><blockquote>Remain calm during interviews. Stress and panic hinder your ability to solve a question. Try to have fun, keep it lax, and let your brain do what it does best.</blockquote><p>Of course, telling you to “not panic” is easier said than done, but this will come naturally with practice. Now let&#39;s look at a question.</p><h4>Buy Low Sell High</h4><p>You’re given historical price data for a stock:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eAuJ15pzO8wYpQKwT8HCA.png" /></figure><p>You must find a <em>start_time</em> and <em>end_time</em> such that buying a stock at the <em>start_time </em>and selling that stock at the <em>end_time</em> yields the highest profit. Obviously, <em>end_time</em> must come after <em>start_time:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U78Vjp655SvlnTjqPT5mQ.png" /></figure><p><em>You may pause here and try to come up with a solution. Your input data is an array of prices, and your output must be the index at which to buy/sell:</em></p><pre>Input:<br>[5, 3, 2, 4, 6, 7, 6, 5, 5, 6, 7, 9, 10, 9, 7, 5, 6]</pre><pre>Output:<br>(2, 12)</pre><p>The first solution you may consider is the “brute force” solution. You create an outer/inner loop to consider every pair of <em>start</em> and <em>end times.</em> You keep track of which pair has the highest difference in price as you’re looping through, and return that pair at the end:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2481014bc90bdcc6192651c638a197d4/href">https://medium.com/media/2481014bc90bdcc6192651c638a197d4/href</a></iframe><p>This algorithm has a complexity of O(N²). Can we do better? Of course, we can! This is where lateral thinking comes into play. The question is framed with the notion of time, which we know only goes forward, never backward. Consequently, our brain spits out solutions that “go forward”, that is to say from left to right. There is no constraint that disallows us from traversing the data backward.</p><p>We know we will always buy at some local minimum and sell at some local maximum (unless the graph is always decreasing). The root of the question is to pair every local minimum with a local maximum and choose the pairing with the highest profit. The difficulty of the “forward” approach lies in the temporal nature of the question. When we go left to right, we must remember <em>every</em> local minimum/maximum we’ve seen in the past in case a better pairing surfaces in the future. This pairing logic is extremely complicated to program in one loop.</p><p>If we go from right to left, we don’t have to keep track of <em>every</em> local minimum/maximum. The problem becomes much simpler. We know data we haven’t traversed yet occurred in the past, so we only need to keep track of the best we’ve seen and replace it if we find something better:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32f1d646475a81dff6034806414cddcf/href">https://medium.com/media/32f1d646475a81dff6034806414cddcf/href</a></iframe><p>A brief explanation of the code: For every local maximum, we keep track of the “best” local minimum until we find a higher local maximum. We repeat this logic until we’ve traversed the array, keeping track of the best pairing throughout. Here’s a graph which illustrates the algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4loqeuf2rJJntRLRFkgpow.png" /></figure><p>This algorithm has a complexity of O(N). Which is, of course, the best we can do. For this question, to think laterally meant to <strong>go backward</strong>. Situations where you may consider exploring the “backward” approach:</p><ul><li>When you’re working with temporal data, as we did in this question.</li><li>When you’re working with strings (in English), which we read from left to right. What if traversing the string backward is easier?</li></ul><p><strong>Exercise</strong>: Here’s a coding challenge for practice: <a href="https://leetcode.com/problems/backspace-string-compare/">Backspace String Compare</a></p><h3>Using Data Structures</h3><p>To excel in programming interviews you need an excellent command of data structures. Questions that seem “easy enough” become hairy when you start writing the code. In these cases, leveraging data structures to help simplify the code you need to write is essential. You may need to use more than one data structure, or create your own altogether.</p><h4>LRU Cache</h4><p>In an LRU (least recently used) cache, the stalest item in the cache is evicted to make space for a new one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt1ERio66Ut8NWGrOa7tig.png" /></figure><p>Let’s think about how we would develop an LRU cache with <em>get</em> and <em>put</em> operations.</p><p>What if we used a queue in the form of a linked list? For the <em>put</em> operation, we insert an item into the queue, evicting the stalest (last) item if the queue is full. For the <em>get </em>operation<em>,</em> we traverse the queue to find the item. If found, we remove the item from its current location and insert it back into the list, thereby making it “fresh”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHHm3t8hy6pVvGo6g1dDjg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a79f926642293d7938b3fd02208c2c18/href">https://medium.com/media/a79f926642293d7938b3fd02208c2c18/href</a></iframe><p>The <em>put</em> operation inserts an item into the queue and if need be, pops an item if the queue is full. It has O(1) runtime complexity. The <em>get</em> operation, in the worst case, must traverse the entire queue to find an item. This operation has O(N) runtime complexity. Caches are usually optimized for reads (i.e. <em>get</em> operations), so we need a better implementation, ideally O(1). (You knew a simple linked list implementation wouldn’t cut it…)</p><p>The next data structure that comes to mind is a set or a hashmap. Something that has O(1) lookup. But how do we codify staleness? A linked list represents the staleness of an item beautifully (an item’s location in the list). A set doesn’t have any notion of order.</p><p>What if we store the “staleness” of an item in the hashmap as well? Would that help? The key would then be the hash of the item and the value would be its staleness. Our cache hit/miss logic would be O(1), we just need to confirm if the item exists in our hashmap. We still need to figure out how to update the “staleness” of the item on cache hit.</p><p>One possible solution is to keep an increasing count. We can use this count to update the staleness of the time on cache hit. A lower count means a staler item. During the <em>put </em>operation, should we need to evict an item, we evict the item with the lowest count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-KGafy3rtSrMDbRQbZdAQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70bebf98162844655bd326de62e618cc/href">https://medium.com/media/70bebf98162844655bd326de62e618cc/href</a></iframe><p>The <em>get</em> operation now has a runtime complexity of O(1), and the <em>put</em> operation has a runtime complexity of O(N) (since if we need to evict an item, we must traverse the entire hashmap to find the stalest item). Using a clever trick, we’ve successfully optimized for <em>get</em> operations. Let’s see if we can do even better…</p><p>Our linked list approach gave us an O(1) <em>put </em>operation. Our hashmap approach gave us an O(1) <em>get </em>operation. If we can somehow find a way to merge both approaches, we can achieve constant time <em>get</em> and <em>put </em>operations.</p><p><em>I’m going to describe the solution in the next paragraph, see if you can figure it out before moving forward.</em></p><p>What “sucks” about the linked-list is we must traverse every item during the <em>get</em> operation. Assuming we have a hashmap, we don’t need to traverse the list. The part that “sucks” about the hashmap is when finding an item to evict, we must traverse all items in the hashmap. If we have a linked list at our disposal, then we can pop the last item, and we’ll know which item to evict in the hashmap. It seems like the hashmap and the linked list play to each other&#39;s weaknesses. Let’s start reasoning through the <em>get &amp; put</em> operations.</p><p>To add a new item, we’ll insert it in the hashmap and the linked list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zOW3rjQjj2AURn89-1H6g.png" /></figure><p>What if the cache is full? What would eviction look like? For eviction, we can remove the last item in the queue. Since we have the evicted item on hand, we can remove it from the hashmap as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgHrJz4gqo8MPzmxAhFDPA.png" /></figure><p>Sweet, that worked out pretty well. Okay now let’s consider the <em>get</em> operation. Checking if the item exists is trivial, we simply check the hashmap. If it doesn’t, we say it was a cache miss. What if it exists? We need to update the item’s staleness. This is where things get hairy. We need to traverse the linked list to find the item and move it to the front. The difficulty lies in having to traverse the list. Can we somehow avoid the traversal?</p><p>A linked list is, in a sense, a collection of pointers to nodes. We need to traverse the linked list to get to the pointer we want. We need an alternate way of accessing this pointer. If only we had a constant time lookup data structure where we can store these pointers… Oh wait, we do!</p><p>Let’s keep track of every item’s pointer in the linked list by storing them as values in the hashmap. Now we can use the hashmap to access the pointer, and use the pointer to re-position the item in the linked-list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1qDzFgXAPWsKmoqFUfNJQ.png" /></figure><p>And voila! We now have an LRU cache with an O(1) <em>get</em> operation and an O(1) <em>put</em> operation, all because we bent data structures to our will. Pretty nifty stuff.</p><p><strong>Exercise</strong>: I’ll leave you to code this solution. It’s not that I’m lazy, I <em>would</em> code it up and paste it here… but you may get asked this question, or something similar, in an interview and having been through this exercise is good practice. Also, I’m a bit lazy…</p><h3>Understand Time And Space</h3><p>Almost every question you attempt will have solutions with various levels of runtime and spacetime complexity. Runtime complexity and spacetime complexity are, from what I’ve seen, related to some degree.</p><p>When an interviewer asks you if you can do better than your initial approach, you’ll likely need to sacrifice your spacetime complexity in order to achieve better runtime complexity. Luckily for you, interviewers seldom care about spacetime complexity. They may ask you to analyze it, but rarely will they ask you to improve it.</p><p>There are countless examples of the tradeoff between runtime and spacetime complexity. Take <strong>Finding a Duplicate</strong> for example:</p><p>Given an array, return True if there are duplicate numbers, False otherwise:</p><pre>[0, 1, 2, 3] -&gt; False<br>[3, 1, 2, 3] -&gt; True</pre><p>An O(1) spacetime solution is to use an outer/inner loop to compare every number with every other number, returning True if both numbers are the same. This solution has an O(N²) runtime complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PNOeKmhHRZqWpwsB0hRqQ.png" /></figure><p>Let’s sacrifice some of our spacetime complexity and create a sorted array. Duplicates are now adjacent to one another and we simply need to traverse the array to find them. We’ve gone from O(1) to O(N) spacetime complexity, and we’ve reduced our runtime complexity to O(N log N).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGpvdEhNoVTTIBj03uPQZg.png" /></figure><p>Let’s sacrifice more spacetime complexity and use a hashmap. We’ll traverse the list, using the numbers as keys for our hashmap, and keeping a count of how many times we’ve seen that number as the value. Once we’ve created our hashmap, we traverse the hashmap and return True if we see any value greater than 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ah4J0WSAwQDlB2d59p7vLg.png" /></figure><p>Our runtime complexity reduces to O(N) and our spacetime complexity raises slightly (since a hashmap is less memory-efficient than an array), albeit its still O(N).</p><p>There are countless of other coding challenges that exhibit the same time-space tradeoff. Take the LRU cache we developed in the previous section. The solution with the highest runtime efficiency also used the most space. Understanding the time-space complexity tradeoff gives you a systematic way to improve the runtime complexity of your solution. If you’re asked to find a better approach, ask yourself, how can I use space to my advantage:</p><ul><li>Are there any useful values I can pre-compute?</li><li>Can I reformat my input in a way that’s optimized to work with my algorithm?</li><li>Can I map the data to represent a problem I’m familiar with?</li></ul><p>In some cases, you’ll be asked to improve both time/space complexity and you won’t be able to conjure any data structures that will come to your rescue. Such questions are designed to stump you, and there is usually a detail in the question or a property of the problem you’re not leveraging. So make sure you read the question very carefully.</p><h3>Closing Thoughts</h3><p>Hopefully, my “tips” change the way you look at coding problems and help you during your interviews. I’ll re-iterate them again:</p><ul><li><strong>Lateral Thinking </strong>— Let your brain explore different ways to attack the problem.</li><li><strong>Using Data Structures</strong> — Use data structures for cleaner and more efficient code.</li><li><strong>Understand Time And Space </strong>— Sacrifice space for better time complexity (and vice versa). When asked to improve both time/space, try leveraging a property/detail of the problem.</li></ul><p>Of course, completing the coding questions alone won’t be enough to pass the interview. There are other things interviewers consider. During the interview, make sure you:</p><ul><li>Talk about what you’re thinking. (e.g. I’m having trouble with this aspect of the problem, I’m thinking if there’s some way I can get around it.)</li><li>Be positive! Light conversation and smiles go a long way.</li><li>Ask questions. You are evaluating the company just as much as they’re evaluating you. Is this a company you’d be excited to work for every day?</li></ul><h4>Exercises</h4><p>The problems covered in this article were relatively simple but they sufficed to illustrate the point. Along with the exercises listed in each section, here are some other coding challenges to help you practice:</p><ul><li><a href="https://leetcode.com/problems/two-sum/"><strong>Two Sum</strong></a></li><li><a href="https://leetcode.com/problems/merge-intervals/"><strong>Merge Intervals</strong></a></li><li><strong>Item Order Data Structure</strong>: Write a data structure that will be used for keeping track of the order of items in a list. The data structure should have <em>insert_item</em>, <em>delete_item</em>, and <em>reorder_item</em> operations. All operations should have O(1) runtime complexity.</li></ul><p>Good luck with your next coding challenge! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c1c90c121d0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/tips-for-your-next-coding-challenge-7c1c90c121d0">Tips for Your Next Interview Coding Challenge</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming, Business, & Metrics]]></title>
            <link>https://medium.com/@talham7391/programming-business-metrics-91426a20e9f0?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/91426a20e9f0</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[prioritization]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 04:01:18 GMT</pubDate>
            <atom:updated>2020-03-19T04:01:18.707Z</atom:updated>
            <content:encoded><![CDATA[<p>We start our programming journeys with no opinions, no biases, and our perspectives are subject to influence as we start learning more about writing code. A vast majority of our early experiences (from school assignments to software interviews) narrow our lens to consider just the correctness and performance of the code we write, but there’s more to it.</p><p>This article aims to further shape your perspectives and consider the act of programming in a different light.</p><h4>Disclaimers</h4><ul><li>The graphs used in this article are a visual aid. Their sole purpose is to communicate an idea — they’re not derived from real datasets.</li><li>Senior developers will find the content in this article “rudimentary”. I wouldn’t discourage you from reading it, maybe you’ll find my ideas “fresh”. Just don’t expect to be enlightened ;)</li></ul><h3>Facets of Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qOsVCm6fVFQszeGT" /><figcaption>Photo by <a href="https://unsplash.com/@zuizuii?utm_source=medium&amp;utm_medium=referral">Zui Hoang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As we mature as developers, our understanding of code evolves. Instead of spending time on trivial bugs, we start spending time on issues regarding scale, developer experience, and the like. Understanding the different perspectives from which we assess our code and how they relate with one another will:</p><ul><li>Help you <strong>improve code quality</strong>.</li><li>Clarify what’s <strong>providing business value</strong> and what isn’t.</li><li>Provide a means to <strong>make tough decisions</strong> regarding code structure.</li><li>Improve<strong> communication</strong> with your peers.</li></ul><p>What aspects of code creation do we consider?</p><h4>Correctness</h4><p>This may be the first aspect we consider: Will my solution work? Correctness is important/necessary but expensive. We go through many exercises to achieve this end:</p><ul><li>We write unit tests &amp; integration tests.</li><li>We invest in building automated testing pipelines in order to gate deployments and catch buddy code.</li><li>We seek review from our peers to catch gaps and errors in our logic.</li><li>If someone reports a bug, we spend time investigating and resolving the issue.</li></ul><p>Correctness is such a central component to programming that most (if not all) programming practices can be traced back to correctness.</p><h4>Maintainability</h4><p>At some point, you’ll undergo a shift in perspective from writing code you understand to writing code others will understand (including your future self). You’ll also realize code is a construct that requires constant maintenance and refactoring. There is no such thing as “fire and forget”. These realizations influence our decisions when writing code and we focus on:</p><ul><li><strong>Readability</strong> - Is it clear what this code is doing? Any code that isn’t easily understood because of contextual reasons is supplemented with comments.</li><li><strong>Extensibility</strong> - Code changes as we fix bugs and add features. Can the current code structure support this change with little/no friction?</li><li><strong>Code Structure</strong> - The speed at which new developers learn a codebase or the risk of making a change are all affected by code structure. We try to write well-defined, loosely coupled components.</li></ul><h4>Performance</h4><p>Most changes to the code base are relatively straight forward. There are times however where we must consider the performance implications of the code we’re about to write. There are different ways to achieve an adequate level of performance:</p><ul><li>Applying your knowledge of data structures &amp; algorithms.</li><li>Writing stateless applications so that you can horizontally scale your servers on commodity hardware.</li><li>Leveraging highly performant technologies in your architecture that fit your use case. (<a href="https://redis.io/">Redis</a>, <a href="https://neo4j.com/">Neo4j</a>, <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a>, etc…)</li></ul><h4>Business Value</h4><p>All code we write has one and only one purpose: to further business interests. Understanding how code will impact the business in the present and in the future is a very important skill. Let consider how the practice of “Daily Deploys” affects the business:</p><ul><li><strong>Customer satisfaction</strong> goes up as you can deliver more value in less time.</li><li>“Bad” decisions become <strong>less expensive</strong> as Daily Deploys shorten your <a href="https://en.wikipedia.org/wiki/Lead_time">lead time</a>. This enables your organization to take calculated risks and run insightful experiments. Your <strong>costs go down</strong> and your companies <strong>competitive advantage </strong>goes up.</li></ul><p>Seeing the direct business impact of the code you’re writing can be a very rewarding experience. Of course, that may not always be true. Many developers are programming enthusiasts; as such, they will propose ideas that align with their interests but may not align with the business’s interests.</p><h4>Conventions</h4><ul><li><strong>Correctness</strong>, <strong>Maintainability</strong>, <strong>Performance</strong>, and <strong>Business Value</strong> will henceforth be known as the <em>facets of programming</em> or simply, <em>facets</em>. I’m not claiming this is a complete list of “facets”. They are merely a means to help communicate the forthcoming ideas in this article.</li><li>I will use bold lettering when referring to <em>facets</em>. (e.g. I really need to focus on <strong>performance</strong> when developing certain features.)</li></ul><h3>How Facets Relate to Work</h3><p>When we write code, our aim should be to maximize the potential for growth and profitability for the business:</p><ul><li>Driving outcomes that impact the company’s bottom line helps build credibility and authority. These accomplishments make for great points on your resume and excellent examples that support a case for promotion.</li><li>Growth benefits employees who have a vested interest in the business. (e.g. you may own company stocks or you may receive a bonus based on the company’s monetary performance).</li><li>Seeing the tangible impact of your efforts can be extremely rewarding and obviously, increasing profitably isn’t <em>too bad</em> for the business either…</li></ul><p>The <em>facets</em> I’ve mentioned have implications for the cash influx/outflux of the business. For example, code becomes complicated/messy if we neglect <strong>maintenance</strong> and as a result, features (that provide <strong>business value</strong>) take longer to develop. The cost of developing features correlates with the maintainability of your codebase.</p><p>We can group these <em>facets</em> into 2 categories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIdMLQ-U9LPq-_PC7zjLsA.png" /></figure><p>Ideally, we should always write code that’s sound from a <strong>correctness</strong>, <strong>maintainability</strong>, <strong>performance</strong>, and <strong>business value</strong> perspective. This would maximize revenue, minimize cost, and maximize profits.</p><p>It’s easy to satisfy all <em>facets</em> when the codebase is small but as the system grows in complexity, we’ll have to opt to satisfy one <em>facet</em> at the expense of another. For example, if we’re running behind schedule, we’ll have to do things the “wrong” way in order to ship the feature on time. The “wrong” way could mean relaxed testing, bad programming practices, or poor performance.</p><p>Suppose we have a backlog of pending tasks; some tasks focus on providing <strong>business value</strong> and others focus on <strong>maintenance</strong>. What prioritization strategy should we adopt?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCmPT4pEFRoVMBifbhcgiA.png" /></figure><h4>Be Greedy?</h4><p>Adopting a greedy approach means to prioritize tasks with the highest expected profit (i.e. choosing Task A). This is the fastest way to bring cash into the business, but it isn’t sustainable. Every feature you develop will cost a bit more than the last. Eventually, you’ll reach a point of <a href="https://en.wikipedia.org/wiki/Diminishing_returns">diminishing returns</a>, where the cost of adding new features will trump the expected revenue/growth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kp74ZF18WesFvMmWd-d5FA.png" /></figure><p>After the point of diminishing returns, a greedy prioritization strategy harms the business. Many startups adopt this model as they rush to capture market share. (Did someone say <a href="https://lmgtfy.com/?q=startup+guide+to+getting+acquired">acquisition strategy</a>?)</p><h4>Focus on Code Quality?</h4><p>The other extreme would be to prioritize <strong>maintenance</strong> and <strong>performance</strong> (i.e. choosing Task B). You may consider adopting this approach when paying down tech debt but there are some things to keep in mind:</p><ul><li>This strategy is slow and expensive. It is just as unsustainable as the greedy approach if the cost of writing/maintaining code isn’t superseded by the value it’s providing.</li><li>A slowly moving organization will eventually be outclassed by competitors in a fast-moving market:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcROQJhSPRircgri20UIog.png" /></figure><p>As a developer, you may love working with clean code but it isn’t a necessity for the success of the business.</p><h4>Focus on Metrics.</h4><p>There is no globally optimal strategy. Startups need to be greedy when they’re young and moderate-sized organizations eventually need to slow down. The key is to focus on what your business needs now, and what it may need in the future. We can make use of <a href="https://en.wikipedia.org/wiki/Proxy_(statistics)">proxy measures</a> to see where the business is struggling and where we can have an impact:</p><ul><li>If there’s a large number of <a href="https://wiki.audacityteam.org/wiki/Bug_Lists">P0 &amp; P1 bugs</a> in the backlog you may want to prioritize <strong>correctness</strong>.</li><li>If your average/median lead time is higher than 3–4 days then you may want to prioritize <strong>maintainability.</strong></li><li>If your P90 response time for important API endpoints is greater than 200ms then you may want to prioritize <strong>performance</strong>.</li><li>If your product is losing its competitive edge then you may want to prioritize <strong>business value</strong>.</li></ul><p>A metrics-focused approach also works in reactive situations:</p><p>Suppose you’re falling behind on a project. You must extend the delivery date or cut scope. If you decide to cut scope, you’ll need to compromise on code quality or drop certain features. If you decide to drop certain features, you’ll need to decide whether to drop the ones that require the most work or the ones that provide the least value. Clearly, a lot of decisions need to be made… and fast. What’s the best move?</p><p>In these situations, metrics become useful heuristics. If you’re prioritizing <strong>correctness </strong>(because your proxy measure, the number of customer complaints, is too high) then you may consider extending the delivery date so that you don’t ship buggy code.</p><p>Some other cool properties of a metrics-focused approach:</p><h4>Measurable</h4><p>Metrics are measurable. You’ll know whether or not your efforts are making a difference. This is much more reliable than “trusting your gut”.</p><h4>Easily Communicated</h4><p>Decisions backed by metrics communicate well to your peers. “We need to clean up our code because it’s too messy” isn’t as impactful as “Let’s clean up our code so that we can reduce our lead time and stay competitive”.</p><h4>Alignment</h4><p>The beauty of adopting a metrics-focused approach is that it aligns your organization across different units of work, which is critical for larger organizations.</p><ul><li>This approach helps guide which projects to work on.</li><li>When working on a project, it helps decide which task to prioritize.</li><li>When working on a task, it helps resolve conflicting opinions on implementation.</li></ul><h3>Conclusion</h3><p>We usually view coding as a way to tell computers what we want them to do. In a different context, coding becomes much more than than. In this article, we looked at code through the lens of the business. We considered its <strong>correctness</strong>, <strong>maintainability</strong>, <strong>performance</strong>, and <strong>business value</strong>. Using these <em>facets, </em>we derived a way to prioritize the code we write in the context of our business.</p><p>In a different context, we may need to consider yet another set of <em>facets</em>. Understanding these <em>facets</em> in relevant contexts and how these <em>facets</em> relate to one another can help you write not just better, but meaningful code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91426a20e9f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structuring a Robust Data Pipeline]]></title>
            <link>https://medium.com/swlh/structuring-a-robust-data-pipeline-24ff67783782?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/24ff67783782</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 02:53:39 GMT</pubDate>
            <atom:updated>2020-03-09T00:31:10.925Z</atom:updated>
            <content:encoded><![CDATA[<p>We all know and love data. Data holds insight. Data helps you make decisions. But data is a dog (pun <a href="https://www.datadoghq.com/">here</a>)… things can get real messy if you’re not careful. Let’s talk about how to build good dogs :)</p><h4>Prologue</h4><ul><li>“Data pipeline” is a pretty broad term; when I say “data pipeline”, I’m referring to infrastructure that supports <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load">ETL workflows</a>. If you don’t know what that is, familiarizing yourself with ETL would provide valuable context.</li><li>We work with existing data sources when building most ETL workflows. Resulting pipelines are brittle and hard to test. In order to build good pipelines, we need to think about data from the beginning instead of as an afterthought. This article will talk about how to build good data sources which will make our ETL workflow simpler. We’ll go over properties every ETL workflow should have but it might be hard to introduce some concepts into existing ETL workflows; especially ones that work with aggregated data sources.</li></ul><h3>Motivation</h3><p>A data pipeline is just like any other software system:</p><ul><li>It will start off simple and grow in complexity over time.</li><li>You will need to make decisions involving tech debt and how to pay that debt down in the future.</li><li>You will need to worry about scalability, maintainability, and operational stability.</li></ul><p>If your data pipeline doesn’t have a strong architectural foundation, it will break. I’ve had the fortune (at the misfortune of my company) of experiencing such a failure. A critical data pipeline for our FinOps department exploded.</p><ul><li>Some employees were <strong>stalled</strong>; they couldn’t do their work without the data.</li><li>Some employees were <strong>distracted</strong>; they paused their work in progress to get the pipeline working again.</li><li>Some employees were going <strong>crazy</strong>; they were trying to find people that could put out the fire.</li></ul><p>This incident pointed to the brittleness and instability of not just the pipeline that failed, but other pipelines in our system. After this incident, we invested time in making our pipelines more reliable but our infrastructure is still far from perfect. The anecdotes described in books like <a href="https://www.goodreads.com/book/show/17255186-the-phoenix-project">The Phoenix Project</a> about what happens when things go wrong are all too real.</p><p>In contrast, I’ve also had the fortune of working with an operationally sound pipeline that handles <strong>hundreds of millions</strong> of events per month. Weeks or even months go by and I almost forget this pipeline exists. It’s reliable, well tested, and easy to maintain. In this article, we’ll be looking at this pipeline and seeing what makes it robust.</p><h3>Avoiding Data Armageddon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FIMFrxdmIzeZ3-y1" /><figcaption>Photo by <a href="https://unsplash.com/@thefredyjacob?utm_source=medium&amp;utm_medium=referral">Fredy Jacob</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Like many other companies, our engineering department is slowly transitioning from monolithic to service-oriented architecture. Observability is a mandatory requirement for any critical service in our ecosystem. As we spin up more and more critical services, we’ll be generating more and more data. Without a sophisticated solution to manage all that data, we’ll head towards <strong>data armageddon </strong>— a place where people are running around screaming because data is disorganized, hard to access, and always causing fires.</p><p>First off, I would like to give credit where credit is due. “Data Armageddon” was a term coined by a very talented engineer, and my colleague/mentor/friend, <a href="https://www.linkedin.com/in/christian-battista-36a6b733/">Christian B</a>. The pipeline I’m about to introduce was his brainchild.</p><p>We worked on separate teams; I’m on the platform team and Christian worked on the Data team. Our teams collaborated on a joint initiative to:</p><ul><li>Increase the observability of our services.</li><li>Improve our data turn around time from days to minutes.</li><li>Explore any future projects Data and Platform might collaborate on.</li></ul><p>Our solution involved collecting data generated by several backend systems and storing them in our data warehouse.</p><h4>Data Structure</h4><p>Data structure is very important as it heavily influences your data pipeline. Namely, it will guide the infrastructure you’ll need to support your extraction and transformation steps. We knew this pipeline would be used by all of our backend services. What would our infrastructure look like if each service for responsible for its own data structure?</p><ul><li>Each service/team would spend time coming to a consensus on a data structure.</li><li>If services were expected to push their data into the pipeline, they would need to write validation, error handling, and data batching logic.</li><li>If our pipeline instead pulled data from services, service owners would need to modify the pipeline’s code so that it can understand &amp; pull their data.</li></ul><p>What I’ve described is a lot of work. Even more so considering <em>every</em> service would need to do this. This isn’t ideal. Our pipeline should be plug-n-play so that we can:</p><ul><li><strong>Increase operational stability</strong> as service owners aren’t introducing changes and using well-tested code.</li><li><strong>Decrease onboarding time</strong> for services wanting to participate in the pipeline.</li></ul><p>In order to create a pipeline any service can use, we need a common data/event structure across all our services. Such an event structure needs to be intuitive and versatile in order to satisfy all of our services’ use cases. An easy way to solve this problem is to choose from structures people are already familiar with. One such class of structures you might consider is <a href="https://en.wikipedia.org/wiki/Linguistic_typology">linguistic topology</a>, or in other words, the sentence structures which support different languages.</p><p>Deciding on a fixed structure unlocks the ability for you to abstract away the extraction and transformation steps. This abstraction enables you to bake important properties like durability and resiliency into your data pipeline.</p><p>We decided to use the <a href="https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object">subject-verb-object</a> (SVO) structure leaving services the freedom to decide which subjects, verbs, and objects they want to use. Check out <a href="https://snowplowanalytics.com/blog/2013/08/12/towards-universal-event-analytics-building-an-event-grammar/">this article</a> for more information on event grammar. Here are some examples of what events would look like (obtained from our data warehouse):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbAtcgzNRhU6mOrllSVmQQ.png" /></figure><p>Once you’ve found a structure that works for you, you can easily enhance the events you emit by attaching:</p><ul><li>Emitted timestamp / Ingested timestamp</li><li>Service Name / Process Name</li><li>Event Version</li><li>and anything else you might find useful!</li></ul><h4>Extraction</h4><p>Once you’ve decided on a data structure, abstracting away the extraction step is relatively straightforward. The approach you adopt will depend on your existing architecture and tools but will likely involve writing a client library that will either:</p><ul><li>Push data into your pipeline.</li><li>Configure your service so that your data pipeline can start pulling data.</li></ul><p>A common theme, however, is developer experience. We want to make it as easy as possible for developers to use the abstraction. Here’s what our client library looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*kxV2hGPlDCz-YyB91V-T7A.png" /></figure><p>Any service wanting to participate in the data pipeline would install the client library in their service. This library would expose an interface enabling developers to send structured SVO events to <a href="https://aws.amazon.com/kinesis/">Amazon Kinesis</a>.</p><p>Code that developers would be writing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4727d7b4227d12f8f690277fb258320/href">https://medium.com/media/a4727d7b4227d12f8f690277fb258320/href</a></iframe><p>Here’s the idea of what the library is doing behind the scenes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b379c294c14e679ce34af813ee88b71/href">https://medium.com/media/1b379c294c14e679ce34af813ee88b71/href</a></iframe><p>The code I’ve shown is very rudimentary. To create a robust client library, you must also consider:</p><ul><li><strong>Testability</strong> - you shouldn’t be emitting events when running local unit tests or continuous integration tests. To solve this problem, you can use dependency injection/patching so that your test framework uses a “mock emitter” while running unit tests.</li><li><strong>Network Failures</strong> - a network request can fail for any number of reasons. Having a retry / alerting policy in place will help you catch &amp; diagnose issues early in the pipeline.</li><li><strong>Batching</strong> - services may emit millions of events. Instead of making a separate network request for each event, you should batch several events into the same network request. Of course, this is only possible if the service ingesting the data supports batched events.</li><li><strong>Asynchronous Emitting</strong> - the code I’ve shown emits events synchronously, resulting in slower response times for the end-user (e.g. If an API endpoint has a response time of 100ms and we introduce a synchronous call with a response of time of 50ms to the endpoint handler, then our new API endpoint will have a response time of 150ms.). In most cases, events can be emitted asynchronously. This can be done by placing all events in a queue and have a worker running on a separate thread process that queue.</li></ul><h4>Transformation</h4><p>Now we’ll develop the transformation step. The transformation step is arguably the most failure-prone component of your pipeline because its most subject to change. Even more so if you’re working with multiple data sources/sinks. When designing your transformation step, make sure you think about:</p><ul><li><strong>Validation</strong> - If you have data coming from many different places, you’ll need to validate the data to make sure it isn’t corrupted. The transformation step is an excellent place to validate data coming in and data going out.</li><li><strong>Testability</strong> - Pipelines can sometimes be hard to test. Especially considering data can come from many different places with no deterministic structure. In certain cases, where you know the structure of the data (like in our pipeline), you should write integration tests to make sure your transformations work as expected.</li><li><strong>Scaling</strong> - If you’re streaming data (like we are) then chances are your data volume will vary throughout the day. Adopting a solution that can scale may result in substantial cost savings and will ensure your pipeline doesn’t crash under high pressure.</li><li><strong>Deployment Automation </strong>- Making use of scripts or infrastructure as code for deployments will increase your operational stability and help you quickly recover from mistakes.</li><li><strong>Monitoring</strong> - Capturing metrics such as CPU usage, Memory Usage, events processed, number of exceptions, etc… allow you to get a holistic view of how well your pipeline is working. Solutions that are ill-suited to capture these metrics are hard to debug.</li></ul><p>There are many different ways to implement your transformation step. It could be in the form of a cron job that runs every 5 minutes, a process running on your server, etc…</p><p>We decided to use an AWS Lambda function which gets triggered when there are new events to process. Adopting a serverless solution with a mature cloud provider meant we would get <strong>scaling</strong> and <strong>monitoring</strong> for free!</p><h3>Tying It All Together</h3><p>Here’s a holistic view of our pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*mCDYHUw6TQoQl8_hhqJO2Q.png" /></figure><ul><li>The pipeline starts with services sending their SVO events to AWS Kinesis.</li><li>AWS Kinesis is configured to batch incoming events into files. Each file holds approximately 5 minutes’ worth of events.</li><li>These files are stored in AWS S3 where they await processing.</li><li>When a new file is stored in S3, an AWS Lambda function is triggered with that file’s key.</li><li>The AWS Lambda function reads, validates, transforms, and loads the events in the file to <a href="https://cloud.google.com/bigquery">Google Bigquery</a> (our data warehouse).</li><li>Once the file has been processed, the lambda deletes the file from S3.</li></ul><p>Let&#39;s see what makes this a robust data pipeline.</p><h4>No Data Loss</h4><p>Before our events are processed, they are saved in a durable store: S3. If our lambda throws an exception while it&#39;s processing an event file, we don’t lose any data as the file still exists in S3. Once we’ve diagnosed and resolved the issue, we can have the lambda try to reprocess that file. We can safely delete the file from S3 after we’ve successfully loaded the data into our data warehouse.</p><p>Saving data in a temporary location while it awaits processing is a very powerful pattern used by various distributed systems. For example, in message brokers, events remain in the queue until a consumer deletes them. Using this pattern helps us avoid failures due to:</p><ul><li>Malformed/corrupted events and files</li><li>Buggy code</li><li>Transient network issues</li></ul><h4>Bought Not Built</h4><p>Building your own solutions is a lot of fun but…</p><blockquote>Using third-party tools helps us deliver <strong>more value</strong> at <strong>less cost</strong> and in <strong>less time</strong>.</blockquote><p>By leveraging AWS, we’ve avoided having to build a lot of functionality:</p><ul><li>AWS Kinesis handles data ingestion and the batching of events into files.</li><li>AWS Lambda automatically scales to handle the number of incoming events/files. Its also tightly integrated with AWS CloudWatch which enables us to monitor several metrics.</li><li><a href="https://github.com/julian/jsonschema">JSON Schema</a> helps us validate events against an incoming/outgoing schema.</li></ul><p>By using mature &amp; well-tested technologies to obtain the properties we wanted our pipeline to have, we’ve saved costs pertaining to development, maintenance, and operations.</p><h4>Plug-n-Play</h4><p>Services wanting to participate in the pipeline can do so by simply installing &amp; using the client library. They don’t have to introduce any changes to the pipeline and with fewer changes, there are fewer failures. As a bonus, we’ve saved developers the time it would’ve taken to:</p><ul><li>Agree on a data structure.</li><li>Write code to enable batched asynchronous event transmission.</li><li>Write unit &amp; integration tests to make sure their solution works.</li><li>Debug any issues &amp; putting out any fires.</li><li>and much more!</li></ul><p>In fact, our pipeline is so easy to use that in addition to all backend services, we’ve onboarded our frontend and mobile clients.</p><h3>Conclusion</h3><p>We’ve covered a lot of ground. We’ve talked about certain properties data pipelines should have and seen how they can be used in practice to avoid data armageddon. Of course, good code/architecture by itself isn’t enough to avoid failures. You’ll need to strive to create a culture of operational excellence. There’s a lot to say about that, but here are some ways to get started:</p><ul><li>Make sure you’re not the only one that understands how the pipeline works.</li><li>Hold monthly fire drills to make sure everyone on your team knows what to do in the event of a failure.</li><li>Plot important metrics on a dashboard and check that dashboard once every day. (This can be done as a team exercise during agile standups).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24ff67783782" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/structuring-a-robust-data-pipeline-24ff67783782">Structuring a Robust Data Pipeline</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Document Upload]]></title>
            <link>https://medium.com/@talham7391/implementing-document-upload-32fa76e8a1cb?source=rss-aeb11c1cc00b------2</link>
            <guid isPermaLink="false">https://medium.com/p/32fa76e8a1cb</guid>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Talha M]]></dc:creator>
            <pubDate>Mon, 17 Feb 2020 21:37:29 GMT</pubDate>
            <atom:updated>2020-02-17T21:37:29.610Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost one year ago I developed a <a href="https://github.com/talham7391/notebank-service">web app which allows students to upload &amp; share notes</a> with each other. I initially planned on monetizing this platform for a healthy side income but was deterred by the sheer amount of work that would require.</p><p>I ended up finishing the web app anyway thinking it would be a good learning experience. I wanted to make sure I nailed the “Document Upload” part as that would be central to the app. This article explores different ways I thought of implementing document upload; hopefully you’ll learn a thing or two!</p><h3>Preamble</h3><p>Before I get into implementation, let’s consider the problem:</p><blockquote>Students should be able to share documents with other students. This can be accomplished by allowing the student to upload the document along with some metadata. The web app will subsequently generate a link which other students can visit to view &amp; interact with the document.</blockquote><p>At a high level, here is what the solution will look like:</p><ol><li>The student initiates document upload from the client.</li><li>The server facilitates storage of the document in a deterministic location. (Either on the server’s file system, a database engine, or a cloud storage service like <a href="https://aws.amazon.com/s3/">AWS S3</a>)</li><li>The server records an entry in the database linking the document to the student.</li><li>The student is given a shareable link which will retrieve and present the uploaded document.</li></ol><p>Now let’s consider the lower level components we can stitch together to implement this high level solution. I’ve provided code written in Python and the <a href="https://www.djangoproject.com/">Django Web Framework</a> to help illustrate the different approaches I considered.</p><h4>Disclaimer</h4><p>The code in this article has been tested and is fully functional however the complete solution isn’t described. This includes any steps taken to configuring servers, setting up API clients, and installing dependencies.</p><p>In addition, my judgment of the different approaches we’ll be looking at in this article assumes our server is designed using a <a href="https://stackoverflow.com/questions/25834333/what-exactly-is-a-pre-fork-web-server-model">pre-fork worker model</a>. You may consider adopting a different approach if your server has a different design (e.g. asynchronous &amp; single threaded like NodeJS).</p><h3>Figuring out Storage</h3><p>We need to decide how/where we’re going to store our documents. The two approaches we’ll be considering are file system storage and cloud storage. There are some questions we should first ask ourselves:</p><ul><li>Is my backend running on <a href="https://www.docker.com/resources/what-container">ephemeral containers</a>?</li><li>Am I looking for a scalable solution or something quick and dirty to get the job done?</li><li>How much money am I willing to spend on document storage?</li><li>Am I willing to invest time into learning new technologies?</li></ul><p>The answer to these questions will dictate which of the following options will work best.</p><h4>File System Storage</h4><p>When a student uploads a document, we simply save that document on our server’s file system in a deterministic location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*m_AO7gMzNpIgHmHBLgZW2Q.png" /></figure><p>An example implementation:</p><pre>import os<br>from django.views import View<br>from django.http.response import HttpResponse</pre><pre>UPLOAD_FOLDER = &quot;/student_documents&quot;</pre><pre>class Index(View):<br><br>    def post(self, request):<br><br>        # omitted: request validation before doing the real work<br><br>        student_name = request.POST[&quot;student-name&quot;]<br>        student_folder = os.path.join(UPLOAD_FOLDER, student_name)<br>        file_location = os.path.join(<br>            student_folder,<br>            request.FILES[&quot;file&quot;].name<br>        )<br><br>        if not os.path.exists(student_folder):<br>            os.mkdir(student_folder)<br><br>        with open(file_location, &quot;wb&quot;) as f:<br>            f.write(request.FILES[&quot;file&quot;].read())</pre><pre>        # omitted: save the location of the file in the database</pre><pre>        return HttpResponse(&quot;Worked!&quot;)</pre><p>This is the simplest approach for storing documents. There are some things however we should keep in mind:</p><ul><li>In Python, when read() is called on a file, the contents of the file are loaded into memory. If we’re reading/storing many large files concurrently then we’ll run out of memory. Reading the file in chunks helps avoid this issue:</li></ul><pre>with open(file_location, &quot;wb&quot;) as f:<br>    for chunk in request.FILES[&quot;file&quot;].chunk(chunk_size):<br>        f.write(chunk)</pre><ul><li>To avoid overriding existing files, we can make use of uuid to make sure each upload has a unique storage location:</li></ul><pre>import uuid</pre><pre>student_name = request.POST[&quot;student-name&quot;]<br>student_folder = os.path.join(UPLOAD_FOLDER, student_name)<br>file_name = f&quot;{request.FILES[&quot;file&quot;].name}-{uuid.uuid4()}&quot;</pre><pre>file_location = os.path.join(student_folder, file_name)</pre><p>For simple use cases this approach works well. There is no infrastructure setup involved, we don’t need to learn a new technology, and we don’t incur additional costs due to storage. Depending on how much disk space your server has, this approach can easily handle thousands of small/medium sized documents. Here are some reasons why file system storage may not work for you:</p><ul><li>Your servers don’t have enough disk space to store the anticipated number of uploads.</li><li>Your backend runs on ephemeral containers; when the container’s go away, the uploaded documents are lost. (You can combat this using <a href="https://docs.docker.com/storage/volumes/">volume mounts</a>).</li><li>You need durability and availability; If your server goes down, you want the files to be accessible and not end up corrupted/missing.</li></ul><p>I decided this approach is too rudimentary for my use case:</p><ul><li>I need a solution that can handle hundreds of thousands of documents.</li><li>I want to be able to <a href="https://en.wikipedia.org/wiki/Scalability#Horizontal_(Scale_Out)_and_Vertical_Scaling_(Scale_Up)">horizontally scale</a> the servers to handle the load. Consequently, the servers need to be stateless, otherwise a document uploaded on one node won’t be accessible from another.</li><li>I can’t risk losing the documents students have uploaded if the server crashes.</li></ul><h4>Cloud Storage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ULweUouyUyqiGbW-pbROWA.png" /></figure><p>When a student uploads a document to our server, we will upload that document to a cloud storage service instead of saving it to the local file system. There are a lot of cloud storage providers out there, but we’ll be looking at <a href="https://aws.amazon.com/s3/">AWS S3</a>.</p><blockquote>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance.</blockquote><p>If you’ve never worked with a cloud storage service before, think of it as a key-value store you interface with using an API; the key is the name of the file and the value is the file itself. Read <a href="https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html">this guide</a> to learn how to use S3.</p><p>For our use case, we’ll create a S3 bucket called student-uploads and upload all our files to a deterministic location within that bucket.</p><pre>from django.views import View<br>from django.shortcuts import render<br>from django.http.response import HttpResponse<br>import os<br>import boto3</pre><pre># these variables shouldn&#39;t be in your code<br>ACCESS_KEY_ID = &quot;secret1&quot;<br>SECRET_ACCESS_KEY = &quot;secret2&quot;</pre><pre>s3_client = boto3.client(<br>    &quot;s3&quot;,<br>    aws_access_key_id=ACCESS_KEY_ID,<br>    aws_secret_access_key=SECRET_ACCESS_KEY,<br>    region_name=&quot;ca-central-1&quot;,<br>)<br><br>S3_BUCKET_NAME = &quot;student-uploads&quot;<br><br><br>class Index(View):<br><br>    def post(self, request):<br><br>        student_name = request.POST[&quot;student-name&quot;]<br>        file_location = os.path.join(<br>            student_name,<br>            request.FILES[&quot;file&quot;].name<br>        )<br><br>        s3_client.put_object(<br>            Bucket=S3_BUCKET_NAME,<br>            Key=file_location,<br>            Body=request.FILES[&quot;file&quot;],<br>        )</pre><pre>        return HttpResponse(&quot;Worked!&quot;)</pre><p>S3 is perfect for my use case:</p><ul><li>Using an external centralized storage solution allows my servers to remain stateless. This enables horizontally scaling without having to worry about spatial locality.</li><li>S3 scales with demand; I won’t have to worry about document storage limitations being a bottleneck for the service.</li><li>S3 is durable. There is almost no chance of documents being lost/corrupted due to an outage.</li></ul><p>Although S3 is perfect for this use case, it introduces a new complication we must consider:</p><p>Saving files to the local file system is a relatively fast operation. Uploading files to S3 isn’t; this can take several seconds depending on the network and file size. As a result, our server can get bogged down and stop processing requests if it’s too busy performing uploads. We’ll explore solutions to this problem in the next section.</p><p><em>p.s. Keep in mind, using a cloud storage service costs money. I decided I was okay with spending a few dollars on cloud storage every month.</em></p><h3>Figuring out Upload</h3><p>We’ve figured out we need to use a cloud storage solution, but we need to make sure our approach is scalable. Let’s consider our options:</p><h4>Synchronous Upload</h4><p>When a student uploads a document, the worker handling the request will accept the upload and then upload the document to the cloud storage service. This is considered a synchronous approach because when the function that does the upload returns, we’ll know the upload has either finished or failed. The code from the previous section is an example of a synchronous upload:</p><pre>def post(self, request):<br><br>    student_name = request.POST[&quot;student-name&quot;]<br>    file_location = os.path.join(<br>        student_name,<br>        request.FILES[&quot;file&quot;].name<br>    )</pre><pre>    # synchronous upload to AWS S3<br>    s3_client.put_object(<br>        Bucket=S3_BUCKET_NAME,<br>        Key=file_location,<br>        Body=request.FILES[&quot;file&quot;],<br>    )</pre><pre>    return HttpResponse(&quot;Worked!&quot;)</pre><p>This is the simplest option but it doesn’t scale well. If enough students start uploading documents at the same time, the server will get too busy to handle other requests. A synchronous approach would’ve been fine if uploads were infrequent enough in our web app, but we expect a high number of uploads. Let’s consider another option.</p><h4>Asynchronous Upload</h4><p>When a student uploads a document, the server accepts the upload and places the document in a queue. A separate set of workers that operate on this queue are responsible for uploading the documents to the cloud storage service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*YpC03w2P477qIi1PZPxPGg.png" /></figure><p>This insures workers which handle web requests aren’t bogged down by too many upload requests. There are many different queueing solutions available for different web frameworks. For instance, if you use Django then you may consider using <a href="https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html">Celery</a>:</p><p>In the request handler we’ll place the file on the queue:</p><pre>def post(self, request):<br><br>    student_name = request.POST[&quot;student-name&quot;]<br>    file_location = os.path.join(<br>        UPLOAD_FOLDER,<br>        f&quot;{student_name}-{request.FILES[&#39;file&#39;].name}&quot;<br>    )</pre><pre>    # save the file in a deterministic location<br>    with open(file_location, &quot;wb&quot;) as f:<br>        f.write(request.FILES[&quot;file&quot;].read())</pre><pre>    # Placing this file_location on the queue:<br>    # A celery worker will read the queue and upload our file to s3.<br>    tasks.upload_to_s3.delay(file_location)<br><br>    return HttpResponse(&quot;Worked!&quot;)</pre><p>The code that gets executed by the celery worker to do the upload:</p><pre>@shared_task<br>def upload_to_s3(file_location):<br>    with open(file_location, &quot;rb&quot;) as file:<br>        s3_client.put_object(<br>            Bucket=S3_BUCKET_NAME,<br>            Key=file_location,<br>            Body=file,<br>        )</pre><pre>    # We can delete the file once it&#39;s been uploaded<br>    os.remove(file_location)</pre><p>The main drawback of this approach is we don’t know when the files have finished uploading. A busy server may not execute an asynchronous upload for minutes. What does this mean in terms of UX?</p><ul><li>When students upload a document, we will need to show them a “Your file is being processed” message.</li><li>We cannot show a progress bar since we can’t be certain when a worker is ready to process their upload.</li><li>When the user loads a page which depends on that document, we will have to check if their upload has been processed as we render the response - increased complexity… not good.</li><li>What if we don’t want the user to have to refresh a page to see if their upload has been processed? We’ll need some JavaScript. We can either have the client connected via WebSockets and send updates or have the client repeatedly poll the backend every few seconds - again, increases complexity… not good.</li></ul><p>The root of the problem is we are trying to represent a synchronous workflow asynchronously. If we didn’t care when the upload was processed, an asynchronous approach would work beautifully. So how can we represent this workflow synchronously yet protect our server from a tsunami of upload requests?</p><h4>Client Upload</h4><p>This approach requires a bit of client/server cooperation. All files will end up in a cloud storage service anyways, so why not have the client upload to it directly? Let’s get rid of the middle man.</p><p>S3 enables client-side uploads using <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURL.html">pre-signed URLs</a>. Pre-signed URLs are a way to authorize clients to upload to S3 without the need for secrets. The workflow essentially looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zq_wsee3iO9sp0_PmGqZKw.png" /></figure><ol><li>The client requests a file upload from the backend server.</li><li>The backend generates a pre-signed url the client can use to upload their file.</li><li>The client uploads their file to the given url.</li></ol><p>An example implementation on the client:</p><pre>function uploadButtonClicked() {<br>    var studentName = document.getElementById(<br>        &quot;student-name-input&quot;<br>    ).value;<br>    var file = document.getElementById(&quot;file-input&quot;).files[0];<br>    var fileName = getFileName(file.name);<br><br>    requestUpload(studentName, fileName).then(presignedUrl =&gt; {<br>        doUpload(presignedUrl, file);<br>    });<br>}<br><br>function requestUpload(studentName, fileName) {<br>    var formData = new FormData();<br>    formData.append(&quot;student-name&quot;, studentName);<br>    formData.append(&quot;file-name&quot;, fileName);<br><br>    var xhr = new XMLHttpRequest();<br>    xhr.open(&quot;POST&quot;, &quot;/&quot;);<br>    xhr.setRequestHeader(&quot;X-CSRFToken&quot;, csrfToken);<br><br>    return new Promise((res, rej) =&gt; {<br>        xhr.onload = function() {<br>            presignedUrl = JSON.parse(this.responseText);<br>            res(presignedUrl);<br>        }<br>        xhr.send(formData);<br>    });<br>}<br><br>function doUpload(presignedUrl, file) {<br>    var xhr = new XMLHttpRequest();<br>    xhr.open(&quot;POST&quot;, presignedUrl[&quot;url&quot;]);<br><br>    var formData = new FormData();<br>    for (var i in presignedUrl[&quot;fields&quot;]) {<br>        formData.append(i, presignedUrl[&quot;fields&quot;][i]);<br>    }<br>    formData.append(&quot;file&quot;, file);<br><br>    xhr.send(formData);<br>}<br><br>function getFileName(filePath) {<br>    var x = filePath.split(&quot;\\&quot;);<br>    return x[x.length - 1];<br>}</pre><p>Here’s what the server is doing:</p><pre>def post(self, request):<br><br>    student_name = request.POST[&quot;student-name&quot;]<br>    file_name = request.POST[&quot;file-name&quot;]<br>    file_location = os.path.join(student_name, file_name)<br><br>    url = s3_client.generate_presigned_post(<br>        S3_BUCKET_NAME,<br>        file_location,<br>    )<br><br>    return JsonResponse(url)</pre><p>When the backend was doing the upload, the supported upload capacity was limited by the power/size of our server. By having the client do the upload, we’re now limited by the supported upload capacity of S3, which is high enough that S3 won’t be a bottleneck. Now our web server can scale independently of the number/size of uploads.</p><p>Our frontend code has increased complexity but the upload logic can be easily abstracted away behind a function call. We’ve achieved a scalable upload solution and we’ve unlocked the ability to show user’s their upload progress.</p><h3>Conclusion</h3><p>That brings us to the end of the article. We’ve stepped through different ways of implementing document upload, starting from a simple approach for simple use cases to more complex approaches for complex use cases. Some closing remarks:</p><ul><li>There’s one piece of the puzzle we didn’t cover: generating a shareable URL. There are many different ways to implement this, but here’s the basic approach I took: I defined a URL pattern that translates to a student’s profile, and created a database table that maps a student’s profile to the URLs of their uploads. I simply serve the document from the appropriate URL when someone makes a request for it.</li><li>We covered POST performance in this article but not GET performance. To make document retrieval faster, consider using a <a href="https://en.wikipedia.org/wiki/Content_delivery_network">CDN</a> to cache documents closer to their requesters.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32fa76e8a1cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>