<?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 Neal Hu on Medium]]></title>
        <description><![CDATA[Stories by Neal Hu on Medium]]></description>
        <link>https://medium.com/@nealhu?source=rss-db899621b12b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*utcBmIHkRqU7tHwOKCEMHA.jpeg</url>
            <title>Stories by Neal Hu on Medium</title>
            <link>https://medium.com/@nealhu?source=rss-db899621b12b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:23:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nealhu/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[Why Should You Build Your Own Kubernetes Operator]]></title>
            <link>https://itnext.io/why-should-you-build-your-own-kubernetes-operator-f60c25df0b1c?source=rss-db899621b12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f60c25df0b1c</guid>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Neal Hu]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 06:08:23 GMT</pubDate>
            <atom:updated>2020-06-09T06:08:23.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s easier and more beneficial than you think</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJf5IIeh8Mz_B-pAsXPTJA.jpeg" /><figcaption>Credit: CorrieMiracle/P<a href="https://pixabay.com/photos/beach-sand-ocean-sand-castle-2445836/">ixabay</a></figcaption></figure><p>Kubernetes Operator is one of the most trending technologies in the Kubernetes community. As of May 2020, the <a href="https://github.com/operator-framework/awesome-operators/blob/master/README.md">Awesome Operators</a> repo lists 145 Operators. Every major software that is hostable on Kube — such as MySQL, Kafka, and Elasticsearch — has one or more Operators. If you’re a regular Kube user who doesn’t host your databases, you might consider building an Operator irrelevant, which is just plain wrong.</p><p>This article discusses what a Kubernetes Operator is and why all Kube users should consider building one for their apps.</p><h3>Kubernetes Operators in a nutshell</h3><p>A Kubernetes Operator is a program that follows Kube’s Operator pattern. According to the official <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/operator/">Kubernetes website</a>:</p><blockquote>Operators are software extensions to Kubernetes that make use of <strong>custom resources</strong> to manage applications and their components. Operators follow Kubernetes principles, notably the <strong>control loop</strong></blockquote><p>As you can see, the Operator pattern consists of two major components:</p><ul><li><strong>Custom resource (CR):</strong> A CR is a Kube API object similar to out-of-box Kube resources like Pod, Deployment, and Service, but Kube users define most of its schema. A CR has specs and status sections, and is maintained by Kube so that users can create, read, update, and delete (CRUD) it via Kube APIs. The specs section allows users to describe the <strong>desired states</strong> of their apps in their respective languages. For example, users can create a key in CR named “replicasPerRegion,” which stores how many instances of an app each region should have.</li><li><strong>Control loop: </strong>A control loop is a piece of code implemented by Kube users. The loop’s job is to continually interact with Kube APIs and to compare and reconcile the reality with the desired states (CR). Hence, its other name: the reconcile loop. The loop also puts the results of the comparison and reconciliation in the CR’s status section.</li></ul><p>Any program that follows this pattern is a Kube Operator. You might also have heard of something called the <a href="https://github.com/operator-framework/operator-sdk">Operator SDK</a>, but it’s nothing more than a framework to build Operators and therefore unnecessary.</p><h3>Why should I build an Operator</h3><h4><strong>OOP for Kubernetes</strong></h4><p>The Operator pattern optimizes and refactors containers, just as Object-Oriented Programming (OOP) does for software systems. It manages complexities by improving modularity, readability, and reusability of container-based apps.</p><p>Programming languages like Java come with built-in primitives and data structures like integer, map, and list, allowing users to build complex custom classes on top of them. As all seasoned programmers know, according to OOP principles, rather than using a built-in type Map&lt;String, String&gt; to store student info, one should create a class as follows:</p><pre>public class Student {<br>  private String firstName;<br>  private String lastName;<br>  private String id;<br>}</pre><p>Similarly, Kube offers a set of “primitives” for running containers like Pod, Replica Set, and Deployment. While it’s convenient to use them to run some containers quickly, as the system’s complexity grows, maintaining all the containers becomes more challenging. By defining your own CR, and letting the control loop logic create more Kube “primitives,” you can archive things such as</p><ul><li>More meaningful names in your Kube manifest files for better readability.</li><li>Validations specific to your use cases. For example, you might have Kube reject a CR if it sets the number of instances of an app to something less than 3.</li><li>Custom deployment logic on top of Kube “primitives.” For example, forcing one Deployment to have the same number of replicas as another Deployment.</li><li>· Complexities hidden from operational staff such that they don’t need to learn tens of YAML files but only a few facade CRs.</li></ul><h4>Portability</h4><p>A reason to use Kubernetes is portability. It provides a universal layer on top of which your container-based apps can run, regardless of the underlying infrastructure, AWS, IBM Cloud, or your own data centers. Operators further enhance that portability.</p><p>Deploying a complex app is not trivial: some containers might need to wait for others, or a part of deployment logic might need to be disabled in certain circumstances. People have invented continuous delivery (CD) frameworks like Spinnaker and Jenkins, as well as tools like Helm and Kustomize, to tackle such complexities. It’s therefore common to deliver an app as a set of images, Kube manifests, and deployment scripts/charts/config files. But let’s face it: different teams pick different tools, and different customers have different CD setups. Operators can rescue you from the hell of replicating and tailoring the same deployment logic for different setups.</p><p>With the Operator pattern, Kube Operator’s control loop handles deployment logic of orders and conditions. The Operator itself is a container that can run on any Kube cluster, which minimizes the deployment dependency requirements outside Kube. To deploy an app, all users need is to create Operator container and one or several CRs, and the Operator takes care of the rest. CD and other deployment tools are still required, but their logic boils down to a few lines of code lines that take mere minutes to port from one to the other.</p><h4>Better operation</h4><p>The Operator pattern aims to simulate and automate human operators’ behavior. A human operator:</p><ol><li>Establishes the desired states of the system from documentations like a runbook. For example, how many instances should be healthy or certain checks pass.</li><li>Checks whether the current situation meets the desired states, and proceed to step 3 if it’s not.</li><li>Takes action to fix the situation.</li><li>Repeats step 2 and 3 until desired states are met.</li></ol><p>For human operators, whether they’re SREs or customers who bought your app to run onsite, the Operator pattern directs their attention to the right places. The specs sections of CRs spell out the desired states for human operators, while the status sections of CRs show how the reality aligns with said desired states. Their declarative style also makes states easy to read and maintain, while also hiding the complexity of how desired states are archived. Last but not least, your app gains the ability to “self-heal,” since the control loop doesn’t stop until desired states are met.</p><h4>Enjoy the Kube ecosystem</h4><p>Since CRs are also Kube API objects like Deployment and Pod, they are inherently compatible with tools in the Kube ecosystem. Instead of investing in your own tools to visualize, manage, and monitor your app, you’d do better to use tools such as kubectl and Kube dashboard. The Kube community offers more features, bug fixes, and tutorials comparing to in-house operation tools. Plus, human operators can avoid spending time learning new tools and get onboard faster.</p><h4>It’s easy</h4><p>Lastly, <a href="https://sdk.operatorframework.io/build/">Operator SDK</a> has made building an Operator easy. It supports building an Operator with Golang, Ansible, or Helm. I strongly recommend starting with an <a href="https://sdk.operatorframework.io/docs/ansible/quickstart/">Ansible-based Operator</a>, even when you’re already familiar with Golang. With the help of Ansible’s k8s and template modules, you can describe your Operator’s tasks in a rather straightforward YAML file and get a non-trivial Operator up and running within a few hours.</p><h3>Conclusion</h3><p>Kube Operator should be at the top of your to-do list if you deliver complex apps on Kubernetes. It’s simple to use, but can improve your apps’ structure, portability, and operation experience while saving development time in the long run.</p><p>If you enjoyed this article, <a href="https://medium.com/@nealhu">follow me</a> on Medium! I write about distributed systems and software architecture, such as:</p><ul><li><a href="https://itnext.io/before-you-use-kustomize-eaa9529cdd19">Before You Use Kustomize</a>. The pros and cons of the popular Kubernetes config management tool Kustomize</li><li><a href="https://itnext.io/logging-like-a-pro-8cc6ad09e415">Logging-Like-a-Pro</a>. Tips on designing your software systems toward better automations</li><li><a href="https://itnext.io/automation-friendly-software-systems-and-how-to-build-them-7a7c5e3c1a15">Automation-friendly Software Systems and How to Build Them</a>. Tips on designing your software systems toward better automations</li><li><a href="https://itnext.io/minimalist-software-architecture-426888684e60">Minimalist Software Architecture</a>. Lessons learned from building large-scale multi-region distributed systems</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f60c25df0b1c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/why-should-you-build-your-own-kubernetes-operator-f60c25df0b1c">Why Should You Build Your Own Kubernetes Operator</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging Like a Pro]]></title>
            <link>https://itnext.io/logging-like-a-pro-8cc6ad09e415?source=rss-db899621b12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cc6ad09e415</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Neal Hu]]></dc:creator>
            <pubDate>Tue, 19 May 2020 07:05:42 GMT</pubDate>
            <atom:updated>2020-05-19T07:05:42.168Z</atom:updated>
            <content:encoded><![CDATA[<h4>Theories and best practices on effective application logging</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFMhghRhxBenlCCzWaNSGw.jpeg" /><figcaption>Credit: <a href="https://pixabay.com/photos/police-crime-scene-murder-forensics-3284258/">Alexas_Fotos</a> on Pixabay</figcaption></figure><p>Logs are like evidence in crime scenes, and developers are like CSIs. Logs play a crucial role in developers’ investigation of a bug or an outage. Same as how lack of evidence leads to cold cases, lack of meaningful logs makes troubleshooting time-consuming or even impossible. I have seen people wrestle with tools such as strace and tcpdump, or deploy new code to production during an outage just to get more logs to diagnose a problem.</p><p>As the old saying goes, “A beard well lathered is half shaved,” all professional developers should learn to log effectively. This article aims to not only provide a list of useful application logging practices but also explain the theories, such as the what, the when and the who in logging.</p><h3>How do we debug</h3><p>It’s hard to talk about logging without first discussing what a program is and how people debug because logs are supposed to help with debugging.</p><h4>Program as state transitions</h4><blockquote>A program is a series of <strong>transitions among states</strong>.</blockquote><p><a href="https://en.wikipedia.org/wiki/State_(computer_science)">States</a> are what a program stores in its memory at a particular time point, and the code of a program defines how the program transit from one state to another. Developers using imperative programming languages such as Java often focus more on the procedure (code) than states. However, considering a program as a series of states is a crucial mindset to adopt, because states are keener to what the program should do, rather than how the program does it.</p><p>For instance, if a robot is getting my car’s gas tank filled, when described as state transitions, it needs to go from the state (tank=empty, money=$50) to the state (tank=full, money=$15). When described as a process, the robot needs to find a gas station, get the car there, and pay. The procedure matters a lot, but states are more direct in measuring the correctness of the program.</p><h4>Debug</h4><p>Debugging is a mental reconstruction of state transitions. In their minds, developers replay how a program accepts inputs, goes through a series of state changes and produces outputs, then figure out what goes wrong. In development, developers use a debugger to assist with this mental process, while in production, it’s much harder to use debuggers therefore logs are used more often.</p><h3>What to log</h3><p>With the definition of debugging, what to log becomes more straightforward:</p><blockquote>Logs should contain sufficient information to help with the reconstruction of <strong>state transitions</strong>.</blockquote><p>It’s impossible and unnecessary to capture all states at all time points. The polices don’t need hologram videos but a few good sketches to catch criminals. It’s the same for logs, developers only need to log when <strong>critical state transition </strong>happens, and logs should contain the <strong>key characteristics of the current state </strong>and <strong>the reason for transition.</strong></p><p><strong>Critical state transition</strong></p><p>Not all state transitions are worth logging. The key is to think about the execution of a program as a series of state changes, divide them into phases, then focus on the time when the execution goes from one phase to another.</p><p>For example, assume there are 3 phases in the startup of an app</p><ul><li>loads configurations</li><li>connects to dependencies</li><li>starts a server</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-GVen0-aghOecjR9S5stQ.png" /><figcaption>The startup of an app described as state transitions</figcaption></figure><p>It would be very reasonable to log at the beginnings and the ends of all these phases. Should there be any error connecting to dependencies and the app hangs, logs can clearly show that the app has loaded its configuration, entered the dependency connection phase but didn’t complete. With that, developers can quickly pinpoint the problem.</p><p><strong>Key characteristics</strong></p><p>Logging states is like sketching your program, only <strong>key characteristics</strong> of the core business logic need to be capture. If there is any sensitive information such as <a href="https://en.wikipedia.org/wiki/Personal_data">PII</a>, they should still be logged but masked or described indirectly.</p><p>For instance, when an HTTP server changes from the state “await request” into the state “request received,” it should log HTTP method and URL because they describe the basics of an HTTP request. Other elements of an HTTP request such as headers or part of the body should be logged if their values affect business logic. E.g., if the server behavior differs significantly between Content-Type:application/json and Content-Type:multipart/form-data, the header should be recorded.</p><p><strong>Reason for state transition</strong></p><p>Logging the reason of state transition is extremely helpful to debugging. Logs should briefly cover the meanings of the previous and the next states, and explain why. They help developers to connect dots and navigate the reconstruction(debugging) of program execution.</p><p><strong>Example</strong></p><p>A simple example to put all these together: assuming a server receives a malformed <a href="https://www.usrecordsearch.com/ssn.htm">SSN number</a>, and a developer wants to log about that event.</p><p>A few anti-pattern logs that lack key state characteristics and reasons:</p><ul><li>[2020–04–20T03:36:57+00:00] server.go: Error processing request</li><li>[2020–04–20T03:36:57+00:00] server.go: SSN rejected</li><li>[2020–04–20T03:36:57+00:00] server.go: SSN rejected for user UUID “123e4567-e89b-12d3-a456–426655440000”</li></ul><p>They all contain some information but not enough to answer questions developers might have during troubleshooting such as: What kind of request did the server fail? Why was the SSN rejected? Which user was impacted? A good log that helps with debugging is:</p><ul><li>[2020–04–20T03:36:57+00:00] server.go: Received a SSN request(track id: “e4a49a27–1063–4ab3–9075-cf5faec22a16”) from user uuid “123e4567-e89b-12d3-a456–426655440000”(<strong>previous state</strong>), rejecting it(<strong>next state</strong>) because the server is expecting SSN format AAA-GG-SSSS but got **-***(<strong>why</strong>)</li></ul><h3>Who should log</h3><p>A pitfall that many overlook is “the who” in writing logs. Writing logs from the wrong functions cause logs to contain either duplicated or insufficient information.</p><h4>Program as layers of abstraction</h4><p>Most well-constructed modern program is like a pyramid with layers of abstractions. Upper-layer classes/functions break a complex task into subtasks, while lower-layer classes/functions abstract subtask implementations like black boxes and provide interfaces for upper-layer to invoke. This paradigm makes programming easier because each layer only needs to focus on its logic without worrying about all the gory details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3rVqqX9iWKKTt5HJZjPFQ.png" /><figcaption>Layers of abstractions</figcaption></figure><p>For example, a website can consist of the business logic layer, the HTTP layer, and the TCP/IP layer. When responding to a request to some URL, the business logic layer focuses on deciding which webpage to show, and passes webpage content to the HTTP layer. The HTTP layer bakes the content into an HTTP response, then has the TCP/IP layer turn the HTTP response into TCP packets and send them out.</p><h4><strong>Don’t log at the wrong layer</strong></h4><p>As a consequence of abstraction, different layers have different levels of knowledge of an ongoing task. In the previous example, the HTTP layer does not have many ideas about how many TCP packets are sent, nor users’ intention when they are requesting this URL. When trying to log something, developers should pick the right layer that has a full view of state transitions and reasons.</p><p>In our SSN validation example, assuming SSN validation logic is wrapped into a Validator class such as</p><pre>public class Validator {<br>    // other validation functions ...<br> <br>  public static void validateSSN(String ssn) throws ValidationException {<br>    // do the validation<br>    String regex = &quot;^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$&quot;;<br>    Pattern pattern = Pattern.compile(regex);<br>    Matcher matcher = pattern.matcher(ssn);<br> <br>    if (!matcher.matches()) {<br>      <strong>// --&gt; Log Location A &lt;--</strong><br>      logger.info(&quot;Bad SSN blah, blah, blah...&quot;);<br>      throw new ValidationException(String.format(&quot;expecting SSN format AAA-GG-SSSS but got %s&quot;, ssn.replaceAll(&quot;\\d&quot;, &quot;*&quot;)));<br>    }<br>  }<br>}</pre><p>And there is another function that validates a request that updates user info, and it invokes SSN validation:</p><pre>public class Validator {<br>    // other validation functions ...<br> <br>  public static void validateUserUpdateRequest(UserUpdateRequest req) {<br>    // validate other attribute of req ...<br> <br>    try {<br>      validateSSN(req.ssn);<br>    } catch (ValidationException e) {<br>      <strong>// --&gt; Log Location B &lt;--</strong><br>      logger.info(String.format(&quot;Received a user update request(track id %s) from user uuid %s, rejecting it because %s&quot;, req.trackID, req.uid, e.getMessage()));<br>      // other error handling logic ...<br>    }<br> <br>    // other logic ...<br>  }<br>}</pre><p>There are two places, locations A and B, to write logs about an SSN validation failure, but only location B has sufficient information to log about. At location A, the program does not know what kind of request it’s handling nor which user is the request from. Logging does not do much but adding verbosity. It’s more appropriate for <em>validateUserUpdateRequest</em> to throw the error out to the caller (<em>validateRequest</em>) who has more context to log.</p><p>Although that is not to say that logging at lower layers of a program is all unnecessary, especially when lower layers don’t expose errors to high layers. For example, the network layer can have retry logic embedded, which means high layers don’t notice some of the intermittent network issues. In general, lower layers can write logs more at DEBUG level rather than at INFO level to reduce verbosity. If needed, developers can tune the log level to get more details.</p><h3>How many logs?</h3><p>There is an obvious trade-off between log volume and usefulness. The more meaningful logs, the easier to reconstruct the state transitions. There are two things you can do to control your logging bill:</p><h4>Estimate the relationship between your logs and workload</h4><p>To control log volume, it’s important first to give it a fair estimate. Most programs have two types of workload:</p><ul><li>Receive work items(requests) then respond</li><li>Poll work items from somewhere else then perform actions</li></ul><p>Most logging is triggered by workload, the more workload the program has, the more logs it writes. There can be other non-workload associated logs but they become trivial when a program starts taking workload. Developers should keep the relationship between # of logs and # of work items linear, or in another word:</p><blockquote># of logs = X * # of work items + constants</blockquote><p>where X can be determined by examining the code. Developers should have a good idea of the X factors for their programs and match it with the logging capacity and budget. A few common cases of X are:</p><ul><li>0 &lt; X &lt; 1: This means that logs are sampled and not every work items have logs. E.g. only log on error, or use some other log sampling algorithms. It helps reducing log volumes but it can also limit troubleshooting.</li><li>X ~ 1: This means that, on average, every work item produces roughly one record. It’s usually reasonable as long as that one log contains sufficient information(see “what to log” section).</li><li>X &gt;&gt; 1: People should have a very good reason to have an X that is way larger than 1. Because when the workload pikes, for example, the server receives a sudden storm of HTTP requests, X amplifies that and puts a huge load on the logging infrastructure, which is usually a call for trouble.</li></ul><h4>Make use of log levels</h4><p>What if X is still too large, even after optimization? Log levels can help. If X is way larger than 1, maybe some logs can be put at the DEBUG level to lower the X of the INFO level. When troubleshooting, the program can run at the DEBUG level temporarily to provide more information.</p><h3>Summary</h3><p>To write logs like a professional, one should consider a program as a series of state transitions with layers of abstractions. With those theories in mind, these key questions in application logging can be answered:</p><ul><li><strong>When to log</strong>: Log when critical state transition happens.</li><li><strong>What to log</strong>: Key characteristics of the current state and the reason for state transition.</li><li><strong>Who to log</strong>: Log at the right layer of abstraction that has sufficient context.</li><li><strong>How many logs</strong>: Estimate the X factor(X as in, <strong># of logs = X * # of work items + constants</strong>), and tune it to a budget but helpful value.</li></ul><p>If you enjoyed this article, <a href="https://medium.com/@nealhu">follow me</a> on Medium! I write about distributed systems and software architecture, such as:</p><ul><li><a href="https://itnext.io/automation-friendly-software-systems-and-how-to-build-them-7a7c5e3c1a15">Automation-friendly Software Systems and How to Build Them</a>. Tips on designing your software systems toward better automations</li><li><a href="https://itnext.io/minimalist-software-architecture-426888684e60">Minimalist Software Architecture</a>. Lessons learned from building large-scale multi-region distributed systems</li><li><a href="https://itnext.io/before-you-use-kustomize-eaa9529cdd19">Before you use Kustomize</a>. The pros and cons of the popular Kubernetes config management tool Kustomize</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cc6ad09e415" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/logging-like-a-pro-8cc6ad09e415">Logging Like a Pro</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before you use Kustomize]]></title>
            <link>https://itnext.io/before-you-use-kustomize-eaa9529cdd19?source=rss-db899621b12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaa9529cdd19</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Neal Hu]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 13:56:52 GMT</pubDate>
            <atom:updated>2020-06-09T19:16:32.744Z</atom:updated>
            <content:encoded><![CDATA[<h4>The pros and cons of the popular Kubernetes config management tool Kustomize</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2P6_eyzkcQWmKGtYIcbPQ.jpeg" /><figcaption>Credit: <a href="https://www.pexels.com/photo/man-wearing-black-and-white-stripe-shirt-looking-at-white-printer-papers-on-the-wall-212286/">Pexels</a></figcaption></figure><p>Kustomize is a tool used to manage and customize YAML files- particularly Kubernetes config YAML files. It gained popularity quickly over the past two years and has become part of kubectl since v1.14. Therefore, when our organization was considering moving away from our in-house Kubernetes config management tools, Kustomize was on the top of our candidate list. Here is what I found after researching and prototyping on Kustomize.</p><h3><strong>TD;LR</strong></h3><p>Kustomize relies on a “select &amp; patch” mechanism to simplify and refactor Kubernetes config YAML files. While this powerful approach offers many benefits, it also has limitations for certain tasks.</p><h3><strong>The problem</strong></h3><p>Our team has multiple microservices deployed in many different environments. After reviewing our config files, we found:</p><ul><li>commonalities among configurations of different microservices, such as labels and annotations.</li><li>commonalities among configurations of the same microservice in different environments, such as DNS, CPU, and memory settings.</li></ul><p>Therefore, our ideal tool should leverage those to refactor and avoid repeating ourselves(<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>).</p><h3><strong>A templateless solution</strong></h3><p>Inspired by the article “<a href="https://github.com/kubernetes/community/blob/master/contributors/design-proposals/architecture/declarative-application-management.md">Declarative application management in Kubernetes</a>,” Kustomize despises the use of complex templates and solves the problem by decomposing YAML files into base YAML files and overlay YAML files, then assembling them depending on the situation. In general, Kustomize has three types of files:</p><ul><li><strong>Base YAML files:</strong> these define the skeletons of Kube YAML files.</li><li><strong>Overlay YAML files</strong>: these are small bits of Kube YAML files, such as specs for a volume mount or a container.</li><li><strong>Kustomization files</strong>: these define how overlay files should be applied to base files in order to produce the final YAML files, called variants. They can also contain lightweight overlays such as common labels and annotations, as well as generate config maps and secrets. Typically each environment has its own kustomization file to tweak the configurations for that environment. For example, the dev kustomization file adds a sidecar container to a particular deployment while the production kustomization file does not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aw9cD6ItGkBupxCeJUuf5g.png" /></figure><p>What distinguishes Kustomize from a generic YAML file merger is that Kustomize understands Kube YAML syntax. For example, a feature in Kustomize named <a href="https://github.com/kubernetes-sigs/kustomize/blob/master/examples/patchMultipleObjects.md#target-selector">Target Selector</a> allows users to apply overlays only to deployment files that contain specific labels or annotations in their Kube metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6IYZJAtMuhlW9m5VhuRFA.png" /></figure><h3><strong>What’s good</strong></h3><p>Compared to template solutions, Kustomize forces people to avoid common pitfalls when writing config files. A typical templated config file consists of 3 parts:</p><ul><li>the part that doesn’t change after rendering(texts)</li><li>the part that changes after rendering(templates)</li><li>the control logic that combines them</li></ul><p>When the file is filled with templates and if…else statements to handle different scenarios, it becomes extremely unreadable and hard to maintain. In the meantime, the lack of integration with Kube syntax also makes some tasks, such as adding a name prefix to all Kube resources, tedious and error-prone, because users need to go over all files and manually add templates for name prefix.</p><p>Kustomize promotes good practice by separating the three parts of templated config files. Since Kustomize can only combine raw templateless Kubernetes YAML files, all control logic such as if…else statements must stay in Kustomization files. With the help of base YAMLs and overlay YAMLs, Kustomize encourages putting the fixed text into base YAMLs and the changing part in overlay YAMLs. Meanwhile, Kustomize has a series of handy transformers that understands Kube syntax. They can be used to avoid human mistakes and apply changes to all Kube resources like common labels.</p><h3><strong>What’s not so good</strong></h3><p>Trade-offs are burdens that all software designs have to bear, and Kustomize is no exception. Kustomize can help to refactor and customize configurations for different environments, but it has limitations when it comes to refactoring configurations shared among microservices.</p><p>Kustomize lets users create overlay YAMLs and use Kustomization files to decide how to apply them to base YAMLs. It seems like a good idea to leverage that and extract some common attributes of Kube resources into overlay files, such as labels, security contexts, and environment variables. However, that only works if Kustomize can put the extracted parts back to their original places. It might sound very straightforward, but it is not always simple with Kustomize.</p><p>There are two ways to let Kustomize know where to apply the overlay:</p><ul><li><strong>by paths</strong>: the path-based method allows users to embed the paths to override in overlay files’ YAML structure, or explicitly state that info in a Kustomization file with a <a href="https://github.com/kubernetes-sigs/kustomize/blob/master/examples/jsonpatch.md">Json6902</a> transformer. This approach is not very helpful in refactoring, because it requires a 1-on-1 mapping between overlays and paths in base YAMLs, and no parts can be shared.</li><li><strong>by selectors</strong>: the selector approach, such as <a href="https://github.com/kubernetes-sigs/kustomize/blob/master/examples/patchMultipleObjects.md#target-selector">Target Selector</a>, is much more suitable for refactoring. It allows users to specify a selector, for example, all deployments with specific annotations, and apply an overlay to those deployments.</li></ul><p>However, not all elements in Kube config YAMLs are “selectable,” because selectors always rely on some attributes, such as the kinds of Kube YAML, labels, or annotations to select the Kube elements. Still, not all of Kube elements have those. For example, a Kube deployment can have a list of containers, but there are no annotation-like attributes on those containers for Kustomize selectors to use. In order to apply a common overlay to containers in multiple deployments, the containers must have the same name. This makes refactor tasks such as common environment variables or container security contexts nearly impossible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmDc5CS0Q7Rbo8rR5qX-KA.png" /></figure><h3>Should I use Kustomize?</h3><p>The problem mentioned above is not entirely unsolvable, but it is somewhat fundamental. To make every part of Kube YAML “selectable,” it calls for a change or hack on Kube object schema, e.g., adding annotation-like fields to every object, or reusing some existing fields as annotations and then extending Kustomize to support them.</p><p>However, the problem is only likely to appear when the complexity of microservices reaches a certain level. Overall, I think Kustomize’s advantages still outweigh its disadvantages, especially if your team hasn’t yet tried a Kube config management solution.</p><p>If you enjoyed this article, <a href="https://medium.com/@nealhu">follow me</a> on Medium! I write about distributed systems and software architecture, such as:</p><ul><li><a href="https://itnext.io/why-should-you-build-your-own-kubernetes-operator-f60c25df0b1c">Why Should You Build Your Own Kubernetes Operator</a>. It’s easier and more beneficial than you think</li><li><a href="https://itnext.io/automation-friendly-software-systems-and-how-to-build-them-7a7c5e3c1a15">Automation-friendly Software Systems and How to Build Them</a>. Tips on designing your software systems toward better automations</li><li><a href="https://itnext.io/minimalist-software-architecture-426888684e60">Minimalist Software Architecture</a>. Lessons learned from building large-scale multi-region distributed systems</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaa9529cdd19" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/before-you-use-kustomize-eaa9529cdd19">Before you use Kustomize</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automation-friendly Software Systems and How to Build Them]]></title>
            <link>https://itnext.io/automation-friendly-software-systems-and-how-to-build-them-7a7c5e3c1a15?source=rss-db899621b12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a7c5e3c1a15</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Neal Hu]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 15:25:34 GMT</pubDate>
            <atom:updated>2020-03-31T04:44:29.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XsNOs5VLYO5DyEweGe5lA.jpeg" /></figure><h4>Tips on designing your software systems toward better automations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVRKdoTkmy3dUUPCNX7FpA.png" /></figure><h3><strong>Why should I care?</strong></h3><p>Mere mention of “automation” makes us think of DevOps. After building an app or a service, we must manage its life cycle. Environment setup, provision, maintenance, upgrade, and decommission naturally come into play. Designing your app to better support the automation of that life cycle makes DevOps and your life easier.</p><p>There is, however, a more important angle to consider when it comes to automation-friendliness: making your customers happy. In the context of an SaaS or PaaS, your product will be an integral building block of customers’ own larger systems. Said customers will therefore need to manage the life cycles of your product, preferably in automated fashion. Even if you think you can get away without automation for yourself, for your customers it’s a different story.</p><p>This article offers guidelines for designing software systems on which you and your customers can build good automation.</p><h3><strong>Defining good automation?</strong></h3><p>Not all automation is created equal. The best automation, at its core, must be <strong>easy to understand</strong> and <strong>easy to fix</strong>. From the perspective of automation users, it can be a simple matter of tweaking configurations, modifying snippets of code in a standard CI/CD system (e.g., Travis or Jenkins), or working with an in-house admin app/dashboard. By having more code (toward Turing completeness), you gain flexibility at the expense of making automation more complicated.</p><p>Your automation should favor the config end of the spectrum, because SREs, support engineers, or new developers filling in for you while you’re on vacation are more likely to be users than the original developers themselves. The more code you have, the steeper the learning curve is, thus increasing the possibility of error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kS4QTrdaFqD3BRInjo_R_w.png" /><figcaption>The tradeoff between complexity and flexibility</figcaption></figure><p>Failures are inevitable and interrupt your automation with network breaks, incorrect credentials, or mere changes of mind. Under ideal circumstances, your automation should be able to fix these undesirable setbacks with ease. When good automation fails, the fix should be as simple as “re-run until it succeeds.” Bad automation, on the other hand, generates a tangle of temporary states that must be manually cleaned up before retrying.</p><p>Now that we have a viable automation metric, we can move on to the topic of design.</p><h3><strong>Let there be APIs</strong></h3><p>Any automation-friendly system should have APIs — that is, ways of manipulating the state of your app programmatically. The golden rule: Any action performable by a human should map onto an API.</p><h3><strong>Declarative APIs with reconciliation</strong></h3><p>Though having APIs is the bare minimum required for automation, they don’t necessarily make automation easier. Declarative APIs with reconciliation, however, take your automation to the next level.</p><p>In short, declarative APIs focus on the “what” (desired states) instead of the “how” (changes between states). With declarative APIs, users are dictators who only tell your system the desired states it should be in, as opposed to imperative APIs, through which users function as orchestrators of your system. While both may achieve the same results, their differences in focus impact user experiences of automation.</p><p>Let’s say, for instance, your system provides backup capabilities. A declarative API will allow users to designate the desired state of the backup, for example, there exists a backup file for every N-day period. Your system takes note of that and keeps ensuring that it happens (reconciliation). An imperative API will allow users to create a backup job and have it run every N days. In practice, systems like Puppet and Kubernetes are exemplars of the declarative design paradigm.</p><p>Declarative APIs are preferable because they help simplify automation and translate naturally into configurations of desired states. This reduces the amount of code you need to write and turns the question of automation into a more straightforward “config file management” problem. Plenty of effective solutions in this regard, such as Git and GitOps, are available. Moreover, declarative APIs relieve failure by relegating errors to your system’s reconciliation logic, which is better equipped to handle them. Automation must ensure the desired states are received by your system and watch how it transits into those states. Lastly, declarative APIs are born to be idempotent and re-run safe. With imperative APIs you might worry about re-running certain automation tasks, such as requesting new resources and generating duplicates, whereas declarative APIs provide your system with a list of what’s needed. You can keep sending the same list and the system will make sure everything on that list is fulfilled instead of creating duplicate lists.</p><h3><strong>Fewer orders</strong></h3><p>While declarative APIs leave your system well-primed for automation, there is more you can do.</p><p>Most people who shy away from declarative APIs cite their inability to handle complicated workflows requiring sequences of steps that must happen in a certain order.</p><p>Let’s use a resource creation scenario as an example. Say we have two APIs, one for provisioning storage and the other for creating credentials. A user must first call the storage API, wait for the API to interact with the underlying infrastructure, and get an ID back. The user then needs to pass that ID to the credential API to create credentials for new storage. It’s hard to express such operational logic with declarative APIs and configurations due to their lack of imperative order and steps. You can “cheat” by letting people manually configure the steps they want, but that just makes your APIs imperative. It’s akin to inventing your own mini-language and letting people write snippets of code with it. The resulting solution will have the same pros and cons as any other imperative systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iu6CraFjMn2kSBlkMzRuXQ.png" /><figcaption>A resource creation example</figcaption></figure><p>Orders are the Achilles’ heel of declarative APIs. As a developer you can help by removing the need for orders. The following are two tricks you can try:</p><p><strong>Move orders into your system</strong></p><p>This can be done by wrapping imperative logics and merging a sequence of API calls into a higher-level “cover-all” API. In our example, your user desires to create storage and a credential for that storage. By packing everything into a “give me storage with a credential” API, your user only needs to call it once and let your system handle the specific steps required to return the final results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFeFYNUOWoiIxha_srubSw.png" /><figcaption>Removing orders with “cover-all” APIs</figcaption></figure><p><strong>Remove dependencies among steps</strong></p><p>When two steps no longer depend on each other, orders become unnecessary. One way to achieve this is by making your APIs more deterministic. Steps depend on each other because they lack certain information from other steps to proceed. Looking back on our previous example, credential creation must wait for provisioning out of need for a storage ID, not the readiness of the new storage. If we have a seer who tells the credential API the future-storage-ID-to-be, it can create a credential entry (ID, username, password) right away, or start a reconciliation loop to create it once the storage is ready. It’s true that users will not be able to use the credential until the storage is ready, but it’s effectively the same result as the imperative solution. The only difference is that, in this case, users provision, get a credential, then wait, while in the imperative solution users provision and wait before getting a credential.</p><p>So where do you find a seer? If your API results are deterministic, you don’t need to. We typically need a seer to tell the future storage ID because it’s some random value generated by our system at the time of provisioning. It doesn’t need to be that way because you can let your user pass in an ID for your system to use. You don’t need to worry too much about user-generated IDs not being unique enough, since there are plenty of ways to help uniqueness such as namespacing (e.g., setting ID as {username}/{user-gen-id}) or just checking and rejecting duplicates (e.g., twitter username).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sE1XtG9Vm7pqDTyzXvyEoA.png" /><figcaption>Removing orders with deterministic APIs and reconciliation</figcaption></figure><p>In summary, deterministic APIs translate running a sequence of imperative steps into sending declarative configurations once before waiting for all pieces to converge into desired states with the help of reconciliation loops.</p><h3><strong>Bonus: create a CLI</strong></h3><p>Declarative or not, CLI (command-line interface) is a great catalyst for automation. It allows people to automate your system with a few lines of script instead of creating a whole coding project — at least in the beginning. It’s a common practice these days and all major IaaS, PaaS, and SaaS services such as AWS, Azure, and IBM Cloud make use of one. Those interested can check out such frameworks as <a href="https://github.com/urfave/cli">https://github.com/urfave/cli</a> and <a href="https://github.com/pallets/click">https://github.com/pallets/click</a> to save you a lot of hassle while building beautiful yet professional CLIs.</p><p><em>Header image credit: </em><a href="https://pixabay.com/users/Pexels-2286921/"><em>Pexels</em></a><em>/Pixabay</em></p><p>If you enjoyed this article, <a href="https://medium.com/@nealhu">follow me</a> on Medium! I write about distributed systems and software architecture, such as:</p><ul><li><a href="https://itnext.io/minimalist-software-architecture-426888684e60">Minimalist Software Architecture</a>. Lessons learned from building large-scale multi-region distributed systems</li><li><a href="https://itnext.io/before-you-use-kustomize-eaa9529cdd19">Before you use Kustomize</a>. The pros and cons of the popular Kubernetes config management tool Kustomize</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a7c5e3c1a15" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/automation-friendly-software-systems-and-how-to-build-them-7a7c5e3c1a15">Automation-friendly Software Systems and How to Build Them</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimalist Software Architecture]]></title>
            <link>https://itnext.io/minimalist-software-architecture-426888684e60?source=rss-db899621b12b------2</link>
            <guid isPermaLink="false">https://medium.com/p/426888684e60</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Neal Hu]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 20:42:40 GMT</pubDate>
            <atom:updated>2020-03-31T04:44:45.757Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons learned from building large-scale multi-region distributed systems</h4><p>No man is an island, and neither are software systems. When designing a system, the software architect usually needs to choose dependencies — infrastructure, authentication, storage, the list goes on and on. When I first started taking on software architecture responsibilities at IBM, I tended to pick dependencies that got the job done, but soon I learned this lesson: Be a minimalist. Only introduce a new dependency when you absolutely need it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QbSF_MEyK9fHajJEWu3ow.jpeg" /><figcaption>Credit: <a href="https://pixabay.com/users/Pexels-2286921/">Pexels</a>/Pixabay</figcaption></figure><h3>What is a dependency, really?</h3><p>The answer seems straightforward. If your system relies on something to function, it’s a dependency. However, that is just the tip of the iceberg. A dependency needs:</p><ul><li>Presence: wherever your system goes, it goes, too.</li><li>Compliances: it meets the same compliances your system requires.</li><li>“UX”: it makes your users happy.</li><li>Maintenance: you need to spend extra resources to maintain it.</li></ul><p>Of course, there are many other factors when picking a dependency, but I feel these are worth talking about.</p><h3>Presence: a war story</h3><p>At IBM Watson, like at many other global businesses, our system is deployed all over the world. When designing an internal SaaS, our team wanted to use a database-as-a-service hosted by another IBM team. We did a prototype with it in our dev environment and even did an alpha rollout in our US production. Everything looked great.</p><p>However, when we were asked to deploy our system to non-US locations like Europe and Australia, on a deadline, we realized that the database team had its own schedule of global rollout. We could either wait for them or create a flag in our code to disable some functions depending on the DB’s presence.</p><p>We ended up going with the latter. But it introduced fragmentation to our deployments, which led to more trouble in our CI/CD pipeline. It also caused unnecessary complexities in our codebase. When we added new features, we needed to consider two cases (with that database or without it). If you have N dependencies, you potentially end up with 2^N combinations of dependency presence cases. Needless to say, it will be a nightmare.</p><p>That’s why when you choose a dependency, get a guarantee that it will be present wherever you are.</p><h3>Compliances</h3><p>Today there are more regulations and compliances on computing systems than ever. If your company serves EU citizens, you can be subject to GDPR. If you wish to serve healthcare businesses in the US, you have to meet HIPAA. All these regulations put requirements on your system and your dependencies. Just like you need to ensure presence, you need a guarantee that your dependencies meet the same compliances. Otherwise, the moment they break compliances, so does your system.</p><h3>“UX”: Kafka Streams vs Flink</h3><p>User experience matters more when you are designing a framework and giving other people the code to use rather than hosting a SaaS. Remember that when users invite your framework into their house, they have to welcome the dependencies, too.</p><p>Take Kafka Streams and Apache Flink, for example. I researched both of them when building a stream processing pipeline based on Kafka. Some quick context: Kafka is an open-source distributed queue system, and Kafka Streams is a framework based on Kafka that helps process data in Kafka. Flink can complete similar tasks.</p><p>Kafka Streams and Flink have lots of pros and cons, but the deal-breaker for me was their dependencies. Kafka Streams requires only Kafka, which we had already. Flink, on the other hand, requires a Zookeeper cluster to achieve HA (high availability). We didn’t have the resources to host such a cluster on our own; therefore, we chose Kafka Streams over Flink.</p><h3>Maintenance</h3><p>Adding a new dependency also has hidden maintenance costs, such as additional metrics, monitoring, and alerting, failure scenarios, and automation. Dependencies can get slow, or just fail, and your system needs to have logic to detect and handle them. When you deploy your system, your continuous delivery system should set up everything, including dependencies, so a new dependency usually means new logic in your automation. Be prepared for the extra work!</p><p>If you enjoyed this article, <a href="https://medium.com/@nealhu">follow me</a> on Medium! I write about distributed systems and software architecture, such as:</p><ul><li><a href="https://itnext.io/automation-friendly-software-systems-and-how-to-build-them-7a7c5e3c1a15">Automation-friendly Software Systems and How to Build Them</a>. Tips on designing your software systems toward better automations</li><li><a href="https://itnext.io/before-you-use-kustomize-eaa9529cdd19">Before you use Kustomize</a>. The pros and cons of the popular Kubernetes config management tool Kustomize</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=426888684e60" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/minimalist-software-architecture-426888684e60">Minimalist Software Architecture</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>