<?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 Roy Sommer on Medium]]></title>
        <description><![CDATA[Stories by Roy Sommer on Medium]]></description>
        <link>https://medium.com/@roysom?source=rss-853c689531d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_hKp4eRPCvnk91o5z4FW8Q.png</url>
            <title>Stories by Roy Sommer on Medium</title>
            <link>https://medium.com/@roysom?source=rss-853c689531d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:34:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roysom/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[Getting Started With React Class Hooks In Five Steps]]></title>
            <link>https://medium.com/@roysom/getting-started-with-react-class-hooks-in-five-steps-b14442b12ac2?source=rss-853c689531d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14442b12ac2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Roy Sommer]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 12:17:05 GMT</pubDate>
            <atom:updated>2020-01-24T11:37:21.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2tcgzueDIRugOGCO" /><figcaption>Photo by <a href="https://unsplash.com/@stevebruce?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Steve Bruce</a> on <a href="https://unsplash.com/s/photos/climbing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://reactjs.org/docs/hooks-intro.html">The introduction of React Hooks</a> back in 2018 has hit us with a bang. Up until then, many of us thought of functional components as mere stand-ins to class components that only had a render method. Hooks promised to turn that around: their goal, as stated in the official docs, was to let us use state and other React features without writing a class. But hooks also brought another thing to the world of react, and its quite amazing: hooks can actually abstract away entire pieces of logic, and hide it from the unsuspecting component, making it reusable by design, and even composed upon by other hooks! In short, hooks did to logic what components did to UI.</p><p><strong>Class Hooks</strong> (<a href="https://github.com/class-hooks/class-hooks">github</a>) intends to leverage on that principal. The idea is to turn hooks into fully fledged <strong>logical components </strong>that completely manage themselves, and instead of rendering UI, they return an API for their host component to use. It’s like HoC but without the <em>Ho</em>, like container components without the container; like render props without having to write shadow components. Class Hooks <strong>augment your class components</strong> in a way that is invisible to them, to their API, to the entire react tree, and most importantly — to you. All you get is a class field that contains a clean API for you to utilize your application model.</p><p>Not buying in just yet? Then let me invite you on bite-sized adventure, where we’re going to build a todo application, written using class hooks and in under a hundred lines of code. It’s going to have state, and persistency, and inline interactive examples. And all of that goodness — in just five steps.</p><p>Ready?</p><h3>Step One: Kickstart Our Project</h3><p>The first step would be to create a new React application. Use your favorite tool of choice, and let’s get started! The only dependency we need to install would be class-hooks , so let’s add it to our project:</p><pre>npm install class-hooks</pre><p>Class Hooks contain three granular hooks: useLifecycle , useState and useContext . Much like with their functional counterparts, the idea is to build custom hooks on top of the basic ones, and so create a holistic piece of logic.</p><p>For our project, we’re going to use two of those hooks: useState and useLifecycle, and we’ll see exactly how they help us with building our application.</p><h3>Step Two: A Basic UseTodos</h3><p>We’re going to have one hook in our application, and that is useTodos . This is not your everyday hook, mister or miss! useTodos is a one stop shop for all of your todo needs. Let’s rough something up real quick:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9c8c44c8209389ae3e1a8f1273d6fa/href">https://medium.com/media/8a9c8c44c8209389ae3e1a8f1273d6fa/href</a></iframe><p>What do we have here? First of all, a hardcoded list of todos. Seem like we <strong>do have milk</strong>, thanks for asking, but not yet are we done with building our class-hooks react app. Secondly we have a getter, getTodos , which returns our list, and that is what the hook exposes to the outside world.</p><p>Let’s see how our component utilizes useTodos:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633b307b27b4433ab66bb3edadebd661/href">https://medium.com/media/633b307b27b4433ab66bb3edadebd661/href</a></iframe><p>Oh, this is interesting. We call useTodos upon construction! There’s a reason for that, though. As opposed to functional hooks, with class hooks we create an instance of our hook <strong>once per component and upon construction</strong>. Following the <a href="https://github.com/tc39/proposal-class-fields#field-declarations">class fields syntax</a>, we call our hook right before our constructor is called (if one exists). This method of using class fields helps us keep a clean look to our component, almost as if we’re using class decorators (and in a way, we are).</p><p>Another thing we do is to pass this into the hook. We do that because class hooks actually <em>hook</em> into the class. Behind the scenes, class hooks bring a mechanism from functional programming called <em>composition, </em>where they wrap around our class and enrich its behavior by adding functionality on top of it.</p><p>Our class hook does not do anything with this , yet. But it soon will, don’t worry.</p><p>The final thing that’s worth noting here, is that we use this.todos.getTodos() from our render function. Here, we use this.todos to render the list of todos, but bear in mind that class hooks are designed so they can be used from anywhere within our component! But more on that later.</p><p>Run your app. Looks gorgeous, right?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-class-hooks-todos-1-t4md0%3Ffontsize%3D14%26hidenavigation%3D1%26module%3D%252Fsrc%252FApp.jsx%26theme%3Ddark&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Freact-class-hooks-todos-1-t4md0%3Ffontsize%3D14%26hidenavigation%3D1%26module%3D%252Fsrc%252FApp.jsx%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft4md0%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcc7cb87f3d81a4965968369a7f9f3d9/href">https://medium.com/media/fcc7cb87f3d81a4965968369a7f9f3d9/href</a></iframe><h3>Step Three: Introduce State</h3><p>Try clicking on one of the checkboxes. Shockingly enough, nothing happens. Our component loyally reflects our “todo” data, and we don’t really have a way to toggle their done property just yet. Let’s solve this by adding a new method to our useTodos class hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e5860f6443f0856c0e77487624beda/href">https://medium.com/media/26e5860f6443f0856c0e77487624beda/href</a></iframe><p>And connect it to our component, binding it to the onChange events of our checkboxes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eb380af2a0d1f008ff9b98811378871/href">https://medium.com/media/6eb380af2a0d1f008ff9b98811378871/href</a></iframe><p>Hurray! Let’s get psyched and hit those checkboxes, only to find out that still, nothing happens.</p><p>Every React newbie is familiar with this feeling: we build our first component ever, most likely a three-dimensional chess game with nukes, but when we click stuff nothing happens. This is because we have not utilized <em>state</em> correctly. And that’s the case here as well. In order to fix it, we’re going to use our first class hook ever: useState .</p><p>Let’s take a look over our revised useTodos code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c1ceb4fe4011a3941b757808b408b98/href">https://medium.com/media/4c1ceb4fe4011a3941b757808b408b98/href</a></iframe><p>First thing to notice is the todos = useState(target, ...) statement. As we said before, the convention with class hooks is that the first parameter of the hook is always the target component. <strong>Now </strong>we make use of the this that was passed to us — we hand it over to useState.</p><p>In order to get our state, we need to call todos.getState() , and that’s what we do in our getTodos function. In order to change our state, we need to call todos.setState, and we do so in toggleTodo . That’s where the interesting part begins.</p><p>Since our todo list is part of a state now, we have to treat it as an immutable object. So instead of simply editing the desired item, we create a new copy of our todos list (we call it todosListWithToggledItem), and in order to generate it, we map our current state into a new one, where the selected todo item is actually toggled (not too keen on what’s going on there? <a href="https://www.youtube.com/watch?v=4LzcQyZ9JOU">here’s</a> a really nice video about immutability).</p><p>What really happens when we use useState? Much like with functional hooks, useState actually stores information on the component’s local state level. That’s why our component actually <strong>knows</strong> when we alter our todos state, even if it’s hidden inside a useTodos hook! That’s also the reason why we have to treat our todo list as an immutable object.</p><p>Let’s go back to our preview. Things are looking good!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-class-hooks-todos-2-rjbwo&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Freact-class-hooks-todos-2-rjbwo&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Frjbwo%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/34a2b3ffbd6f38cf6c7dec0b5a430421/href">https://medium.com/media/34a2b3ffbd6f38cf6c7dec0b5a430421/href</a></iframe><h3>Step Four: List Management With Functional SetState</h3><p>In our toggleTodo function, we construct a new todo list with the desired todo item toggled, and then pass it into our setState function, which in turn replaces our entire state with this new object. That’s one way to set a state and probably the most intuitive one.</p><p>That said, there’s another way to update our state: by using a reducer function. You are probably familiar with it under the name of <a href="https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous">functional </a><a href="https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous">setState</a>. Let’s see how we use functional setState with our useState class hook, as a method of adding and removing todo items:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8bb593325c3376e282bd787b21080f/href">https://medium.com/media/cb8bb593325c3376e282bd787b21080f/href</a></iframe><p>So what’s going on? First, let’s take a look at addTodo . As its name suggests, this method appends new todo items to our list. We do so by using a function that, given a prevTodos array, returns a new array that contains everything in prevTodos , plus our new item. We have a similar implementation in removeTodo , but here we return a new array that contains everything from prevTodos except for the item that we wanted to remove. The last thing is that we removed the hardcoded todos. We don’t need them anymore, now that we can add items ourselves.</p><p>Now that our class hook is all set, let’s give the UI some love. We can start by adding a text input and a “submit” button to our react component, for creating new items, as well as an <em>X</em> button next to each item, in order to remove it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a344c37948201237cbbaff4b0e1bfd2e/href">https://medium.com/media/a344c37948201237cbbaff4b0e1bfd2e/href</a></iframe><p>Remember that we said that class hooks can be used from anywhere in the component? Then take a look at that onClickAddTodo function. When using class components, it is very common to use class methods for handling certain aspects of our component’s logic, and here we actually use our class hooks inside one of those. That’s really where class hooks shine: they are complete companions to your component, and can be legitimately used anywhere, from render function, lifecycle methods, class methods, and even event handlers.</p><p>Finally, here’s how our application looks right now:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-class-hooks-todos-3-bewmj&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Freact-class-hooks-todos-3-bewmj&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fbewmj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d116413314d6425f70c631ad8090af1e/href">https://medium.com/media/d116413314d6425f70c631ad8090af1e/href</a></iframe><h3>Step Five: Saving and Loading Automatically With UseLifecycle</h3><p>Something’s off in our app, though. Since we removed the hard-coded todo items, it’s always empty when we launch it. Also, what happens if our cat decides to make itself comfortable on our keyboard, and mistakenly refreshes the page? Everything we’ll be gone!</p><p>Here’s an idea, though. Why not <strong>save</strong> the list every time we update it, and <strong>load</strong> it along with our component? “That’s interesting, but how might we do that?” you might ask. Enter our second ever class hook: useLifecycle .</p><p>useLifecycle is basically the class hook counterpart to useEffect. Much like useEffect, it is meant for managing side effects. Unlike useEffect, it uses the Component Lifecycle mechanism to do so.</p><p>For instance, if we wanted to call a function when the component mounts, we would use useLifecycle(target, &#39;componentDidMount&#39;, fn) . This is a very powerful utility — as it lets you hook into the component’s lifecycle, without having to implement anything in your component class, or getting in the way of its own lifecycle methods! Let’s see it in action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e09fc091cbbcacd22ebfd4ec27a52c5/href">https://medium.com/media/5e09fc091cbbcacd22ebfd4ec27a52c5/href</a></iframe><p>What we basically do, is that we hook into the componentDidMount lifecycle method, and basically tell our hook: whenever the host component is mounted, load the todos list from localStorage , if it exists.</p><p>On the other hand, we hook into componentDidUpdate , and tell our hook: whenever the host component updates, save the todos list into localStorage.</p><p>And now for the punchline: the mount \ update logic is completely contained in our hook. If we refresh our app <strong>right now </strong>everything will just work. As the load \ save logic has nothing to do with the UI, our component does not even care about it.</p><p>The only thing left is to sit back and enjoy our state of the art todo application, written entirely with class hooks:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2Freact-class-hooks-todos-xdmmv&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-class-hooks-todos-xdmmv&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/efe850ad4105e4af47acf4fad3af2b53/href">https://medium.com/media/efe850ad4105e4af47acf4fad3af2b53/href</a></iframe><p>As our modern-age adventure is at a close, let’s take a moment to appreciate what we’ve done here together:</p><ol><li>We wrote a clean todo app using under a hundred lines of code.</li><li>Our component did <strong>nothing </strong>but manage the UI. No side-effect management \ initialization, no knowledge of the inner workings of our application model, no subscribing for updates or events — just a simple component that uses an even more simple API, given to it by the useTodos class hook.</li><li>Our class hook managed everything related to the application model: state management, initialization, persistency. It was able to hook into our component, but could just as easily be ported and used with any other component, and in conjunction with any other class hook. It is completely independent from our UI.</li></ol><p>What did you think? Did you enjoy our little ride? If so, you’re more than welcome to head over to the <a href="https://github.com/class-hooks/class-hooks">class hooks github repository</a>, where you can find the docs and follow its status. The library is still at its early stages, but it can probably find a home in one of your next small projects. Play around, open issues, contribute code and don’t forget to ⭐️ !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14442b12ac2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revocable User Sessions with (Probably) No DB Access — A Passing Thought]]></title>
            <link>https://medium.com/@roysom/revocable-user-sessions-with-probably-no-db-access-a-passing-thought-b59edfe9c096?source=rss-853c689531d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b59edfe9c096</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Roy Sommer]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 14:23:33 GMT</pubDate>
            <atom:updated>2019-02-16T15:36:31.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revocable User Sessions with (Probably) No DB Access — A Passing Thought</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_myoyoLQmeW-cD-p2wlcHg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/4FXhqFqvdV8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When it comes to authorization, we constantly find ourselves having to balance between consistency and availability. On one hand, we do not want to make too many trips to our database just to confirm sessions, but on the other, we want to have as much control over the user’s state as we can possibly afford.</p><p>In this article we’re going to explore the standard practices in the world of access control, and suggest a hybrid approach for session revocation that both ensures immediate propagation of change while still saving us most (if not all) of our database queries — with just a tiny bit of probabilistic magic…</p><p>Let me begin with a short story: this is Saturday night, and you’re about to throw the greatest party of all time. Since your party is so great, many <strong>many</strong> people have signed up for it, and you know for certain, that many others might try to crash it without an invitation. In order to make sure that things don’t go out of hand, you decide that some method of authorization would be in place.</p><p>Your first idea is to manage a guest list, and use it to verify every guest at the entrance. Your excitement is short lived, though, as a friend of yours points out that so many people have RSVP’d, that it would take some good amount of time for the bouncer to verify each and every one of their names, especially if many of them come at once. You decide that he might be right, and instead come up with another method.</p><p>The other method you can think of, consists of handing out invitations to your guests, each containing their name. That way, while the invitations are not directly managed by you, you can still ensure their authenticity and authorize your guests on a name basis without managing a guest list…</p><p>Handling user authorization in web applications often looks much like throwing a party. We must find a way to make sure that only our guests get in, and when they do, we have to make sure that they don’t step out of line. How do we do that?</p><p><strong>Note: if you’re already familiar with modern-day authorization methods, feel free to skip to the next section.</strong></p><p>There are two main approaches to solving this problem. The first is the centralized approach, where every access request is being verified against a user (or session) database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*_5lnL3OlAHcmUxyD9KpIuQ.png" /><figcaption>Every request has to pass through the database for confirmation</figcaption></figure><p>From a security point of view, this approach is as fail-proof as it gets, since every request is being verified with a single source of truth, prior to performing any kind of action. <strong>This is our guest list</strong>.</p><p>But as our friend mentioned, this approach has its downsides. At the very least, it makes requests take <strong>longer</strong>, as we add another stop between our users and what they want to do. Also, by making them go through the database with every request, we introduce another point of failure — even if our server is up and running, any issue with our database would lead to denial of service. The root of the problem here is the fact that we introduce a server-side state to the authorization process, which means that we have to maintain some kind of data store to contain and check that state whenever we need to let guests in.</p><p>The second approach is more distributed: rather than saving our user access permissions in our servers, we tell them what their permissions are, and ask them to remind this to us with every request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*JL76fo5V9MyAhP963IWUhw.png" /><figcaption>We can easily identify data which we signed before, without needing a database</figcaption></figure><p>In order to prevent them from lying to us about what permissions we gave them in the first place, we sign the permission we give them cryptographically, using a secret only known to us. That way, we can make sure that they have not tampered with their session. (Note: the same thing goes with the database approach — we sign their session identification, so they won’t be able to try and guess some other user’s session).</p><p>Once we are done with identifying the user for their log in process, we don’t need the database anymore! We can locally and efficiently ensure that they really are who they say they are, and have the permissions they claim to have!</p><p>“But wait!”, says that annoying friend of yours. “What will you do if you change your mind about one of the guests? Once you sign their invitation, there’s no way for you to take it back!”</p><p>And he would be entirely right. Since we sign the user’s identity at the time of login, we only know about their state <strong>at that time</strong>. If we later on decide that their set of permissions have changed or, god forbid, that they’re banned from our party, we won’t be able to tell that simply by looking at their invitation!</p><p>The most popular approach to solving the issue of changes in user state, is to issue each session (or invitation to the party) with an inherent expiration date. That way, every now and then, the user will <strong>have</strong> to renew their session, at which point we’ll be able to update their state, or block them entirely from our service. One very common implementation of that method can be found in the <a href="https://jwt.io/">JWT</a> (or JSON Web Token) standard. JWT lets you store user data in the form of a signed (or encrypted) JSON object, which contains an expiration date as part of its metadata (or “headers”, as they call it).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*yuUaZ9GU27q-CWBLo8us2A.png" /><figcaption>Whenever a session expires, we have to confirm the user’s current state with the database</figcaption></figure><p>The main drawback of this method, of course, is the fact that it is time based, and the size of the time frames can only ensure one of two things: make it too frequent, and you find yourself making too many trips to the database, but make it too sparse, and it will take too long for changes in authorization to propagate, which greatly reduces their effectiveness.</p><p>We are now approaching the point of this article: there is another approach that might help us both maintain consistency <strong>and</strong> save us a lot of trips to the database; an approach based on <strong>chance</strong>…</p><p>Back in 1970, a man named Burton Howard Bloom came up with a rather sophisticated idea. He wanted to maintain a set of unreasonably large number of items (for that time) that required an amount of memory that he could not possibly get. Bloom then thought of the idea of a probabilistic data structure: a set that could tell you whether or not it <strong>probably</strong> contains an item. That data structure, is called the <strong>Bloom filter</strong>.</p><p>The way a Bloom filter works is rather simple: you have an <em>m</em> sized bit-array in which you want to store <em>n</em> elements. (Note: bit, an 8th of a byte, is a storage unit that can basically hold just a boolean value: 0 or 1). For each element we want to put in our set, we run it through a group of hash functions, each function giving us an index inside said array. For every index <em>i </em>we come up with, we turn the <em>ith</em> bit in the array on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*5_Ktmq2lwl8bawQ1f83yGw.png" /><figcaption>“Ice Cream” was hashed as 1, 4 &amp; 13, and so we turn on the corresponding bits in the array</figcaption></figure><p>We then want to check for the existence of an item in the set. We do that by passing the new item through the same group of hash functions, and then we go on to check the array. Hash functions are deterministic by nature, and will always map a given input (Ice Cream) to the same output (1, 4, 13), so if <strong>at least one </strong>of the bits is turned off, then we can safely assume that this item <strong>is not in the set</strong>. If it were, all the bits should have been turned on before. But what happens when the test comes back positive? Can we say for certain that the item exists within the set? The answer is no.</p><p>Due to the fact that bits are arbitrarily assigned to every element, there might be collisions. In the example above, the value “Ice Cream” is assigned with the 1st, 4th and 13th indices. But nothing ensures us that those indices were not covered by one or more elements that are <strong>not</strong> Ice Cream.</p><p>Now let’s go back to our case of user sessions. Since we want to reduce the amount of database access for the average authorization process, we forfeit the reliability of our state. But that doesn’t mean we cannot rely on chance, in the form of a <strong>probable set of access denial, </strong>stored locally on our server.</p><p>Let’s say that we have a database consisting of one million users. Whenever a user logs in, we save their data on a session and sign it, so we can easily trust it later on. One of the things we would probably store in the session is some sort of a session ID.</p><p>Now let’s say we want to revoke a session. If we stored the session ID of the user in the database when we issued that session (as we should have), we can restore it from there. We then put the session in the <strong>set of access denial</strong>, a Bloom filter that contains all the IDs of the sessions that we have previously revoked.</p><p>When a user next tries to gain access, we run that session’s ID through the set. If it returned a negative result, then that session was <strong>certainly not revoked</strong>, and that’s a key factor here — unauthorized access is not possible with this approach. On the other hand, if we find it to be positive, then the session was probably revoked, and the user will not be able to carry on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*o0ftpaerweP_RwFT0a9MQA.png" /><figcaption>The server can immediately check the set for the given session ID</figcaption></figure><p>The problem is that a user might be denied access even if we didn’t mean to block them. As with the Ice Cream example, their set of bits in the array might be accidentally covered by other users. We can ease that by referring to a <a href="https://en.wikipedia.org/wiki/Bloom_filter">general rule of thumb regarding Bloom filters</a>: if we have 10 bits per expected item in the set, we have a probability of less than 1% for a collision. For a user base consisting of 1 million users, this is roughly 1 MB of space. Not too shabby, huh?</p><p>But then a new problem arises. Gradually but surely, we <strong>will</strong> exhaust our set. As more and more sessions are revoked, more and more bits are turned on, and the chance of false positivity rises sharply. We can prepare ourselves for 1 million session revokes, but what happens when we hit 10 million users? Or 50 million?</p><p>The answer is something we’ve already discussed — expiration. Let’s say, once again, that we have one million users, out of which 10,000 are daily active. Say that their sessions are good for a limited amount of time (for the sake of our example, let’s make it a day), after which they require renewal against the database. In that case, we can also empty the set of access denial once a day, as we can shut down the session upon the mandatory renewal anyways. Furthermore, we can even shrink the allocated memory for the set down to match the amount of expected daily users (in our case, it would take 12.5 kb for 10,000 daily users instead of 1 MB for all of our users), and <strong>scale it </strong>according to traffic. When we hit 50 million users, we’ll still be good to go, as we change the set’s size on a day-to-day basis.</p><p>And what will happen if the user was falsely logged out? They’ll have to log in again. When you rely on chance you might make mistakes, but if you keep the collision rate below a certain ratio, this will be so rare that it won’t be more than a minor inconvenience.</p><p>To sum it all up, by using the traditional method of session expiration, we can dramatically reduce the amount of database queries required for the average authorization process. Combined with a Bloom filter, we can further reduce them, as we can make the expiration interval less frequent while still maintaining an immediate consistency of session revocation and access denial. Probably.</p><p>This is, of course, theoretically speaking. In real life, there are many other concerns about which we have not yet discussed, such as how this system would work in a distributed environment, or within a serverless framework. This is a story for another day, though.</p><p>The party, by the way, was a hit.</p><p><strong>This story was also published on the </strong><a href="https://wix.engineering/blog/revocable-user-sessions-with-probably-no-db-access-a-passing-thought"><strong>Wix Engineering Blog</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVNnAQvblFTXHehuQTeJOw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/hTv8aaPziOQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alexander Popov</a> on <a href="https://unsplash.com/search/photos/party?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b59edfe9c096" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>