<?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 Rahat Shaikh on Medium]]></title>
        <description><![CDATA[Stories by Rahat Shaikh on Medium]]></description>
        <link>https://medium.com/@rahatshaikh?source=rss-c85bb7d01c5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PY7t8YpnbtJMC3IH1GGRTA@2x.jpeg</url>
            <title>Stories by Rahat Shaikh on Medium</title>
            <link>https://medium.com/@rahatshaikh?source=rss-c85bb7d01c5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:00:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahatshaikh/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[Identity Management: OAuth and OIDC Simplified]]></title>
            <link>https://levelup.gitconnected.com/identity-management-oauth-and-oidc-simplified-4056ef04a146?source=rss-c85bb7d01c5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4056ef04a146</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Rahat Shaikh]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 19:12:01 GMT</pubDate>
            <atom:updated>2022-12-28T03:11:15.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*f52SNY1qkRz9Z-JP1GkUvg.jpeg" /></figure><p>How many times have we seen this screen and dreaded coming up with yet another strong password or lazily used one of our existing passwords?</p><p>Thankfully, applications now have made it easy to skip this dreadful step, by allowing us to use social media login. We can log in with one of our existing accounts and gain access to a new application and its features with just one click. NO MORE creating and remembering new passwords!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QeZUOQU6TZUzxv6E" /></figure><p>The journey of application security has come a long way. Each iteration has presented solutions and in turn, new concerns that had to be addressed to create secure applications and great user experiences while meeting the demands of the ever-growing internet.</p><p>Application Security and Identity Management are key to every software design and architecture. Understanding Identity Management has become important for both engineers and consumers alike to protect and secure their digital identity and assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*WjBoMzE74keuGGaE.jpg" /></figure><p>In this article, we will go through a few of the approaches and walk through a behind-the-scenes journey of Identity Management evolution. We will also discuss some of the concerns in the approaches that demanded improvement.</p><p>Before we dive into deeper concepts of Identity Management, a quick review of the terminology used in this article</p><blockquote><strong>Identity</strong>: Attributes associated with a person or entity that uniquely describe them within a given context</blockquote><blockquote><strong>Authentication</strong>: The process of determining whether the person or entity is who they say they are</blockquote><blockquote><strong>Authorization</strong>: The process of determining a person or entity’s permission to have access to resources or capabilities</blockquote><h4><strong>1. Silo Identity: Each application has its authentication and authorization mechanism</strong></h4><p>In this case, each application will have its database where they store user identity. Every time a user logs in, applications will validate against their database and accordingly grant resource access to the users.</p><p>While this is still widely used for consumer-facing applications, for large organizations having to replicate the storage and maintenance of multiple employee identities, authentication and authorization mechanisms across each of their applications can be quite cumbersome.</p><p><strong><em>Disadvantage</em></strong>:</p><ul><li>Consumers/Employees have to remember multiple credentials across sites/applications.</li><li>Organizations have to manage the replication of Identity Management for each application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*nekRzlg1k1lWNYyB.jpeg" /></figure><h4>2. <strong>Centralized Identity Repository: Directory services to store user identity</strong></h4><p><strong><em>Problem to Solve: </em></strong><em>Users have to remember multiple usernames and passwords across enterprise applications.</em></p><p>With growing business functions, many organizations shifted to Directory services to centralize user identities.</p><p>When a user logs in, each application refers to the Directory service to store, and validate the user credentials.</p><p>Centralizing the user information reduced identity management overhead at each application. The users, however, still had to enter their credentials on each application.</p><p><strong><em>Disadvantage</em></strong>:</p><ul><li>A single point of control for password management also meant a compromise in one application would risk other applications too.</li><li>A centralized repository or using a single password is not suited for consumers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*CE7gR-Z_T5cL81e9.jpg" /></figure><h4>3. Single Sign-On: Layer over Directory Services to maintain sessions for already authenticated users</h4><p><strong><em>Problem to Solve:</em></strong> <em>While Directory services centralized the credentials, a user still had to enter his credentials in multiple applications across an organization.</em></p><p>When a user tries to log in to an application, the application would redirect the user to an SSO server to have the user authenticated. The SSO server leverages the Directory Service to authenticate the user.</p><p>In addition, it provides a layer on top that maintains a user session. So if the user tries to log in to another application, the SSO server will detect the user’s existing session. The SSO server will then redirect the user back to the application with a success status without the user being required to enter their credentials again.</p><p><strong><em>Disadvantage</em></strong>:</p><ul><li>If the SSO server goes down, all connected application access can halt.</li><li>Due to its reliance on cookies, it does not extend well to external SaaS applications in other domains.</li></ul><h4>4. Security Assertion Markup Language (SAML) 2.0: Single Sign-On across domains and Federated Identity</h4><p><strong><em>Problem to Solve:</em></strong> <em>Cross-domain single sign-on.</em></p><p>SAML was designed as an XML-based framework to allow the exchange of security information between cross-domain partners. It delegates user authentication to an entity called an identity provider. The identity provider authenticates the user and returns an assertion with information about the authenticated user and authentication event to the application. If the user accesses a second application that delegates authentication to the same identity provider, the user will be able to access the second application without being prompted to enter credentials again.</p><p>SAML also provides a federated identity mechanism in which an application and identity provider can use a shared user identifier to exchange information about the user. The federated identity can use the same identifier across systems or it can use an internal identifier mapped to the identifier used by the user in each system. Since identity federation provided a way to link an identity used in an application with an identity at the identity provider, password policy and multi-factor authentication could all be implemented in a single place.</p><figure><img alt="SAML Single Sign-on" src="https://cdn-images-1.medium.com/max/1024/1*EYHkYzngCvvERiCp3Rwxng.png" /><figcaption>SAML Single Sign-on</figcaption></figure><p><strong><em>Disadvantage</em></strong>:</p><ul><li>Not viable to address consumer-facing applications and use cases.</li><li>Does not solve API Authorization.</li></ul><h4>5. OAuth 2.0</h4><p><strong><em>Problem to Solve:</em></strong><em> Authorize applications to call APIs on behalf of the user.</em></p><p>OAuth 2.0 solved an important API authorization use case. It allows a user to authorize a client application, to send a request to an API on the behalf of the user to retrieve data stored at the resource server.</p><p>An authorization server obtains the user&#39;s consent for the application to access its resources and passes a token to the application, enabling it to call the resource server on the user’s behalf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rpdDSbBFm3ga4M9DPv2Bw.png" /><figcaption>OAuth 2.0 Authorization code grant + PKCE</figcaption></figure><blockquote><strong>Proof Key for Code Exchange (PKCE, pronounced pixie) </strong>is a mechanism that protects against malicious interception and that the application that requested the authorization code is the same application that is trying to obtain the access token. While it was initially designed for mobile apps, its ability to prevent malicious CSRF and injection attacks makes it useful for all OAuth implementations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*-k84MKt6R1UVPpmb.png" /></figure><blockquote>To use PKCE, the application creates a high-entropy cryptographically random string, called a code verifier, and computes a derived value, called a code challenge using one of the two transformations below</blockquote><p>plain<br> code_challenge = code_verifier</p><p>S256<br> code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))</p><blockquote>When the application sends an authorization request, it includes the code challenge and the code challenge method. The authorization server associates the authorization code with the code challenge and method for verification later.</blockquote><blockquote>When the application sends the authorization code to the token endpoint to get the access token it includes the code verifier. The authorization server calculates the code verifier value using the code challenge method and validates if the result matches the code challenge sent with the authorization request. This prevents the authorization server from an intercepting application to steal an authorization code from another application.</blockquote><pre>Sample API authorization request with PKCE<br>GET /authorize?<br> response_type=code<br> &amp; client_id=&lt;client_id&gt;<br> &amp; state=&lt;state&gt;<br> &amp; scope=&lt;scope&gt;<br> &amp; redirect_uri=&lt;callback uri&gt;<br> &amp; resource=&lt;API identifier&gt;<br> &amp; code_challenge=&lt;PKCE code_challenge&gt;<br> &amp; code_challenge_method=S256 HTTP/1.1<br> Host: authorizationserver.com<br><br>Authorization server response to the application&#39;s callback: redirect_uri <br>HTTP/1.1 302 Found<br>Location: https://clientapplication.com/callback?<br>code=&lt;authorization code&gt;<br>&amp; state=&lt;state&gt;<br><br>Application request to the authorization server&#39;s token endpoint to obtain the access token.<br>POST /token HTTP/1.1<br>Host: authorizationserver.com<br>Content-Type: application/x-www-form-urlencoded<br>grant_type=authorization_code<br>&amp; code=&lt;authorization_code&gt;<br>&amp; client_id=&lt;client id&gt;<br>&amp; code_verifier=&lt;code verifier&gt;<br>&amp; redirect_uri=&lt;callback URI&gt;<br><br>Token endpoint response <br>HTTP/1.1 200 OK<br>Content-Type: application/json;charset=UTF-8<br>Cache-Control: no-store<br>Pragma: no-cache<br> {<br> &quot;access_token&quot;: &quot;&lt;access_token_for_API&gt;&quot;,<br> &quot;token_type&quot;: &quot;Bearer&quot;,<br> &quot;expires_in&quot;: &lt;token expiration&gt;,<br> &quot;refresh_token&quot;: &quot;&lt;refresh_token&gt;&quot;<br> }</pre><p><strong><em>Disadvantage</em></strong>:</p><ul><li>OAuth 2.0 was not designed as an authentication service and could not securely be used for this purpose.</li></ul><h4>6. OpenID Connect (OIDC)</h4><p><strong><em>Problem to Solve:</em></strong><em> User Authentication as well as API Authorization.</em></p><p>OIDC was devised as a layer on top of the OAuth 2.0 protocol to provide information in a standard format to applications about the identity of an authenticated user. This provided a solution for user authentication as well as API authorization.</p><p>OIDC is widely used by social media/service providers like Google, PayPal, Yahoo, and many others for creating social media login integrations we saw earlier in the article. But its adoption and usage are not limited to consumer-facing integrations and use cases.</p><p>OIDC offers benefits to</p><ul><li>users through leverage of one account to log in to multiple sites without providing their credentials to them,</li><li>application developers who can delegate the authentication and password management to an OIDC provider,</li><li>and identity providers that continue to attract users to their platforms.</li></ul><p>OIDC provides the web single sign-on benefits that were attractive in SAML 2.0 and, when combined with OAuth 2.0, provides a solution with authentication as well as the API authorization capabilities needed by modern applications.</p><p>The OIDC Authorization Code Flow shares a similarity to OAuth 2.0. Authorization Code Grant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LgLhFwtp_01TtLYnPfgrQ.png" /><figcaption>OIDC Authorization code flow + PKCE</figcaption></figure><blockquote>An ID Token is a security token used by an OpenID Provider to convey claims to an application about an authentication event and authenticated user. ID Tokens are encoded in JSON Web Token format consisting of a header, a payload, and a signature (encoded into a base 64 URL-safe string).</blockquote><blockquote>The header section of the ID Token contains information on the type of object (JWT) and the specific signature algorithm (HS256 — HMAC with SHA256 or RS256 — RSA Signature with SHA256). The payload section contains the claims about a user and the authentication event. The signature section contains a digital signature.</blockquote><pre>Authentication request to the OpenID Provider&#39;s authorization endpoint<br>GET /authorize?<br>response_type=code<br>&amp; client_id=&lt;client_id&gt;<br>&amp; state=&lt;state_value&gt;<br>&amp; nonce=&lt;nonce_value&gt;<br>&amp; scope=&lt;scope&gt;<br>&amp; redirect_uri=&lt;callback_url&gt;<br>&amp; code_challenge=&lt;code_challenge&gt;<br>&amp; code_challenge_method=&lt;code_challenge_method&gt; HTTP/1.1<br>Host: authorizationserver.com<br><br>OpenID Provider response to the callback URI. It also returns the exact state value that was passed in the authentication request<br>HTTP/1.1 302 Found<br>Location: https://clientapplication.com/callback?<br>code=&lt;authorization_code&gt;<br>&amp; state=&lt;state_value&gt;<br><br>Application token request to the OpenID Provider&#39;s token endpoint<br>POST /token HTTP/1.1<br>Host: authorizationserver.com<br>Content-Type: application/x-www-form-urlencoded<br>Authorization: Basic &lt;encoded client credentials&gt;<br> grant_type=authorization_code<br>&amp; code=&lt;authorization_code&gt;<br>&amp; redirect_uri=&lt;redirect_uri&gt;<br>&amp; code_verifier=&lt;code_verifier&gt;<br><br>Requested tokens in JSON format returned by the OpenID Provider <br>HTTP/ 1.1 200 OK<br>Content-Type: application/json;charset=UTF-8<br> Cache-Control: no-store<br> Pragma: no-cache<br>{<br> &quot;id_token&quot; : &lt;id_token&gt;,<br> &quot;access_token&quot; : &lt;access_token value&gt;,<br> &quot;refresh_token&quot; : &lt;refresh_token value&gt;,<br> &quot;token_type&quot;: &quot;Bearer&quot;,<br> &quot;expires_in&quot; : &lt;token lifetime&gt;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*245mn3uhojBDpd5F.jpg" /></figure><p>Hope this behind-the-scenes sneak peek was useful to you all in understanding the complexities that go behind securing user identity and creating seamless user experiences. For developers, I hope this article can help you evaluate the right identity solution for your next application.</p><p>I would love to hear your comments and how you have implemented Identity Management in your applications.</p><p>Please feel free to reach out to me with any questions, you can also go through the reference links below to learn more about different OAuth grant types and OIDC flows.</p><p><strong><em>References</em></strong>:</p><ul><li><a href="https://www.rfc-editor.org/rfc/rfc7522">RFC 7522: Security Assertion Markup Language (SAML) 2.0 Profile for OAuth 2.0 Client Authentication and Authorization Grants</a></li><li><a href="https://oauth.net/2/">OAuth 2.0 - OAuth</a></li><li><a href="https://openid.net/connect/">How OpenID Connect Works - OpenID Foundation</a></li><li><a href="https://learning.oreilly.com/library/view/solving-identity-management/9781484250952/">Solving Identity Management in Modern Applications: Demystifying OAuth 2.0, OpenID Connect, and SAML 2.0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4056ef04a146" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/identity-management-oauth-and-oidc-simplified-4056ef04a146">Identity Management: OAuth and OIDC Simplified</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[Understanding the Reality of Perceptions]]></title>
            <link>https://medium.com/swlh/understanding-the-reality-of-perceptions-a84b025a3eed?source=rss-c85bb7d01c5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a84b025a3eed</guid>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[inspiration]]></category>
            <dc:creator><![CDATA[Rahat Shaikh]]></dc:creator>
            <pubDate>Thu, 21 May 2020 07:52:36 GMT</pubDate>
            <atom:updated>2020-06-06T23:09:19.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I Cut the Noise Out</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xdJ2om2wNO3MH4Dk" /><figcaption>Photo by <a href="https://unsplash.com/@marc_schulte?utm_source=medium&amp;utm_medium=referral">Marc Schulte</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever had those moments where you’re trying to communicate with someone and they misinterpret where you’re coming from? And it doesn’t just end at inordinately long pauses and awkward glares… Being the emotionally-led beings people are, your audience will probably mentally tie you to this unpleasant interaction and form a (mostly unfavorable) opinion of you.</p><p>I have spent way too long trying to re-communicate things that have been misinterpreted and way too long trying to change people’s opinions about me. I hate to admit it but I did this even when they didn’t have much stake in my life. I have also spent way too long worrying about how people see me because, for the longest time, I saw myself through their eyes too.</p><p>It took a great book by Daniel Kahneman (Thinking, Fast and Slow) and a few weekends of deep introspection for me to realize that I was wrong.</p><p>“Their” perception is not my reality. It is not reality at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*yKNzhB1QM_qGmIlH" /><figcaption>“This is not a pipe.” © C. Herscovici/Artists Rights Society (ARS), New York</figcaption></figure><p>While our perceptions act as a lens through which we view reality, they are largely influenced by our individual experiences, knowledge, emotions, preconceived notions and interests. On the other hand, “Reality” is self-sufficient, objective and not subject to human convention and decisions. Understanding this distinction was my point of inflection.</p><p>Kahneman explains this succinctly through a simple test of <a href="https://en.wikipedia.org/wiki/Cognitive_bias">Cognitive Bias</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*h_9eaUyEy41gdnGYSzJMBw.jpeg" /><figcaption>First, read the image on the left and then the one on the right.</figcaption></figure><p>Chances are you read the left image as “ABC” and the right one as “12, 13, 14”. On closer inspection, you will notice that the character “B” in the left image is the same as the one for “13” in the right image.</p><p>Still, our mind was quick to read the same character differently as our tendency to read our ABCs and numbers informed our “perception of reality”.</p><p>We ascribe value to characters and situations and fit them to our context and notions. I often wonder how much this ability of ours holds us back but that’s a question for another time.</p><p>Armed with this knowledge, I created a plan for myself. A checklist of sorts to help me wade through other people’s perceptions of me.</p><p><em>Here are the things I remind myself of whenever (and as many times as) I need to hear them.</em></p><h4>1. Look at yourself with kinder eyes and have confidence in who you are</h4><p>Someone’s opinion of you may be the result of whatever limited interaction they’ve had with you. If an opportunity to seek resolution comes up organically, then maybe take the time to clear things but don’t feel pressured to do so. Remember, you are not their perception of you.</p><h4>2. Reputation is built by repetition. Be patient through this process</h4><p>People form first impressions, but they also tend to change them given enough evidence. You will get opportunities to exhibit your true self and your strengths. As the saying goes — “Through patience, great things are accomplished.”</p><h4>3. Always be ready to challenge your perception</h4><p>You know yourself better than anyone but be willing to take constructive criticism. Sometimes, even strangers can bring in fresh insight to ourselves and help us identify gaps we never knew existed.</p><h4>4. Focus on your goals and eliminate distractions</h4><p>It is not always possible to make everyone happy. So, start with y<em>ourself</em>. List your goals and vision, create a plan and then design your environment to help you bring that vision to life. Don’t be distracted by what people think or say about you. Instead, invest that “investigative” energy into your goals.</p><h4>5. Create your inner circle</h4><p>I can’t stress the importance of having family, friends and mentors guide you through your journey. They are perhaps the only people who can help you take-off and keep you grounded at the same time.</p><h4>6. Treat people the way you want to be treated</h4><p>Don’t be too quick to judge someone even if they don’t have the best opinion of you. Continue being yourself and repaying every interaction with kindness.</p><p>When the going does get tough, I hope this list serves you as a reminder that you are more than what they see in you. And I hope you take care and look after yourself.</p><blockquote><em>“You presume you are a small entity, but within you is enfolded the entire Universe. What you seek is within you, if only you reflect.”</em></blockquote><blockquote><em>-Imam Ali</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a84b025a3eed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-the-reality-of-perceptions-a84b025a3eed">Understanding the Reality of Perceptions</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[CompletableFuture : A Simplified Guide to Async Programming]]></title>
            <link>https://medium.com/swlh/completablefuture-a-simplified-guide-to-async-programming-41cecb162308?source=rss-c85bb7d01c5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/41cecb162308</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Rahat Shaikh]]></dc:creator>
            <pubDate>Fri, 08 May 2020 19:35:01 GMT</pubDate>
            <atom:updated>2020-05-20T01:08:25.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>CompletableFuture : A Simplified Guide to Async Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*xYB8ywUAA3b4BQJ2h8nxzw.png" /></figure><p>Technology has been evolving at an unprecedented rate (and for quite some time now) to keep up with our ever-changing and ever-urgent expectations as consumers. It’s now got to a point where technology can even <em>pre-empt</em> demands so it can better satiate our predilection for instant gratification.</p><p>A large part of this fantastic growth can be directly attributed to improvements in microprocessor technology. You need only look into your pockets; at your smartphone to appreciate this fact. And it’s not just phones — entire cities are now turning “smart” thanks to advancements in technology and processor architecture and design.</p><p>No surprise then that Software Design and Programming practices have also evolved to extract maximum performance from the machines that serve us.</p><p>Which brings us to our topic of discussion…</p><p>Introduced in Java 8, CompletableFuture allows programmers to efficiently write asynchronous and non-blocking code to leverage the power of multicore processors. To understand what makes CompletableFuture tick, let us first study some of its precursors:</p><h4>1. Fork-Join framework</h4><p>The Fork/Join framework was first introduced in Java 7 and let users recursively split a parallelizable task into smaller subtasks. These subtasks are distributed into several worker threads in a common thread pool called ForkJoinPool. It then combines the interim results of subtasks to form an overall result.</p><p>Worker threads in the ForkJoinPool implement a “workstealing” algorithm — allowing idle threads to steal from busy threads. The task is (mostly) evenly distributed across the threads in the ForkJoinPool held in a doubly-linked queue. However, some threads might complete their tasks faster than others. In such a case, rather than sit idle, threads randomly choose another queue and start “stealing” the task. This goes on until all queues across all threads are empty and the task is completed.</p><p>The Fork/Join essentially ensures CPU cores run at maximum efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*f-_yzB4fZPQ4mmlkch7uJg.png" /></figure><h4>2. Future Interface</h4><p>The Future Interface was introduced in Java 5 to model an asynchronous computation and provide a reference to a result that is available only when the computation is completed.</p><p>It delegates the long-lasting operation to a separate thread while the main thread continues focusing on other tasks. When the main thread cannot proceed without the result of the asynchronous operation, it retrieves it from the Future by invoking its <em>get() </em>method. This method immediately returns the result of the long process (if completed) or blocks the main thread until the result is available.</p><pre>ExecutorService executorService = Executors.<em>newCachedThreadPool</em>();<br>java.util.concurrent.Future&lt;String&gt; future = executorService.submit(<strong>new </strong>Callable&lt;String&gt;() {<br>    @Override<br>    <strong>public </strong>String call() <strong>throws </strong>Exception {<br>       <strong>return </strong><em>longProcess</em>();<br>    }<br>});<br><strong>try </strong>{<br>    String result = future.get();<br>} <strong>catch </strong>(InterruptedException e) {<br>   e.printStackTrace();<br>} <strong>catch </strong>(ExecutionException e) {<br>  e.printStackTrace();<br>}</pre><p>As highlighted above, long computation is done in a separate thread while the main thread can continue processing until the <strong><em>future.get() </em></strong>is invoked. At this point, if the result is available, it is returned; if it isn’t available, the thread is blocked until the result is computed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/0*UyyeIdBnSlCREkQJ.png" /></figure><p>The Future interface provides a method <em>get(long timeout, TimeUnit unit) </em>which would wait only until the <strong><em>timeout</em></strong> value provided and then exit to avoid running processes <em>ad infinitum.</em></p><p>In the code snippet above, replace the<strong> <em>get()</em></strong> as follows</p><pre><strong>try </strong>{<br><em>// wait 10 ms for result from future before exiting</em><br>     <strong><em>String result = future.get(10, TimeUnit.MILLISECONDS);<br></em></strong>}<strong>catch </strong>(TimeoutException e) {<br>     e.printStackTrace();<br> }</pre><p>Now, imagine a scenario where the long computation is never completed. In this instance, the main thread would continue to be blocked forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*brJVnlnc3POITREVHNchzw.png" /></figure><h3>CompletableFuture</h3><p>While Future Interface was a great improvement over Threads when it came to asynchronous programming, it still had several limitations most notable of which was the blocking call.</p><p>When CompletableFuture was introduced, it overcame some of Future Interface’s shortcomings and resolved several of its limitations. Namely:</p><ol><li>Non-blocking</li><li>Ability to Programmatically completing a future</li><li>Perform Error handling</li><li>Ability to Chain several futures</li><li>Ability to combine results of multiple futures (that run in parallel)</li></ol><h4>A) Complete a Future and Error handling</h4><p>Here is a basic example of CompletableFuture where a long-running process is executed inside a separate thread.</p><pre>CompletableFuture&lt;Double&gt; futureResult = <strong>new </strong>CompletableFuture&lt;&gt;();</pre><pre><strong>new </strong>Thread( ()-&gt; {<br>    <strong>try</strong>{<br>    <em>//some long process<br>    </em>futureResult.complete(10.0);</pre><pre>    }<strong>catch</strong>(Exception e){<br>    futureResult.completeExceptionally(e);<br>   }<br>    }).start();<br><strong>return </strong>futureResult;</pre><p>The <em>futureResult</em> is returned without waiting for the long process to complete. Callers who want to get the result of this CompletableFuture can call <em>futureResult.get().</em></p><p>Notice the <em>complete()</em> and <em>completeExceptionally()</em> methods: Both methods help manually complete a Future.</p><p>When a caller invokes <strong><em>futureResult.get()-</em></strong></p><p>If the long process has executed with no exceptions:<br>The <em>complete()</em> method sets the value returned by long computation as 10 on the <em>futureResult</em> and returns it to the caller.</p><p>In case of an exception in the long-running process:<br><em>completeExceptionally()</em> would be called returning the exception to the caller to take further necessary action.</p><h4>B) CompletableFutures using Factory Methods: runAsync and supplyAsync</h4><p><strong>static CompletableFuture&lt;Void&gt; runAsync(Runnable r ):</strong> It accepts input as Runnable and returns a new CompletableFuture.</p><pre>CompletableFuture&lt;Void&gt; future = CompletableFuture.<em>runAsync</em>(() -&gt; {<br>    <strong>try </strong>{<br>        <em>//long running process<br>        </em>TimeUnit.<strong><em>SECONDS</em></strong>.sleep(2);<br>    } <strong>catch </strong>(InterruptedException e) {<br>     <strong>throw new </strong>IllegalStateException(e);<br>    }<br>});</pre><p><strong>static &lt;U&gt; CompletableFuture&lt;U&gt; supplyAsync (Supplier&lt;U&gt; s):</strong> It accepts input as Supplier and returns a new CompletableFuture with value obtained by invoking the Supplier.</p><pre>CompletableFuture&lt;String&gt; future = CompletableFuture.<em>supplyAsync</em>(() -&gt; {<br>    <strong>try </strong>{<br>        <em>//long running process<br>        </em>TimeUnit.<strong><em>SECONDS</em></strong>.sleep(2);<br>    } <strong>catch </strong>(InterruptedException e) {<br>        <strong>throw new </strong>IllegalStateException(e);<br>    }<strong>return &quot;supply Async&quot;</strong>;<br>});<br><strong>try </strong>{<br>    String result = future.get(); <em>//blocking </em><br>} <strong>catch </strong>(InterruptedException e) {<br>    e.printStackTrace();<br>} <strong>catch </strong>(ExecutionException e) {<br>    e.printStackTrace();<br>}</pre><p>The difference between <em>runAsync()</em> and <em>supplyAsync()</em> is that the former returns a Void while <em>supplyAsync() </em>returns a value obtained by the Supplier.</p><p>Both methods also support a second input argument — a custom Executor to submit tasks to. This allows one to configure the thread pool size to better suit the application’s needs.</p><p><strong>static CompletableFuture&lt;Void&gt; runAsync (Runnable r, Executor exec) static &lt;U&gt; CompletableFuture&lt;U&gt; supplyAsync (Supplier&lt;U&gt; s, Executor exec)</strong></p><p>If the custom Executor is not provided, both methods are asynchronously completed by tasks running in the ForkJoinPool (explained above in precursors).</p><h4>C) Chaining multiple CompletableFutures: Non-Blocking</h4><h4>1. Purchasing movie tickets online</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*ouG4STt2LDDzABVmEbKEWg.png" /></figure><p>1. View the movie list and select a particular movie</p><p>2. Select seats</p><p>3. Apply any available promotional codes and retrieve the final ticket price</p><p>4. Make payment</p><pre><em>// Get Movies playing for the selected showtime (date and time)</em></pre><pre>CompletableFuture&lt;List&lt;Movie&gt;&gt; getMovieList(String day){<br>        <strong>return  </strong>CompletableFuture.<em>supplyAsync</em>( ()-&gt; {<br>            List movieList = <strong>new </strong>ArrayList&lt;Movie&gt;();<br>            <em>//getMovieList from backend<br>            </em><strong>return </strong>movieList;<br>    });<br>}</pre><pre><em>// Select seats for the movie<br>//ShowDetails includes movie selected, date and time of the movie, along with seats selected for that show</em></pre><pre>CompletableFuture&lt;ShowDetails&gt; selectSeats (ShowTime showTime) {<br>      <strong>return </strong>CompletableFuture.<em>supplyAsync</em>(() -&gt; {     <br>        ShowDetails showDetails = new ShowDetails();<br>        showDetails.setSeats(selectSeatsForShow());<br>        <strong>return s</strong>howDetails;<br>    });<br> }</pre><pre><em>//Customer selects a movie from the movie list<br></em>CompletableFuture&lt;Movie&gt; selectMovie(List&lt;Movie&gt; movies){<br>    <em>//user selects movie<br>    </em><strong>return </strong>CompletableFuture.<em>supplyAsync</em>(() -&gt; {<br>        movie = getCustomerSelectedMovie();<br><strong>        return movie</strong>;<br>      });<br><em>    </em>}</pre><pre><em>//Calculate ticket price<br></em>CompletableFuture&lt;TicketPrice&gt; getTicketPrice (ShowDetails showdetails){<br>      <strong>return </strong>CompletableFuture.<em>supplyAsync</em>(() -&gt; {<br>          ticketPrice = getTotalTicketPrice(); <br>          <strong>return </strong>ticketPrice; <em>//final price</em><br>      });<br>}</pre><pre><em>// Apply promo code if available<br></em>ShowDetails applyPromoCode (ShowDetails showdetails, String promoCode){<br>    showdetails.setFinalDiscount(getDiscount(promoCode));<br>    <strong>return </strong>showdetails;<br>}</pre><p><strong><em>Chaining multiple futures to book the Movie Show</em></strong></p><pre><strong>public void </strong>bookMyShow(ShowDetails showDetails, String promoCode)</pre><pre>{<br>CompletableFuture result =                 getMovieList(showDetails.getShowTime().getDay())<br>            .thenCompose(movies -&gt; selectMovie(movies))<br>            .thenCompose(movie -&gt;                     selectSeats(showDetails.getShowTime())<br>            .thenApply(showDetails1 -&gt; applyPromoCode(showDetails1,promoCode))<br>            .thenCompose(showDetails2 -&gt; getTicketPrice(showDetails2)));<br>}</pre><p>In the above example, we take the output of one future and pass it as input to the next in the chain.</p><p><strong>&lt;U&gt; </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>CompletableFuture</strong></a><strong>&lt;U&gt; </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenApply-java.util.function.Function-"><strong>thenApply</strong></a><strong>(</strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html"><strong>Function</strong></a><strong>&lt;? super </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>T</strong></a><strong>,? extends U&gt; fn): </strong>The input is a function to use to compute the value of the returned CompletionStage.</p><p><strong>&lt;U&gt; </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>CompletableFuture</strong></a><strong>&lt;U&gt; </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenCompose-java.util.function.Function-"><strong>thenCompose</strong></a><strong>(</strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html"><strong>Function</strong></a><strong>&lt;? super </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>T</strong></a><strong>,? extends </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html"><strong>CompletionStage</strong></a><strong>&lt;U&gt;&gt; fn) : </strong>The input is a function returning a new CompletionStage.</p><p><strong>Step by step guide through the example:</strong></p><p>Step 1: <em>getMovieList() </em>returns a CompletableFuture. This is the first CompletableFuture in the chain and created with a <em>supplyAsync()</em></p><p>Step 2: The next step is selecting a particular movie from the list retrieved, <em>thenCompose()</em> indicates that we want to execute another CompletableFuture and get its completion result</p><p>Step 3: Once the movie is selected, we now select seats by chaining each of the asynchronous tasks through <em>thenCompose()</em></p><p>Step 4: Before calculating the total price of the tickets, apply any promotional code through <em>applyPromoCode()</em></p><p>Notice <em>applyPromoCode()</em> passed to the <em>thenApply()</em> does not return a Completable future. This task is synchronous and returns an object instead.</p><p>If this task were to return a CompletableFuture, the result of <em>thenApply() </em>would be a nested CompletableFuture —</p><p>&lt; CompletableFuture&lt;CompleteableFuture&gt;&gt;</p><p>This is an important difference between <em>thenApply() </em>and<em> thenCompose() </em>where the latter returns a flattened result, synonymous to the difference between a <em>map()</em> and <em>flatMap()</em></p><p>Step 5: The last step is to calculate the final ticket price and purchase the tickets</p><h4>2. Ordering snacks at the movies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*-hcyVu7noGuidOGu1xVBjQ.png" /></figure><p>1. At the movie, you order popcorn and a soda</p><p>2. The manager takes the order and lets his staff know. One staff member preps the popcorn and the other fills the soda. Basically, both do the tasks <strong>simultaneously — </strong><em>your order is not fully complete until both these tasks are done</em></p><p>3. Both get their orders to the manager</p><p>4. You are now ready to enjoy your refreshments!</p><p><strong><em>Multiple independent futures running in parallel</em></strong></p><pre>CompletableFuture&lt;String&gt; getPopCorn(){<br>    CompletableFuture&lt;String&gt; future =  CompletableFuture.<em>supplyAsync</em>(() -&gt; {<br>          <strong>return</strong>(<strong>&quot;Popcorn ready&quot;</strong>);<br>   });<br>    <strong>return </strong>future;<br>}</pre><pre>CompletableFuture&lt;String&gt; getDrink(){<br>    CompletableFuture&lt;String&gt; future =    CompletableFuture.<em>supplyAsync</em>(() -&gt; {<br>        <strong>return</strong>(<strong>&quot;Drink ready&quot;</strong>);<br>    });<br>    <strong>return </strong>future;<br>}</pre><pre><strong>public </strong>String snackReady(){<br>       <strong>return &quot;Order is ready - Enjoy your movie snacks&quot;</strong>;<br>}</pre><pre>//snacks are ready when popcorn and drink are ready<br><strong>public void </strong>getSnacksForMovie(){<br>    CompletableFuture snacks = getPopCorn()<br>            .thenCombine(getDrink(),(str1,str2)-&gt;{<strong>return </strong>snackReady();}) ;<br>}</pre><p><strong>&lt;U,V&gt; </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>CompletableFuture</strong></a><strong>&lt;V&gt; </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenCombine-java.util.concurrent.CompletionStage-java.util.function.BiFunction-"><strong>thenCombine</strong></a><strong>(</strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html"><strong>CompletionStage</strong></a><strong>&lt;? extends U&gt; other, </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html"><strong>BiFunction</strong></a><strong>&lt;? super </strong><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>T</strong></a><strong>,? super U,? extends V&gt; fn):</strong> The input is a second CompletionStage and a supplier function that executes with the two results as arguments. The result returned is a new CompletionStage.</p><p>Both the <em>getPopCorn()</em> and <em>getDrink()</em> are executed in parallel. Once both of them have completed, they are passed as input to our supplier function to print the result <em>snackReady().</em></p><p>CompletableFuture API is constantly updated with newer, more powerful improvements and methods with every version of Java. Suffice to say that we’ve barely just scratched the surface here.</p><p>That said, I do hope this article has helped you understand this critical feature better.</p><p>I’d love to hear from you… Please feel free to drop in any questions or share your thoughts in the comment section!</p><p>Stay safe. 👍</p><h4>Further Reading</h4><ul><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">CompletableFuture (Java Platform SE 8 )</a></li><li><a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/CompletableFuture.html">CompletableFuture (Java SE 11 &amp; JDK 11 )</a></li><li><a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/CompletionStage.html">CompletionStage (Java SE 11 &amp; JDK 11 )</a></li><li><a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html">Future (Java Platform SE 7 )</a></li><li><a href="https://www.manning.com/books/java-8-in-action">Java 8 in Action</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41cecb162308" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/completablefuture-a-simplified-guide-to-async-programming-41cecb162308">CompletableFuture : A Simplified Guide to Async Programming</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[Cloud Design Patterns— Explained Simply]]></title>
            <link>https://levelup.gitconnected.com/cloud-design-patterns-explained-simply-113c788b33ff?source=rss-c85bb7d01c5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/113c788b33ff</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Rahat Shaikh]]></dc:creator>
            <pubDate>Fri, 17 Jan 2020 05:01:50 GMT</pubDate>
            <atom:updated>2020-05-13T18:33:55.707Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>“There are only patterns, patterns on top of patterns, patterns that affect other patterns. Patterns hidden by patterns. Patterns within patterns…”</strong></blockquote><blockquote>- Chuck Palahniuk</blockquote><p>Perhaps the simplest way to describe a pattern would be a regularity that predictably repeats itself. The beauty of patterns lies in their ubiquity — From the way organelles are arranged in the smallest of micro-organisms to the way stars line up in galaxies, patterns exist everywhere. You simply can’t escape these patterns which govern most (if not all) laws of our physical world.</p><p>Unsurprisingly, design patterns also exist in the universe of software design.<em> A software design pattern is a reusable solution (template) to commonly occurring issues.</em> The world first started to take note of design patterns in software in the 1970s and much like the technologies they have come to now build, patterns have been evolving ever since.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*9mlCqxntCdGP-Im-t1VRaw.jpeg" /></figure><p>Building efficient and scalable software is a lot like building a brick wall — A brick-layer takes great care to ensure the pattern and symmetry of their wall is maintained. This allows the foundation to be strong enough to support the weight of everything that is stacked on top of it. It allows the building of a taller, stronger, more “scalable” wall (pardon the pun). Like the brick-layer, a software engineer needs to pay attention to the design patterns that direct the underlying software if they are to create a solution that is both efficient and scalable.</p><p>With the rising popularity of Cloud Computing, the focus of Engineers everywhere has now shifted to harnessing the patterns that govern these processes.</p><p>Here’s a compilation of cloud design patterns that I’ve found to be repeatedly useful to me.<em> </em>I admit this list is biased from my own experience but I will try and add to it as I learn more. Hope this helps you understand design patterns that much better.</p><h3><strong><em>1. Asynchronous Request and Reply</em></strong></h3><p><strong>Problem Statement</strong></p><p>When we talk about Cloud Applications, Micro-services often come to mind. This is an architecture style where multiple micro-services i.e. remote APIs or third-party services are composed to perform dedicated functions to provide a particular functionality to a client application.</p><p>In such a setup, synchronously processing the client request before all the back end work is completed may not always be feasible. This is especially true in the case of long-running processes. Furthermore,<em> latency</em> also becomes a consideration when the response to the client needs to be a few milliseconds.</p><p><strong>Solution: Asynchronous Processing (HTTP Polling or Event Notification)</strong></p><ul><li>The client makes an API request</li><li>The application now offloads the work to another back end service or message queue</li><li>The client can poll for the resource/process status using an HTTP GET (HTTP Polling) at regular intervals as appropriate for the client application</li><li>The status API returns “In-Progress” indicating the back end process is still running</li><li>Once the process completes, the status will return the required output or another reference to the resource</li><li>The application can also push event notifications once the process is complete without the need for the client to poll repeatedly</li></ul><p><strong>Let us simplify with an example</strong></p><ul><li>Imagine you’re too tired to make dinner and decide to place a takeaway order over the phone at your favorite restaurant (API request)</li><li>The restaurant provides you with an order number (Acknowledgement and reference identifier)</li><li>You arrive at the restaurant to pick up your order, provide give them the order number and the restaurant staff informs you that your order is still not complete</li><li>If you’re particularly hungry, you might return to the reception to inquire about your order every 5–10 mins (HTTP Polling)</li><li>Or, the restaurant can provide you with a pager that buzzes once your order is complete (Event Notification)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*jOHfNclcriyi_GkLt_MdZg.png" /></figure><h3><strong><em>2. Command and Query Responsibility Segregation (CQRS)</em></strong></h3><p><strong>Problem Statement</strong></p><p>Traditionally, people interact with Information Systems through a CRUD data store. Read and Write Data models are often the same. As the complexity of the application increases, multiple representations of the information are created, all referring to one common data (conceptual) model. This can lead to data/resource contentions, performance slowdown and in some cases, security issues.</p><p><strong>Solution: Separate the Read and Write models</strong></p><ul><li>This can be done by creating separate schemas or different databases for the Read and Write operations. All reads from a single data store and all Writes/Updates to a separate data store</li><li>Creating separate databases provides additional isolation that helps with scalability and performance</li><li>The Write databases can be relational while Read databases can be No SQL document-based</li><li>This approach not only provides separation of concerns but also allows each data store to independently scale based on its workload</li><li>The important consideration in this model is to maintain sync between the Read and Write stores. This is typically achieved through publishing events from the Write store and consumed by the Read store</li></ul><p><strong>Let us simplify with an example</strong></p><ul><li>Imagine you’re still waiting at the same restaurant for your order… Your stomach’s growling in hunger as you wait for your takeaway.</li><li>You notice the delay is due to there being only a single server who is taking care of all diners and takeaway orders</li><li>While Roger, our extremely busy server, is taking orders from one of the diners, the other diners are all waiting to place their orders</li><li>Then some (like you) are waiting for a status on their takeaway orders and others who have placed their order and now waiting to be served</li><li>Sadly, Roger has become the bottleneck in this operation and the overall performance of the restaurant has degraded</li><li>Thankfully, Charlie is back from his break and gets to work on accepting takeaway and dine-in orders while Roger proceeds to serve food to the tables and takeaway diners</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*DqXcvOc6E95RowOMRBe8_w.png" /></figure><h3><strong><em>3. Event Sourcing</em></strong></h3><p><strong>Problem Statement</strong></p><p>When interacting with data, most applications store the current state of the data. Updates to the data elements are typically overwritten by the latest. If one wanted a history of all the updates, the application would need to be built to maintain history tables. Every time an update request is made, the current data would be moved to the history table before being overwritten. This adds to the overhead of having a robust historical backup and ensuring the application scale plan includes scaling the historical stores as well.</p><p><strong>Solution — Event Store</strong></p><ul><li>Define application change as a sequence of events and record them in an event store in the sequence they were applied (an audit trail)</li><li>The events are immutable and stored as append-only but can be published to consumers who may process them as required</li><li>This model not only stores the history of the state of the application but also allows a replay of those events to obtain the current state of the application — one of the following</li></ul><p><em>- A complete rebuild<br>- A point in time rebuild<br>- Reverse events</em></p><ul><li>The trick here is dealing with external systems in a manner where they do not know the difference between real transactions and replays</li></ul><p><strong>Let us simplify with an example</strong></p><ul><li>Event sourcing works a lot like Book Keeping: A bookkeeper will log the day’s financial transactions such as payments, receipts, purchases etc made by an organization and document it within either a supplier or general ledger</li><li>All the financial events, money-in and money-out are now available in these ledgers (..the audit trail)</li><li>An accountant can use this information to create reports for any custom time-period</li><li>Going through the transactions (replay), the accountant could potentially recreate the same report multiple times and still get the same result for that specified period</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*kkcBRaHzZej7Kc9KCUav3g.png" /></figure><h3><strong><em>4. Retry</em></strong></h3><p><strong>Problem Statement</strong></p><p>A distributed environment is prone to transient errors due to slow networks, timeouts etc. But these issues typically self-correct and if the action is re-triggered, it’s likely to succeed. In such situations, applications need to handle these transient failures without impacting the end-user experience.</p><p><strong>Solution — Try and try again</strong></p><ul><li>There are 3 ways to handle transient failures</li></ul><p><em>Stop and Report exception: </em>If a fault isn’t transient or cannot succeed when repeated, the application could raise an alert and log the exception</p><p><em>Retry immediately: </em>If a fault is rare, the application could retry the failing request immediately and the request may be successful</p><p><em>Retry with a delay: </em>If a fault is caused by connectivity issues or issues that may need a short period, the application could retry the failing request after a reasonable amount of time has passed</p><ul><li>The time delay and number of retries can be configured to suit the application needs</li><li>If the request still fails even after the desired retry count, the application could report it as a fault and raise an alert</li></ul><p><strong>Let us simplify with an example</strong></p><ul><li>It’s your dear friend’s birthday! You want to be the first one to wish them so you call them exactly as the clock strikes 12</li><li>The phone’s busy… You figure someone beat you to it. You hang up (kind of disappointed)</li><li>But you also know the phone won’t be busy for too long. So you redial, and this time you get through and wish them. #Hurray</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*xCQcDbhY4FVrYS7xbcxMtQ.png" /></figure><h3><strong><em>5. Circuit Breaker</em></strong></h3><p><strong>Problem Statement</strong></p><p>There are situations where failures can be caused by unexpected situations and take relatively longer to fix. Retry or waiting for the request to timeout may not be the best option as it may cause further cascading issues such as resource contention and/or blocked threads.</p><p><strong>Solution — Fail fast</strong></p><p>Prevent the application from retrying an operation likely to fail</p><ul><li>A circuit breaker acts as a proxy that monitors recent failures of an operation</li><li>The proxy maintains a count of failures and if it crosses the set threshold, it’s placed in an Open state</li><li>In the Open state, the request fails immediately and is handled appropriately by the application</li><li>However, limited requests are still allowed to pass through to check if the operation is still failing or has been successful (fixed)</li><li>If the operation continues to return failures, the Open state continues</li><li>If the operation was successful, it is assumed the issue has been fixed and the circuit breaker switches to Closed state</li><li>Error and failure handling in this pattern requires careful consideration to create an acceptable end-user experience</li></ul><p><strong>Let us simplify with an example</strong></p><ul><li>This pattern is inspired by the actual circuit breaker present in the electrical lines at home or office</li><li>Electrical Circuit breakers are a protective measure against damage to a circuit in the event of an electrical current overload</li><li>It connects to your circuit board and interrupts the flow of electrical current if it detects a fault in the flow</li><li>In the event of a fault, the breaker switch automatically goes off and stops the electricity from flowing through the circuit (Open)</li><li>Without circuit breakers, in the event of a power surge, you’d be left with blown fuses</li><li>With a circuit breaker, all you do is unplug some of the appliances that caused the power surge, and flip the circuit breaker switch back to the “on” position (Closed)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LwoJYhhb18fTrrgT.jpg" /></figure><h3><strong><em>6. Sidecar</em></strong></h3><p><strong>Problem Statement</strong></p><p>Peripheral tasks such as Monitoring, Logging etc are critical to most applications and often integrated within them. However, these tasks run alongside the same process as the application which is potentially inefficient and points to improper separation of concerns. Plus, outages caused in these monitoring and logging components could severely impact the entire application functions.</p><p><strong>Solution: Co-locate as Sidecar</strong></p><ul><li>Co-locate the set of tasks along with the application but place them in their process or container as a Sidecar</li><li>Sidecars are typically small/pluggable components and can be written in different languages</li><li>Both application and sidecar are deployed as a single unit, therefore latency is low</li><li>The sidecar can be used for modifying how the application container works without having to make any changes to the code</li><li>The sidecar is bolted to the application and its lifecycle is dependent on the application</li><li>If the sidecar container logic gets complex or tightly coupled with the main application, it may better be integrated with the main application’s code instead</li></ul><p><strong>Let us simplify with an example</strong></p><ul><li>A common example of the sidecar is the literal sidecar attached to a motorcycle — working as a single unit</li><li>The sidecar enhances the usability of the motorcycle by increasing passenger capacity</li><li>The sidecar could be made by another company and need not be bought from the motorcycle manufacturer — providing modularity and flexibility of choice</li><li>It does not have an engine of its own but relies on the engine of the actual motorcycle. If the motorcycle stops, the sidecar stops</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ua4SzEnuRehslIDd.jpg" /></figure><p><em>While we’ve only barely scratched the surface here, I do hope this list was helpful to you.</em></p><p><em>Which design patterns do you find yourself employing constantly? — I ‘d love to hear more about them.</em></p><p><em>Please feel free to post your recommendations in the comments below and I’ll do my best to try and update this list to include them.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113c788b33ff" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/cloud-design-patterns-explained-simply-113c788b33ff">Cloud Design Patterns— Explained Simply</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>
    </channel>
</rss>