<?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 Dan Mitreanu on Medium]]></title>
        <description><![CDATA[Stories by Dan Mitreanu on Medium]]></description>
        <link>https://medium.com/@danmitreanu?source=rss-5f9d5108995e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Dan Mitreanu on Medium</title>
            <link>https://medium.com/@danmitreanu?source=rss-5f9d5108995e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:18:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danmitreanu/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[Handling user authentication and authorization after load balancing your web app.]]></title>
            <link>https://levelup.gitconnected.com/handling-user-authentication-and-authorization-after-load-balancing-your-web-app-c87ccba35a75?source=rss-5f9d5108995e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c87ccba35a75</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dan Mitreanu]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 18:58:38 GMT</pubDate>
            <atom:updated>2021-06-12T01:39:18.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling user authentication and authorization after load balancing your web app</h3><p>Load balancing your web application is the way to go when expecting or experiencing a large amount of traffic, but when it comes to designing an authentication and authorization flow it can become more complicated on the back-end side.</p><h3>Why load balance?</h3><p>In high traffic scenarios, such as hosting a social networking website, a popular blog, an API or just about any app on the Internet with a large number of valid incoming requests it can be overwhelming for the physical server to handle all of these requests and produce the desired responses.</p><p>Continuing I will be discussing the apparent and deeper implications of scaling up your authentication and authorization flow (<strong><em>auth</em></strong> from now on) handled by your web server into a system which cannot guarantee that subsequent requests from the same client will be handled by the same server.</p><h3>Before we start…</h3><p>If you are reading this you probably have got an idea what load balancing is, but for the sake of this article, I do feel the need of making sure we are all on the same page.</p><h4><strong>What is load balancing?</strong></h4><p>In short, load balancing is the process of distributing traffic across multiple, different server instances using a particular load balancing algorithm. Think of it as a cop standing in front of a toll plaza that redirects you to the toll booth with the smallest queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*-1jiIZ2CSAlGHkBkOUyo3w.jpeg" /><figcaption>Toll plaza, courtesy of tribuneindia.com (<a href="https://cmsimages.tribuneindia.com/gallary_content/2020/4/2020_4$largeimg_1893155391.jpg">https://cmsimages.tribuneindia.com/gallary_content/2020/4/2020_4$largeimg_1893155391.jpg</a>)</figcaption></figure><p>Let’s assume that your original server provided by your hosting platform can handle a maximum of 1,000 requests per second before the experience of waiting for a response becomes frustrating. You are flourishing and users are starting to use your app more and more, hence the traffic. You wouldn’t want them to grow frustrated, would you?</p><p>So what do you do? You implement a load balancer. You either pay for an instance provided by AWS or whichever service you use, or you take the time to configure your own. But a load balancer won’t work on its own as if it’s magic. You need multiple servers so the balancer knows where to redirect your request so it is processed, and this becomes your new problem when it comes to auth flow. Why? Take a look:</p><figure><img alt="Load balancing" src="https://cdn-images-1.medium.com/max/1024/1*zACMdeoJoQHVBAvXusTnaw.png" /><figcaption>Load balancing an API</figcaption></figure><p>As you can see, even though Bob sends two requests to the same API in a very small time interval, his response is still being handled by different server instances. This example goes to show that you absolutely cannot predict which instance will ultimately handle your client’s request. And even if you can, I doubt you can reliably do so with a load balancer that does its job properly.</p><h3>Authentication and authorization</h3><h4>JWT, of course</h4><p>In an era where everybody can build a website, JWT, known for its easy implementation, is widely used for auth.</p><p>And hey, it works right? Well yes, it works and it’s fast and kind of reliable. Read more about how JWT works <a href="https://flaviocopes.com/jwt/#:~:text=It%20works%20this%20way%3A%20the,comes%20from%20a%20particular%20identity.">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1fM3oaH859rTJEUByJrFA.png" /><figcaption><a href="https://jwt.io/">jwt.io</a></figcaption></figure><p>At first glance, you’d think that this would be the obvious solution for all of our problems, load balanced or not. I see that. I mean, JWT does not require much back-end work to validate and authorize, user information is directly embedded inside the token reducing the need for database trips and all of the data is stored on the client sparing your much needed server memory. Pretty smart, right? Yes, but no.</p><p>When you start designing your user authentication features problems are already starting to become apparent as you build your “<em>reset password</em>” feature. Until this point, JWT was great for having the advantage of not having to check validity of information with a database upon authenticating or authorizing. Now? Not so much. When a user of your application decides to reset their password because they have forgotten it or for whatever reason really, you need a way to log out all other devices the user has been logged on.</p><p>How do you expire your user’s JWTs without waiting for them to go out on their own? A fast way would be to change your encryption key. But wait, that would expire all of your users’ tokens… Woops. Okay, okay, I have an idea. Maybe integrate a database which holds all of the expired keys and check against that? Or maybe all of the valid keys? I mean it would be simple, first check if the JWT itself is valid, then check against the database if it’s not blacklisted. But wait, doesn’t that pretty much throw JWT’s <em>fast, no need for database checking, quick verification</em> points out the window? Kind of does, doesn’t it? Integrate caching to reduce database trips then, you might say. Okay, that will work, but keep in mind that the cache must also be shared between the multiple web server instances and your implementation must be fault-tolerant, especially for a user security feature such as the <em>reset password</em> example.</p><p>If the story ends here, you are lucky. If all goes well, this will not be the last time you are upscaling your app. Your next step will be adding another load balancer and another cluster of web servers and possibly even geo routing to send requests on their way to the closest load balancer available to reduce latency. Are you ready to guarantee consistency between multiple distributed caches? This is the big headache here.</p><p>If you are ready and willing, you are more of a man than I am.</p><h4>Sticky sessions</h4><p>When designing your website to use sessions, you are already past the “no back-end work” dream that JWTs might have had you excited about.</p><p>When using sessions the server gives the client a unique identifier (let’s call it <em>key</em>) and the user passes that key in subsequent requests so that the server knows who it’s talking to. The keys are best stored in HTTP-only, secure cookies. The server stores information about the user in a lookup table under the generated key and when the request is sent it simply uses that key to retrieve the data associated with the client that expects the response. You might see the problem here. You have multiple web servers. <strong>How can you guarantee that the session is the same between all the load-balanced servers?</strong></p><p>Sticky sessions try to solve that issue by forcing the load balancer to send all the following requests to the same web server. This might work to some extent, but other than being blatantly lazy (under normal circumstances) it also has several downsides:</p><ul><li>The load <strong>will</strong> be uneven across your servers. Some users will spend more time than others on your website.</li><li>The load balancer will not read and process the request, that’s not its job. Thus, the only way that it can identify where that request is coming from is by IP and I don’t think that I need to tell you how many people use their mobile phone data and then switch to wi-fi in a café. This results in losing the session. To put it shortly: <strong>inconsistency</strong>.</li></ul><h4>Distributed sessions</h4><p>The other worthy contestant in this contest is distributed cache + session state = distributed sessions. In the current context, the race is really between <strong>JWT</strong> and <strong>distributed session state</strong> since distributed cache has to be implemented for both in a load balanced environment.</p><p>Or at least, distributed cache should be implemented for both in a load balanced environment as any other solution is less efficient and more troublesome to implement. I don’t think you’d want to keep a copy of the same cached data on every server and update several server instances whenever a change is made.</p><p>Before I tell you why this is probably better and more efficient to implement than JWT in large-scale applications, let’s go over how it works.</p><p>I think you already figured it out, but what is distributed cache? Distributed cache is simply cache that is accessible by multiple parties. It offers a layer of consistent data between all of your servers. The way it is used is fairly simple: server looks for some information, if it’s cached it uses it and end of story. If it’s not then it gets it from a permanent data source (database), caches it so it can access it faster in the future, then uses it. Especially when storing session state the cached data has a sliding expiration time so that it doesn’t just stay there when it’s not being used. If it’s not accessed for let’s say 20 minutes, it is deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*4XUrt8DxIjjSqHTvm-ThNg.png" /><figcaption>Simple example of using session state with distributed caching to achieve fast retrieval time of data</figcaption></figure><p>How is this paired with sessions? Simple, you keep your users’ sessions inside a distributed cache instead of local cache. They make a request, their session gets created and stored inside the cache server. For any subsequent requests, in case they are redirected to another instance, the web server can access the client’s session by fetching their session state from the distributed cache. When the user performs any action that has an impact on their data, the change is being recorded and both the database and the cache is updated. If database changes like these are done asynchronously, the end-user won’t experience any punishment on page load times.</p><p>Okay, but the JWT blacklist caching method offers the same benefits: less database queries and cached data making responses very fast. <strong>What makes distributed sessions take the cake?</strong> A couple of reasons:</p><p>Easiest argument would be that JWTs were just not built to be used in this way. They are supposed to be portable, quick and easy to validate. Adding another layer of validation by using a data store (blacklist or whitelist) is exactly like implementing distributed session state but instead of storing your user’s info nicely packed and hidden inside of your data store, you are leaving it exposed on the client-side cookie and also keep a copy of the JWT in your data store as well. Why leave user information on the client-side when you already have it nicely packed away from public access, even if the data is not considered to be <em>secret</em>?</p><p>Other than that, implementing a server-side session state gives you more room for further implementation of more features. You can start working with more delicate data regarding the client’s session to enforce tighter session hijacking security (such as last authorization IP, location etc.). If you have a post-it note app storing a note’s content in session state is a way faster solution for retrieval than a database query is.</p><h3>Conclusions</h3><p>Load balancing a huge service that requires authentication and authorization? Cache is king. Not only for auth.</p><p>Seriously, cache everything you can.</p><p>This one goes to <strong>distributed session state</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c87ccba35a75" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/handling-user-authentication-and-authorization-after-load-balancing-your-web-app-c87ccba35a75">Handling user authentication and authorization after load balancing your web app.</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>