<?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 Rakesh Malhotra on Medium]]></title>
        <description><![CDATA[Stories by Rakesh Malhotra on Medium]]></description>
        <link>https://medium.com/@chatrakesh?source=rss-23444f43894b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_Pd6bD1aq73pHyGq.jpg</url>
            <title>Stories by Rakesh Malhotra on Medium</title>
            <link>https://medium.com/@chatrakesh?source=rss-23444f43894b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:52:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chatrakesh/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[Let’s walk-through Pipes and Filters]]></title>
            <link>https://chatrakesh.medium.com/lets-walk-through-pipes-and-filters-e6204456497a?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6204456497a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[distributed-architecture]]></category>
            <category><![CDATA[pipe-and-filter]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 11:02:01 GMT</pubDate>
            <atom:updated>2022-10-31T06:53:27.449Z</atom:updated>
            <content:encoded><![CDATA[<p>We often come across situations in Software development that are quite common in nature and people have experienced them before, in one way or the other. These situations can be handled either by building a very custom and specific solution or by the use of an existing, widely accepted, and time-tested Design Pattern. Today the topic of our discussion is also one of the Design Patterns that has been around for quite some time now and has been the basis of quite a few well-known implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*r8V0l6D5APlzR_f5P5LLsg.jpeg" /></figure><h3><em>The Problem</em></h3><p>Applications perform a variety of tasks on the data they receive from a variety of sources. When all of those tasks are performed within the context of the same deployable it becomes difficult to optimize the overall processing. As an example, let’s assume an application is performing 4 tasks T1, T2, T3, and T4 in sequence with the data it receives. Of these tasks, T2 is the most complicated, CPU-intensive operation. Since all of these tasks are part of the same deployable, it becomes tricky to optimize T2 if the only thing that can be done for its optimization is to enhance the underlying hardware.</p><p>Apart from this there could be a need where the ordering of these tasks may need to change and/or a new task need to be brought in the overall processing requirements, for these, we may need to re-shuffle/re-factor the tasks in such a way that we can accommodate either a new sequence or a new task altogether. In either case, the change in the existing tasks is unavoidable and that would lead to the execution of regression cycles on already tested functionalities.</p><p>These needs make it difficult for the application to perform at its peak. The below picture depicts these tasks working as part of a single deployable and are tightly coupled that limits changes in them to accommodate dynamic business needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxYf-eYQUgNxvQdBqZ9PGA.png" /></figure><p>With that said, what are the options for tackling this? Let’s dive in…</p><h3>The Proposal</h3><p>The best thing one can do for this is to decompose the application in such a way that all these tasks can be individually controlled, managed, deployed, etc., i.e. they all have their own life cycle and are not dependent on each other. As mentioned in the example we gave in the ‘The Context’ section, task T2 is the most complicated, CPU intensive out of the 4 tasks that the application runs in order to process the incoming data. When we split these tasks since task T2 is more CPU intensive, we can scale out and provide more CPU power to it and that will reduce the overall processing time.</p><p>The order in which these tasks are to be executed will not change with this split, the change that will come in the overall processing would be that the tasks would independently be deployed, the resources on which they operate can be independently scaled up or down, can be re-factored without impacting others. What this change would also mean is that all these tasks would need to define the contracts upfront so that each of them can honor them while they are processing the real-time data.</p><p>Splitting them also brings another advantage in that is they become more manageable, reusable while being more efficient. While we get all these benefits there is a small caveat attached to it as well since the processes would be split into distributed machines, which would bring in additional complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDsTAI5ZzR7zMcQig9x5hg.png" /></figure><h3>The Pattern</h3><p>These tasks that we have been referring to are nothing but ‘Filters’ and the conduits by which they are connected with each other are called ‘Pipes’ and the design pattern that we have been after, is well know as Pipes and Filters Pattern. We can have as many Filters as we need for handling any business use case while each such Filter remains ignorant of any other Filter present in the overall chain.</p><p>The following diagram depicts the overall picture. In the chain, as we have learned we can have as many Filters as needed. One thing to note in this design is the efficiency of the overall processing boils down to the slowest running Filter in the chain. Hence in order to optimize the overall processing time, we just need to optimize the slowest running Filter which is a huge advantage as opposed to the conventional design where all the tasks were part of the same deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwL_zjzUrDKm22TcN4NYzg.png" /></figure><p><strong>Filter — </strong>It is a component that is tied to a Pipe and is mainly responsible for transforming or filtering the data that it is receiving from the Pipe it is connected with. There is no limit on the number of input and/or output Pipes associated with any Filter</p><p><strong>Pipe — </strong>It is a conduit that connects one Filter with another and is mainly responsible for carrying the data. It normally has buffering capabilities so that in the events of subsequent Filter being unavailable it can retain the message and can pass it to the Filter as and when it comes back online</p><p>In the modern world, when everything is on the cloud and distributed across different Regions/AZs we can use our discretion to deploy whichever Filter to whichever Region/AZ combination allows each such task to run in close proximity with the data it needs.</p><p>When the data is being streamed from the Source, various Filters which are participating in the chain can work in parallel what that means is the previous Filter doesn’t need to be completed fully before the subsequent Filter can pick up the previous Filter’s output as its input.</p><p>Another aspect worth mentioning in the context of this Pattern is how Fault-tolerant it can be. Assuming we have 3 Filters running in succession on the data which is being emitted by a Source. Out of them if T2 happens to misbehave or fail randomly, what is going to happen with the changes that T1 has already committed to its datastore? We are not worried about T3, as nothing would have happened on it since the processing stopped at T2 itself. This is an important aspect that can’t be left aside for future handling. Well, in such cases, we need to build something similar to the ‘SAGA’ design pattern. This can bring a couple of aspects:</p><ol><li>Compensation</li><li>Idempotency</li></ol><p>When we opt for Compensation, the Filters which have executed successfully before something broke subsequently in the chain, need to have a path defined in their context which they can tread upon to bring their state to where they were before things changed at them.</p><p>And should we pursue on Idempotency route, we need to ensure that the Filters can handle the repeated invocation for similar data. What this means is they need to have a mechanism that can stop them from going into an inconsistent state even by multiple similar invocations.</p><h3>An Example</h3><p>So far we have been talking along with a theoretical example, now let’s dive in with this Pattern by taking one real-life example. Let’s say there is a Source that is emitting messages. These messages contain a string that is a mixture of numerics, alphabets, special characters. This string is totally jumbled up and what we as business users need from the system is to produce a message that consists of a string of numbers that are sorted in ascending order.</p><p>Alright, so we have a task at hand, so in summary, if we put down the requirements in bullet points it would look like as below:</p><ol><li>Remove Alphabets</li><li>Remove Special characters</li><li>Sort the list of numbers in ascending order</li></ol><p>At a high level what we can think of is to define 3 Filters, let’s call them AlphabetFilter, SpecialCharacterFilter, and AscendingSortFilter</p><p>The jumbled-up string from the Source would land on AlphabetFilter which will produce a string that will just have a mix of special characters and numbers.</p><p>The SpecialCharacterFilter will pick this as an input and will produce a string that would just have unsorted numbers while filtering out all the special characters.</p><p>Lastly, the AscensingSortFilter will pick the unsorted number string and will produce a string of numbers that are sorted as desired. This list so obtained can be sent to other components of the system for further processing.</p><h3>Conclusion</h3><p>As we discussed above, this Pattern is great when we have to perform multiple operations on the data being emitted by a Source. There are considerations that we need to be watchful of while opting for this Pattern, some of them that we talked about were Complexity, Fault tolerance, Distributed Nature, Idempotency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6204456497a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gatekeepers of the Treasure-house — Part 2]]></title>
            <link>https://chatrakesh.medium.com/gatekeepers-of-the-treasure-house-part-2-55d2cf9950bf?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d2cf9950bf</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[openid]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 11:05:53 GMT</pubDate>
            <atom:updated>2021-07-09T11:05:53.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gatekeepers of the Treasure-house — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3AXhf0DUQnpDRW1D" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s continue our expedition and see what else can be brought to make sure that the system we are building is secure and has a strong defense against any kind of attack. We will resume from where we left in our previous article which can be referred to <a href="https://chatrakesh.medium.com/gatekeepers-of-the-treasure-house-c61637ea0ccf">here</a>.</p><p>Just to summarize in the previous article, we talked about the need for having dependable Authentication and Authorization mechanism, and specifically, we delved deeper into the Authorization part and saw how this can be achieved according to the specifications and guidelines provided by OAuth 2.0.</p><p>OAuth 2.0 in general is an Authorization framework as it majorly deals with permissions that ‘<em>The Client Application</em>’ can get on behalf of ‘<em>The Resource Owner</em>’ from ‘<em>The Authorization Server</em>’. At no point in its journey does it deals with the Profile data (name, email, age, gender, etc.) of the user. Although, we saw that ‘<em>The Client Application</em>’ can send ‘profile’ in the ‘<em>scope</em>’ field while sending a request that goes to ‘<em>The Authorization Server</em>’ and can get some part of the user profile back <em>but</em> <em>this is literally just about it</em>! In case ‘<em>The Client Application</em>’ needs to fetch more details around the user, there was no better way available for the same.</p><h3>Incomes OpenID Connect</h3><p>OpenID Connect saw the light of the day in 2014 and is a standard for Identity Providers (IdP) and since the beginning, it became a common buzzword owing to its simplicity, as it was based on OAuth 2.0, and it was easy to consume, as the tokens they generated were in JSON format.</p><p>Upon successfully authenticating with Identity Providers, the user is issued an Identity Token. This works as a gateway for entering into the system, as it possesses the claims, but at the same time, the user is not allowed to perform an inch extra which is not part of the claims that the token carries.</p><h3>How to get one?</h3><p>As briefed above, OpenID Connect is based on OAuth 2.0 or rather we should say that it is an extension of OAuth 2.0. The mechanism of implementing it is also not very much different from OAuth 2.0 flows that we have covered <a href="https://chatrakesh.medium.com/gatekeepers-of-the-treasure-house-c61637ea0ccf">here</a>.</p><p>Summarizing them, there are two parts to it as long as we are talking about a typical web application that has a frontend that is supported by a backend.</p><ol><li><strong>Getting the Authorization Token</strong>: The frontend of ‘<em>The Client Application</em>’ makes a call to an OpenID complaint ‘<em>The Authorization Server</em>’ as shown below:</li></ol><blockquote><a href="https://{authServerDomainName]/auth?response_type=code&amp;client_id={clientId}&amp;redirect_uri={redirectURI}&amp;scope=openid%20profile&amp;state={randomStateString}">https://{authServerDomainName]/auth?response_type=code&amp;client_id={clientId}&amp;redirect_uri={redirectURI}&amp;scope=openid%20profile&amp;state={randomStateString}</a></blockquote><p>In the above call, there is one difference from the regular OAuth 2.0 call. As can be seen, we are sending ‘<em>openid</em>’ and ‘<em>profile</em>’ as part of the ‘<em>scope’ </em>field. This tells ‘<em>The Authorization Server</em>’ that ‘<em>The Client Application</em>’ is interested in getting the ID Token along with the Authorization Code.</p><p>2. <strong>Getting the Access Token</strong>:<strong> </strong>As we saw in the previous post the next step in the OAuth 2.0 protocol is to exchange the Authorization Code with ‘<em>The Authorization Server</em>’ to get the Access Token. The backend of ‘<em>The Client Application</em>’ will send the Authorization Code to ‘<em>The Authorization Server’ </em>and in response ‘<em>The Authorization Server</em>’ will send back the Access Token along with the ID Token, as in Step#1 ‘<em>openid</em>’ was also sent as part of the ‘<em>scope</em>’ field.</p><p>The URL for the above remains the same as was the case with normal OAuth 2.0 exchange</p><blockquote><a href="https://{authserverdomainname}/token?grant_type=authorization_code&amp;code={authorizationCode}&amp;redirect_uri={redirectURI}&amp;client_id={clientId}&amp;client_secret={clientSecret}">https://{authServerDomainName}/token?grant_type=authorization_code&amp;code={authorizationCode}&amp;redirect_uri={redirectURI}&amp;client_id={clientId}&amp;client_secret={clientSecret}</a></blockquote><p>Upon success, ‘<em>The Authorization Server’ </em>will generate a response that looks like below:</p><blockquote>{<br> “<strong>id_token</strong>”:“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c” <br>“<strong>access_token</strong>”: “SlAV32hkKG”, <br>“token_type”: “Bearer”, <br>“expires_in”: 3600, <br>}</blockquote><p>The value that we see for ‘<em>id_token’ </em>field appears to be a gibberish sequence of characters but actually, it has significance and is popularly know as JSON Web Token or <em>JWT</em> in short. Every JWT token has 3 main parts: Header, Payload, and Signature.</p><p>Along with ‘<em>id_token</em>’ we can see the response also contains ‘<em>access_token</em>’ this is to ensure that the exchange between the backend of ‘<em>The Client Application</em>’ and ‘<em>The Authorization Server</em>’ is an OAuth complaint. Any subsequent request to ‘<em>The Resource Server</em>’ from the backend of ‘The Client Application’ has to have the Access Token.</p><p>As part of the JWT Token ‘<em>The Client Application</em>’ will get the basic information of the user that comes embedded within the ‘<em>payload</em>’ part of the JWT Token, but should there be any further need by ‘<em>The Client Application</em>’ to fetch more details for the user, they can invoke a dedicated endpoint /userInfo available on the OpenID compatible Authorization Servers.</p><h3>What comes by default</h3><p>OpenID connect specifies a standard set of <a href="https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">claims</a> and they provide ‘<em>The Client Application</em>’ all the basic needs for all that it needs to know about a user. ‘<em>The Client Application</em>’ should ensure that they are putting the ‘<em>claims’ </em>to as low or as much as needed. At any later point, the user can deny the release of some claims, and the application should be able to handle such situations gracefully.</p><p>There are a couple of ways in which ‘<em>The Client Application</em>’ can get the claims they are after:</p><ol><li>By explicitly passing what they need in the ‘<em>scope</em>’ field. A complete list of what they can send in ‘<em>scope</em>’ field is covered <a href="https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">here</a></li><li>By sending the optional ‘<em>claims’</em> parameter in the request. As shown <a href="https://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter">here</a></li></ol><h3>Original Specs</h3><p>More on the subject can be found <a href="https://openid.net/connect/">here</a></p><h3>Conclusion</h3><p>In these two posts, I’ve tried to add more light to the two aspects of OAuth 2.0 and OpenID Connect which is an extension of OAuth 2.0 especially around the usage and intent of these two specs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d2cf9950bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gatekeepers of the Treasure-house!]]></title>
            <link>https://chatrakesh.medium.com/gatekeepers-of-the-treasure-house-c61637ea0ccf?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61637ea0ccf</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 12:55:38 GMT</pubDate>
            <atom:updated>2021-07-06T12:55:38.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5UrCreniOzZAk-j5" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Software development is a field that has evolved over a period of time, people used various sets of technologies that were deemed the latest and greatest at the time when the development was happening, but with time everything evolves and makes way for something new and fresh. However, some of the aspects have stood the test of time and have remained as important and relevant as they were at any point in time. Best practices like various Architectural patterns, Design patterns, SOLID principles, etc. are still considered the backbone of any good quality software. Along with these, there is another aspect that everyone should be very much careful of to keep the trespassers, the hackers, and bad guys at bay and that is nothing but the defense mechanisms of the system being developed.</p><p>In this article, we will try to present an overview of the approach and the tools we have with us to make a truly secure system.</p><h3>Security of the System</h3><p>We can build a system and use what not available at that time but if the security of the system is compromised then whatever we have used will not come to rescue the system, so it is of paramount importance to think of having a good safety mechanism in place while the system is being designed. In that sense two things are commonly referred to and used: Authentication and Authorization, let’s spend some time understanding these two.</p><h4>Authentication</h4><p>It is a process where the users prove themselves to be what they claim. This is normally the first line of defense of a system. There are various ways this can be done and normally it is implemented using passwords, biometrics, one-time passwords, or one-time pins or MFAs.</p><h4>Authorization</h4><p>It is a process to ensure that the user trying to access a resource does really have the needed permissions, otherwise the system shouldn’t allow the user to access the resource.</p><p>With this brief, let’s jump straight on to the topic of this article which is Open Authentication shortly referred to as <em>OAuth.</em></p><h3>Why OAuth?</h3><p>Well, we may say if we have a way to create an Account or Register to any site then what else is needed for having another buzzword called <em>OAuth</em>. The answer lies in the fact that we may not have trust on the site we are trying to create an Account on or sometimes (<em>ideally this should be avoided at all costs</em>) users end up sharing the same passwords on multiple accounts, for these and various other reasons OAuth gives us the alternative to not have Account or get into a situation where we may have to share the passwords at multiple places.</p><p>Imagine you need to build a collage of your favorite memories and want to share that with your best friend and with little googling you come across a site that offers to build collages and share that with the world but you are not sure how this site would use your profile obviously that includes user username, password, name, age, etc. <em>What do we do now?</em></p><p>For these reasons nowadays the applications that offer to provide some kind of service to the users have a way that allows the users to bypass this process and that means they are <em>OAuth</em> compatible. Let’s dwell further into <em>what</em> part now.</p><h3>What is OAuth?</h3><p>OAuth is an open-source Authorization protocol that lets the application secure access to resources on behalf of the user. Let’s say there’s a collage building application and it allows the users to maintain the state of work and for that it mandates the users to build their profile before venturing into collage making process. It though has an integration with Facebook and allows the users the authenticate on Facebook and then the application would request Facebook to share the basic information (<em>information that is needed to build a profile on the Collage application</em>) back to it only if the user gives consent. This way the user can have a sound sleep of not creating an account on an application that he/she is not very sure of and of anything that goes wrong with the Collage application!</p><h3>How does it work?</h3><p>The OAuth <a href="https://oauth.net/2/">specifications</a> are not very apparent and are a bit confusing at times, we will present the details of using OAuth in a fairly simple and practical way. While talking about OAuth there are few keywords that we should understand before getting closer into the nitty-gritty of the protocol.</p><h4>The Client Application</h4><p>It is a third-party application that needs to get access on behalf of the user at the same time it can’t get access until and unless explicitly allowed by the user</p><h4>The Resource Server</h4><p>It is a server where the resources that ‘<em>The Client Application</em>’ needs to access are residing</p><h4>The Authorization Server</h4><p>It is a server that is responsible for authorizing ‘<em>The Client Application</em>’ to get access to the resources present on ‘<em>The Resource Server</em>’</p><h4>The Resource Owner</h4><p>It is a person who gives consent to ‘<em>The Authorization Server</em>’ when ‘<em>The Client Application</em>’ tries to access some part of his/her account</p><h4>How they fit in?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2ygkPwvmcmRsBNM0xa-RQ.png" /><figcaption>Model#1</figcaption></figure><p>The above illustration depicts the ecosystem of the OAuth and how each participant is related to others and how the coordination happens. At a high level, ‘<em>The Resource Owner’ </em>delegates ‘<em>The Client Application</em>’ to get the access token from ‘<em>The Authorization Server</em>’. Using this access token, ‘<em>The Client Application</em>’ then goes and gets the needed resource from ‘<em>The Resource Server</em>’.</p><p>As said this is at a very high level, now let’s get a little deep to understand what makes this flow work on the ground.</p><h3>The Details</h3><p>The key point in the above diagram is ‘<em>The Client Application</em>’ acting on behalf of ‘<em>The Resource Owner</em>’. But for that to happen, ‘<em>The Client Application</em>’ needs to register itself with ‘<em>The Authorization Server</em>’. The registration process involves submitting basic information like application name, website name, logo, etc. Along with these details, it also needs to provide a callback URI or a redirect URI that ‘<em>The Authorization Server</em>’ would use for communicating back with ‘<em>The Client Application</em>’. Upon submitting these details, ‘<em>The Client Application</em>’ will get a <strong>Client ID</strong> and a <strong>Client Secret</strong>. Client ID is public information whereas the Client Secret has to be kept secret under all circumstances preferably on the backend of ‘<em>The Client Application</em>’.</p><p>All this and what comes next can be understood by going over this flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9S8f2Knsq1-tLcmASE6dHw.png" /><figcaption>Model#2</figcaption></figure><p>For Web-based or Mobile-based applications the next thing in line is ‘<em>The Resource Owner</em>’ clicking on some interface on the front-end of ‘<em>The Client Application</em>’ to get authenticated with ‘<em>The Authorization Server</em>’. ‘The Resource Owner’ is redirected to the login page of ‘The Authorization Server’. Upon submitting his/her credentials a consent screen is displayed to the user, and at this point, the user is completely at his discretion to either Accept or Deny the prompt shown on the screen. <em>What happens under the carpet here</em>, let’s understand.</p><p>The front-end of ‘<em>The Client Application</em>’ submits a request to ‘<em>The Authorization Server</em>’ for getting the Authorization Code. In the process, it submits the following details to ‘<em>The Authorization Server</em>’</p><ol><li><strong>response_type=code</strong><br>This tells ‘<em>The Authorization Server</em>’, that the front-end of ‘<em>The Client Application</em>’ is seeking the Authorization Code in the response</li><li><strong>client_id <br></strong>It is the Client ID that ‘<em>The Client Application</em>’ got upon successful registration with ‘<em>The Authorization Server</em>’</li><li><strong>redirect_uri <br></strong>It is the callback URI that ‘<em>The Authorization Server</em>’ would invoke post successful authentication</li><li><strong>scope<br></strong>These are the values that indicate what part of the User’s profile is ‘<em>The Client Application</em>’ interested in</li><li><strong>state<br></strong>This is a random field that ‘<em>The Client Application</em>’ would verify later</li></ol><p>The front-end of ‘<em>The Client Application</em>’ sends an HTTP GET request and the URL looks like below:</p><blockquote><a href="https://auth-server.com/auth?response_type=code&amp;client_id={clientId}&amp;redirect_uri={redirectURI}&amp;scope=profile&amp;state={randomString}">https://{authServerDomainName]/auth?response_type=code&amp;client_id={clientId}&amp;redirect_uri={redirectURI}&amp;scope=profile&amp;state={randomStateString}</a></blockquote><p>When ‘<em>The Authorization Server</em>’ receives this request, it displays an Authorization prompt and after getting the consent from the user it sends the Authorization Code back to the front-end of ‘<em>The Client Application</em>’ by invoking the callback URI which is submitted at the time of the registration process. The front-end of ‘<em>The Client Application</em>’ also receives the <strong>state </strong>in the response and it validates that with what it sent as part of the initial request. This ensures the connection is not forged between the two parties.</p><p>Now since the front-end of ‘<em>The Client Application</em>’ has the Authorization Code, it trades it with ‘<em>The Authorization Server</em>’ for getting the Access Token. The front-end of ‘<em>The Client Application</em>’ sends the Authorization Code to its back-end. The back-end of ‘The Client Application’ now takes charge and sends an HTTP POST request and the URL looks like below:</p><blockquote><a href="https://{authserverdomainname}/token?grant_type=authorization_code&amp;code={authorizationCode}&amp;redirect_uri={redirectURI}&amp;client_id={clientId}&amp;client_secret={clientSecret}">https://{authServerDomainName}/token?grant_type=authorization_code&amp;code={authorizationCode}&amp;redirect_uri={redirectURI}&amp;client_id={clientId}&amp;client_secret={clientSecret}</a></blockquote><ol><li><strong>grant_type=authorization_code<br></strong>The grant type for web-based and mobile-based applications would be authorization_code only</li><li><strong>code<br></strong>It contains the Authorization code received as part of the previous call to ‘The Authorization Server’</li><li><strong>redirect_uri<br></strong>The callback URI where the Access Token would be sent back to ‘<em>The Client Application</em>’</li><li><strong>client_id<br></strong>The Client ID of the ‘<em>The Client Application</em>’</li><li><strong>client_secret</strong><br>The Client Secret of ‘<em>The Client Application</em>’</li></ol><p>The response of the above call in case it is successful yields <em>Access Token</em> and a time duration within which the <em>Access Token</em> would expire.</p><p>Now the back-end of ‘The Client Application’ with the help of the Access Token, can make a request to ‘<em>The Resource Server</em>’ for getting the desired resource. ‘<em>The Resource Server</em>’ also validates the Access Token with ‘<em>The Authorization Server</em>’ and post validation it sends back the resource to the back-end of ‘<em>The Client Application</em>’</p><h3>Why 2 steps?</h3><p>If we look at Step#1 of getting the Authorization Code it all happens on the Front channel. A Front channel is a channel where normally the data transmission happens over the browsers. The front-end of ‘<em>The Client Application</em>’ sends re-direct to the login page on ‘<em>The Authorization Server</em>’. Post this, ‘<em>The Authorization Server</em>’ makes a callback on the front-end of ‘<em>The Client Application</em>’, as can be seen here all of these are browser redirects. So there are chances that some can squint or oversee what’s being exchanged and therefore the credibility of the tokens being transmitted can be compromised.</p><p>For this as well as the need of keeping the Client Secret always under the confines the actual request for getting the Access Token is sent from the back-end of ‘The Client Application’ which is also called the Backchannel.</p><p>There are applications where this may not be possible like single-page apps where keeping the <strong>Client Secret </strong>may be challenging. For them, there are different mechanisms that are used that involve sending a dynamically generated secret with each request.</p><h3>Conclusion</h3><p>I tried to detail out some of the confusing aspects in OAuth usage although there are other grant types that are supported by OAuth specifications. But the one talked about here ‘authorization_code’ is the most widely used type of grant type. I’ll share more details around these and some other aspects of OAuth in my next!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61637ea0ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Letting Microservices dance to the tune of…]]></title>
            <link>https://chatrakesh.medium.com/letting-microservices-dance-to-the-tune-of-9308f0eb876b?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9308f0eb876b</guid>
            <category><![CDATA[choreography]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 10:55:18 GMT</pubDate>
            <atom:updated>2021-06-08T10:55:18.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZKlEfiHR9_j7cL11" /><figcaption>Photo by <a href="https://unsplash.com/@dascal?utm_source=medium&amp;utm_medium=referral">Adrian Dascal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>An enterprise-class application often has multiple disparate systems which work toward a common goal of giving an unmatched experience to its end users. The components working together can be part of the same umbrella or maybe some are controlled by third parties. And if we have to relate this with today’s approach of building such systems, one thing that pops out would be, is to have such an application with multiple microservices with each having its own purpose, its own reason of existence.</p><p>Architects and Designers spend a considerable amount of time deliberating the right approach of splitting the services and wiring them up in such a way that the integration and the data flow between them become smooth. As said before this is an intense step in determining the right combination for the task at hand and has to be bang-on or else the repercussions could be huge and therefore it is advisable to have a team of experts especially with some prior experience who can ask the right set of questions, can set right set of expectations, can take the right set of assumptions when talking to business owners, users, and various other stakeholders.</p><h3>Calling the shots</h3><p>When talking about an enterprise-class application with multiple microservices within its scope, it is imperative that all these services must work together as a unified system and for that to happen they need to stay and work with each other in harmony! Getting to the ultimate state where the services becomes autonomous, they are proactively instrumented, they generate alarms, they auto-heal themselves are some of the goals that we should aspire to and inorder to achieve them we need start well and splitting the services properly and coordination between them plays a vital role.</p><p>Let’s try to spend some time in this article to understand how the coordination between services is planned, executed and what each such approach brings to the table and the things we should be wary of!</p><h4>Orchestration</h4><p>It is a technique in which the microservices talk to each other with one central controller in between. This controller is responsible for calling the shots and decides what all microservices should be involved in any given workflow. This is a mode that works much like a Conductor giving instructions to musicians who are well versed in playing their instruments. The Conductor in an orchestra controls the overall performance of the band, similarly, in the Orchestration mode, there is a microservice that dons the hat of being a Conductor and runs the show.</p><p>As visible in the diagram below, Microservice A and Microservice B are the controllers here and acts as an orchestrator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*NMi8FINru0lxmnATigdxeg.png" /><figcaption>Orchestration</figcaption></figure><h4><strong>Why Orchestration?</strong></h4><ol><li>Centralized control that leads to simplified management of the workflow</li><li>Logging and Monitoring the workflow becomes easier</li><li>Synchronous nature of Orchestration makes the coordination of flow more efficient</li></ol><h4>and Why not?</h4><ol><li>Tight coupling between the services leads to an overly interdependent system, and any failure in any of the services can lead to drastic implications and can even bring the entire system to a halt</li><li>With Orchestrator controlling the show, it acts as a single point of failure, in the events of it going down, the entire system could be at risk</li><li>Over dependent on one mode of communication can at times makes the implementation overly in favor of REST</li><li>With large number of microservices in the system, and with multiple flows converging to single microservice can lead to scaling and performance issues</li></ol><h4>Choreography</h4><p>This technique on the other side doesn’t prefer a single controller to lead the show, in fact all the services in the enterprise application act as autonomous and can work independently of each other. However, each service knows how to handle the messages coming from other services, they are aware of the syntax and semantics of processing them. It is like a group performance where each performer knows about the steps that he/she has to take to make the entire performance, a hit! As and when each microservice receives a message and knows that the message is valid, it triggers the appropriate workflow and would then emit an event via message broker and that’s it. The job of the microservice is, by and large done, post this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gcPIPh59yJ_b0Mn828MDA.png" /><figcaption>Choreography</figcaption></figure><h4>Why Choreography?</h4><ol><li>Reduces coupling between services and thereby dependency</li><li>More flexible and agile development</li><li>Not anymore single point of failure</li><li>Easy to plugin new microservices into the overall ecosystem</li></ol><h4>and Why not?</h4><ol><li>Scale and complexity of the overall application grows especially when there are a significant number of operating services</li><li>This also leads to decentralization of the business logic as there would co-exist mini-functional owners in form of different microservices</li><li>There is a paradigm shift from conventional synchronous style to the asynchronous style of design and development</li></ol><h4>Middle Ground</h4><p>As we can see, there are pros and cons of both Orchestration and Choreography and hence we should be pragmatic in our selection for architecting any system. A common ground could be to mix the best of these two approaches and build systems on top of that! This approach wouldn’t only suite in cases where we are building a fresh system from scratch but in case where we are re-architecting or doing adjustments in the existing application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9308f0eb876b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Integration & challenges]]></title>
            <link>https://chatrakesh.medium.com/service-integration-challenges-edac8468849f?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/edac8468849f</guid>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[integration]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 14:16:17 GMT</pubDate>
            <atom:updated>2021-04-28T14:16:17.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ASS4R0kKYguJqqPF" /><figcaption>Photo by <a href="https://unsplash.com/@johnschno?utm_source=medium&amp;utm_medium=referral">John Schnobrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Services have been around for a while now and more recently they have taken the shape of Microservices and concepts like Domain-Driven Design, and others have been the guiding principles in their development. More often than not when an enterprise application is built along the lines of microservices architecture, the application ends up having multiple of them.</p><p>In this article, we will not delve into the intricacies of how to define the boundaries of a microservice and how many we should have, what granularity are we seeking, etc. Our focus in this article would be around the challenges or the pitfalls that one needs to be wary of while integrating with multiple services (within and outside of the enterprise application)</p><p>Let’s assume Microservice A is talking to another service B. The integration between these two can be either synchronous or asynchronous depending upon the nature of the use case that one is dealing with. But whatever it may be, there are chances that microservice B may get overwhelmed and starts deteriorating in performance by virtue of calls coming from A. What this will do is it will impact the performance of not just microservice A but the entire application in general. Do we have some remedy for this?</p><p>One thought that comes to the forefront is to upscale microservice B so that it can handle the load it is getting from service A. But if this load increases beyond what microservice B is upgraded to handle, we will end up circling back to deal with the same situation. What next?</p><p>Every microservice has limited resources (irrespective of how much we upscale the infrastructure), with this thought in the back of our minds, what naturally succeeds the previous thought is either microservice B starts rejecting calls beyond its capacity or somehow microservice A only send that many number of requests to B which it can tolerate and work with. In a distributed system, these concepts are implemented using Backpressure or by Throttling.</p><p><strong>Throttling</strong> is an important concept where the microservice starts rejecting the calls based on how many it can safely handle without suffering the quality. There are various ways in which this can be implemented as an example. Throttling the Rate, Throttling the IP, Throttling the Scope, etc.</p><p>There’s another aspect that one needs to be aware of and that is <strong>Timeouts</strong>. When there are calls happening across microservices, especially when some of the calls are going beyond the logical and physical boundaries of the application, it is a defacto standard of defining the timeouts at various levels. Timeouts for the Read requests, Timeouts for Write requests, Timeouts for connection, etc.</p><p>Timeouts can occur for multiple reasons like the service is too busy doing something and hence any further requests landing on it get timed out, it could also occur due to service being not available at all and hence the caller is not receiving the expected response.</p><p>One more thing in line with this that one can think of is to use <strong>Circuit breakers</strong>. They can help in diverting the traffic from the service which is unavailable for any reason to some default implementation. What this will do is the application will not be unavailable completely and will continue to serve the requests which are possible with the default implementation.</p><p><strong>Decoupling </strong>is another approach one can think of. Instead of processing the complete request in one go (<em>there are obvious reasons if one does it</em>), one can think of splitting the overall transactions into multiple parts and let some part of it be done asynchronously. It will give two benefits, the first being the response generation would be faster and secondly, the system will be relatively more available to process any new request.</p><p><strong>Bulkhead </strong>is another approach where the service dedicates resources to different categories of request processing components. This way the problem in one category is isolated and doesn&#39;t impede the availability and performance of other components</p><p>As we can see there is so much that happens while integrations and equally important what we can do in order to keep our application resilient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edac8468849f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActorModel — Getting started]]></title>
            <link>https://chatrakesh.medium.com/actormodel-getting-started-df39a36c4076?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/df39a36c4076</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 12:00:02 GMT</pubDate>
            <atom:updated>2021-04-22T12:00:02.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>ActorModel — <em>Getting started</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2I2_sc3pEZdOiDW9" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ith the advent of more and more powerful hardware, efficient network, and equally capable software the expectation of the overall business experience from any Platform has dramatically increased. Frameworks like Angular and React have given so much more to the users to work with on the screens and that has attracted an increased focus on the User Interface development more than ever. More and more users would be using the software especially when there is an event or a year-end sale or something of that sort.</p><p>What this has done to the system underneath is it has put an additional load on the overall resources supporting the Platform. As an Architect one needs to ensure that the system is not getting into an choked. The platform should remain Available, Scalable especially when the system is experiencing a sudden surge of traffic.</p><p>With this backdrop, let’s try and explain the problem that we are going to target in this blog and see what all options we have with us.</p><h4>The Problem</h4><p>Often in the circumstances we briefly touched upon above we have seen that systems if not built with these concerns in mind either gets into an inconsistent state or are unable to handle this much load and start deteriorating and become unusable and eventually collapse. If none of this happens then surely these concerns are handled within the Platform, the Architects, Leads, Development teams must have given a thorough thought before deploying the solution. More often than not, handling concurrency has been a challenge, threads compete with each other for the shared resources and they get into a race for updating that and ensuring they are not working on the obsolete state of the resource.</p><p>We all know how much it takes to manage concurrency, i.e. managing the consistent state of the shared resources in a multithreaded environment. The threads take a lock on the semaphore, executes their business logic, and release the lock so that other competing threads can get access to the semaphore. Especially when the system is experiencing a tremendous load we can just imagine how many permutations possibly can arise.</p><p>Well, we have been talking about the concerns that come along with having a multithreaded environment, is there anything that can be used out of the box and free up the developers to focus on the actual business requirements that they need to work on? The answer is <em>Yes!</em></p><h4><em>Akka to the rescue!</em></h4><p>What Akka provides distinctively is that the developers don’t need to worry at all about the multithreading issues anymore. They just need to focus on developing their business logic and Akka takes care of ensuring that the Platform in general remains in a consistent state.</p><p>Akka is a framework that vows to make the most of the resources and facilitates the developers in building an application that’s scalable enough to manage literally any workload from big data, applications involving financial transactions at a rapid rate to developing gaming apps, to say the least.</p><p>As we have seen above, it is not easy to handle issues with multiple threads without seriously impacting the performance of the underlying platform, with Akka however all these concerns are nicely abstracted from the developers. Now, what are the tricks of the trade that one needs to know, let’s take a quick look at all the building blocks of an Akka system.</p><h4>Basic Components</h4><p>Just like every other Framework Akka is no different from being composed of some of the basic building blocks that help its users to make the most use of its capabilities.</p><ol><li><strong>Actors<br></strong>Actors are the basic building blocks of the Akka system. They are the basic unit of work that the overall system is dealing with. It has a state and also encapsulates the behavior. Actors would always be running in a single-threaded environment thereby ensuring that the issues related to concurrency do not creep in at all. Another key point with Actors is they communicate with each other only via messages. What this also means is there’s no scope of directly invoking the behavior of an Actor by anything outside of an Actor. Another point worth noticing with respect to Actors is that they work on immutable messages. While they are not processing any message they remain in a dormant mode. The overall architecture while working with the Akka framework tends to be Asynchronous and hence there’s no blocking of threads. Every Actor has a unique address just like any computer on the internet has an IP Address, and all the messages that are sent for an Actor are stored in their mailbox. These messages are then read by the Actor in a FIFO mode and the framework ensures that they are processed once at a time. Refer to Figure#1 for more clarity</li><li><strong>Actor System<br></strong>It is essentially the area where all the bootstrapping happens an application that’s driven by Akka. It provides a place where all configurations go in and it is generally one per application. It provides a platform using which the Actors can be categorized and also provides the support for ensuring smooth communication across Actors. The Actors are designed and implemented with the Single Responsibility Principle in mind and are broken to that extent which ensures the intactness of this fundamental principle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojrbNDuh-OiTFJGLSojHxQ.png" /><figcaption>Figure#1</figcaption></figure><h4>Fault Tolerance and Exception Handling</h4><p>How often we have felt the need for a worthy controlling mechanism especially when things go out of control? Akka is no different in this regard. But the good thing with Akka is that there is a sound emphasis given to the core of the framework itself. Yes, that’s right. Let’s find it out.</p><p>In Akka an Actor is not an independent entity, i.e. there is a supervisor for every Actor within the Akka system and that is responsible for the life cycle of an Actor. During the course of execution, there happens to be some exception, the very first thing that the Actor does is to inform the supervisor. The supervisor is also just like any other Actor but it knows how to deal with the messages that it receives from its child. When Actor gets into any trouble what it also does is immediately suspend itself and all of its children and inform the parent about this.</p><p>From here, the supervisor or the parent Actor needs to take some course of action in order to handle this signal it has got from its child. There are the following options available with the parent Actor</p><ol><li><strong>Resuming the Child<br></strong>In this strategy, the Parent decides to resume the child and its children, the only condition being the error has not corrupted the state of the Actor</li><li><strong>Restarting the Child<br></strong>When the Parent knows that the error might have resulted in the state corruption of the Actor, then it issues a restart signal to the Actor and resets the state of all the children</li><li><strong>Stopping the Child<br></strong>In this, the Parent decides to stop the child Actor as it feels that the error is irrecoverable and resuming and re-starting will not solve it</li><li><strong>Stopping itself<br></strong>In this strategy, the Parent Actor once notified of an error in the child, decides to shut itself down and escalates the error to its Parent. This happens when the Supervisor is unable to handle the kind of error it has received from its child.</li></ol><h4>Where we should use it</h4><p>With what we have learned from above it is imperative that we also got a sense of where the framework can be utilized. In general, Akka can be used in areas involving concurrency, i.e. where multiple threads are competing with each other for shared resources. It can be applied to but not limited to the following areas:</p><ol><li>Transaction handling</li><li>Gaming and betting Apps</li><li>Batch processing</li><li>Data Mining apps</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df39a36c4076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scattering and Gathering the workload]]></title>
            <link>https://chatrakesh.medium.com/scattering-and-gathering-the-workload-6cd3d9ed3b0d?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cd3d9ed3b0d</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[gather-scatter]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 11:33:27 GMT</pubDate>
            <atom:updated>2021-04-07T11:33:27.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UC4ZOnowmIiIPZBF" /><figcaption>Photo by <a href="https://unsplash.com/@nordwood?utm_source=medium&amp;utm_medium=referral">NordWood Themes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have been living in a world that is predominantly governed by software, and especially in these unprecedented times where everyone feels comfortable getting access to groceries, medication, daily needs, etc. from the confines of their homes has become even more critical.</p><p>Software companies are churning out software that suites these needs and much more at an unmatched pace and trying to acquire more and more market value with new and innovative ideas. One thing although that has stood the test of times is the way to Architect and Design the software that is efficient, resilient, robust, scalable, maintainable, extensible, and what not!</p><p>There are many Architecture and Design patterns that software can be built upon, the one that has got the limelight in today’s scenario is none other than Microservices based architecture.</p><p>But just by using Microservices architecture ensures the guarantee to success? <em>Maybe, May not be,</em> let’s try and explore a scenario that is generally overlooked and is not given the importance and recognition that it deserves.</p><h4><strong>The scenario</strong></h4><p>When working on an architecture that is Microservices based, generally we end up having multiple microservices, all of them jointly producing a coherent user experience. There are times when some of the steps that need to be performed to process any given request can be taken out of the main flow or main thread and can be offloaded to separate jobs or threads. There are various advantages and benefits that one gets should this approach is taken. <em>But there’s a caveat here!</em></p><p>Let us be specific now to make it more clear, there is Microservice A that emits an event that is specific to a customer (the weight of each such event depends on the number of employees the Customer has on its rolls) as part of some request processing. If the architecture uses Kafka as a broker, and also assume there’s a Microservice B with 4 consuming Pods (a Kubernetes terminology). This message would land on one of the partitions (let’s make another assumption that the Topic has 4 Partitions) of the Topic and would be consumed by only a single Pod of Microservice B. Refer to the below diagram for more clarity.</p><p>Now consider Microservice A is emitting events for customers which vary drastically in the number of employees on their rolls. For all practical and theoretical purposes, there are chances that any Pod out of those 4 Pods could potentially end up being too busy and the other Pods are relatively free or less busy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlkHKkiMhhsIulXLop04yA.png" /></figure><p>As can be seen in the above depiction, POD 2 is incidentally receiving messages which are relatively bulkier (<em>the ones which need more Memory and CPU during processing</em>) in nature as compared to the other three Pods. There are chances that a busy Pod if remains in that state for quite some time may end up crashing and Kubernetes may have to spin up another Pod to maintain the balance in the cluster. What will happen to the inflight requests? What will happen to any uncommitted data present in Heap? <em>Well</em> <em>these are serious concerns, aren’t they</em>? Definitely, the problem needs to be addressed from a Design standpoint and can’t be just left alone on the infrastructural components.</p><h4><strong>What options we have</strong></h4><p>Let’s explore together what tools and techniques we have in our armory to handle this</p><p><strong><em>Option#1 — Scaling</em><br></strong>The very first thing that one can do is scale up the Pods to an extent that they can tolerate whatever traffic they may end up getting at any given point in time. This approach may work but who knows the system may have to process an event for a customer which has 1000s of employees. Moreover, if the Pods are not processing such huge events every time (<em>which at most times is going to be the case</em>) then we are literally wasting the overall capacity.</p><p><strong><em>Option#2 — Publisher discretion<br></em></strong>In this approach, Publisher which in our example is Microservice A needs to do the following:</p><ol><li>Needs to categorize events into Large, Medium, and Small by checking all the possible factors which can cause additional load on the consumers. For the example we are working on, it will be the number of employees on rolls of a customer, but it certainly can vary</li><li>The next thing the Producer needs to maintain somewhere is a brief history of all events that it has emitted and to which partition. Using this the Producer can determine which of the consuming pods are relatively busier and the Producer can avoid emitting events to such partitions. Now the question may arise, how does the Producer can come to know that which Pod is busy vs not so? <em>Well</em> there are Metadata APIs that modern brokers like Kafka support and that can be used for this purpose</li></ol><p>Of all the above things that the Producer needs to do, it appears that most of the stuff doesn’t align with the core context for which Microservice A came into existence in the first place, and hence the team working on developing Microservice A needs to accommodate this additional piece on their plates.</p><p><strong><em>Option#3 — Scatter and Gather<br></em></strong>This is one of the Enterprise Integration Design patterns and the core idea behind this being is to break the message into multiple parts, let these messages be processed independently, and finally, the results of the independent processing can be consolidated.</p><p>Now let us figure out how we can use this Pattern in the example that we have been talking about so far. In our example, Microservice A is emitting random events, now to apply this pattern, we have below alternates:</p><ol><li>We can let Microservice A additionally take the responsibility for scattering the messages, i.e. instead of sending a single event for all the employees, it will first fetch the list of employees on a customer’s rolls and then will emit as many messages as many employees are there or alternatively,</li><li>Microservice A can continue sending a single event per customer and let Microservice B before processing the message, does get all the employees and emit as many messages as many employees it finds and then also consumes them for eventual processing</li></ol><p>The problem with Microservice B donning an additional hat for this purpose is from design-wise it doesn’t appear aesthetic and also violates the single responsibility principle, whereas if Microservice A is doing this it appears neater and less coupled.</p><p>So with #1 above, the problem of scattering the messages is tackled, now let’s try and find out how to gather all that we have broken or scattered?</p><p>Since Microservice A has initiated the transaction which is spanning across Microservice B, it needs to know when to mark the transaction as either Success or a Failure. For this what Microservice B has to do is to maintain a track of all the messages that it expects vs how many it has received and how many of them it has processed (either Successfully or Unsuccessfully). Since all the Pods of the Microservice B are going to use a common persistence store, the above information can be maintained in that store and can be checked if everything is complete or something has failed or things are still in progress.</p><p>Post this, Microservice B can emit an Ack message back for Microservice A’s consumption and upon the receipt of this message, Microservice A can mark the transaction complete (Success/Failure based on whatever message it received from Microservice B)</p><h4>Conclusion</h4><p>As we saw in the above example this is not a message distribution problem in all respects in fact the problems rests on the weight of the messages being emitted by the Publisher and as explained above there are multiple ways we can handle this and whichever option we end up using has to deliberated based upon the use case at hand.</p><p>At the same time, the Scatter-Gather pattern should not be only used to speed up the overall request/task processing by parallelizing it but also to optimally utilize the overall resources which the cluster has.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cd3d9ed3b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling interwoven reads and writes]]></title>
            <link>https://chatrakesh.medium.com/decoupling-interwoven-reads-and-writes-a59f9dd926ce?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59f9dd926ce</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[distributed-applications]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 12:20:34 GMT</pubDate>
            <atom:updated>2020-12-16T12:20:34.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kaWj-XmT6ANRE9JT" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The approach to software development has evolved considerably over the last decade or so. Technology has certainly improved in this period and so is the hardware and computing capabilities. Along the same lines, the approach to software development has also seen leaps and bounds improvement in the way it is approached.</p><p>We use to have big monoliths often termed as “one man armies” which were capable of handling literally everything. The main advantages being:</p><ol><li>Fewer integration issues</li><li>Lesser code as the components were co-located</li></ol><p>However, the monoliths have drawn flak on account of the inherent restrictions like they become an unmanageable beast over a period of time and any change (small or large) leads to lots of ripple effects.</p><p>A shift of mindset in the Design and thereby the Implementation from Monoliths to Microservices has certainly helped in moving away from some of the inherent shortcomings in the Monoliths, but just by using the Microservices architecture, the deal is not done.<em> </em>So<em> </em>are there some best practices/guidelines that the Architects need to keep in the back of their minds? Let’s try and find out together.</p><h3>Is everything alright?</h3><p>The dictionary meaning of the word Consistency is “<em>the quality of always behaving or performing in a similar way, or of always happening in a similar way</em>”. It is the ability of a system to respond similarly to multiple interactions with it. In the world of software, there are primarily two such kinds of it: Strong consistency and Eventual consistency. Which one to choose while designing, majorly depends on the business requirements.</p><p>When we are talking about Microservices architecture we are talking about Choreography and or Orchestration primarily and by and large they go hand in hand in most of the projects, but irrespective of the pattern that is used, every microservice that needs to support both reads and writes have to be watchful of the way it will handle these two types of requests. Let’s dive deeper into the exact problem and the approaches that can be explored to find the solution.</p><h3>What are we after</h3><p>When a microservice is serving both reads and writes then it needs to be careful of the following:</p><ol><li>All the writes that are happening on the microservice are not slowing down the read requests landing on it</li><li>With multiple writes, landing on the microservice, there are chances that read requests end up reading inconsistent data or partially committed data</li><li>Since the microservice would be having its own database, any requirement that warrants to maintain the historical state of the data updates, would not be catered to by default</li><li>It becomes difficult to scale different parts of the application if at all there’s a business need for it</li><li>Sometimes what needs to be shown on the user interface is different from what is getting persisted as part of write requests landing on the system. This means that the application may have to read data from multiple sources (multiple microservices or multiple parts of the same service) to generate the complete context as the write requests have only persisted granular data in the database</li></ol><h3>What can be done</h3><p>Now that we know the problem domain and the direction in which we are heading let’s move on in trying to find out what options we have:</p><p>Typically when we are designing any system, we primarily talk about the entities, their attributes, their state, etc. Down the line, we end up having class diagrams, entity-relationship diagrams that depict the relationship between these entities.</p><p>Conventionally in most of the Architectures, the prime concern relies on the entities i.e. how they are created, how they are modified, how they are accessed, etc. The events or commands that lead to the change in the state of the entity are often not given their due importance.</p><p>To understand this better, let’s take an example of any typical organization, there are employees which are located at different locations and they work for different departments. When an employee joins an organization, its record is created along with that, the company also stores the associated department, its work location, and his/her reporting manager. Over a period of time, if the employee goes through some changes in the department, location, or its own profile, the company keeps the latest information, i.e. the company generally doesn’t bother to keep track of what lead to the change in the Employee information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*YvbAVlZqT6j0XSGPVLYebA.jpeg" /><figcaption>Ilustration#1 — Entity Store</figcaption></figure><p>The above hierarchy shows the Organization has four employees and how Employee#2, Employee#3, and Employee#4 are reporting to Employee#1</p><p>On the contrary,<em> Event Sourcing </em>takes a novel approach! <br>The primary concern in Event sourcing is the events or commands that lead to the generation of events. The focus relies on how the events would be persisted, how they would be used to generate the state of an entity, how they can be used as the source of truth for any requirement that is not apparent at the time of designing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*RTuxiCJKR7WWCbN46gkhFw.jpeg" /><figcaption>Illustration#2 — Event Store</figcaption></figure><p>As can be seen above, the application instead of maintaining the current or the latest state of the employee is keeping track of all the events that are fired on the employee entity. In this way, the event store brings a unique thought process of maintaining the information, now how this can be used for extracting all that was straight away possible with entity store, let’s explore in the following section.</p><h3>How it works</h3><p><strong>Entities</strong> are the core of any application, users interacting with the application ultimately end up issuing <strong>Commands</strong> on the Entities either directly or via some interface. These commands, in turn, end up firing <strong>Events</strong>. Let’s continue with the same example that we took before to understand this better.</p><p>In this, Employee is an Entity, the activity of adding, removing, or updating an employee can be considered as Commands and the corresponding reaction that they will generate like Employee Added, Employee Deleted, or Employee Updated can be considered as Events. There is general convention while naming the events, and that is they are normally named in the ‘<em>Past</em>’ tense as they represent what happened in the application at any point in time.</p><p>So to begin with, we start with an empty Organization, and then</p><ol><li>We added an Employee to it, which leads to the triggering of the Employee Added event, next up</li><li>We added another Employee, which leads to the triggering of another Employee Added event and finally</li><li>We updated the first Employee and that lead to the triggering of the Employee Updated event</li></ol><p>The final state of the Organization can be determined by playing all the events in a sequential manner however if we want to generate the state of the Organization at any point in time that too is feasible as the Event Store has captured all the events in the order they were generated in the application along with a timestamp.</p><p>So far we have talked about positive flows where-in the application received events, processed and persisted them in the event store, what if something goes wrong during the command execution, well for application errors, we can have a separate log of all the error events that failed to got process.</p><p>Now the problem with this kind of storage mechanism is that over a period of time the number of commands on an entity can go out of being just a handful and drawing the final state or even the intermediate state would mean playing all the events in the sequence every time the application needs to send back that state to the user requesting it. Is there anything that can be done, yes incomes <em>CQRS!</em></p><p>CQRS stands for Command and Query Responsibility Segregation, what this essentially means is separating the Commands that generate events from the Read requests that are landing on the application. The primary benefit that the application draws from such a pattern is that the application gets freed from handling both read and write concerns together. Along with Event sourcing, the CQRS pattern decouples the reads and writes.</p><p>In our previous example, every time a Command executes, an event will be augmented in the event store. This activity would also trigger an event that all the external systems, applications, and microservices within the same application can subscribe to and do whatever they are intended to perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyB6Cn82fokCgtN5gt6GPA.jpeg" /><figcaption>Illustration#3 — CQRS</figcaption></figure><p>As we can see in the above illustration, a series of events are being recorded in the order they are generated within the application in an event store. In this way, the event store is acting as a source of truth for all that is happening within the application. One more thing apart from just persisting the events, the event store also notifies other systems, external applications, and or microservices that are part of the same ecosystem.</p><p>As is visible from above, these events upon subscription are consumed by various views/microservices, and they proactively format the data and create a presentable view as is desired by the User interface, so that any runtime calculations can be avoided, thereby making the user experience more fluent.</p><p>Apart from this, any need from business to collect the data for auditing and tracking purposes can also be achieved by subscribing to these events.</p><h3>Gains</h3><p>There are certain advantages that we get out of this one of them being that at any point in time we lose any view due to some x, y, z reasons, we can recreate that in no time by replaying all those events that are persisted in the event store.</p><p>Along with this, sometimes the business is not clear upfront of all the User facing requirements and may come up with new screens to be incorporated in mid of the show, all that the application development teams need to do is to replay the events from the event store and prepare the desired view that would satisfy the screen demands.</p><h3>Can this be de facto?</h3><p>Well, there are some considerations before attempting this kind of pattern in an application, the foremost being that this system would be Eventually consistent which may or may not be in alignment with what the business demands. If the users can tolerate a small delay in seeing the screens taking effect of their actions, then we can use this, else we should fallback to the Strongly consistent approach.</p><p>Another factor that we should keep in mind is that adopting this pattern is a change in the mindset from being an entity store to the event store. The development teams have to come out of their basic CRUD mindset and start thinking about events being the source of everything within the application.</p><p>Additionally, over a period of time, because the events in the event store are immutable, the event store may end up getting bigger and bigger, so the Architects and developers have to keep this in the back of their mind of creating some kind of periodic snapshots which can be replayed to regenerate the state of the entity as and when needed.</p><p>Extra care should also be taken to handle events coming from distributed instances of the application to the event store. Generally having a timestamp or some kind of unique identifier helps in order to determine the correct sequence of events in the event store while replaying them to generate the current state of the entity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59f9dd926ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed nature of Microservices and things we should be wary of!]]></title>
            <link>https://chatrakesh.medium.com/distributed-nature-of-microservices-and-things-we-should-be-wary-of-d8ea66567fba?source=rss-23444f43894b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ea66567fba</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Rakesh Malhotra]]></dc:creator>
            <pubDate>Wed, 11 Nov 2020 11:58:02 GMT</pubDate>
            <atom:updated>2020-11-11T11:58:02.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uHpOIdCadYdEOJjI" /><figcaption>Photo by <a href="https://unsplash.com/@rupixen?utm_source=medium&amp;utm_medium=referral">rupixen.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We are living in a digital world where most of the businesses small, medium, or an enterprise-class have their presence on the web. The key to success in today’s fast-paced, highly competitive environment is to stay ahead of others by having a captivating user experience that is delivered by performant components running under the hood. On top of this, these requests can originate from varieties of devices like a desktop, a laptop, a tablet, a smartphone, and or a smartwatch, etc.</p><h3>How to be relevant and competitive?</h3><p>It’s not a distant past when we use to think of ‘<em>everything</em>’ as part of a big monolith system that was designated to serve everything (literally <em>everything</em>) that landed on it; our imagination didn’t take us beyond the apparent practice of slicing the monolith into logical partitions of Presentation, Business, and Persistence layers. But these Monoliths could not withstand the test of time, and that led the technocrats to think of the system that can sustain the ever-emerging demands of:</p><ol><li>Scalability</li><li>Availability</li><li>Reliability</li><li>Time to market</li><li>Adopting new technologies</li></ol><h3>Microservices comes to the rescue!</h3><p>The idea here is to break the big Monolith into smaller inter-related domains; how that can be done however can be based on various factors including how we want our domains to be in sync with our business functions. This makes our lives a lot easier, as technical teams can take advantage of having a dedicated set of members, a preferred technical stack, decentralized control, and scaling domains independently of others.</p><p>As said before, these domains need to work in synergy with each other and together should serve the entire ecosystem. The big question being: How to handle requests that span multiple domains? Should there be areas teams need to be aware of as they start? Are there fallacies around distributed architectures, well <em>Yes!,</em> there are few, have a look at <a href="https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing">this</a> page? This brings us to the heart of this article.</p><h3>Distributed nature of Microservices</h3><p>When the whole is broken into multiple logical components more often than not, the call flow spans multiple such components or microservices. In this article we will not delve deep into what should be the ideal size of a microservice, what are the boundaries it should adhere to; we will assume that we have a system that consists of multiple such services, and they together are serving as a whole. Enough of theory, let’s put some pragmatic context to all that we have been talking about thus far.</p><p><strong>Synchronous Integration<br></strong>Let’s say there’s a web application which has an Orchestrator service that routes the requests to Service A and Service B, here’s how we can see it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQqfxQ76lycLoSaFB-w-zg.jpeg" /><figcaption>Integration#1</figcaption></figure><p>As we can see, in order to process a request originated from the Actor, the Orchestrator has to call Service A followed by Service B. Till the time, things (network, infra, etc.) are working fine, everyone is happy and merrier. But just like we have an off day, these things <em>do</em> have an off day and if that happens then we are in big trouble. Let’s say, the mutation in Service A was successful, and while the call to Service B broke. The consistency of the overall system would go for a toss.</p><p><strong>Fallback option(s)</strong><br>The easiest thing that one can do is to have a re-try mechanism in place that can try repeating the execution on the failed service (obviously that can be either for configurable number of times and that too in an exponential interval), but for this to be successful, one needs to ensure that all the endpoints on the services are idempotent and are not resulting into an inconsistent state when invoked multiple times (this is easier said than done, as the design and implementation team needs to keep this in the back of their minds while doing all the modeling)</p><p>Another option that comes in handy is to have a Rollback/Compensation mechanism (<em>Saga Pattern</em>) in place wherein the Orchestrator should <em>un-mutate </em>all that was mutated as part of a happy flow. This is also a painstaking exercise as the service where the mutation has happened, needs to maintain its prior state or needs to know how it can go back to its previous state, if and when needed.</p><p><strong>Asynchronous Integration</strong><br>Now let’s talk about another common way of integration that we see in a microservice world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuDPr8AnlggFABWS47ipRg.jpeg" /><figcaption>Integration#2</figcaption></figure><p>As can be seen in the above diagram, Service A is publishing an event on a Topic created on a Message Broker. Service A however waits for the Ack from the broker, before considering it as a done deal, i.e. generating a response back to the caller. Now the problem with this approach is not drastically different from the Synchronous Integration, that we saw earlier. In this, let’s say Service B after polling messages from the broker, fails to process them successfully, that means we have an out-of-order Service A and Service B, leading us to solve a potentially similar problem.</p><p><strong>Fallback option(s)<br></strong>In any integration approach, we have to focus on the potential areas of concern. In this case, if the request fails on Service A itself before it mutates its database, it’s not going to majorly impact the system, however, if Service A was successfully mutated but the mutation on Service B was a failure, that’s something to worry about.</p><p>Tricks like manual commit can come in handy wherein we need to play with the lifeline of the messages in the broker. What this means is, the broker would hold on to the messages till the time Service B sends a manual commit back to the broker, informing it to increase its offset and take down the message from its persistent store. Again we need to ensure that the subscribers, in this case, Service B is idempotent and can handle repeated requests.</p><p>Is this the best we can do? In comes to ‘<em>Transactional Outbox Pattern’</em></p><p><strong>What is Transactional Outbox Pattern and how can it be beneficial?<br></strong>The details of the Pattern can be found on <a href="https://microservices.io/patterns/data/transactional-outbox.html">microservices.io</a>. But at a high level, the approach includes having some kind of store for keeping all the events that a given Microservice would be publishing upon some activity. The transaction on the Service should encompass the mutation of the database along with persisting these messages in the database. Once both these operations are successful, the transaction can be marked successful. Let’s see how that looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iFU2o2wTJ3kJg93Q2hFtQ.jpeg" /><figcaption>Integration#3</figcaption></figure><p>As can be seen above, the main transaction ends as soon as Service A is mutated and the messages that need to be sent as part of notification are persisted in the database. What this means is, we need some async component/relayer which can Publish these messages to whosoever is interested in receiving these messages. In our example, it would be Service B. The responsibility of this relayer would be to ensure that the messages are published to the message broker even if it is Not Available at the time when the messages were first attempted by the relayer. Till the time messages are not relayed successfully to the message broker, they will continue to remain in Service A’s database. We also need to ensure that Service B follows the manual commit strategy so that it can reuse the persistence capabilities of the broker just in case it is not able to process the messages due to a potential problem in the code, infra, or due to some other reason.</p><p>As long as the intent of the application is just to send notifications to Service B of any activity that happens within Service A, we should be alright in following this approach as the relayer would ensure the system is eventually consistent, but if we are looking for strongly consistent nature of the application, then we have to consider Synchronous Integration with the Fallback option(s) described above.</p><h3>Conclusion</h3><p>Alright, all that being said and discussed we know that there are some benefits that we can reap by using Microservices-based architecture, but we need to be double sure of what the boundaries of microservices are and most importantly they are in alignment with the Business domains. We also should strive for making our services less chatty and last but not least try to avoid distributed transactions as much as possible, if not, try to leverage some of the best practices that are outlined above in the Fallback option(s) of various integration approaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ea66567fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>