<?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 Manav Garg on Medium]]></title>
        <description><![CDATA[Stories by Manav Garg on Medium]]></description>
        <link>https://medium.com/@manavgarg0706?source=rss-dcb26a4c1055------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zdpHjRo48_A12Xat4RCqjQ.jpeg</url>
            <title>Stories by Manav Garg on Medium</title>
            <link>https://medium.com/@manavgarg0706?source=rss-dcb26a4c1055------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:53:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manavgarg0706/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[Reduce Backend TCP Response Latency: TCP_NODELAY]]></title>
            <link>https://medium.com/@manavgarg0706/enhancing-backend-tcp-response-latency-tcp-nodelay-ee37b715abd5?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee37b715abd5</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Fri, 03 May 2024 07:49:25 GMT</pubDate>
            <atom:updated>2024-05-03T13:28:45.674Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I encountered this problem where there were random delays in the client-side app, and the packets were not reaching the server as fast as they should. In the world of backend optimization, even the slightest tweak can make a significant impact. Enter TCP_NODELAY, a tool designed to streamline TCP communication and enhance response times. But before diving into TCP_NODELAY, it’s essential to understand Nagle’s algorithm, a fundamental aspect of TCP transmission.</p><p>Nagle’s algorithm is a protocol used to improve network efficiency by reducing the number of small packets sent over the network. It works by buffering small amounts of data in the send buffer, waiting for more data to arrive or for a certain timeout period to elapse. Once enough data is accumulated to fill a full-sized TCP segment, Nagle’s algorithm sends it out for transmission.</p><p>However, in scenarios where immediate responsiveness is crucial, Nagle’s algorithm can introduce unwanted delays. This is where TCP_NODELAY comes into play. By setting the TCP_NODELAY option on a socket, applications can bypass Nagle’s algorithm and send data without delay. This is particularly useful for real-time communication applications, such as chat or gaming platforms, where low latency is paramount.</p><p>When deciding whether to use TCP_NODELAY, it’s essential to consider the specific requirements of the application. For tasks where low latency is critical, TCP_NODELAY can significantly improve responsiveness. However, in situations where network efficiency is a priority, such as transferring large files or sending batches of small messages, Nagle’s algorithm may offer better performance by aggregating data before transmission.</p><p>In conclusion, TCP_NODELAY is a valuable tool for optimizing backend TCP response latency. By understanding its role in TCP communication and knowing when to leverage it, developers can fine-tune their applications for optimal performance in real-world scenarios.</p><p>Connect with me on <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><strong><em>LinkedIn</em></strong></a> — I’m always eager to discuss ideas, trends, and challenges in the tech space. Lastly, if you found value in our discussion today, please consider upvoting and commenting below. Your feedback not only supports my work but also helps amplify our conversation, enabling it to reach others who share our passion for mindful technology use and design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee37b715abd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hooked Unhooked: A Concise Journey Through Habit-Forming Design and Its Morals]]></title>
            <link>https://medium.com/@manavgarg0706/hooked-unhooked-a-concise-journey-through-habit-forming-design-and-its-morals-e4dadd17e35f?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4dadd17e35f</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[nir-eyal]]></category>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[product-development]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 09:46:56 GMT</pubDate>
            <atom:updated>2024-04-07T09:46:56.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I came across this beautiful book named “Hooked: How to Build Habit-Forming Products” by Nir Eyal. It reveals the psychological mechanisms that tech giants use to make their products indispensable parts of our lives. Although I have been reading quite actively in the past year, this book has had an impact that none of the others had on me, and hence, I could not stop myself from writing about it. As a tech enthusiast, let’s enter the world of ethical design and habits together. This blog post invites you on a journey through the heart of habit-forming technology, guided by the insights of “Hooked.” As we explore the secrets to creating products that stick, we’ll also confront the responsibility that comes with such knowledge. Because the power to shape habits is profound, let’s discover how to wield it wisely.</p><p>Have you ever mindlessly scrolled through your social media feed, only to look up and realize more time has passed than you intended? Or perhaps you’ve noticed how certain apps have become non-negotiable parts of your morning routine, seamlessly integrated into your daily life without a conscious decision to make them so. This isn’t by accident; it’s by design.</p><p>In a world where attention is the most coveted currency, understanding what captures and keeps our attention is more critical than ever. Why do some products become fleeting obsessions while others embed themselves into our routines with the tenacity of a daily habit? The answer lies in the Hook Model — a four-step process that, when executed effectively, can capture our attention and transform it into a predictable use pattern. But as we delve into the intricacies of Trigger, Action, Variable Reward, and Investment, we face a pressing ethical dilemma: where is the line between engagement and exploitation?</p><h4><strong>Welcome to the Habit Zone: Your Daily Tech Rituals Explained</strong></h4><p>Before moving to the Hooked model, talking about the Habit Zone is empirical<strong><em>. </em></strong>Ever wonder why some apps feel like a natural part of your day? They’ve made it into your <strong>Habit Zone — where technology meets routine</strong>.</p><blockquote><strong>The Secret Behind the Habit Zone</strong></blockquote><p>In the Habit Zone, products achieve what every creator dreams: they become indispensable. Here, usage is no longer a choice but a part of our daily fabric, from waking to the whispers of sleep. Why do we reach for our phones, check our favorite apps, and feel incomplete without them? Because they dwell within our Habit Zone, woven into our routines with threads of convenience, joy, and necessity. This zone isn’t magic; it results from a clever design that blends seamlessly into your life.</p><blockquote><strong>How Products Earn Their Place</strong></blockquote><p>It starts with a nudge — a notification or icon that draws you in. Then, with every tap and swipe, simplicity keeps you moving smoothly. The kicker? The surprise and delight of something new every time you engage. And before you know it, you’re invested; these apps know what you like and serve it up, making each visit uniquely rewarding.</p><blockquote><strong>The Fine Line</strong></blockquote><p>Creating a spot in the Habit Zone is powerful, but with power comes the need for responsibility. It’s all about enhancing life, not exploiting it. The best products make our lives better without us feeling hooked.</p><blockquote><strong>Reflect on Your Tech Habits</strong></blockquote><p>Now, dear reader, pause and reflect. Which products have you invited into your Habit Zone? What magic do they hold over you, and how do they make your daily journey smoother, richer, and more enjoyable? The answers may surprise you, revealing your digital habits and the values and needs that drive them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9hYKAPc9v_zFIgwQ.png" /><figcaption>Habit zone: <a href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQgLo6aPGiKhDTP9rECUR6bQZZ02RrTGMAS6g&amp;s">https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQgLo6aPGiKhDTP9rECUR6bQZZ02RrTGMAS6g&amp;s</a></figcaption></figure><p>The above graph accurately represents the habit zone. Please note it is based on frequency (how often the behaviors occur) and perceived utility ( how useful the behavior is in the user’s mind).</p><p>Now is the time to dive into the most awaited <strong>Hooked Model. </strong>Let’s journey through each stage of the Hook Model, uncovering the art and science that captivates your attention.</p><blockquote><strong><em>Stage 1: The Trigger Phase</em></strong></blockquote><blockquote><strong><em>External Triggers: The Direct Call to Action</em></strong></blockquote><p>External triggers are explicit cues that prompt users to perform specific actions by leveraging notifications, buttons, or other straightforward indicators within a product’s environment. They’re like digital signposts, guiding our behavior directly. These can range from the ding of a notification, a reminder pop-up, or an email in your inbox to an advertisement that catches your eye on social media. They’re explicitly designed to grab your attention and draw you into an app or a website. Tech companies spend considerable time refining these triggers to ensure they’re compelling enough to make you stop what you’re doing and engage.</p><p><strong><em>Engage and Reflect: </em></strong>Think about the last time an app notification made you pick up your phone. What was it about that notification that caught your attention? Was it a message from someone you care about, a reminder for a task you needed to complete, or an alert about a sale or a new feature in a game you play? Reflecting on this can reveal the most effective external triggers in capturing your attention.</p><blockquote><strong><em>Internal Triggers: The Psychological Pull</em></strong></blockquote><p>Internal triggers are associations between a user’s thoughts, emotions, or situations and the use of a product or service. While external triggers are straightforward, internal triggers are more nuanced and deeply embedded in our psyche. These triggers are tied to emotions, thoughts, or pre-existing routines and often stem from a desire to alleviate discomfort. For instance, boredom might prompt you to open YouTube for entertainment, or stress might lead you to scroll through Instagram to relax. Internal triggers are powerful because they are tied to our emotional states and thus can create more enduring habits. The product becomes a natural response to a specific feeling or need.</p><p><strong><em>Engage and Reflect</em></strong>: Now, consider when you reached for your phone without any external prompt. What were you feeling or thinking at that time? Were you seeking distraction, connection, or maybe a sense of accomplishment? Identifying these internal triggers can help you understand the emotional underpinnings of your habits.</p><blockquote><strong><em>The Interplay Between External and Internal Triggers</em></strong></blockquote><p>The mastery of habit-forming products lies in their ability to transition from relying on external triggers to becoming almost exclusively triggered by internal states. This transition is the hallmark of a truly habit-forming product. When users start to automatically turn to a product in response to an internal trigger without needing an external cue, the habit is firmly established.</p><p><strong><em>Engage and Reflect</em>:</strong> Have you noticed any products you now use in response to internal triggers where previously you might have relied on external prompts? This evolution in your behavior highlights the product’s successful migration into your Habit Zone.</p><blockquote>Stage 2: The Path of Least Resistance: Understanding Action Phase</blockquote><p>At its core, the Action phase is about the user taking the simplest step in anticipation of a reward. Think of it as the bridge between desire (triggered by internal or external cues) and the satisfaction of that desire (through the reward). This phase’s success hinges on its ease; the less effort required to take the action, the more likely it will be performed. Nir Eyal succinctly encapsulates this in the principle that behavior is a function of the user’s motivation, the ease of the action, and the trigger.</p><p><strong><em>Engage and Reflect: </em></strong>Reflect on an app you use frequently. What is the first action you usually take when you open it? Is it scrolling, clicking a button, or perhaps typing a search query? How has the app’s design made this action feel almost effortless?</p><p>In designing for the Action phase, product makers meticulously eliminate any friction that might deter the user from completing the action. This could involve simplifying the interface, reducing the number of steps to achieve a result, or optimizing the app’s performance to ensure quick, satisfying interactions. The goal is to make the action as intuitive as tapping a light switch; you don’t think about it; you just do it. Can you think of an instance where a product asked too much of you too soon, perhaps with a complicated sign-up process, and you decided not to proceed? Contrast this with a product that made getting started incredibly easy. How did each experience make you feel?</p><p>The Action phase&#39;s ultimate aim is to encourage a one-time action and instill a habit. When the action becomes as natural and thoughtless as breathing, the product is well on its way to becoming a part of the user’s daily routine. This seamless transition from intention to action separates the fleeting distractions from the tools and platforms that become integral to our lives. Have you noticed any actions that have become automatic in your use of technology? Maybe swiping to refresh your email or double-tapping to like a photo? How do these small, unconscious actions tie you closer to the product?</p><blockquote>Stage 3: The Enchantment of Uncertainty: The Power of Variable Rewards Phase</blockquote><blockquote><strong>The Psychology Behind Variable Rewards</strong></blockquote><p>The concept of variable rewards draws on the basic principles of operant conditioning, where behaviors are influenced by their consequences. Variable rewards introduce an element of unpredictability in the type, timing, or magnitude of rewards, making the action of seeking them out inherently more engaging and addictive. This unpredictability triggers the release of dopamine, a neurotransmitter associated with pleasure and motivation, which encourages us to engage in the behavior again.</p><p><strong><em>Engage and Reflect: </em></strong>Think about your favorite social media platform. What keeps you scrolling: hoping to find a hilarious meme, an insightful post, or perhaps news from a friend? Notice how not knowing what comes next adds to the excitement and draws you in deeper.</p><p><strong><em>Types of Variable Rewards</em></strong></p><p>Variable rewards can be categorized into three main types, each serving a distinct purpose in engaging users:</p><ol><li><em>The Reward of the Tribe</em>: This type of reward satisfies our need for social validation and connection. Likes, comments, shares, and followers are all examples of social rewards that can vary each time we log in, feeding our desire for social interaction.</li></ol><p>2. <em>The Reward of the Hunt</em>: The reward is based on pursuing material resources or information. Whether browsing through an e-commerce app for the best deal or searching a news app for the latest stories, the unpredictability of what we might find fulfills our primal hunting instincts.</p><p>3. <em>The Reward of the Self</em>: These rewards cater to our internal sense of accomplishment and mastery. Completing tasks, leveling up in a game, or unlocking new features in an app can provide a varied sense of personal achievement and progress.</p><p><strong><em>Engage and Reflect</em></strong><em>:</em> Can you identify which type of variable reward you find most compelling in the apps you use regularly? How do these rewards influence your engagement with the app?</p><p>The Balance of Variable Rewards</p><p>For variable rewards to be effective, they must strike a delicate balance. Too much predictability can lead to boredom, while too much unpredictability can lead to frustration. The key is to find the sweet spot where the user feels a sense of anticipation and excitement without becoming overwhelmed or disheartened.</p><p><em>Engage and Reflect:</em> Have you ever lost interest in an app because it became too predictable or felt frustrated when rewards seemed too random or scarce? Reflecting on these experiences can provide insights into how well the app managed the balance of variable rewards.</p><blockquote><strong>Variable Rewards in Action: The Google Pay Scratch Card Phenomenon in India</strong></blockquote><p>A prime example of variable rewards at play can be seen in the early days of Google Pay in India. To entice users and encourage transactions, Google Pay introduced a simple and ingenious feature: scratch cards. With each transaction, users were awarded a digital scratch card that, once “scratched” within the app, revealed potential cashback rewards. Sometimes, users receive a small amount of money and other times, they get nothing.</p><p><strong>The Allure of Uncertainty</strong></p><p>This feature capitalized on the “Reward of the Hunt” by introducing a layer of excitement and unpredictability to each transaction. The thrill wasn’t just in receiving money but in anticipating what each new scratch card would reveal. Initially, the chances of receiving cashback were relatively high, further fueling user engagement and drawing more users to the platform.</p><p><strong>Adjusting the Rewards</strong></p><p>As Google Pay’s user base grew, the frequency and quantity of cashback rewards were adjusted. Despite this, the allure of the scratch cards remained. Users continued to engage with every card, driven by the hope of a reward. This persistence illustrates the powerful grip of variable rewards; even the possibility of a positive outcome keeps us returning.</p><p><strong>The Lasting Impact of Variable Rewards</strong></p><p>The Google Pay scratch card feature demonstrates the lasting impact of well-designed variable rewards. By embedding unpredictability into the transaction process, Google Pay increased its user engagement and ingrained the habit of using the app for transactions among its user base. Even after the rewards were scaled back, the behavior of scratching cards in anticipation of a reward persisted, showcasing the enduring power of this psychological principle.</p><blockquote>Stage 4: The INVESTMENT PHASE OR THE IKEA Effect: Crafting Personal Investment in Digital Realms</blockquote><blockquote><strong>Understanding the Investment Phase</strong></blockquote><p>The Investment phase follows the reward and is pivotal in solidifying the habit loop. Here, users contribute something of themselves back into the product — time, data, content, or even social capital — laying the groundwork for future interactions. This investment enhances the product’s value for the user, not through immediate gratification, like the rewards, but by increasing their commitment to the product and making the prospect of leaving or switching to a competitor less appealing.</p><p><strong><em>Engage and Reflect</em></strong><em>:</em> Think about a digital platform where you’ve customized your profile, curated content, or contributed posts. How did that investment of effort affect your relationship with the platform?</p><blockquote><strong>The Power of User Contributions</strong></blockquote><p>Users&#39; contributions in the Investment phase can take many forms—for example, curating a music playlist on Spotify, saving favorite locations on Google Maps, or building a network on LinkedIn. These actions don’t just personalize the experience; they build a repository of value tied to the user’s efforts and preferences, making each return to the app more meaningful and tailored. One of the very good examples is our Facebook account. Most of us rarely open it now, but still, we haven’t deleted it because of the investment we have made by uploading images, connecting to many people worldwide, etc.</p><blockquote><strong>The IKEA Effect in Action</strong></blockquote><p>The term “IKEA Effect” perfectly encapsulates this phenomenon. Just as assembling a piece of furniture imbues it with added personal value, users&#39; investments in a digital product bind them more closely to it. This effect is a testament to the power of self-effort; the more we invest in something, the more we value it, and the harder it becomes to part with it.</p><p><strong><em>Engage and Reflect:</em></strong> Have you ever experienced the IKEA Effect with a digital product, where your investment in the platform made it indispensable to you?</p><blockquote><strong>Cultivating a Cycle of Loyalty</strong></blockquote><p>In the digital world, the Investment phase is where short-term engagement transitions into long-term loyalty. By inviting users to invest in the platform, companies enhance the user experience and weave their products into the fabric of the user’s digital life. This phase ensures the sustainability of the habit loop, encouraging users to return, driven not just by the allure of rewards but by the value of their contributions.</p><blockquote>The Investment phase, or the IKEA Effect, highlights the transformative power of personal investment in digital product engagement. By understanding and facilitating users’ contributions, digital products can cultivate a deep sense of ownership and loyalty, completing the habit loop in a way that ensures enduring engagement. This phase is a critical component of the Hook Model, ensuring that the user’s journey through triggers, actions, and rewards culminates in a meaningful and lasting relationship with the product.</blockquote><p>Now that we’ve journeyed through the intricacies of the Hook Model, uncovering the layers that make products irresistible and habit-forming, a pivotal question emerges. With this powerful knowledge at our fingertips, how do we tread the fine line between engagement and ethics?<br>The capacity to shape habits offers incredible potential — to foster positive change, enhance daily routines, and even support personal growth. Yet, it bears the weight of responsibility. As we delve into the ethical dimensions of employing the Hook Model, it’s crucial to reflect on our intentions and the impact of these strategies on real lives.</p><p>In crafting digital experiences that captivate and engage, our guiding star should be the well-being of those who navigate them. The book also discusses the ethical considerations that should be reflected upon. As creators, it is imperative to reflect on the implications of our designs. Are we enriching lives or merely entangling users in a web of compulsive interaction?</p><p>As we wrap up our journey through the Hook Model and its blend of engagement and ethics, I want to say a big thank you to all of you, my readers, for joining me on this adventure. While we’ve covered the essentials, remember this exploration is just the tip of the iceberg. The insights shared here are a summary aimed at sparking curiosity and deeper reflection. I highly encourage diving into the original book to fully grasp the nuances and rich knowledge that “Hooked” offers. It’s a resource that transforms your understanding of product design and user engagement. If my summary has piqued your interest and you are hungry for more, picking up a copy of Nir Eyal’s “Hooked” will undoubtedly enrich your perspective. And, as always, I’m keen to hear your thoughts and takeaways.</p><p>Connect with me on <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><strong><em>LinkedIn</em></strong></a> — I’m always eager to discuss ideas, trends, and challenges in the tech space. Lastly, if you found value in our discussion today, please consider upvoting and commenting below. Your feedback not only supports my work but also helps amplify our conversation, enabling it to reach others who share our passion for mindful technology use and design.</p><p>Thank you once again for your time and engagement. Here’s to crafting digital experiences that captivate and contribute positively to our lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4dadd17e35f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search System: Design that scales]]></title>
            <link>https://blog.devgenius.io/search-system-design-that-scales-2fdf407a2d34?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fdf407a2d34</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 19:41:07 GMT</pubDate>
            <atom:updated>2023-03-05T13:59:55.100Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing a search system at scale is critical for most websites nowadays, and many use elastic search mechanisms behind the scenes. In this blog, I will discuss how a search system can be scaled and made available for millions of users. Before moving ahead, the basic requirements of a search system apart from the “Search” mechanism are as follows:<br>a) <strong>Availability</strong>: Users should have high levels of access to the system.<br>b) <strong>Scalability</strong>: The system must be scalable in order to handle the growing volume of data. To put it another way, it should be able to index a lot of data.<br>c) <strong>Quick large data searches</strong>: Regardless of how much material is being searched, the user should receive the results fast.<br>d) <strong>Lower overall cost</strong>: Constructing a search system should be less expensive.</p><p>I won’t go in-depth into how an elastic search is built in this blog, but a basic understanding is required, and I think that much is sufficient for scaling the system. So, our system might contain billions of documents on which we need to run a search query. We need some optimized way to search the documents in a matter of a few milliseconds. Three main components do this: <br>a) A <strong>crawler</strong> that fetches content and creates documents.<br>b) An <strong>indexer</strong>, which builds a searchable index.<br>c) A <strong>searcher</strong> responds to search queries by running the search query on the <em>index</em> created by the <em>indexer</em>.</p><ul><li>The crawler gathers information from the targeted resource.</li><li>The indexer retrieves the documents from a distributed storage and uses <a href="https://www.ibm.com/in-en/topics/mapreduce#:~:text=Get%20connected-,What%20is%20MapReduce%3F,tasks%20that%20Hadoop%20programs%20perform."><strong>MapReduce</strong></a>, which is executed on a distributed cluster of commodity machines, to index these documents. For distributed and parallel index building, the indexer takes advantage of a distributed data processing technology like MapReduce. The distributed storage contains the created index table.</li><li>The index and the documents are stored on distributed storage.</li><li>The user types a search string with many words into the search area.<br>The <strong>searcher</strong> parses the search string, searches for the mappings from the index that are stored in the distributed storage, and returns the most matched results to the user. The searcher intelligently maps the incorrectly spelled words in the search string to the closest vocabulary words. It also looks for the documents that include all the words and ranks them.</li></ul><p><strong>Lucene</strong> does all the above-mentioned things, a library used internally by elastic search. Elasticsearch converts Lucene into a distributed system/search engine for scaling horizontally. Elasticsearch also provides other features like thread-pool, <a href="https://opster.com/guides/opensearch/opensearch-basics/queue">queues</a>, node/<a href="https://opster.com/guides/elasticsearch/glossary/elasticsearch-cluster">cluster</a> monitoring API, data monitoring API, Cluster management, etc. In short, Elasticsearch extends Lucene and provides additional features beyond it.</p><p>But why is elastic search the main question? Elasticsearch provides speed and scalability; it is distributed in nature, which means scaling out is just adding more nodes. More importantly, it provides a very simple rest interface to interface with it. Because of the simple rest APIs, you need a simple HTTP client to talk to elastic search servers, making it super easy to use.</p><p>Until now, we have been clear that we will leverage an elastic search to build our search system. Before this, we need a standardized way for the end user can access the elastic search cluster. We add a proxy between a client and the server. So whichever microservice (assuming the elastic search cluster may be used across teams) needs to access the Elasticsearch needs to go through the proxy. Now because we have a proxy, we can stack a lot of parameters like throttling (rate limiter), router, monitoring, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NdnXxXFvAXpvKXh7v9qXQ.png" /><figcaption>Basic architecture</figcaption></figure><p>The next thing which can affect our elastic search is ingestion. For example, let’s talk in the case of a social media website; there will be content posted every minute, right? Whenever content is posted, it needs to be indexed in the elastic search to make it searchable. If something goes viral and everybody starts posting regarding the event, then a sudden surge in traffic can affect our elastic search. Elasticsearch becomes a little tricky when there is a such increase in traffic because whenever the load increases suddenly, we do not get time to spin up new nodes because it takes time to distribute data. Hence, two things happen due to this:<br><strong>a)</strong> <strong>Increased Indexing latency: </strong>Latency for indexing the new data in the elastic search shoots up.<br><strong>b) Increased Query latency: </strong>Latency to search the data shoots up.</p><p>But on the scale of a website/app having millions of users, getting such surges is very common. So now we have reached our main design problem: how to handle this and protect our ES cluster from such surges?<br>Instead of getting each post directly to the elastic search, the answer to this lies in doing it asynchronously. <br>Any write happening to the elastic search should go through some kind of a queuing mechanism, and the best way to achieve this, as you may have read in my previous blogs, is through a pub/sub system ( for example <a href="https://medium.com/dev-genius/kafka-in-action-a-practical-guide-to-getting-started-with-kafka-7be5074a30c2"><strong>kafka</strong></a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZLsADxIVhrEfcKXOLNeBg.png" /><figcaption>Architecture to push/ write data to the ES</figcaption></figure><p>The proxy now takes the data and pushes it to the kafka; hence, no direct ingestion happens in the ES. This ensures that we put the data in a very streamlined way to the elastic search without increasing any significant load. This provides a number of advantages, as listed below:<br>a) <strong>Batch write:</strong> We can have a batch write to the ES. As shown in the diagram, we can have one topic per elastic search cluster and make a bulk calls and make writes reducing the load.<br>b) <strong>Queuing</strong> of the write requests: In case Elasticsearch is overloaded, the requests can be queued and consumed at a specified pace. <br>c) <strong>Retries</strong>: if the cluster is down, we can retry easily<br>d) <strong>Read latency is not affected: </strong>The read latency is not affected in case of any increase in load.</p><p>Along with this, I want to discuss another service known as Backfill service which I came across while researching this blog. The main job of this service is too dump hundreds of terabytes of data into the ES. In ES, the indexing happens using a MapReduce job which is synchronous. ElasticSearch (ES) is not designed to handle that high ingestion in one shot. Now the indexing request is dumped to temporary storage and consumed asynchronously using similar workers as above. Twitter has implemented this very efficiently at scale. <br>So now, instead of directly dumping the data, the map-reduce job flushes it into a file system which can be any like S3 or HDFS, etc. Instead of writing this directly to the ES, now we have workers reading the data from the file system and pushing it to the ES. So here, massive ingestion occurs, solving the problem of ES, where is cannot take huge ingestion in one shot.</p><p><em>NOTE: The workers can be spun up dynamically by the orchasterator. For simplicity, I have shown only three.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bvf0zowSoWYrXOgjxP5Bng.png" /><figcaption>FINAL ARCHITECTURE DIAGRAM</figcaption></figure><p>The above diagram shows the final architecture. The main learning which we get here is that writes are always asynchronous, and the reads still happen in a synchronous manner. This provides a very seamless system; this is how we built a scalable system such that writes can happen eventually but let the reads happen synchronously. This is a way of ensuring that, at a scale, our ES cluster does not go down.</p><p>Before ending this blog, if you like and want to learn about the <strong>Kafka component</strong>, you can check out my other blog, where I explain in detail and implement a basic version. The link to that is <a href="https://medium.com/dev-genius/kafka-in-action-a-practical-guide-to-getting-started-with-kafka-7be5074a30c2"><strong>LINK</strong></a><strong>.</strong></p><p><strong>Thanks</strong> for reading; I hope it was helpful. If you want to discuss the topic more, connect over <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><em>LinkedIn</em></a>/ <a href="https://www.instagram.com/manav_706/"><em>Instagram</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fdf407a2d34" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/search-system-design-that-scales-2fdf407a2d34">Search System: Design that scales</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notification System: Design that scales]]></title>
            <link>https://blog.devgenius.io/notification-system-design-that-scales-361e03b1d9e0?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/361e03b1d9e0</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 15:19:15 GMT</pubDate>
            <atom:updated>2023-01-02T15:23:23.384Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing notification systems is a tough job and requires a lot of engineering brilliance to come into the picture, especially at scale. In this blog, I will go deep into <strong>scaling</strong> a notification backend service. We will discuss the different components necessary to scale the service and requirement of each item separately. <br><strong><em>Before moving ahead, I want you to think about why YouTube implemented a “Bell icon” for subscribers to receive notifications. </em></strong>I will answer this question at the end of this blog, so let’s jump in.</p><p>First of all, we need to understand about an <a href="https://medium.com/elixirlabs/event-bus-implementation-s-d2854a9fafd5">event bus</a>. An event bus is nothing but a component whose core job is to forward/exchange information whenever an event occurs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vyjihf_YU8AXzn-V.png" /><figcaption><a href="https://medium.com/elixirlabs/event-bus-implementation-s-d2854a9fafd5">https://medium.com/elixirlabs/event-bus-implementation-s-d2854a9fafd5</a></figcaption></figure><p>So this is what some notification service component looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYf8X8nkg42CFQ4xRYjRsw.png" /><figcaption>Basic Requirement</figcaption></figure><p>The design has an event bus that forwards the notifications to the notification service, which will push the notifications to all the users. Simple so far, isn’t it?<br>So what are the main features which a notification service should cater to? Those are push notifications, in-app notifications, email/ SMS service, etc. All these are just network calls (like a call to Mailchimp for email or SNS service for SMS) through an API, but the issue only is fanning out of the notifications. For example, let’s say a celebrity has millions of followers; how would your notifications reach a million people is where the real engineering challenge lies.</p><p>The next question before moving on to scale is after the user receives the notification, how will you handle “<strong>onclick</strong>”? By “onclick, I mean what happens when the client receives a notification. For example, when we get a notification from Instagram signifying that someone has sent us a message, when we click it, the message screen of the app opens. It&#39;s a good practice to send all this information because it&#39;s always beneficial to keep the client (frontend) dumb, as in all the instructions it should get from the backend. The simple reason for this is in case of any updates, the backend can be re-released any number of times, but once a frontend change is rolled out, generally, companies resist rolling multiple changes in close time-frames. So the app notification will look something like this:</p><pre>{<br>    &quot;userID&quot;: &quot;id&quot;,<br>    &quot;createdAt&quot;: &quot;datetime&quot;,<br>    &quot;title&quot;: &quot;string&quot;,<br>    &quot;description&quot;: &quot;string&quot;,<br>    &quot;metadate&quot;:{<br>        // json containing data like what to do onclick<br>        action: ....<br>    }<br>}</pre><p><strong>Key to a good design: </strong>Let the backend take all the load of sending the data that keeps the notification service as generic as possible. The core job of the frontend is to take action on the data sent by the back end.</p><p>Now, let’s jump straight into the design. Before that, I highly encourage you to have a basic understanding of <a href="https://medium.com/dev-genius/kafka-in-action-a-practical-guide-to-getting-started-with-kafka-7be5074a30c2">Kafka</a> or a publish-subscribe model. We will be using message queues in our design too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WB6yuXBlOwk4JBspWgjgtg.png" /><figcaption>High-level design</figcaption></figure><p>The above diagram is what we need to understand; by default, it looks scary isn’t it? Don’t worry; we will understand each component and its requirement. We can see a couple of message queues (for example, SQS) used in the design. The main purpose of the message queues is just that the necessarily authorized entity receives the message.</p><p>First, there is a Kafka component. Supposing you guys have a basic understanding of Kafka or have read my previous blog, we understand that Kafka has the limitation that if a consumer has ten partitions, only ten consumers can consume it. This makes an issue in parallelism because the number of consumers is limited to the number of partitions. <br><strong>This can become a choke point</strong>; why?<br>Let’s say our Kafka component is used for push notifications for the posts, and a famous personality with 30 million followers has posted. We deploy one consumer for delivering notifications for that post. Since it has 30 million followers, it will take a significant amount of time to fan out the notifications, and till this is done, our consumer is blocked, which adds extra pressure on Kafka. Hence, we do not need to use our Kafka component for fanning out. So our listener&#39;s job is to quickly pull the message from our Kafka and put them in the queue. This is because we can have hundreds of consumers in our message queue. Then we will push it to the fan-out workers, who push the notifications to the people. <br><strong>Then why is Kafka needed at all</strong>, instead of sending notifications directly to the fan-out workers using a message queue, isn&#39;t it? This is because many services can consume the same data from Kafka, like trending services, notification services, etc.</p><p><strong>Fan-out</strong> workers are the next main component. Its job is to go through the list of receivers and push them. They are always running, and it&#39;s a long-running process whose job is to pull the follower/ receiver list and push notifications to the next queue. It can take a long time(in minutes) to send notifications to millions of followers of a famous personality. <br>In case I have to implement a fan-out component, the following should be the list of features;<br>1) it should find the list of users to send the notification to. This can include a Db-query or a call to any other service for the same.<br>2) <strong>check</strong> if the receiver should get a notification. This includes cases of the receiver has switched off the notifications.<br>3) <strong>create</strong> a <strong>task</strong> and send the notification to the next message queue.<br>4) it should have a defined list of rules to send the notifications to. Let’s say some configured preference or sending notifications to people who are very inactive on the platform. It&#39;s like having a brain of its own. In a few company blogs which I read, I saw that this fan-out worker is split into multiple components, and some other component is doing this fanning-out stuff, but yeah, again, this depends on a use case.</p><p>So how this should happen is:<br>a) Make a <strong>SQL</strong> query or get the list of receivers. Getting data in <strong>batches</strong> should be preferred for a huge number<br>b) <strong>Filter</strong> out users based on preference or users who don’t need notifications. This is based on the rules like a user has a limit on daily notifications, is a very inactive user, or has a configured preference. <br>c) find users left after this, create a task and <strong>send</strong>.</p><p>Now the notification has reached the step where it can be forwarded to the final message queue and sent to the end user. Again, many new improvements can be made here, which I leave on your understanding and the use case. For a suggestion, it&#39;s like this last message queue is also distributed so that we can define different message queues according to some set priority of notifications. See, in the end, we want the notification to be sent with a minimal lag, and the most important members should receive it first. So all these schemes can be implemented in this section, where a software engineer&#39;s creativity comes in.</p><p>So we have come to the end of this blog; before ending I want to clarify that this is a very simple design and the systems are much more complex in production. But that is again dependent on the different use cases on how to design, but these are the minimum number of components required to design the system. <br>Now I hope you understand why it was a <strong><em>master stroke</em></strong> from the business point of view when Youtube implemented a “Bell” icon, which helps them regulate their notifications. To answer that in short, a bell icon, first of all, helps “Youtube” to send fewer notifications, and it also knows about the loyal fan base of a YouTuber and hence sends notifications only to that user. This “bell” icon feature must have saved them millions from a business point of view which they would have to spend on scaling the components otherwise.</p><p>Before ending this blog, if you like and want to learn about the <strong>Kafka component</strong>, you can check out my other blog, where I explain in detail and implement a basic version. The link to that is <a href="https://medium.com/dev-genius/kafka-in-action-a-practical-guide-to-getting-started-with-kafka-7be5074a30c2"><strong>LINK</strong></a><strong>.</strong></p><p><strong>Thanks</strong> for reading; I hope it was helpful. If you want to discuss the topic more, connect over <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><em>LinkedIn</em></a>/ <a href="https://www.instagram.com/manav_706/"><em>Instagram</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361e03b1d9e0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/notification-system-design-that-scales-361e03b1d9e0">Notification System: Design that scales</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka in Action: A Practical Guide to Getting Started with Kafka]]></title>
            <link>https://blog.devgenius.io/kafka-in-action-a-practical-guide-to-getting-started-with-kafka-7be5074a30c2?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be5074a30c2</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Sat, 24 Dec 2022 20:20:24 GMT</pubDate>
            <atom:updated>2022-12-26T21:21:46.498Z</atom:updated>
            <content:encoded><![CDATA[<p>What is Kafka, really?<br>This question has been disturbing me for the past week, and I think I now have enough knowledge to write about this fantastic piece of technology. So in this blog, I will discuss different <strong>Kafka components</strong> individually, leading us to a <strong><em>code walkthrough </em></strong>and, finally pros &amp; cons of it. It is essential to understand each component separately because I tried to understand them together, and it got confusing later.</p><p>To understand any technology, we must understand why it was created/ invented. Apache Kafka was originally developed at<strong> LinkedIn</strong> in 2010 as a means of handling high-volume, high-throughput, real-time data feeds. LinkedIn was looking for a way to handle the high volume of activity on its platform, which included user updates, relationship updates, and other data that needed to be processed in real-time. These activities could be categorized as events, right? An event can be called an indication in time that something took place. It&#39;s a little cumbersome to store events in databases simply because databases don’t scale very well with logs. Kafka is a way to manage these logs. In it, these events are called topics, and they can store for a short period of time or a long period of time. The topic is just an ordered collection of events that are stored durably.<br>Earlier trend was to use a monolithic architecture for building services, but now developers prefer <strong>microservices </strong>architecture, and hence Kafka comes in very handy when these separate services need to communicate. It is a message broker that allows producers to send messages to a central server, storing them in a highly distributed and fault-tolerant manner. Consumers can then retrieve the messages and process them in real time. <br>We will understand this in detail below.</p><h4>KAFKA COMPONENTS</h4><p>a) <strong>Kafka Broker: </strong>Kafka broker is the first server with which users interact. Since it’s a server, it has an exposed port (by default, 9092)and accepts a TCP connection. There are two sets of abstractions essentially in Kafka, one is producers and consumers, and the second is the TCP connection. Producers are the one which produce and publish content to the broker and the consumer who consumes it. Talking about connection, they are b-directional TCP connections, as the producer can send content to the broker and receive content from the broker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhIQiz1UfV3_v1hUDcxoMg.png" /><figcaption>Kafka</figcaption></figure><p>b) <strong>Kafka Topic: </strong>As the name implies, topics are the logical partitioning of messages(data)in the Kafka stream with identical data. When a producer writes, it needs to specify which topic it wants to write to and when the consumer consumes, it needs to specify which topic it wants to receive/ consume from.</p><p>c) <strong>Partitions: </strong>Next, let’s zoom in and see inside a topic. The producer pushes data inside a topic, but it has a limit, right? This is a similar scenario in databases; we have a limit on the amount of data a single server can hold. We initially address this by vertically scaling or adding storage to it. However, as we are all aware, vertical scaling has a limit. Once that point is reached, we must horizontally scale, which calls for the addition of more nodes and the division of the data among the nodes. This similar concept in Kafka is called partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFAyjX6Aju92OG2MybuvgQ.png" /><figcaption>Screenshot from Hussein Naseer’s blog</figcaption></figure><p>So in the introduction of partitions, as shown in the image, the producer needs to get which topic to write to and which partition to write to. The same goes for the consumer; it also needs to know from which partition to read. As shown in the image, if the producer wants to add “Nader” to the topic “Users,” it needs to use whatever algorithm(generally <a href="https://www.toptal.com/big-data/consistent-hashing#:~:text=according%20to%20Wikipedia).-,Consistent%20Hashing%20is%20a%20distributed%20hashing%20scheme%20that%20operates%20independently,without%20affecting%20the%20overall%20system.">Consistent Hashing</a>) was used to create partitions and find the correct partition. Since it finds the correct “topic,” it returns the position at which it is added to the producer. <br>A customer orders the messages they read from partitions. Therefore, if the numbers 1, 2, 3, and 4 were added to a topic, the consumer would still interpret it that way. Every message has an offset, so once a consumer reads a message, it puts the offset number onto Kafka to indicate that it was the most recent message the consumer read. As a result, if a consumer node fails, it can restart from where it left off after the previous read. Additionally, consumers may always change the offset position if they need to view earlier messages later.</p><p>d) <strong>Consumer Group: </strong>Consumer groups were invented to consume from different partitions and achieve parallelism. This can be confusing, so let’s understand the need for this.</p><p>We need to understand the concept of a Message Queue and a publish-subscribe(pub-sub) system for this. In short, if I say, a message queue is one where a message is published once and consumed once. <strong>In doing so, we want to ensure that the work is executed only once.</strong> In a pub/sub case, a message can be published once but consumed many times. <strong>Simply put, we want all our consuming (subscribing) applications to get <em>at least one</em> copy of the message that our publisher posts to an exchange. </strong>To understand message queues and pub/sub, please read this blog:<strong> </strong><a href="https://www.baeldung.com/pub-sub-vs-message-queues"><strong>Link</strong></a><strong>. </strong>Coming back, Kafka tried to solve the problem of getting both a message queue and pub/sub. The concept of CONSUMER GROUPS answered the answer to this topic.</p><p>A few interesting concepts here are:</p><ol><li><strong>Fan-out exchange</strong>: These exchanges provide the typical publish-subscribe topology. A message sent to a Fanout exchange will be broadcast to all queues and exchanges binding to the exchange. <br>Imagine you are developing an OTP service. You must now send an OTP by email and SMS. As a result, your OTP service may store the OTP in Kafka, after which your SMS service and email service users can receive the message and send out SMSes and emails as needed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsLY4vh9pNZxiWREmCOJDA.png" /></figure><p>2. <strong>Order guarantee: </strong>Now that a topic can be partitioned and multiple consumers can consume from the same topic, how do you maintain the order of messages on the consumer end, one might ask. Good question. Multiple consumers can not read one partition in the same consumer group. The consumer group enables this; only one consumer can read from a single partition. I’m taking the following explanation from a <a href="https://hackernoon.com/">hackernoon</a> article, which I will list below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*ZOKFGZpg4gR-Jm-B.png" /><figcaption><a href="https://miro.medium.com/max/1400/1*qt5_0YD9TSMLd3RywhivrA.webp">https://miro.medium.com/max/1400/1*qt5_0YD9TSMLd3RywhivrA.webp</a></figcaption></figure><blockquote>So your producer produces 6 messages. Each message is a key-value pair, for key “A” value is “1”, for “C” value is “1”, for “B” value is “1”, for “C” value is “2” ….. “B” value is “2”. (Please note that by key I mean the message key that we discussed earlier and not the JSON or Map key). Our topic has 3 partitions, and due to consistent hashing messages with the same key always go to the same partition, so all the messages with “A” as the key will get grouped and the same for B and C. Now as each partition has only one consumer, they get messages in order only. So the consumer will receive A1 before A2 and B1 before B2, and thus the order is maintained, tada 🎉. Going back to our logging system example the keys are the source node ID, then all the logs for node1 will go to the same partition always. And since the messages are always going to the same partition, we will have the order of the messages maintained.</blockquote><blockquote>This will not be possible if the same partition had multiple consumers in the same group. If you read the same partition in the different consumers who are in different groups, then also for each consumer group the messages will end up <strong><em>ordered</em></strong>.</blockquote><blockquote>So for 3 partitions, you can have a max of 3 consumers, if you had 4 consumers, one consumer will be sitting idle. But for 3 partitions you can have 2 consumers, then one consumer will read from one partition and one consumer will read from two partitions. If one consumer goes down in this case, the last surviving consumer will end up reading from all the three partitions, and when new consumers are added back, again partition would be split between consumers, this is called re-balancing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zvn1VHiaYgfGnKhw.png" /></figure><blockquote>This image depicts the idea of partitions, where a single topic has 4 partitions, and all of them hold a different set of data. The blocks you see here are the different messages in that partition. Let’s imagine the topic to be an array, now due to memory constraint we have split the single array into 4 different smaller arrays. And when we write a new message to a topic, the relevant partition is selected and then that message is added at the end of the array.</blockquote><blockquote>An offset for a message is the index of the array for that message. The numbers on the blocks in this picture denote the <strong>Offset, </strong>the first block is at the 0th offset and the last block would on the (n-1)th offset. The performance of the system also depends on the ways you set up partitions, we will look into that later in the article. (Please note that on Kafka it is not going to be an actual array but a symbolic one)</blockquote><p>So with this, Kafka serves our two important needs. So if we want it to act like a message queue, put all the consumers in one group, they will consume a message and move on. <br>If the requirement is of a pub/sub system, then put all the consumers who want to consume from the same partition in a topic in different groups. This is because, as explained above, a partition can be consumed by only one consumer in one group, but if two consumers are different groups, they can consume from the same partition. Hence partition is group-dependent. So what do we get as a result? We get parallel processing.</p><p><strong>DISTRIBUTED SYSTEM (Kafka cluster)<br></strong>Alright, this is the final thing, Kafka is distributed system. By that means, it follows some architecture (like a leader-follower or master-slave) to provide high availability and fault tolerance. It is also known as a <strong>cluster, which is </strong>a group of brokers working together. One of the brokers in a cluster works as the Controller, which basically assigns partitions to brokers and monitors for broker failure to do certain administrative stuff. In Kafka, there is a leader, and it has its followers which have essentially the same data as the leader. All the data writing is done to the leader which is propagated to the followers for consistency. In Kafka, there is also a concept of multiple leaders as in, for one partition in one topic, one broker is the leader, and for the other, the other broker is the leader. This is great because of having the ability to distribute at the partition level.</p><blockquote>So the main question is how the producer know which one is the leader. Here comes a <strong>Zookeeper. </strong>Kafka does not function without zookeeper even if we want to work with broker. Zookeeper works as the central configuration and consensus management system for Kafka. It tracks the brokers, topics, and partition assignment, leader election, basically all the metadata about the cluster.</blockquote><p>Now let’s dive into an example. Here is what we will do:<br>a) Spin up a zookeeper<br>b) Spin up a Kafka cluster (from docker)<br>c) Create a topic in nodejs (Kafkajs library)<br>d) Create a producer (nodejs) and consumer (nodejs)</p><blockquote>Incase the following does not work for you, for another working example using docker-compose file, please visit, official documentation of Kafkajs: <a href="https://kafka.js.org/docs/running-kafka-in-development">https://kafka.js.org/docs/running-kafka-in-development</a></blockquote><blockquote>You need to have a docker before starting. <a href="https://docs.docker.com/get-docker/">Install</a> it in case you don’t have one.</blockquote><p>a) Spin up Zookeeper: Write the following command in the terminal, and it will install and run zookeeper. In this, I have mapped my port 2181 to the same port as the default port for zookeeper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05NUXbkWfXcuO1C-hDKSBA.png" /></figure><p>b) Spin up a Kafka cluster: I will not have multiple Kafka brokers for demonstration purposes. So the following is the command to run a Kafka cluster; scary, isn’t it? Let’s learn what each of them means.</p><pre>docker run -p 9092:9092 --name kafka -e<br> KAFKA_ZOOKEEPER_CONNECT=manavgarg:2181 -e<br> KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://manavgarg:9092 -e<br> KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 -d confluentinc/cp-kafka</pre><p><strong>Line 1</strong>, we understand; it’s just mapping my port 9092 to Kafka’s default port 9092. From line 2, we begin with environment variables (-e).<br><strong>Line 2</strong>: It needs a zookeeper instance, so the command must specify the port on which it is running. In our case, it’s on the same machine; hence the system’s name is provided. <br><strong>Line 3: </strong>We need to specify the listener as there can be multiple. Also, we need to specify the protocol the connectors will use. We have a PLAINTEXT and SSL, which is for encrypted communication. We will use PLAINTEXT and specify only one port on which we are listening. <strong><br>Line 4: </strong>Zookeeper, by default, assume we have three instances, but since we only have one broker, we need to specify that.<strong> <br>Line 5: </strong>Finally, we provide the image name.</p><p>c) Let’s create our first topic:<br>First, in a new folder, we create a new nodejs project. After running “npm init -y” and installing kafkajs (npm install kafkajs), create a new file called topic.js.</p><pre>// https://kafka.js.org/<br>// In topic.js file<br>const Kafka = require(&quot;kafkajs&quot;).Kafka;<br><br>async function run() {<br>  const kafka = new Kafka({<br>    clientId: &quot;myapp&quot;,<br>    brokers: [&quot;manavgarg:9092&quot;], //array since can have multiple brokers<br>  });<br>  try {<br>    const admin = kafka.admin(); //need admin interface to create topics<br>    console.log(&quot;Connecting to kafka&quot;);<br>    await admin.connect(); //to connect<br>    console.log(&quot;Connected!&quot;);<br><br>    //create topics, it takes a name and number of partitions in each topic<br><br>    await admin.createTopics({<br>      topics: [  //Any number of topics can be created<br>        {<br>          topic: &quot;Users&quot;,<br>          numPartitions: 2,<br>        },<br>        {<br>            topic: &quot;Codes&quot;,<br>            numPartitions:3<br>        }<br>      ],<br>    });<br>    console.log(&quot;topic creation done!&quot;);<br>    await admin.disconnect();<br>  } catch (ex) {<br>    console.error(`Error occured: ${ex}`);<br>  } finally {<br>    process.exit(0);<br>  }<br>}<br>run();</pre><p>d) Then, we need a producer to produce messages. I will show a sample code. Comments in the code will help in understanding. <br>To run, use “node producer.js &lt;message&gt;”</p><pre>// https://kafka.js.org/<br>//in producer.js file<br>const Kafka = require(&quot;kafkajs&quot;).Kafka<br><br>const msg = process.argv[2];<br>run();<br>async function run(){<br>    try<br>    {<br>         const kafka = new Kafka({<br>              &quot;clientId&quot;: &quot;myapp&quot;,<br>              &quot;brokers&quot; :[&quot;manavgarg:9092&quot;]<br>         })<br><br>        const producer = kafka.producer(); //kafka producer<br>        await producer.connect()<br>        console.log(&quot;Connected!&quot;)<br><br>        const partition = msg.length&gt;10 ? 0: 1 //algo to divide it msg to partitions<br>        const result =  await producer.send({ //send command will publish message to the provided topic<br>            &quot;topic&quot;: &quot;Users&quot;,<br>            &quot;messages&quot;: [<br>                {<br>                    &quot;value&quot;: msg,<br>                    &quot;partition&quot;: partition<br>                }<br>            ]<br>        })<br><br>        console.log(`Send Successfully! ${JSON.stringify(result)}`)<br>        await producer.disconnect();<br>    }<br>    catch(ex)<br>    {<br>        console.error(`Something bad happened ${ex}`)<br>    }<br>    finally{<br>        process.exit(0);<br>    }<br><br><br>}</pre><p>e)Then, finally consumer is as shown. Please keep this running and start producing messages from the producer; they will be visible here on the terminal. To run it in a new terminal: write node consumer.js.</p><pre>// https://kafka.js.org/<br>// kafkajs provides long polling behind the scenes<br>// in consumer.js file<br><br>const { Kafka } = require(&quot;kafkajs&quot;);<br><br>run();<br>async function run() {<br>  try {<br>    const kafka = new Kafka({<br>      clientId: &quot;yourchoice&quot;,<br>      brokers: [&quot;manavgarg:9092&quot;],<br>    });<br><br>    const consumer = kafka.consumer({ groupId: &quot;Users&quot; }); //consume<br>    await consumer.connect();<br>    console.log(&quot;Connected!&quot;);<br><br>    await consumer.subscribe({ //There subscribe to the topics<br>      topic: &quot;Users&quot;,<br>      fromBeginning: true,<br>    });<br><br>    await consumer.run({<br>      eachMessage: async (result) =&gt; {<br>        console.log(<br>          `Message received ${result.message.value} on partition ${result.partition}`<br>        );<br>      },<br>    });<br>    //It will never end like producers and hence will always be connected and consume messages<br>  } catch (ex) {<br>    console.error(`error: ${ex}`);<br>  } finally {<br>  }<br>}</pre><p><strong>PROS/ CONS<br></strong>a) <strong>APPEND ONLY commit log</strong>: append-only log files record data changes that occur by writing each change to the end of the file. In this, we know where the end is, and we can go very fast to the end. <br>b)<strong> PERFORMANCE</strong>: It is very fast because of the log, which is append-only. Reading and writing occur very fast.<br>c) <a href="https://ably.com/topic/long-polling#:~:text=Rather%20than%20having%20to%20repeat,available%20or%20a%20timeout%20threshold"><strong>Long Polling</strong></a><br>d) <strong>Distributed<br>e) EVENT DRIVEN ARCHITECTURE: </strong>can implement a queue and pub/sub both at once<br>f) <strong>PARALLEL PROCESSING</strong></p><p><strong>CONS:<br></strong>a) Cannot use Kafka without a zookeeper. <br>b) Complex to install, configure and manage: It took me a whole weekend to set up and connect to zookeeper and write the above code. It wasn’t connecting to the zookeeper for weird reasons I don’t understand.</p><p><strong>CONCLUSION:<br></strong>Kafka provides many features, which without it would have been a nightmare to implement for many companies which use microservices architecture.</p><p>References:<br>a) <a href="https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works/?ref=hackernoon.com">Confluent blog<br></a>b) <a href="https://www.youtube.com/watch?v=TGKUYoegrDY&amp;list=PLxv3SnR5bZE82Cv4wozg2uZvaOlDEbO67">Youtube</a><br>c) <a href="https://www.baeldung.com/pub-sub-vs-message-queues">Pub/sub vs queue</a></p><p>Thanks for reading; I hope it was helpful. If you want to discuss the topic more, connect over <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><em>LinkedIn</em></a>/ <a href="https://www.instagram.com/manav_706/"><em>Instagram</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be5074a30c2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/kafka-in-action-a-practical-guide-to-getting-started-with-kafka-7be5074a30c2">Kafka in Action: A Practical Guide to Getting Started with Kafka</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ChatGPT and Its Revolutionary Implications]]></title>
            <link>https://blog.devgenius.io/understanding-chatgpt-and-its-revolutionary-implications-7d82e7cae5ec?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d82e7cae5ec</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[instructgpt]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 16:27:23 GMT</pubDate>
            <atom:updated>2022-12-28T13:22:55.055Z</atom:updated>
            <content:encoded><![CDATA[<p>We have all heard about Chatbots, right; they suck, and they are a joke. But what if a chatbot worked and understood and answer? Imagine having a program that can give you investment research, generate and debug code, and create a Twitter bot for you when you have no knowledge of coding, create a weight loss plan, mental health support, marketing, and SEO specialist, write essays, and much more. This is now a reality with a program named <a href="https://chat.openai.com/chat"><strong>ChatGPT</strong></a>, which was released on the 30th of November, 2022, and could turn the work of one man into the productivity of 10 men. In this blog, I will touch briefly on technology and what this could mean to the world at large.</p><p><strong>OpenAI</strong> (the company behind chatGPT) has received significant funding and support for its work on ChatGPT and other AI language models. In 2021, it raised $1 billion in a funding round led by <strong>Microsoft</strong>, which has been a critical partner in developing ChatGPT and other OpenAI projects. In addition to Microsoft, OpenAI has also received funding from other major tech companies and investors, including Nvidia, Sam Altman, and Elon Musk. Since its release, it has become an internet phenomenon, and in just five days of its release, it has crossed 1 million users. The ability to ask open-ended questions and receive a response that is not hand-coded has a market with virtually unlimited demand.</p><p><strong>HOW IT WORKS?<br></strong>ChatGPT is an improved version of <a href="https://openai.com/blog/gpt-3-apps/"><strong>GPT-3</strong></a>, which OpenAI calls GPT-3.5. GPT-3 is trained on billions of words on the internet, and when generating text, it tries to predict the next word in a given sentence. The issue with GPT-3 language models was that they could perform natural language tasks. Still, it did not filter untruthful, toxic words or reflect harmful sentiments. A technique called reinforcement learning from <strong>human feedback </strong>(RLHF) was used to make the models in GPT-3 safer. In short, they have added human feedback to the training process. In essence, during the training, multiple versions of responses were ranked by humans from best to worst, and when the AI improved itself, it was digitally rewarded. This data is used to fine-tune GPT-3. The resulting <strong>InstructGPT</strong> models are much better at following instructions than GPT-3. They also make up facts less often and show small decreases in toxic output generation. This method produces an AI language model that is a hundred times smaller than GPT-3 but performs better. The real breakthrough was the humans involved in the training process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3FNASDpimCNdcCptXq10g.png" /><figcaption><a href="https://openai.com/blog/instruction-following/">Method</a></figcaption></figure><p>First, a dataset of human-written demonstrations on prompts was submitted to an API and was used to train the supervised learning baselines. Next, a dataset of human-labeled comparisons between two model outputs on a larger set of API prompts was collected. Then the reward model (RM) on this dataset was trained to predict which output the labelers would prefer. Finally, they used this RM as a reward function and fine-tuned the GPT-3 policy to maximize this reward using the <a href="https://openai.com/blog/openai-baselines-ppo/">PPO algorithm</a>.</p><p>In the next graph, the Quality ratings of all the models in provided against the model size, and it is clear that InstructGPT wins with a clear margin. Compared to GPT-3, InstructGPT produces fewer imitative falsehoods (according to TruthfulQA17) and is less toxic (according to RealToxicityPrompts18).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Onunbvb6kMQ3sl2O2VHIkQ.png" /></figure><p>To get into more detail about the work and the results of the OpenAI organization on ChatGPT, please go to their <a href="https://openai.com/blog/instruction-following/"><strong>official blog</strong></a>. They have explained much about the model&#39;s working from a technical perspective.</p><p><strong>WHY THIS POPULARITY?<br></strong>Here I will provide some examples and let you be the judge.</p><p>a) Some users wrote on Twitter that chatGTP worked better than any mental health chatting interface they had used. An example screenshot is provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTfUEUr7Wt1_NwGkq9QNew.png" /><figcaption>Twitter screenshot</figcaption></figure><p>b) The following is an example of someone who mentors an individual with poor literacy skills. He created a GPT-powered Gmail account that converts his client’s poor writing to professional text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zICi2BmZDAAK-Wpk9AD-jw.png" /><figcaption>Twitter screenshot</figcaption></figure><p>c) Another example includes a user using chatgpt to get help with his health issue. Apparently, chatgpt could suggest a treatment plan based on past successes and failures of the patient’s problem and current problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJV3t1X3qfyb5G7YPrza7A.png" /><figcaption>Twitter screenshot</figcaption></figure><p>Another user asked AI to be its personal trainer. Given his weight and age, it calculated his energy expenditure, gave an explanation, and then asked how many calories he needed to lose every day to lose six kilograms. It then created a meal plan about how to achieve this in three months and how to cook it.</p><p>d) As a software engineer myself, I tried this on a few code problems myself to test it. Initially, I tried on a few simple front-end stuff, and the results were amazing. It provided me with the steps and a sample code that worked, but as the problem became, it started to provide wrong outputs with confidence. I tried a few leetcode medium-level questions, and they failed miserably, signifying this is definitely a help but not a replacement for software engineers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdxO-bYlQFWn2wGkiFvtaA.png" /><figcaption>Input (frontend Image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAFVqcp0liRWc6rS4671ig.png" /><figcaption>The output of the generated code (Frontend)</figcaption></figure><p>e) ChatGPT can form opinions on specific topics at a user’s request, which I think no search engine can do. But this is just the beginning; there is more than this. There has been a report that several people are using chatGPT to cheat on their exams. Hence as AI systems infiltrate society, pershaps critical thinking will be more valued.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IckGwrMQt3s1SrMq_XxyoQ.png" /><figcaption>Example screenshot</figcaption></figure><p><strong>WHY CAN’T WE HAVE IT ALL ON OUR SMARTPHONES?<br></strong>So the question is begging to be asked why can’t we all have this service on our smartphones at once? An ALPHABET employee, who attended the Google internal talk about large language models, revealed that these systems require huge computing power, and it can perhaps be free to a few million users. Still, it&#39;s just not feasible to scale it to the size of a billion requests per day. The service will be too expensive, and the latency will be too high. Currently, one AI search adds up to ten to a hundred times a cost of a normal google search. According to Sam Altman, the CEO of OpenAI, a cost of a single search is in single digits, and assuming it&#39;s 5 cents per search, and google carries out 8.5 billion searches per day, this would mean a bill of 425 million dollars per day.</p><p><strong>LIMITATIONS<br></strong>ChatGPT, no matter how interesting it looks, is still in its infancy stage. There have been many cases where it has provided wrong, rather dangerous explanations to the questions. This is the problem with any open-ended language model; it is hard to maintain due to its unpredictability. <br>There have been examples like AI creating or compiling a full website that looked like the New York Times. The AI would write the full articles using tweets as prompts. Another user decided to push the safety limits and asked the AI how to make a molotov cocktail, and it was able to provide a step-by-step process for doing so. This is obviously a violation of open ai’s content policy. Apart from this, there have been examples of failures in factual questions, like sometimes it hallucinated coherent but non-sensical answers; for example, one user asked which is heavier, one kilogram of beef or one kilogram of compressed air. The AI said that the beef weighs more and gave a confident explanation. Hence this is an example of why this thing should not be used for anything important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUAsxj9E6salQrbpd0KCbA.png" /><figcaption>Twitter screenshot</figcaption></figure><p>This one-kilogram mistake did not happen for me personally, but at large, that means this is how these language models work: they can say strange things at random points. ChatGPT sounds overly verbose when it says it is incapable of doing something, and the same question is asked in another way; it just goes ahead and does it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_goV0Y1072DlssRagNgfTQ.png" /><figcaption>Wrong answer (ChatGPT explaining Abacus is faster than GPU)</figcaption></figure><p><strong>WHAT ABOUT HUMANS</strong>?<br>We can see professional artists beginning to panic as AI-generated art is very hard to distinguish from professional art. This might lower the market value of art by increasing supply. Next white-collar jobs might be in danger because as AI improves, there is a high chance that fewer workers would be needed in multiple fields. <br>As far next new companies are concerned, they can use these large AI models and tune them for their purposes, like medicine, law, etc. This was said by Sam Altman, CEO of OPEN AI systems, that there will be a few companies that will be training/ controlling the large model AIs. The same AI that understands 98% of whatever is asked has general knowledge and reasoning; it can understand the world and its events. On top of this base layer, new startups will use this base layer to provide power in their specific industries. They can tweak the base layer to become the king of their particular field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsgC07fDW-_C5j3v2ean3Q.png" /><figcaption>Explanation screenshot from Coldfusion youtube channel</figcaption></figure><p>But all this once said, I don’t think AI can beat humans at everything. There are just some things which we need humans for.</p><p><strong>CONCLUSION<br></strong>So, in conclusion, ChatGPT is limited, get’s things wrong, and is unfeasible at a large scale right now, but clearly, it is a peak into the future. It has shown promise and clear signs for a multi-billion dollar industry to arise. If Microsoft, the largest funder in the project, finds a way to scale the system and integrate it into the Bing search browser, it might not be a very good sign for Google. Again, all that said, this can be seen as major breakthrough, and we are surpassing the information age and entering the knowledge age.</p><p>Thanks for reading; I hope it was helpful. If you want to discuss the topic more, connect over <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><em>LinkedIn</em></a>/ <a href="https://www.instagram.com/manav_706/"><em>Instagram</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d82e7cae5ec" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-chatgpt-and-its-revolutionary-implications-7d82e7cae5ec">Understanding ChatGPT and Its Revolutionary Implications</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layer-4 Load Balancers and Layer-7 Load Balancers]]></title>
            <link>https://blog.devgenius.io/layer-4-load-balancers-and-layer-7-load-balancers-4be18abfa47b?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be18abfa47b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 19:20:43 GMT</pubDate>
            <atom:updated>2022-12-28T13:22:45.952Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog covers the difference between layer-4 load balancers and layer-7 load balancers. It is critical to understand the basic concepts of networking before reading this.</p><blockquote><strong>Load balancing</strong> refers to efficiently distributing incoming network traffic across a group of backend servers, also known as a <em>server farm</em> or <em>server pool</em>. Modern high‑traffic websites must serve hundreds of thousands, if not millions, of concurrent requests from users or clients and return the correct text, images, video, or application data, all in a fast and reliable manner. Modern computing best practice generally requires adding more servers to scale to meet these high volumes cost-effectively scale.A <strong>load balancer</strong> acts as the “traffic cop” sitting in front of your servers and routing client requests across all servers, capable of fulfilling those requests in a manner that maximizes speed and capacity utilization and ensures that no one server is overworked, which could degrade performance. The load balancer redirects traffic to the remaining online servers if a single server goes down. When a new server is added to the server group, the load balancer automatically sends requests.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BN3WyxHwigDwbTI7m8jGRQ.png" /></figure><p>A load balancer is one case of a reverse proxy where it has a balancing logic implemented in it. Layer-4 is the transport layer in the <a href="https://www.geeksforgeeks.org/layers-of-osi-model/">OSI model</a>, and layer-7 is the Application layer.</p><figure><img alt="OSI MODEL" src="https://cdn-images-1.medium.com/max/248/1*P6AQzxikOGgy-y-Ddy5UIA.png" /><figcaption>OSI MODEL</figcaption></figure><h4><strong>LAYER-4 LOAD BALANCER</strong></h4><p>A layer-4 load balancer has an established connection with the back-end and sends the data to the dedicated back-end for the particular request and gets the response back. As we understand from the OSI model, layer 4 has the ports, IP addresses, and data that are just segments that should not be touched. So, this behaves like a hop in the middle, which sends the request to a back-end depending on the algorithm used for routing the request. All the connections here are the TCP connections with the client connected to the Load balancer and the load balancer to the back-end.</p><p><strong>PROS<br></strong>a) Simple Load balancing: It does not look up the data; it&#39;s just the ports and the IP addresses. As its forwards the request and no data lookup, it&#39;s more efficient. <br>b) More Secure: Again, since there is no data lookup, it is much more secure than layer 7. <br>c) Works with any protocol: Since it does not look at the content, it&#39;s agnostic. That is, it sends the data and receives a response.</p><p><strong>CONS</strong>: <br>a) No smart load-balancing: There is no smart load-balancing because we are not looking at the data. Any smart decisions based on the data, let&#39;s say that any request to a back-end with multiple APIs one of them is very heavy and time-consuming; it can&#39;t be isolated for a separate back-end. <br>b) No Caching: No data lookup, no caching.<br>c) It must be sticky because it is a stateful protocol. When a connection is made, it is sent to one back-end server. Through this connection, every packet is sent to a single server. The next connection will pick a different server in accordance with the algorithm.<br>d) Microservice architecture implementation becomes very hard.</p><h4>LAYER-7 LOAD BALANCER</h4><p>In the case of a layer 7 load balancer, the load balancer becomes protocol specific. When a client connects to the load balancer, it tries to understand the request. All this happens in layer 7 of the OSI model; hence, the full request module is available.</p><blockquote><strong>Layer 7 load balancing</strong> operates at the high‑level <em>application</em> layer, which deals with the actual content of each message. HTTP is the predominant Layer 7 protocol for website traffic on the Internet. Layer 7 load balancers route network traffic in a much more sophisticated way than Layer 4 load balancers, particularly applicable to TCP‑based traffic such as HTTP. A Layer 7 load balancer terminates the network traffic and reads the message within. It can make a load‑balancing decision based on the content of the message (the URL or cookie, for example). It then makes a new TCP connection to the selected upstream server (or reuses an existing one, by means of <a href="https://www.nginx.com/blog/http-keepalives-and-web-performance/"><strong>HTTP keepalives</strong></a>) and writes the request to the server.</blockquote><p><strong>PROS</strong>:<br>a) Smart load-balancing: Since we have the final data available here, we can understand the load balance accordingly. for example, if we are going to /v1/posts, go to the backend one; in case of /v1/comments, go to the backend two; and in case of /v1/messages, go to the backend three. <br>b) Caching: Since the data is available<br>c) Great for microservices<br>d) Authentication or API Gateway logic can be done within the load balancer.</p><p><strong>CONS</strong>:<br>a) Expensive (looks at the data): Because it&#39;s doing more work. It&#39;s buffering, it&#39;s reading, it&#39;s decrypting, so it&#39;s more, it&#39;s more expensive.<br>b) Decrypts and hence terminates TLS. So there is a need to have the SSL certificates stored on the load balancer. <br>c) Again, it must share a TLS certificate.<br>d) Needs to understand the protocol.</p><p><a href="https://www.nginx.com/resources/glossary/layer-7-load-balancing/"><strong>AN EXAMPLE :</strong></a><strong><br></strong>Let&#39;s look at a simple example. A user visits a high‑traffic website. Over the course of the user&#39;s session, they might request static content such as images or video, dynamic content such as a news feed, and even transactional information such as order status. Layer 7 load balancing allows the load balancer to route a request based on information in the request, such as what kind of content is being requested. So now, a request for an image or video can be routed to the servers that store it and are highly optimized to serve multimedia content. Requests for transactional information, such as a discounted price, can be routed to the application server responsible for managing to price. With Layer 7 load balancing, network and application architects can create a highly tuned and optimized server infrastructure or <a href="https://www.nginx.com/resources/glossary/application-delivery/"><strong>application delivery</strong></a> network that is both reliable and efficiently scales to meet demand.</p><h3>Load Balancing Algorithms (Extra)</h3><p>Different load balancing algorithms provide different benefits; the choice of load balancing method depends on your needs:</p><ul><li>Round Robin — Requests are distributed across the group of servers sequentially.</li><li>Least Connections — A new request is sent to the server with the fewest current connections to clients. The relative computing capacity of each server is factored into determining which one has the least connections.</li><li>IP Hash — The IP address of the client is used to determine which server receives the request.</li><li>URL Hash — This ensures that client requests to a particular URL are always sent to the same back-end server.</li></ul><p>Here I am listing some resources for a better understanding of load balancers or back-end in general:<br>a) <a href="https://www.nginx.com/resources/glossary/layer-4-load-balancing/">Layer 4</a><br>b) <a href="https://www.nginx.com/resources/glossary/layer-7-load-balancing/#:~:text=Layer%207%20load%20balancing%20allows,to%20serve%20up%20multimedia%20content.">Layer 7</a><br>c) <a href="https://www.youtube.com/@hnasr">Youtube channel for back-end engineering</a><br>d)<a href="https://cloud.google.com/load-balancing/docs/ssl-certificates"> SSL certificates</a><br>e) <a href="https://docs.nginx.com/nginx/admin-guide/load-balancer/">https://docs.nginx.com/nginx/admin-guide/load-balancer/</a><br>f) <a href="https://medium.com/@itIsMadhavan/what-is-load-balancer-and-how-it-works-f7796a230034">Load Balancers</a><br>g) <a href="https://www.udemy.com/course/nginx-crash-course/">Introduction to Nginx</a>: Excellent paid course for practically implementing load balancing</p><p>Thanks for reading; I hope it was helpful.<br>In case of any further doubts, feel free to connect over <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><em>LinkedIn</em></a>/ <a href="https://www.instagram.com/manav_706/"><em>Instagram</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be18abfa47b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/layer-4-load-balancers-and-layer-7-load-balancers-4be18abfa47b">Layer-4 Load Balancers and Layer-7 Load Balancers</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sync/Async Programming]]></title>
            <link>https://blog.devgenius.io/sync-async-programming-2a6bf8e99c68?source=rss-dcb26a4c1055------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a6bf8e99c68</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[client-server]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Manav Garg]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 13:38:53 GMT</pubDate>
            <atom:updated>2022-12-28T16:43:59.874Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this blog, I try to explain best what synchronous and asynchronous programming is.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*UBZ3KMuac0GPtCzmi9ox5A.png" /><figcaption>Sync/Async</figcaption></figure><p>If a caller sends a message to a receiver and is waiting for a response, can it do something else? I am saying a caller/receiver instead of a server/client, as these calls happen everywhere. By design, when we first built computing, everything was synchronous. This can be seen as a sine wave where a caller and a server are in sync or the same rhythm. Asynchronous means they are not in sync.</p><blockquote><strong>Synchronous I/O</strong><br>The caller sends the request to the receiver and then blocks it. This is when the caller is blocked, not doing anything, and hence a total time waste. In the old days, the CPU removed the process from the processor, thinking it is just blocked, and added a new process that is not blocked (Context switching). So the caller cannot execute in the meanwhile. Finally, when the receiver responds, the Operating system can put the process back to the processor. Hence the caller unblocks. This shows how the client and the server are entirely in sync.</blockquote><p><strong>Example of OS Synchronous I/O:</strong><br>1. Program asks the CPU to read a file from the disk.<br>2. Program’s main thread is taken off the CPU.<br>3. Read completes, and the program starts executing again.</p><pre>// A simple Js example<br>// Program starts<br>// Programs uses CPU to execute work.<br><br>SampleFunction();<br>// Program reads from the disk<br>// Program can&#39;t do anything until file loads<br>readfile(&quot;SyncExample.dat&quot;)<br><br>// Program resumes</pre><blockquote><strong>Asynchronous I/O</strong><br>The caller sends the request to the receiver and can work until it gets the response. But now the main question is how to know when it gets the response. Here are two choices, <br>a) The caller can check when the response is ready. This is very popular in Linux, known as <a href="https://en.wikipedia.org/wiki/Epoll"><strong>epoll</strong></a>. This is where the caller checks again and again if the response is ready.<br>b) The receiver calls back when it&#39;s done. This is where in windows, there are I/O completionist ports (<a href="https://en.wikipedia.org/wiki/Input/output_completion_port">IOCP</a>), or in Linux, it is io-uring. It works on the mechanism of a completionist queue where the receiver writes when the things are done.</blockquote><p>Talking specifically from the point of NodeJs, it uses epoll in Linux, and in the case of windows, it uses a completionist stack. Another thing that nodeJs does is spins up a new thread that blocks in case something requires to do a blocking operation. By default, Nodejs has 4 worker threads in <a href="https://libuv.org/"><em>libuv</em></a> library, which it uses for I/O operations, but it&#39;s configurable.</p><p><strong>Example of an OS asynchronous call (NodeJS)<br></strong>a) Program spins up a secondary thread<br>b) the Secondary thread reads from the disk. Obviously, OS removes from the current processor<br>c) the Main program still runs and executes. <br>d) Thread finishes and calls the main thread.</p><pre>// A simple Javascript example<br>// Program starts<br>// Programs uses CPU to execute work.<br><br>SampleFunction();<br>// Program reads from the disk<br>// Program hapilly moves on to the samplefunction2<br>readfile(&quot;SyncExample.dat&quot;, onReadFinish(console.log))<br>//file is not probably read yet<br><br>SampleFunction2();<br>//onReadFinish function called<br>// executing it</pre><h4><strong>Synchronous v/s Asynchronous in Request Response</strong></h4><p>Now we are going to discuss things purely from the perceptive of a client and server (backend). <br>So synchronicity can also be known as a client property where it can wait or move on. Nowadays, no client is synchronous, and most libraries are asynchronous. Mostly client sends the request, and it gets a response, and some callback is getting called whenever the response is getting executed. So in Node.js specifically, there is an event loop main loop that checks out for the response. <br>This can be confusing, as it was always for me when someone explained it with this beautiful real-life example that synchronous is like asking a question in a meeting where the meeting will move on if the presenter responds. Asynchronous is like asking a question in an email which can be responded to whenever the receiver gets time.</p><h4><strong>Asynchronous backend Processing</strong></h4><p>Being a backend engineer, it would be unfair if I don’t talk about making the backend asynchronous. In many code/ repositories, the client is primarily asynchronous, but the backend still makes it wait. So when a client requests to push some data, let’s say to do a database call, many times it&#39;s asked to wait for the response from the backend, which returns a status 200 response after the commit. Now, if we move out the lens to the backend, the frontend is asynchronous, but the back end is still synchronous. So how do we return an immediate response?<br>One of the solutions is to use this beautiful data structure, named a queue. If a client sends a request, we will not promise to execute it immediately, but we will flush it into the queue. The reason for this is that the backend might be completing the previous requests, and the client is not blocked anymore; we can send the response that we have queued the request, and here is a promise/JobID. For more information, you can read about <strong><em>message queues</em></strong>.<br>There are very popular solutions apart from this, depending on the use case.</p><p>A real-world example of an Asynchronous workload:<br>a) Asynchronous commits in Postgres <a href="https://www.postgresql.org/docs/current/wal-async-commit.html">↗</a>.<br>b) Asynchronous I/O in Linux (io-uring).<br>c) Asynchronous I/O fsync (fs-cache): Whenever we write something to any file, it is not directly written to disk but to the file system cache. There is a cache in the Operating system, and the writes go into pages. And then, the operating system flushes all the pages in one go.</p><p>We can summarise the entire thing as follows:<br>a) The synchronous programming approach executes tasks sequentially. Each task is carried out after it has waited for any preceding task to finish.<br>b) When a task is run in an asynchronous programming model, we can move on to another without waiting for the previous one to finish.</p><p>Thanks for reading; I hope it was helpful. <br>In case of any further doubts, feel free to connect over <a href="https://www.linkedin.com/in/manav-garg-b00963182/"><em>LinkedIn</em></a>/ <a href="https://www.instagram.com/manav_706/"><em>Instagram</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a6bf8e99c68" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/sync-async-programming-2a6bf8e99c68">Sync/Async Programming</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>