<?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 Kaustubh on Medium]]></title>
        <description><![CDATA[Stories by Kaustubh on Medium]]></description>
        <link>https://medium.com/@kaustubhai?source=rss-a9a3e12d78f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UicAyOlOIEs9oHOmjHTMFg.jpeg</url>
            <title>Stories by Kaustubh on Medium</title>
            <link>https://medium.com/@kaustubhai?source=rss-a9a3e12d78f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:18:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaustubhai/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[Forgot password service on node?]]></title>
            <link>https://kaustubhai.medium.com/forgot-password-service-on-node-ac4d0cd7f352?source=rss-a9a3e12d78f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4d0cd7f352</guid>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kaustubh]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 18:35:37 GMT</pubDate>
            <atom:updated>2023-02-06T18:35:37.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forgot password service on node!</h3><p>Ever created a basic authentication service on node? Most common authentication services I’ve seen being developed online, always seems to miss a key aspect when compared to a full-fledged website.</p><p>An option to forget your password is both very useful to a user and very easy for a developer to develop. I have no idea why most online teachers/courses seem to miss this key feature in there basic apps. However here I am to tell you how you can put up that extra feature on your basic app to look not so basic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*trpjEHRWDzDBzJ6c.jpg" /></figure><p>Before we begin, you should have a basic registration feature on your website. To extend your signup feature to include the forgot password feature you will require packages like <a href="https://www.npmjs.com/package/bcryptjs">bcrypt</a> and <a href="https://www.npmjs.com/package/jsonwebtoken">JWT</a>, not something that you are not using already in your registration service.</p><h3>System design</h3><p>Let’s figure out the system design of this proposed feature. Below is the rough drawing of the system flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*XqbZipn9FYEF5nMW68VLvQ.png" /></figure><h3>Explanation</h3><p>The complete flow is pretty straight forward, but as you ca see step 3 is marked in a different colour to mark its importance. The token we generate in step 3 is very critical, so follow the steps and checks carefully.</p><p>At step 1, the user has told us that I have this email and I don’t remember my password.</p><p>Before proceeding further, you need to pass the email from step 2, i.e., verifying if the email actually belongs to a valid user or not.</p><p>If the user at this step, it means that the user is verified that it exist and we can proceed to help him/her change the password. Now comes the crucial part, creating a token for this user. This token has to be unique and one time usable only, also with a valid and sensible time strain attached to it. All these measures ensure that the token created for this user is not getting misused by someone or the user itself.</p><p>Step 4 is pretty self-explanatory, we share the created token with the user. This will help us to verify at step 7 that the user entering new password for the account is the same exact person who requested it.</p><p>Step 5 goes to user to collect the password. It is then shared with us along with the token</p><p>In step 6, we verify the shared token first. After this the token shouldn’t be reusable anyhow.</p><p>We then verify all the password constraints that we have in place for any user like if the length matches the minimum length or not, if the new password any how matches with the old password and so on in step 7</p><p>After all the said verification is completed in step 6&amp;7, we then proceed to encrypt and update the user’s password in our system</p><h3>Development Part 1</h3><p>This service we are about to build will have 2 basic parts. In first part, you will create a forgot password request and in second you will handle the request. Both these parts of the service are critical and need to be secured through heavy logic. As mentioned earlier, the packages that you are going to need are jsonwebtoken and bcryptjs, both of them which you should be already using for your registration service. Now, lets begin developing this feature.</p><p>At first, lets start by creating endpoints that we will be using for these services, so where you have defined the endpoint for your registration service, go ahead and define two additional routes there,</p><pre>Router.post(&#39;/login/forgotPassword&#39;, authController.forgotPasswordRequest)<br>Router.post(&#39;/login/:uid/:requestId&#39;, authController.resetPassword)</pre><p>Nothing here to explain much, lets proceed,</p><p>Let us now go ahead and create two controllers to serve the above mentioned routes,</p><pre>forgotPasswordRequest: async (req, res) =&gt; {<br>    try {<br>      const { email } = req.body;<br>      let user = await User.findOne({ email }); // Step 1<br>      if (!user) return res.status(400).json({ msg: &quot;No User Founded&quot; }); // Step 2<br><br>      const generatedToken = <br>      userService.generateForgotPasswordRequest(user.email, user.password); // Step 3<br>      res.json({ uid: user._id.toString(), token: generatedToken }); // Step 4<br>    } catch (error) {<br>      console.log(error);<br>      res.status(500).json({ msg: &quot;Internal Server Error&quot; });<br>    }<br>  },</pre><p>Here, we have taken email from the UI of the website to find the user in the database who want to utilise this feature. If the user is found, we go ahead and call the generateForgotPasswordRequest service with user’s current password. We will proceed from step 5 in a different controller on a different route. Following is the code for the 3rd and most important step being held in the generateForgotPasswordRequest service.</p><pre>generateForgotPasswordRequest: async (email, password) =&gt; {<br>    try {<br>      const token = jwt.sign({ email }, password, { //usable once andd unique<br>        expiresIn: 3600,  // Time strain<br>      }); // Step 3<br>      return token;<br>    } catch (error) {<br>      console.log(error);<br>      res.status(500).json({ msg: &quot;Internal Server Error&quot; });<br>    }<br>  },</pre><p>This is the service to create a token. If you remember the key points mentioned earlier, this token is</p><ul><li>Usable once</li><li>Time strained</li><li>Is Unique for every request</li></ul><p>Time strain is straight forward from the code, it will be unique because for every request, even for the same password, jwt creates a new token for every request. Now comes the usable once part.</p><p>Its singular usage comes because of the signature being used to verify the token. We are using the user’s old password itself as the signature. After the user successfully uses the generated token to update the password, the password will get change and hence if some malicious request comes with the same token, it will be impossible to verify the token because the old password is no longer in the system.</p><p>This is what makes this system secure.</p><blockquote><em>We are sending _id of the user as well to client so that it can send us _id back to help us find the user in the resetPassword controller as it will be a non-protected route and we will have no way to identify them.</em></blockquote><h3>Development Part 2</h3><p>Alright, now let’s begin verifying the request that we will receive to update the user’s password. We will do 3 things in this controller, first we will verify the token sent to us along with the request and then verify the password if its secure enough and then finally we will update the password.</p><pre>resetPassword: async (req, res) =&gt; {<br>    try {<br>      const { uid, requestId } = req.params<br>      const { password } = req.body; // Step 5<br>      const user = await User.findById(uid);<br>      jwt.verify(requestId, user.password, (err) =&gt; { // Step 6<br>        if (err) {<br>          return res.status(400).json({ msg: &quot;Token Expired&quot; });<br>        }<br>      });<br>      <br>      if(password.length &lt; 8) // Step 7<br>        res.status(400).json({ msg: &#39;Password should be 8 characters long&#39;});<br>      if(await bcrypt.compare(password, user.password)<br>        res.status(400).json({ msg: &#39;Password cannot be same as old one&#39; });<br>      <br>      const passwordHashed = await bcrypt.hash(password, 8);<br>      user.password = passwordHashed;<br>      await user.save(); // Step 8<br>      res.json({ msg: &quot;Password Changed Succesfully&quot; });<br>    } catch (error) {<br>      console.log(error);<br>      if (tokenValid) res.status(500).json({ msg: &#39;Internal Server Error&#39;);<br>    }<br>  }</pre><p>Here we see steps being executed from step number 5 to step number 8.</p><blockquote><em>Please always use some sort of encryption to store passwords (like we are doing here by using </em><a href="https://www.npmjs.com/package/bcryptjs"><em>bcrypt</em></a><em> package) or any other sensitive data in your DB to not compromise the security of your system.</em></blockquote><h3>That’s it</h3><p>It’s that simple to add this simple yet unique feature in your project. If you are planning to go to prod, this is a must have feature and it’s also easy to implement. That’s it from my side currently, will see you again when I will have something special to share with you.</p><h3>P.S</h3><p>If you want to have a quick registration and login service set up in node, do checkout my template repositories, this one for using <a href="https://github.com/kaustubhai/AuthAPI">mongodb</a> and this one for <a href="https://github.com/kaustubhai/AuthAPI-PERN">postgreSQL</a>. Do consider giving them your like and me a follow if you like it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4d0cd7f352" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick notes: System designing]]></title>
            <link>https://kaustubhai.medium.com/quick-notes-system-designing-90c06b188ad?source=rss-a9a3e12d78f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c06b188ad</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Kaustubh]]></dc:creator>
            <pubDate>Tue, 15 Nov 2022 20:30:29 GMT</pubDate>
            <atom:updated>2022-11-15T20:32:01.733Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, here are few penned notes of mine, which I created to tackle hot topics in the interviews of system designing, hope it helps you.</p><p><strong>Latency, Availability, and Throughput,</strong> these 3 factors for the performance of a feature/website. If we want our service to be fast and responsive, these 3 factors are something that we should take care.</p><h4>Latency</h4><p>Time taken for data to travel from point A to point B. Data travel can be between different storage devices or from server to client or vice-versa. It is measured in ‘ms’(milliseconds). It is increased because of longer travelling distance for data packets, or complex computation happening to produce result.</p><h4>Throughput</h4><p>Throughput is the count. It is the count of data actually travelled from point A to B regardless of everything speed, latency or bandwidth. It is a count, done every second and is measured in bits per second(bps). It is caused because of low data transfer cap or high congestion in the path of data traversal. (Also, more the latency, lesser the throughput)</p><blockquote><em>Latency is how long it takes you to drive from A to B, bandwidth is how wide the roads are, and throughput is how many cars are on the road right now.</em></blockquote><h4>Availability</h4><p>Availability is measure of service uptime. It is measured by percentage of time as part of a year. If a service is up for say 6 months, availability of the service is 50% and so on.</p><p>Better the availability, more reliable the service is.</p><p>Availability can be measured of a website or a particular feature of a website. Good availability is subjective however and 99.9%(8.77 hours in a year) or <em>3 nines</em> is considered as standard availability. Gold standard however is 99.999%(5.26 minutes in a year) or <em>five nines</em>:</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Load balancing</h3><p>Load balancing (can be achieved via software or a hardware) is a process of distributing request nodes for faster computing and more reliability. There are mainly 2 types of load balancers (depending on the loads used in the balancer) and there are many algorithms that we can choose to how to divide the load in between the servers.</p><p>Load balancing also serves many different purposes other than distributing loads on the server such as, It helps in expanding our system horizontally to any extent, works as a proxy for servers so that user does not need to know the exact location or IPs of servers as they only need to deal with LB. Obviously load balancing increases the throughput.</p><p>Although there are hardware and software available to achieve load balancing, hardware is highly neglected as it is very expensive and provides only limited possibility or configurations.</p><figure><img alt="Load balancer in action" src="https://cdn-images-1.medium.com/max/1000/0*FufqPTPvdRtHt83W.png" /></figure><h4>Load balancing algorithms</h4><p>All examples below are the order of servers that gets request to handle in the order suggested by the algorithm, considering our server ecosystem looks like</p><p>A(1x power) B(1x power) C(2x power)</p><p>The power mentioned is computational power of a particular server.</p><ul><li><strong>Round Robin</strong> is the simplest algorithm used and most popular. It just goes round and round on the servers giving them requests to handle one by one. Example: ABCAB…</li><li><strong>Weighted round robin</strong> is round robin except it also considers the computational power of the servers. Example: ABCCABCCAB…</li><li><strong>Random</strong> works as the name suggests, assigning task randomly</li></ul><p>Although these are nice but using these don’t let us use LBs to thier full potential. For example, with every new request going to a new server, we can use LBs for caching, for that we can use either <strong>URL hashing algorithm</strong> or <strong>User IP Hashing</strong> (storing user IPs or URLs and the mapping same request from same IP or URL to the same server). On a software load balancer, we can decide what algorithm to use whenever we want by simply just typing it in the LB.</p><ul><li><strong>Dynamic least load</strong> algorithm calculates load of servers at a time of incoming requests and then map the request to the least busy server. Load can be measured with a variety of metrics, including number of connections, amount of traffic, and request latency.</li></ul><h4>Choosing right algorithm</h4><p>The algorithm that suits our server ecosystem depends on our ecosystem and nature of the incoming requests. If we have heterogenous servers in our ecosystems, we can use weighted round or, if we have heavy requests coming at high frequency then we can use URL Hashing to use caching in to compute our response.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Caching</h3><p>Caching is a technique in which we store, frequently computed or used data in a low volume, less expensive and more volatile and fast memory database such as Redis. It helps us to decrease latency by giving response faster than the primary db, and also by decreasing throughput by decreasing the number of calls that our server makes to our database.</p><p>Caching is based on time based entry of data. There are two scenarios with it, GET Request and a POST Request.</p><p><strong>In GET Request</strong>:<br>There are two two cases, Cache hit or Cache miss. Cache hit is when the requested data is not in the cached storage and cache miss is when it is not there. Cache hit will take the data out from the cached storage and give out response fast and Cache miss will take time as it now have to go to primary database, get response, add it to cached storage and give it out.</p><p>Cached also stores data that is frequently being used or data that is undergoing shift to primary database or just went into it.</p><p><strong>In POST Request:</strong><br>There are 3 approaches here trading off between speed and consistency.</p><p>First approach is called <strong>write-behind cache</strong> in which, data comes and gets stored in cached storage and then to the primary database (may be instantly or asynchronously). It gives faster writing speed but consistency becomes issue as it is possible that data before coming to primary database, gets replaced.</p><p>Second is <strong>write-around cache,</strong> in which data comes to primary storage first and then to the cached storage. A check can be used here to see if the request from primary storage is responding with latest data it means secondary storage is backlogged and so it is now right time to write latest data to cache now. More consistent as data is never going to lose but slower for first few calls.</p><p>Third is <strong>write-through approach</strong> in which cache and primary storage both gets updated at same time. This is faster as data is getting cached at the time of entry and persistence is also there as latest data is also there in primary storage as well. However, the drawback here is that the writing is slower as both the databases is getting updated at the same time.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Eviction Policy</h3><p>Eviction policy decides that when does a data will be evicted in cache and get into primary storage. These policy depends upon the technique we are using to cache. A good eviction policy means more cache hit then cache miss.</p><ul><li><strong>LRU (Least Recently used):</strong> This basically follows queue system or FIFO System where the data that entered last will get evicted first from cached storage. For this we need to take care of ageing bit of the data to take care of the time the data entered the queue. In LRU the key point to take care is that the data you are using frequently should have its timer reset when it gets used in the response. LRUs are a good suit for websites with log entry like Github where the data recently entered or updated needs to be fast in response rather than some year ago uploaded code.</li><li><strong>LFU (Least frequently used):</strong> In this policy we need to have a counter for frequency of the data used. As this count becomes the lowest in the queue, that data piece is evicted from the queue. This is something you will see on youtube trending section, where the video frequently being used or getting watched stays in the list and gets evicted when some other video starts seeing more clicks on it then the previous one.</li></ul><p>Data that is cached also always have a TTL (time to live) counter on top of it. This is the counter which if gets expired, data has to go from cached storage no matter what. If not handled carefully, a huge amount of data can get loss permanently.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Hashing</h3><p>When using load balancers and using non-hashing compatible algorithms with it like round-robin, caching becomes difficult so we use hashing for using round-robin (and other similar) algorithms with LBs and still leveraging the benefits of caching.</p><ul><li><strong>Consistent or Simple Hashing</strong> is simple hashing done with URLs/IPs to the servers they first responded to following the round-robin method. This works for wighted round-robin as well but the problems begin when we expand our ecosystem and add or decrease the number of servers as now old servers will get new requests and old both but new server will get new requests only so this will make things unbalanced. Alternatively we can remove hashing array and start thing from scratch which will make slow for every request</li><li><strong>Hash Ring</strong> is hashing method where we follow hashing in a circular manner. Here even the problem of expanding our ecosystem does not create any problem as every server finally gets added to the ring itself.</li><li>Here we first setup all the servers in a ring (theoretically only obv.) and divide the requesting clients in between these servers. Then we map this request to the closest server on the ring (clockwise or anticlockwise). This way if we get new server, we just add it somewhere in the ring and map clients nearest to the new server to it instead of there old one so in this way, only few users loses there cache and not every one and new server also gets equal chance to serve new as well as old requests like others</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Sharding</h3><p>Sharding is the expansion of our ecosystem of databases where every single database is called one shard. Nowadays, the data being collected is so huge in quantity that without sharding it is almost impossible to have a fast, consistent database which store all your data as well. We split data into shards by splitting data rows(horizontal sharding) and not columns(vertical sharding). This process is also called as <strong>denormalising of the data</strong> and makes our database efficient, fast and increases its availability as well.</p><p>For sharding, we need to add a key to every row of our data to map it to the exact shard that it is stored in. In sharding it is appreciated to distribute data evenly in small-small shards so that one or more shard should not become hotspot(by getting used more frequently then the others).</p><p>Also while doing sharding or denormalisation of the data, we need to take care that the data is able to be placed in a single row and one data or column is not linked to any data or column existing in any different shard. However, it is not like denormalisation is not possible if the seperation of data is not possible but then the fetching of data becomes tedious and the process gets slower.</p><h4>Benefits of sharding</h4><ul><li>Horizontal expansion of the databases become easier without any limitation</li><li>Database stays fast as they do not get loaded</li><li>It can handle huge amount of data more consistently then a single database</li><li>Gives possibility of more concurrent connections to the database</li><li>Becomes necessary for places where legislation does not allow storing of the data of a particular country outside the specific country (ex: Government of India required Pubg to exist in India if only they will store Indian data inside databases located physically in India)</li></ul><h4>Disadvantage of Sharding</h4><ul><li>Queries become difficult because every time you’ll have to keep in mind your different shards</li><li>Also, as mentioned above, if data not divided perfectly, makes queries slow and defeat the purpose of sharding for many calls</li></ul><h4>Types of Sharding</h4><ul><li><strong>Range based</strong> sharding is where we choose specific key which we are going to use for sharding purposes. For this key, we divide possible value in ranges and then on writing the data, we lookup the range of this key in the input and then select which shard it should go. Here when reading the data, we need the exact value of this key to find which shard it belongs so that we can read the complete data associated with that key. However, it is possible that the key can also get some unexpected out of range value which will fail this approach and also similar values or more closer values togethor can make one shard a hotspot which we do not want</li><li><strong>Hashing</strong> for sharding, is where you except taking the range of a key, hash it and then use it to place it in a specific shard on basis of the hash. However, here you’ll need to have a shard key where every hash and shard liked will be stored and it will hence become a limitation as that key is now a single point of failure for your ecosystem. Also, hashing does better then range based sharding for preventing hotspots however, it still does not guarantee anything in this regard and the problem increases when we increase the number of shard as the calculation again becomes wrong and new shard will now get only new data and old ones new as well as old (like we discussed it earlier with our hashing approach in servers)</li><li><strong>Geo-Based</strong> sharding is used to place a data in a shard according to the location from where the data is coming into the nearest shard possible. Again, this approach can make hotspots if your service is more popular in a specific geographical location because then the nearest shard will feel the most amount of tension then any other.</li></ul><p>SO basically, there is no perfect way for sharding of your data but it depends upon some questions like where is your app/service is going to get used most or what people are going to use it most and only there after you can come up with something that can fits perfectly. Nevertheless, it is proven that sharding is important and when building huge, complex and scalable services, it should be kept in mind.</p><figure><img alt="Sharding in action" src="https://cdn-images-1.medium.com/max/900/0*Lod5SdeF9bgUj5V4.jpg" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Leader Election</h3><p>Leadership election is a major problem ho need to have a clear solution for ecosystems for multiple points of server or database or failure overall.</p><p>So most of the times in an ideal world, the servers or all he endpoints ill wok together but parallel to fetch response of any incoming request but sometimes (like in above example of not well separated rows in case of sharding), multiple shards or servers may have to come up together to get desired outcome. Two equally powerful and equally prioritised shards or server may instead of solving problem, may create a mess and thus it is necessary for them to decide a leader among them and other needs to be follower who only do what leader asks them. Leader election algorithms helps to decide the leader and follower in similar cases. We may need this in case when the pre-decided leader goes down. In situations where more consistency and availability is required, such as in complexed algorithms where we may need 2 or more servers to work together</p><p>It is notable that it comes with several drawbacks like the leader becomes our single point of failure because, if it fails or does not behave as expected, followers are going to follow it. In case of not applying the algorithm properly, there can be no leader or two leader and in both of these case, there will be a <strong>split-brain</strong> problem.</p><h4>Algorithms</h4><p>We need two endpoints in every server to check health, say /health and /alive. Follower will keep hitting these endpoints of leader to know if the leader is healthy and alive or something went wrong. However in synchronous, this works flawlessly but in asynchronous servers, there is no limit for /health to return 200 so it again becomes difficult.</p><ul><li><strong>Bully Algorithm</strong> is a synchronous algorithm where leader is decided on the basis of its id. The highest id with the living status gets to be the leader. Drawback is that one a recently died high id server dies and it comes to life again, it gets to be the leader because of this algorithm and can fail again because of the sudden load increase</li><li><strong>Raft</strong> is an asynchronous algorithm but with a certain democratic approach. Node keep listening for messages and when after some time limit, it does not receive any, it declares itself a candidate and ask for vote by other nodes. The node which gets highest vote emits messages now and become leader and now other nodes wait for time when this messages gets stopped, i.e., the node failed</li><li><strong>Apache ZooKeeper (ZAB)</strong> chooses leader asynchronously by finding node with the most synced history to the dead or previous node and then declaring it the leader by synchronising its history with other nodes so that every one gets a chance to be the leader equally next time</li></ul><p>Obviously, leadership election can be ignored where coordination is possible.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Websockets</h3><p>Polling, Server sent events, and Websockets are all techniques used to transfer high volume data from/to server where you continuously need to fetch or submit data to the server, where normal http protocols will fail because of continuous and so frequent calling. Here these 3 protocols come handy.</p><h4>Polling</h4><p>Polling is continuously making http requests to the server but after a short duration. It is widely supported (as it only makes http calls only) but problem with it is same as discussed earlier, calling http requests repeatedly. There are also two types of polling,</p><ul><li><strong>Short polling</strong> where client requests data, server responds with either new or no information and after receiving this information, client again makes call for data.</li><li><strong>Long polling</strong> is client making request and then waiting for server to respond with some new information and then calling it again to check</li></ul><p>Long polling is obviously better than short polling but not most optimised as it is still http calls, getting called repeatedly.</p><h4>Server sent events</h4><p>Server sent events uses only one http call and then establishes connection with the client until disconnected and keep sending new information to the client as soon as it is available. Overall this is a great approach for continuous data fetching but its drawback is that it is not bidirectional. Say if you are using it for data streaming and user presses pause and now you also want to pause the loading of the video in background, you cannot do it unless you completely disconnect from the server and make a http request again when play button is clicked.</p><h4>Websockets</h4><p>Websocket is a bidirectional server message passing protocol. It is faster as it also makes only 1 http request to server to make a handshake happen between server and client. After that connection gets upgraded and both client and server can make data/message transfer, called as websocket TCPs.</p><p>Main advantage is that both client and server can make data transfer without making a http request so its very fast communication. It is fast but very complex to implement and also substantially increase the investment cost of service and hence it is recommended to use only after Polling and Server sent events don’t work.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Messaging oriented middleware (MOM)</h3><p>Pubs-Subs or Publisher-Subscriber system allows server and client to work independently on messages by providing them a middle-agent making message transfers more efficient. In this system, message is given by <strong>Producer</strong> to <strong>Messaging oriented middleware (MOM)</strong> which then gives it to the <strong>Receiver.</strong> MOM helps in case like the Receiver is busy to handle the new message of Producer, MOM take cares of it and when receiver gets free, MOM then transfers the message to the receiver making this simple process asynchronous.</p><h4>Pub-Subs</h4><p>Pub-Sub system is where there is one publisher and many receivers but the content gets delivered to only users who are subscribed to that message’s publisher. This can be filtered on the basis of category, author or content. Like in twitter, when a user publishes a tweet, not everyone but only those who follows the publisher gets notification of the tweet. It is worth noticing that pub-sub system doesn’t guarantee messages to be delivered in a systematical order given the nature of MOM to be asynchronous.</p><h4>Message queues</h4><p>It is a type of a MOM which follows a FIFO structure for messages so that first sent message gets received first and so forth following a queue. It can also be called pin point messaging as despite being asynchronous, messages are getting delivered in queues only. If we will not use message queues, then message shorter in size may get deliver first due to asynchronous nature of the MOMs</p><p>That’s it for now, they were just few quick topics to look by before interview and their boiled down explanation. All these notes were taken by me during the time I was following a course on system designing, on Udemy by Diwakar singh, checkout the course on udemy <a href="https://www.udemy.com/course/system-functional-design/">here</a>. Peace out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c06b188ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a great portfolio website]]></title>
            <link>https://kaustubhai.medium.com/how-to-build-a-great-portfolio-website-5dee17f95192?source=rss-a9a3e12d78f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dee17f95192</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[website-design]]></category>
            <category><![CDATA[resume]]></category>
            <dc:creator><![CDATA[Kaustubh]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 07:01:52 GMT</pubDate>
            <atom:updated>2021-04-23T10:17:30.559Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we are going to see what makes a portfolio website great, so if you are someone who is planning to have his/her portfolio website, here are some points I’ll like to suggest you keep in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEaTA-p0DeLBt7sMd_ypEQ.gif" /><figcaption>Snapshot of my Portfolio Website</figcaption></figure><h3>Header Section</h3><p>It is the section any visitor on your website will see upon landing. This has to be the eye-grabber, it needs to grab the attention of the visitor and make them view more of the website. This section should be beautifully designed, interactive and abstract.</p><ul><li>For the design part, you can take inspiration from <a href="https://dribbble.com/">Dribbble</a> or <a href="https://www.behance.net/">Behance</a>. You can search for landing pages and see some awesome designed pages. You can also find some coded versions of these pages on these websites if you dig deep enough.</li><li>Many people don’t see it as a necessary thing or skip this part as it may compromise with the beauty of your website, but it is really of huge need to place a call to action. It gives the user a sense of direction on your website and makes it interactive as well. (More about CTA <a href="https://www.investopedia.com/terms/c/call-action-cta.asp">here</a>)</li><li>Make sure anything you put in your header section, any data or any text, should be abstract. You have an infinite amount of page below this so save some of it here and try to be in a strict 10–20 word limit in this section whatsoever.</li></ul><h3>Your Introduction</h3><p>Maybe the first thing anyone is visiting your website is because they want to know more about you. It is your section to show off your skills and your vocabulary here.</p><ul><li>Make sure to use a professional photograph of yourself. Don’t ever use a selfie or casual photo of yours in your resume or portfolio website. You also should be careful about the background of your photo as a poolside photo will not fit in here by any means.</li><li>Use <a href="https://app.grammarly.com/">Grammarly</a>. You will never want your recruiter checking your website and spot spelling or grammatical mistake in it, also Grammarly helps you to change some common words to some more advanced vocabulary which may look cooler on your portfolio.</li><li>List all of your skills whether you are good at it or even familiar with them. Your website should tell the recruiter that how much have you explored your field and related tech stack. Don’t ever use a rating system or progress bars to judge your skills yourself, leave that on recruiters.</li></ul><h3>Your Projects</h3><p>In a modern-day recruitment system, projects are a key aspect of your selection. Good projects can often land you in your dream company so you should be careful about this section particularly.</p><ul><li>You should list your key projects only and avoid listing projects you made following a course or during an internship. You may wanna describe your project in few words and the tech stack you used in the project.</li><li>Always use a graphic or project screenshot along with its name and description. If you think that your screenshot does not look good, You can use services like <a href="https://www.canva.com/">Canva</a> to make a cool thumbnail that goes with your portfolio theme.</li><li>A link to your hosted project or GitHub is more than important. You can use services like <a href="https://www.netlify.com/">Netlify</a> and <a href="https://firebase.google.com/">Firebase</a> for free to host your project or at least share the link to the public repo of your project if not link. In the case of the Github link, make sure the readme of the repo is up to date.</li></ul><h3>Contact Form</h3><p>Probably the most important section of your portfolio from your point of view. If a visitor has made it so far on your website, he is most likely to use it to get in touch with you. Many people provide their mails and leave them on the visitor to mail them, however, I do not prefer this.</p><ul><li>I think you should give your mail address here but also have a contact form here. You should have a back-end connected to it or you can use services like <a href="https://formspree.io/">Formspree</a> to get mails on every submission of the form.</li><li>It is the most important feature so make sure it is not broken or something which can affect the experience of the visitor. You can also provide your social links here as well but make sure they are updated at regular intervals as they can directly impact your profile.</li></ul><h3>Hosting you portfolio</h3><p>You need to host your portfolio website so that recruiters and everyone can see it. However, a key thing to take note of here is the domain you choose to host your portfolio.</p><ul><li>A simple example.com or example.me is perfect to host your portfolio website, it need not be fancy or creative. If you have a problem hosting your website on private domains, you can choose a free hosting service from Netlify and a free domain from <a href="https://education.github.com/pack">Github Student Package</a> (apply for it if you haven’t already) and combine them to get your portfolio website running. You can see documentation to do so on netlify <a href="https://docs.netlify.com/domains-https/netlify-dns/#add-a-domain">here</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ZFTv5rrRzNLHbTz3dpM4_g.gif" /></figure><h3>See Examples</h3><p>If you are still stuck, you can consider checking out the portfolio websites of some peoples on Github. You can see design samples again on Dribbble or Behance.</p><p><a href="https://kaustubhai.me/">Here</a> is my portfolio website, hope you like it. Feel free to use the contact form to reach me anytime. I’ll be more than happy to hear from you what you have to say.</p><p>If you like it, you can also check out this <a href="https://github.com/kaustubhai/portfolio-template">portfolio template</a> I coded for everyone in ReactJS. Feel free to use it, customize it and show off your skills with it. I would very much appreciate a pull request from you if you think you can add something to it</p><h3>Summary</h3><p>Your portfolio website should work to lure more opportunities towards you. No one can get a perfect portfolio, it’s a long process of adding and deleting sections and features and then only you can hit some marks and get visitors to actually visit your contact section. I think this article can give your thoughts a direction, just keep the key points in mind and code the best portfolio website anyone has ever seen. Good luck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dee17f95192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PERN Stack and its deployment]]></title>
            <link>https://kaustubhai.medium.com/pern-stack-and-its-deployment-cd615e5bb760?source=rss-a9a3e12d78f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd615e5bb760</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Kaustubh]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 08:29:03 GMT</pubDate>
            <atom:updated>2021-04-07T08:29:03.534Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will start from scratch about PERN Stack, what is it, why is it, how is it and then we will build a simple PERN App and deploy it on heroku.</p><p><strong>Pern stack: </strong>A web stack consisting of 4 awesome open-source libraries and frameworks, <strong>P</strong>ostgreSQL, <strong>E</strong>xpress, <strong>R</strong>eactJS, <strong>N</strong>odeJS. You can build any full stack website with the help of these technologies together like a one we are going to build here today. Also it is worth mentioning here that PERN stack sounds similar to a more popular tech stack, the MERN stack, as they both share 3 technologies, i.e express, node and react but they both use different technology for databases.</p><p>MERN Stack uses MongoDB, a non-relational database and PERN uses a PostgreSQL, a relational and more robust database. No Doubt both, MongoDB and PostgreSQL share great features but they are very different in the basic structure of a database. As I mentioned earlier, Mongo is a non-relational database, i.e it uses JSON to store its data and Postgres uses Table or Relations to do the same.</p><p>That’s enough talk about our nemesis MongoDB, now lets start the main part and get ourselves into coding</p><h3>Setting Up Postgres Table</h3><p>I’m going to assume that you have Postgres installed in your system already, however if that&#39;s not the case follow along <a href="https://www.youtube.com/watch?v=fZQI7nBu32M&amp;t=0s">this</a> video on YouTube and it will get things done for you to follow along.</p><p>Ok, so make sure you are connected on to your database and lets start,</p><blockquote>Create a database on your localhost</blockquote><pre>CREATE DATABASE todo;</pre><blockquote>Switch to the created database</blockquote><pre>\c todo postgres localhost 5432;</pre><blockquote>Create a relation or a table on created database</blockquote><pre>CREATE TABLE task(work VARCHAR(150), completed BOOL);</pre><p>At this point, you are all set. You have created a database and a table inside it on your local machine. Now you can deal with the data as you are ready to store it now in your relation.</p><blockquote>Insert a value in the database</blockquote><pre>INSERT INTO task(work, completed) VALUES(&#39;Learn postgres&#39;, false);</pre><blockquote>Read all the values stored in your database</blockquote><pre>SELECT * FROM task;</pre><blockquote>Update a value in database</blockquote><pre>UPDATE task SET completed = true WHERE work = ‘Learn Postgres’;</pre><blockquote>Delete a value from the database</blockquote><pre>DELETE FROM task where work = &#39;Learn Postgres&#39;;</pre><p>So you just <strong>C</strong>reated, <strong>R</strong>ead<strong>, U</strong>pdated and <strong>D</strong>eleted data from your database. It means that you are all set to write up your own <strong>CRUD </strong>API using node and express with PostgreSQL</p><p>Now lets start with node and express and build an API. You obviously need node installed in your system, you can check it by running</p><pre>node -v</pre><p>If you get v14.xx.x something, you are good to go, otherwise you can download node <a href="https://nodejs.org/en/download/">here</a>. Just follow the installation wizard</p><p>Now create a folder on your PC and open it in VS Code.</p><p>Open up the terminal and lets’ begin with command:</p><pre>npm init -y</pre><p>This one small command has now just set upped your node app. Now lets go ahead and set up express and other important packages, then our local server</p><pre>npm install express cors pg</pre><p>Now make a ‘server.js’ file in root directory and paste the following code</p><pre>const express = require(&#39;express&#39;)<br>const server = express()</pre><pre>server.get(&quot;/&quot;, (req, res) =&gt; {<br>    res.send(&quot;Hello World&quot;)<br>})</pre><pre>const PORT = process.env.PORT || 5000<br>server.listen(PORT)</pre><p>Now run following command on the terminal</p><pre>node server.js</pre><p>Now Open you browser and go to ‘http://localhost:5000’ you’ll see Hello World on the browser. Now you are all done with the boilerplate stuff, lets begin with the crud API and write 4 endpoints to create, read, update and delete task from our database.</p><p>However, before writing API, you need it to connect it with your local database. Make a file ‘connectDB.js’ and paste following code</p><pre>const pg = require(&#39;pg&#39;)<br>const Pool = pg.Pool;</pre><pre>const pool = new Pool({<br>    user: &quot;postgres&quot;,<br>    host: &quot;localhost&quot;,<br>    port: 5432,<br>    password: &quot;your_password&quot;,<br>    database: &quot;todo&quot;<br>})</pre><pre>module.exports = pool</pre><p>This code is enough for you to connect your code with database, now change your ‘server.js’ as following to make a complete rest API. Keep in mind to change the password with the password you created while setting up postgreSQL on your machine.</p><pre>const express = require(&#39;express&#39;)<br>const pool = require(&#39;./connectDB&#39;)<br>const server = express()</pre><pre>server.use(express.json())</pre><pre>server.post(&#39;/create&#39;, async (req, res) =&gt; {<br>    const { work } = req.body<br>    const response = <em>await</em> pool.query(&quot;INSERT INTO task(work,     completed) VALUES($1, $2) returning *&quot;, [work, false])<br>    res.json(response.rows[0])<br>})</pre><pre>server.get(&#39;/read&#39;, async (req, res) =&gt; {<br>    const response = <em>await</em> pool.query(&quot;SELECT * FROM task&quot;)<br>    res.json(response.rows)<br>})</pre><pre>server.patch(&#39;/update&#39;, async (req, res) =&gt; {<br>    const { work } = req.body<br>    <em>await</em> pool.query(&quot;UPDATE task SET completed = $1 WHERE work = $2&quot;, [true, work])<br>    res.json({ msg: &quot;Task Updated&quot; })<br>})</pre><pre>server.delete(&#39;/delete&#39;, async (req, res) =&gt; {<br>    const { work } = req.body<br>    <em>await</em> pool.query(&quot;DELETE FROM task where work = $1&quot;, [work])<br>    res.json({msg: &quot;Task Deleted&quot;})<br>})</pre><pre>const PORT = process.env.PORT || 5000</pre><pre>server.listen(PORT)</pre><p>This is the code for a simple Express API with Postgres. It is always so simple, easy and fast to make APIs with the help of Express framework. This code can serve as a complete backend API for your todo PERN stack application. Ofcourse, you can make it more better by adding UUID, auth and more such functionalities but this works just fine for now.</p><p>So I guess this is time, to host our backend Postgres, Node and Express API on heroku to serve our upcoming frontend project. Lets begin</p><p>To get started with hosting your API on heroku, we first need to install heroku cli to access your heroku dashboard right from your terminal. Run following command on your terminal to do so</p><pre>npm i heroku-cli</pre><p>You may want to use npm or sudo according to your local environement and settings. Now to access your dashboard, login with heroku,</p><pre>heroku login</pre><p>Follow on-screen commands, you will get a login success message. Now you can close the browser tab and come back to your terminal.</p><pre>heroku create example-pern-app</pre><p>You can use your API name according to you by running this command above. You can also visit your heroku dashboard and see your app actually listed there after success message on your terminal.</p><p>Now after setting up a node application on heroku, comes setting up postgreSQL on heroku. Heroku provides us with a addon service called heroku-postgresql. To add this addon service, go to your dashboard on browser and follow following actions</p><ol><li>Go to your Dashboard</li><li>Select your created app</li><li>Go to resources tabs</li><li>Search for heroku-postgres on addons sections</li><li>Choose Hobby-Dev-Free Plan</li><li>Submit your order form</li><li>Done.</li></ol><p>Now you can go to your terminal and write following command to see your addon linked with your app</p><pre>heroku addons</pre><p><strong>Note for windows user: </strong>Make sure before proceeding that your PostgreSQL path to bin is registered in the environment variable section of your machine. You can check the <a href="https://devcenter.heroku.com/articles/heroku-postgresql#set-up-postgres-on-windows">documentation</a> here.</p><p>Now you are ready to access your postgres database hosted on heroku. Ho ahead and use following command on the terminal.</p><p>Replace the ‘postgresql-something-xxxxx’ part with the name you got under add-on section when you ran the command ‘heroku addons’ and replace ‘example-pern-app’ with the name you selected for your app.</p><pre>heroku pg:psql postgresql-something-xxxxx --app example-pern-app</pre><p>After succesful terminal command execution, you’ll see that you are not exited, but you are in the database. Your terminal must be showing your cursor ahead of</p><pre>example-pern-app:DATABASE=&gt;</pre><p>it means, you are now inside of your database. You can now run the postgres command exactly like you used it in your SQL Shell. Go ahead and copy paste your commands to create the tables inside the database <strong>(Do not use create database and ‘\c’ commands as heroku has settuped your database automatically)</strong> of your heroku app. and you’re done.</p><p>Your complete app is now all set on heroku. You have your node application, linked with your own database and now we are going to deploy it.</p><p>Before deploying however, we’ll have to change the connection string on our postgresDB.js file to make it connect to the one database on heroku and not the one on our localhost. Copy and paste the following in your connectDB.js file.</p><pre>const pg = require(&#39;pg&#39;)<br>const Pool = pg.Pool;</pre><pre>const pool = new Pool({<br>    connectionString: process.env.DATABASE_URL,<br>    ssl: { rejectUnauthorized: false }<br>})</pre><pre>module.exports = pool</pre><p>If you are interseted in knowing what is that ‘process.env.DATABASE_URL’, you’ll have to go to your dashboard again and then</p><ol><li>Go to Settings</li><li>Go to Config vars sections</li><li>Click on Reveal Config Wars</li></ol><p>There you’ll find a long sting in front of DATABASE_URI. This is your connection string including your database username, password, host, port for the database associated with your hosted node app. Heroku provides you simply with this string to connect your app.</p><p><strong>Note: </strong>Before proceeding further, you need git to be installed in your system. Also make sure to make a ‘.gitignore’ file in the root of your folder and add ‘node_modules’ in it</p><p>Okk so now here comes the big moment, uploading your app and deploying it on heroku. Use following commands in your terminal.</p><pre>git init<br>heroku git:remote -a example-pern-app<br>git add .<br>git commit -m &quot;My API upload&quot;<br>git push heroku master</pre><p>So now, you have your app ready, uploaded and well connected. Now you need to do npm install and then start your server. Run following commands after one another</p><pre>heroku run npm install<br>heroku run node server.js</pre><figure><img alt="Hurray" src="https://cdn-images-1.medium.com/max/498/1*8FxWgz_0Yem5qtOlCRMvDQ.gif" /></figure><p>Thats it… You have now successfully uploaded and deployed your API to serve your basic todo application made with PostgreSQL, NodeJS and Express.</p><p>You can go on <a href="https://example-pern-app.herokuapp.com/read">https://example-pern-app.herokuapp.com/read</a> and you’ll get an empty array which is a sign of your successful deployment as your database has no task in it to fetch. You can either test your API via <a href="https://www.postman.com/">Postman</a> or directly via your frontend react app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd615e5bb760" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>