<?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 Waldemar Jankowski on Medium]]></title>
        <description><![CDATA[Stories by Waldemar Jankowski on Medium]]></description>
        <link>https://medium.com/@wrj111?source=rss-c050c515f40c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Y8WZkBGK1VnmpmHeHTDe9Q.png</url>
            <title>Stories by Waldemar Jankowski on Medium</title>
            <link>https://medium.com/@wrj111?source=rss-c050c515f40c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:03:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wrj111/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[Embrace the Chaos … Engineering]]></title>
            <link>https://medium.com/capital-one-tech/embrace-the-chaos-engineering-203fd6fc6ff7?source=rss-c050c515f40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/203fd6fc6ff7</guid>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[chaos-engineering]]></category>
            <dc:creator><![CDATA[Waldemar Jankowski]]></dc:creator>
            <pubDate>Thu, 07 May 2020 15:06:01 GMT</pubDate>
            <atom:updated>2020-05-07T15:06:01.001Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embrace the Chaos … Engineering</h3><h4>An Introduction to Chaos Engineering</h4><figure><img alt="dark wooden pole with many power lines connected to it. there are power lines rolled into circles and some pulled straight" src="https://cdn-images-1.medium.com/max/1024/1*C5nCL2cDMd8zkS3RDUgRYQ.jpeg" /></figure><h3><strong>What is Chaos Engineering?</strong></h3><p>As an Architect at Capital One, I deal with complexity on a daily basis. We’re consistently maturing our software delivery best practices and Chaos Engineering has been a focus for me.</p><p>According to ​<a href="https://principlesofchaos.org/?lang=ENcontent">Principles of Chaos</a>​:</p><blockquote><em>Chaos Engineering is the discipline of experimenting on a system in order to build confidence in the system’s capability to withstand turbulent conditions in production.</em></blockquote><p>That’s a lot of important words, but I like to think of Chaos Engineering as the “secret shopper” of application resiliency. Just like secret shoppers are used by businesses to uncover issues with customer service, Chaos Engineering is used to expose gaps and weaknesses in your applications. For example, a secret shopper is sent into a store to act in unpredictable ways and see how a customer service representative will deal with an irate customer. In a chaos engineering test — more commonly called a chaos experiment — an engineer deliberately injects unpredictability into their system to see how it responds to disruptions.</p><p>Chaos Engineering is an Agile approach to resiliency that complements traditional testing. Just like with Agile software development where you create a product, listen to feedback from your users, and make improvements iteratively, at its core Chaos Engineering follows the same process.</p><p>Chaos Engineering is not about introducing big bang failures like an entire AWS region becoming unavailable (although that can happen and you should be ready for it). It’s more likely to focus on more common issues like your disk running out of space or memory. Start with injecting small failures, observe how your system reacts, and fix any issues that are uncovered. As you increase the scope and run more chaos experiments, your system will iteratively become more resilient.</p><p>There are many different types of chaos experiments that can be unleashed on your applications and infrastructure, but they typically fall into three broad categories:</p><ol><li><strong>Resource</strong>​: How does your system handle resource spikes? For example — CPU, Memory, I/O, Disk space, etc.</li><li><strong>State:</strong>​ What happens if your infrastructure’s state changes? For example — shutdown of a server, killing of a Docker container, change in system time, etc.</li><li><strong>Network: </strong>​How does your application deal with network issues? For example — packet loss, network latency, etc.</li></ol><h3><strong>Difference Between Testing and Chaos Experimentation</strong></h3><p>You may be asking yourself, how is this any different than traditional testing? In Chaos Engineering, the main focus is on the use of ​<em>experimentation</em>​ over tests. But what is the difference between an experiment and a test? The difference is that testing focuses on validating ​<strong>predicted behavior</strong>​ against a specific condition, whereas experimentation focuses on injecting fault into a system to <strong>generate new knowledge </strong>​about how it could potentially fail.</p><p>Injecting failure into a system can ripple out in unpredictable ways, so think about your components and process as one system. You’re not testing a specific feature, but instead are observing how the collection of components respond together to an unpredicted change. This way of thinking requires a new mindset, but it will build confidence in your product’s ability to handle disruptions.</p><p>Testing gets us part of the way there, but complexity makes it impossible to validate every scenario. That’s where chaos experiments can help you uncover the unknown unknowns.</p><p>For example, a test will check that a request for a CPU intensive operation responds under 5ms, but a chaos experiment is a hypothesis that when a system is flooded with multiple requests of high and low CPU usage it will appropriately direct the workloads to executors with enough CPU.</p><h3><strong>Why You Need Chaos Engineering</strong></h3><p>So you’ve created a toothbrush exchange, congrats! It’s easy to brag about your system’s stability when you have only eleven users (and almost half are family). I’ve been there, trust me. If your site is down, it’s not a huge deal because nobody is really using it anyway.</p><p>But who knew the sharing economy was so robust! You now have hundreds of thousands of users optimizing their toothbrush usage across the globe. With your increased scale comes a whole new set of enterprise problems for your app.</p><p>Since you care about user experience, you set up your system to operate in both east and west regions to reduce latency. Everything is working perfectly and the site is steadily growing. Then one day, there is a regional outage and all of your traffic is automatically routed to one region. You have auto-scaling set up (which you’ve tested), but you weren’t prepared to handle all that traffic that used to be distributed across two regions in one region. The application comes to a grinding halt because you’ve hit your auto-scaling limit. All your best laid plans are a mess.</p><p>Your 100% test coverage only tested for things you knew to test for; but what about all the unknowns that were lurking in the dark until your users showed up and started pressing buttons? Unknowns that only show up when component A calls component B that calls component C on Feb 29th during a full moon?</p><figure><img alt="Man wearing a tan jacket fixing an open electric box with many wires" src="https://cdn-images-1.medium.com/max/1024/1*5ZZxXDdNHQBbODg7XD6XMQ.jpeg" /></figure><p>Applications can get complicated quickly, especially at enterprise scale. It takes a lot of work to finally release something to production and intentionally trying to “break” it after going through build, test, and deployment may seem counterintuitive.</p><p>Large enterprises, especially those in regulated industries, need to be even more outage-proof than your average site. Therefore, regulated industries like healthcare or finance should include Chaos Engineering as part of their resiliency efforts to help address failures before they become outages.</p><p>Injecting problems into your live applications may initially seem scary, but that’s exactly what you should do. The key is to do it one step at a time. I would encourage you and your teams to make Chaos Engineering a part of your delivery practices, but remember to start small and increase scope as your comfort level grows. Please don’t run chaos experiments on systems that aren’t ready.</p><h3><strong>How to Get Started with Chaos Engineering?</strong></h3><p>The holy grail of Chaos Engineering is to run chaos experiments in production. But don’t expect to get there immediately.</p><p>I typically recommend an adoption framework like this:</p><figure><img alt="flow chart with black arrows connecting green, blue, and red squares like a staircase" src="https://cdn-images-1.medium.com/max/517/1*ce5sTj5zDH3mxzFFe_HdQA.png" /></figure><ol><li><strong>Small one-off experiments</strong>​ in non-production environments. Pick something low impact and measure/observe. The theme here is to learn, fix, and iterate.</li><li><strong>Increase scope</strong>​ incrementally. Use this as an opportunity to improve your application resiliency and mature your engineering and operational practices. How is your monitoring? Do you understand the recovery steps if something goes wrong? This is a good time to polish your incident management as well.</li><li><strong>Continuous chaos experiments in non-prod. </strong>Now you’re ready to incorporate the experiments into your CI/CD processes (which you hopefully are using, otherwise do that first before you even think about Chaos Engineering). Build chaos experiments into your development cycle along with other forms of testing (eg. end-to-end, performance, load etc.). The goal should be to use what you learn to improve your system resilience and further mature your operational and engineering practices.</li><li><strong>Continuous chaos experiments in prod. </strong>​As confidence in your solution’s ability to handle failure rises, you will begin to shift your perspective on disruptions. Do not move on to chaos experiments in production until you’ve successfully run them in non-prod. This could be a while, but eventually the goal should be to start slowly incorporating chaos experiments into production environments. Just like in non-prod, start with small experiments and observe. Learn from how your system reacts and adapt accordingly. By now you should have deep monitoring enabled and real-time alerting to notify you of any issues caused by either users or your chaos experiments. Make sure you have a way to roll-back in case something unexpected goes wrong. ​<em>I repeat, always have a backup plan.</em></li></ol><p>If you’ve gotten this far, Chaos Engineering is part of your fiber. Well done!</p><h3><strong>What Tools Can Give You a Head Start on Chaos Engineering?</strong></h3><p>Now that you have a framework to adopt Chaos Engineering into your applications, I recommend taking a look at the existing landscape. There are a number of open source products that you can get started with right away, as well as some interesting services to leverage.</p><ul><li><a href="https://github.com/Netflix/SimianArmy">Simian Army</a> ​(Chaos Monkey, Kong) — Suite of tools from Netflix to improve resiliency against random instance/region failures.</li><li><a href="https://www.gremlin.com/">Gremlin</a>​ — Failure-as-a-service (yes it’s a thing) started by Netflix/Google “chaos alumni”</li><li><a href="https://github.com/bloomberg/powerfulseal">PowerfulSeal​ </a>— Bloomberg open source tool that adds chaos to Kube clusters.</li></ul><p>Some additional resources on Chaos Engineering:</p><ul><li><a href="https://www.oreilly.com/library/view/chaos-engineering/9781491988459/">Chaos Engineering</a>​ -​ Book</li><li><a href="https://principlesofchaos.org/?lang=ENcontent">Principles of Chaos Engineering</a>​ — Site</li><li><a href="https://www.youtube.com/watch?v=w_Y6C0QgmL0">Practical Chaos Engineering breaking things on purpose to make them more resilient against failure​ </a>— In-depth talk on Chaos Engineering</li></ul><p><em>DISCLOSURE STATEMENT: © 2020 Capital One. Opinions are those of the individual author. Unless noted otherwise in this post, Capital One is not affiliated with, nor endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are property of their respective owners.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=203fd6fc6ff7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capital-one-tech/embrace-the-chaos-engineering-203fd6fc6ff7">Embrace the Chaos … Engineering</a> was originally published in <a href="https://medium.com/capital-one-tech">Capital One Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursive promises in NodeJS]]></title>
            <link>https://medium.com/@wrj111/recursive-promises-in-nodejs-769d0e4c0cf9?source=rss-c050c515f40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/769d0e4c0cf9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Waldemar Jankowski]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 12:57:38 GMT</pubDate>
            <atom:updated>2019-12-10T12:57:38.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zCYO29-nrVrIeezySic4Q.jpeg" /><figcaption>Real chops</figcaption></figure><p>Recently I was working on a side project that required me to dust off my programming “chops”. Without going into the specifics of the project, one of the tasks required fetching all records in a DynamoDB table. Scanning DynamoDB tables can get expensive, but I had a legitimate reason and my table wasn’t too big. Since the DynamoDB Scan API limits the number of records fetched at one time, you need to call the API repeatedly to get all the records in the table. Each request scan is limited to a maximum dataset size of 1MB. If this limit is exceeded, the scan stops and returns the results with a marker (<em>LastEvaluatedKey</em>) representing the last evaluated record.</p><p>See the Amazon docs for more details about the API: <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html">https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html</a></p><p>I immediately thought about using recursion to solve this, but since my API layer is built in NodeJS (<a href="https://hapi.dev/">hapijs</a>), I heavily rely on asynchronous features. It wasn’t obvious to me how to use recursion with Javascript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Promises</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">Async/Await</a> so hopefully this write-up will help anyone else facing a similar challenge.</p><p>In this article, I will do a brief overview of recursion, Javascript Promises, and show how I was able to recursively call an asynchronous API in NodeJS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HDsG_4dDWxDBj60nsSoHMg.jpeg" /></figure><h3>What is recursion?</h3><p>First, let’s do a quick refresher on recursion. According to <a href="https://en.wikipedia.org/wiki/Recursion_(computer_science)">Wikipedia</a>:</p><blockquote>Recursion in computer science is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem (as opposed to iteration). The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.</blockquote><p>In plain language, it’s the process in which a function repeatedly calls itself until a condition is met that makes it stop. It is similar to iteration with the main difference being that in recursion the function calls itself to execute instructions, but in iteration there is a loop that repeatedly executes a set of instructions. Here is a simple example of recursion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgDE4Us-FUJzAcIfJtMipQ.png" /></figure><p>The above code shows a simple recursive function (“func”) that is called for the first time with a value of “0”. The function’s logic checks if the exit condition is met (num is 11), in which case it prints “done”, otherwise it calls itself with the next number.</p><p>Although this is a trivial example, it illustrates a basic recursive function. Feel free to paste the above code in an editor and run it. The output should be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*NUswJpAkS2Gn6V2WnoDQQg.png" /><figcaption>Recursive code output</figcaption></figure><h3>Synchronous vs Asynchronous Tasks</h3><p>Certain programming tasks can take a long time to execute. Some examples are reading a large file, calling an external API, or running a security scan. When an application starts a long running operation in a synchronous way, it has to wait for it to complete before calling the next operation. This type of sequential execution can have a considerable performance impact on your application. One way to improve the speed of your application is to make those slow running tasks asynchronous. In asynchronous programming, you’re telling your code to “fire and forget”. This allows execution to continue to the next operation without waiting for the previous one to finish. Asynchronous programming introduces some complexity because as your program continues through each operation, you have to define what it should do when the previous operations finish. Traditionally, this was done with a <strong>callback</strong> <strong>function</strong> passed as an argument to the function that starts the asynchronous task. Passing a callback to a function doesn’t seem too bad until the callback you pass also requires a callback and so on. This can quickly become complicated and once you add error handling, you can easily end up in what is commonly known as “<a href="http://callbackhell.com/">callback hell</a>”.</p><h3>What are Promises in Javascript?</h3><p>To avoid “callback hell” and write more readable asynchronous code, Javascript Promises were introduced. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">MDN docs</a> has a great overview of Promises and how to use them. It also has my favorite succinct definition of a Promise.</p><blockquote>A Promise is an object representing the eventual completion or failure of an asynchronous operation.</blockquote><p>If Promises still feel too abstract, remember that a Javascript Promise is just like a promise in real life — an agreement that something will happen in in the future.</p><p>Keeping the real-world meaning in mind, Javascript Promises represent guarantees of operations returning a value in the future. A Promise will either be resolved if it completes successfully or rejected if it fails. A resolved Promise returns the result as a value and a rejected Promise returns a reason for failure as the value. Here is a concrete example of a promise with then/catch methods:</p><pre>const delay = () =&gt;<br>  new Promise(resolve =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve(&#39;resolved&#39;);<br>    }, 2000);<br>  });</pre><pre>delay().then(val =&gt; {<br>  console.log(`Promise has been ${val}`);<br>}).catch(err =&gt; {<br>  console.error(err);<br>});</pre><p>The above code does the following:</p><ul><li>Creates a function called <strong>delay </strong>that returns a new Promise which resolves with the value “resolved” after a brief delay</li><li><strong>delay() </strong>is called and the then() method runs when the Promise in the <strong>delay</strong> function executes successfully and returns the resolved value</li><li>catch() method is used to capture any errors during the execution of the Promise that resulted in a rejection</li></ul><p>ECMAScript 2017 also includes <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><strong>async</strong></a> functions and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await"><strong>await</strong></a> keyword to make it easier to work with Promises. In my opinion, async/await improve readability even more than plain Promises. Async/await provides syntax that makes working with Promises feel more like synchronous code and hides away some of the complexity of Promises. Here is the Promise based code above rewritten with async/await:</p><pre>const delay = () =&gt;<br>  new Promise(resolve =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve(‘resolved’);<br>  }, 2000);<br>});</pre><pre>const asyncCall = async () =&gt; {<br>  try {<br>    const val = await delay();<br>    console.log(`Promise has been ${val}`);<br>  } catch(err) {<br>    console.error(err);<br>  }  <br>};</pre><ul><li>Creates a function called <strong>delay </strong>that returns a new Promise which resolves with the value “resolved” after a brief delay <em>(this is the same as in the full Promise example)</em></li><li><strong>asyncCall </strong>function is marked with the <strong>async </strong>keyword to indicate that it is asynchronous and will return a Promise</li><li><strong>await </strong>keyword<strong> </strong>in the <strong>asyncCall</strong> function lets the program know to “wait” for the asynchronous <strong>delay </strong>function to finish executing and return a resolved value</li><li>Asynchronous call is wrapped in a try/catch to handle errors</li></ul><p>While it’s true that async/await can often be used instead of directly working with Promises, there are some key differences and it’s important to understand the mechanics of Promises before blindly using async/await. One example that comes to mind is executing Promises in parallel instead of sequentially. For example</p><pre>// bar() will not start execution until foo() finishes<br>await foo(1)<br>await bar(2)</pre><pre>// foo() and bar() start execution in parallel<br>await Promise.all(foo(1), bar(2));</pre><p>I encourage you to read this article which does a good job explaining some common use cases and provides guidance on the differences: <a href="https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789">https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789</a></p><h3>Putting it all together</h3><p>Hopefully you’re still with me. This is what it looks like when you combine the concepts together. I’m calling the asynchronous AWS DynamoDB Scan API recursively in an asynchronous function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWGyRMuRd_Aii6lR_eYN2Q.png" /></figure><p><strong>Details of the above code:</strong></p><ol><li>Setup DynamoDB object</li><li>Initialize the DynamoDB client to connect to your DynamoDB</li><li>Define the asynchronous function <strong>getAllItems()</strong> to fetch all the records from a DynamoDB table</li><li>Define the asynchronous function, <strong>runScan()</strong>, to run the actual query on DynamoDB. It takes <strong>ExclusiveStartKey </strong>as a parameter. This is the function that will be called recursively.</li><li>Set the starting record location for the query based on the <strong>ExclusiveStartKey</strong></li><li>Call the DynamoDB <strong>scan</strong> function. The promise() method “promisifies” the <strong>scan </strong>function to return a Javascript Promise</li><li>Add the fetched records to the <strong>allItems </strong>list</li><li>When all records have been fetched (i.e <strong>LastEvaluatedKey </strong>is undefined) resolve the Promise with <strong>allItems </strong>list as the value</li><li>As long as there are more records to fetch, recursively call the <strong>runScan() </strong>function with the <strong>LastEvaluatedKey </strong>as the input parameter</li><li>Handle errors</li></ol><h3><strong>Conclusion</strong></h3><p>In this article I did a brief introduction to recursion, asynchronous programming, and Javascript Promises. I then described an example of calling the DynamoDB API recursively while leveraging asynchronous programming in Javascript. Hope this helps others that are working with NodeJS and find themselves needing to recursively call asynchronous functions.</p><blockquote><strong><em>Disclaimer</em></strong></blockquote><blockquote><em>The ideas in this article are my own thoughts and do not reflect or represent those of my employers or customers.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769d0e4c0cf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>