<?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 Sunandanbose on Medium]]></title>
        <description><![CDATA[Stories by Sunandanbose on Medium]]></description>
        <link>https://medium.com/@sunandanbose17?source=rss-4f70a5247ac3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-_EBxSXZqrY_APnZ</url>
            <title>Stories by Sunandanbose on Medium</title>
            <link>https://medium.com/@sunandanbose17?source=rss-4f70a5247ac3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:28:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sunandanbose17/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[The Hidden Conversations Behind AI Agents]]></title>
            <link>https://medium.com/@sunandanbose17/the-hidden-conversations-behind-ai-agents-7dd7987b8a59?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd7987b8a59</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agent-orchestration]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 13:33:35 GMT</pubDate>
            <atom:updated>2026-06-17T13:33:35.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qg97st-gEUznXfabExvx0w.png" /></figure><p>AI is reshaping the software development lifecycle at a pace few of us anticipated. Keeping up with this rapid evolution and the ever-growing list of new concepts can feel like a challenge in itself.</p><p>Today, I want to capture one of my recent learnings: understanding the relationship between <strong>LLMs, Agents, and MCP (Model Context Protocol)</strong>, and how these pieces come together to form the foundation of modern AI systems. It’s a fascinating ecosystem that is changing the way applications think, reason, and interact with the world around them.</p><h3>Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHzgXmaA07De35CIfwUmPQ.png" /></figure><p>Most of us are already familiar with <strong>LLMs</strong>. To keep things simple, think of an <strong>LLM as the brain. </strong>It can understand language, reason through problems, and generate responses.</p><p>An <strong>Agent</strong> is the body that brings those thoughts into action. While the LLM decides <em>what</em> should be done, the Agent is responsible for <em>doing</em> it. To accomplish tasks, the Agent collaborates with both the LLM and external tools exposed through <strong>MCP servers</strong>.</p><p>A key thing to remember is that agents are usually designed with a purpose. Some specialize in searching the web, others generate images, analyze documents, write code, or automate workflows. Rather than being good at everything, each agent is optimized to perform a specific set of tasks effectively.</p><h3>MCP</h3><p>If the <strong>LLM is the brain</strong> and the <strong>Agent is the body</strong>, then <strong>MCP is the bridge that connects the body to the outside world</strong>.</p><p>An LLM, by itself, only knows what it was trained on. It cannot magically access your database, read a file, search the internet, or interact with business systems. That’s where MCP comes in.</p><p>For example, one MCP server might provide access to a company’s knowledge base, another might expose GitHub repositories, and a third might allow image generation. The agent doesn’t need to know the implementation details it only needs to know how to speak the MCP language.</p><p>In simple terms, <strong>MCP is becoming the USB-C of the AI world</strong>: a common standard that allows agents to connect with tools and data seamlessly.</p><p>While MCP is becoming a popular standard for exposing tools to AI systems, agents can also interact with APIs and services directly. MCP simply provides a common language that makes these integrations easier to standardize and reuse.</p><h3>Rise of Agent-Driven Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4TMEPt6vSJK8gHlUDfwPw.png" /></figure><p>There was a time when building software primarily meant creating services and exposing APIs for other applications to consume. Thankfully, that part hasn’t changed. What has changed is <strong>how users interact with those services</strong>. Instead of navigating multiple applications or calling APIs directly, we are now building intelligent agents on top of these systems. These agents combine the reasoning power of <strong>LLMs</strong>, the connectivity of <strong>MCP</strong>, and the precision of <strong>prompt engineering</strong> to orchestrate services and deliver exactly the answer a user is looking for.</p><p>For example, imagine a query, <em>“Plan a 5-day trip to Vietnam under ₹80,000 and book the best available flights.”</em> Instead of manually searching travel websites, comparing prices, and creating an itinerary, a SkyScanner agent can use MCP connected travel services or other travel services Agent, retrieve flight information, evaluate options using an LLM, and present a personalized travel plan all through a single conversation. The underlying services still exist, but the interaction has become far more natural and intelligent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYBShG35k_nDKfCbjdaa7w.png" /></figure><p>The above use case we’ve all used these features. As a user, it’s easy to feel privileged. AI is simplifying everyday tasks, reducing effort, and making technology more accessible than ever. But as developers, the feeling is often a mix of excitement and anxiety. Excitement because the possibilities are expanding rapidly and the tools we build can now solve problems that once seemed impossible. Anxiety because the landscape is evolving at an incredible pace, and keeping up with the constant stream of new frameworks, protocols, and ideas can sometimes feel like a full-time job in itself. So lets dig a little deep into the implementation.</p><h3>Orchestrating AI Agents</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsH36lMBoHGFnCrqf2BX1Q.png" /></figure><p>So now, we’ll explore <strong>Agents </strong>how a simple agent works, how agents communicate with each other through <strong>A2A (Agent-to-Agent)</strong> interactions, and how multiple specialized agents can be orchestrated to solve complex problems. By combining the reasoning of LLMs with coordinated agent workflows, we can build systems that deliver intelligent and highly customized outcomes.</p><h4>A Simple Travel Agent</h4><p>Let’s build a simple travel agent that can answer a query like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV5llwKlb7Mf38ubReJRgg.png" /></figure><blockquote>“Give me the cheapest flight from Bangalore to Delhi for tomorrow.”</blockquote><p>At a high level, the agent follows three steps:</p><ol><li>Understand the user’s intent.</li><li>Convert the query into a format understood by the Flight Search API.</li><li>Call the API and present the result in a user-friendly way.</li></ol><p>Instead of forcing users to follow a strict format, we let the LLM normalize and optimize the query.</p><pre>user_query = &quot;Give me the cheapest flight from Bangalore to Delhi for tomorrow&quot;<br><br>prompt = f&quot;&quot;&quot;<br>Extract flight search parameters:<br><br>Query: {user_query}<br><br>Return:<br>source<br>destination<br>date<br>sort_by<br>&quot;&quot;&quot;</pre><p>The LLM converts the request into a structured format:</p><pre>{<br>  &quot;source&quot;: &quot;BLR&quot;,<br>  &quot;destination&quot;: &quot;DEL&quot;,<br>  &quot;date&quot;: &quot;2026-06-18&quot;,<br>  &quot;sort_by&quot;: &quot;price&quot;<br>}</pre><pre>response = flight_search_api(<br>    source=&quot;BLR&quot;,<br>    destination=&quot;DEL&quot;,<br>    date=&quot;2026-06-18&quot;,<br>    sort_by=&quot;price&quot;<br>)</pre><p>Output:</p><pre>[<br>  {<br>    &quot;airline&quot;: &quot;IndiGo&quot;,<br>    &quot;departure&quot;: &quot;06:15 AM&quot;,<br>    &quot;price&quot;: 4899<br>  },<br>  {<br>    &quot;airline&quot;: &quot;Akasa&quot;,<br>    &quot;departure&quot;: &quot;07:25 AM&quot;,<br>    &quot;price&quot;: 5299<br>  }<br>]</pre><p>User sees: (Agent converts the raw API response into something meaningful for the user, using prompting to the LLM again)</p><pre>The cheapest flight from Bangalore to Delhi tomorrow is IndiGo at 6:15 AM, priced at ₹4,899.</pre><p>Notice how the flight search service hasn’t changed. The magic lies in the agent’s ability to understand natural language, optimize the request, interact with the service, and present the answer in a conversational manner. This is the essence of an AI agent.</p><h3>Agents talk to Agents:</h3><p>Now that we’ve seen how a single agent works, imagine having an <strong>orchestrator agent</strong> that can talk to multiple travel agents of different company and with other agents where one specializing in discounts, and a third in hotel stays and then recommend the best option. Instead of relying on a single source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wk70QSklNTFBzSjlwa1e2Q.png" /></figure><p>But how do these agents discover and communicate with each other? This is where <strong>A2A (Agent-to-Agent)</strong> communication comes in. A2A is an emerging standard but isn’t a new transport protocol like REST or GraphQL. Rather, it defines a common set of conventions that allow agents to find, understand, and interact with other agents. One of the key concepts is the <strong>/.well-known/agent.json</strong> file. Think of it as an agent&#39;s digital business card. It contains metadata describing the agent its name, capabilities, supported actions, authentication requirements, endpoints, and other details. When an agent wants to collaborate with another agent, it can first read this file to understand what the target agent can do and how to communicate with it, enabling seamless interoperability across different agent ecosystems.</p><p>Install the libraries:</p><pre>pip install a2a-sdk fastapi uvicorn</pre><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/.well-known/agent.json&quot;)<br>def get_agent_card():<br>    return {<br>        &quot;name&quot;: &quot;ABC Flight Search Agent&quot;,<br>        &quot;description&quot;: &quot;Finds the cheapest flights across airlines.&quot;,<br>        &quot;version&quot;: &quot;1.0.0&quot;,<br>        &quot;endpoint_url&quot;: &quot;http://localhost:8000/a2a/v1&quot;,<br>        &quot;skills&quot;: [<br>            &quot;flight-search&quot;,<br>            &quot;fare-comparison&quot;<br>        ],<br>        &quot;supported_interfaces&quot;: [<br>            {<br>                &quot;protocol&quot;: &quot;JSON-RPC&quot;,<br>                &quot;version&quot;: &quot;2.0&quot;<br>            }<br>        ]<br>    }<br><br>@app.post(&quot;/a2a/v1&quot;)<br>async def flight_search_api(request: Request):<br> # code</pre><p>When another agent discovers this endpoint, it knows:</p><ul><li>What this agent does.</li><li>What skills it offers.</li><li>Where requests should be sent.</li><li>How communication should happen.</li></ul><p>For example, an Travel <strong>Orchestrator Agent</strong> could discover multiple agents:</p><pre>Travel Planner Agent<br>    ├── MMT Flight Search Agent<br>    ├── Yatra Flight Search Agent<br>    ├── GoIbibo Flight Search Agent<br>    ├── Ixigo Flight Search Agent <br>    ├── Airbnb Hotel Search Agent<br>    └── Travel Coupons Discount Agent</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3fwkn_rwDHOnnxeVR8KiQ.png" /></figure><p>The orchestrator first reads the /.well-known/agent.json file of each agent, understands their capabilities, and then delegates tasks accordingly.</p><p>The orchestrator acts as the <strong>manager of agents</strong>. It maintains a registry of available agents and their capabilities by reading their Agent Cards during registration. It builds a catalog of who is good at what flight search, hotel booking, discounts, weather information, and so on.</p><p>When a user query arrives, the orchestrator doesn’t blindly call every agent. Instead, it sends the user’s request along with the list of registered agents and their skills to an LLM. The LLM analyzes the intent and returns a structured response indicating which agents should be invoked.</p><pre>def register_agent(self, discovery_url: str):<br>        &quot;&quot;&quot;Fetches the official A2A Agent Card to dynamically map capabilities.&quot;&quot;&quot;<br>        try:<br>            response = requests.get(discovery_url)<br>            response.raise_for_status()<br>            card = response.json()<br>            <br>            agent_name = card[&quot;name&quot;]<br>            self.registry[agent_name] = {<br>                &quot;endpoint&quot;: card[&quot;endpoint_url&quot;],<br>                &quot;skills&quot;: card[&quot;skills&quot;],<br>                &quot;format&quot;: card.get(&quot;required_format&quot;, &quot;text&quot;)<br>            }</pre><pre>def route_query(self, user_query: str) -&gt; str:<br>        agent_manifest = &quot;&quot;<br>        for name, data in self.registry.items():<br>            agent_manifest += f&quot;- Agent Name: {name}, Specialized Skills: {data[&#39;skills&#39;]}\n&quot;<br><br>        router_instruction = f&quot;&quot;&quot;<br>        You are an elite Travel Agent Orchestrator Routing system. Analyze the incoming user query <br>        and select the best agent from the manifest below to answer it.<br>        <br>        Available Agent Manifest:<br>        {agent_manifest}<br>        <br>        You must think step-by-step:<br>        1. Identify the core subject of the user&#39;s request (e.g., flight, train, hotel, place).<br>        2. Match that subject to the agent with the closest matching specialized skills.<br>        3. Output your final choice in a line by itself formatted exactly like this: [CHOICE: Agent Name]<br>        If no agent fits, output: [CHOICE: NONE] <br>        If agent fits, output: [CHOICE: &quot;MMT Flight Search Agent&quot;, &quot;Yatra Flight Search Agent&quot;]<br>        &quot;&quot;&quot;</pre><p>The orchestrator then parses this response and delegates the task only to the relevant agents.</p><pre>agent_selection = llm.select_agents(<br>    query=user_query,<br>    available_agents=registered_agents<br>)<br><br>for agent in agent_selection[&quot;agents&quot;]:<br>    response = invoke_agent(agent, user_query)</pre><p>This pattern keeps the system scalable. As new agents are added, the orchestrator doesn’t need hardcoded routing logic. The LLM dynamically decides which agents are best suited for a given request, making the entire ecosystem flexible and intelligent.</p><p><strong><em>Note:</em></strong><em> The examples in this article are intentionally simplified to explain the concepts. Real-world Agentic AI systems can be significantly more complex depending on scale, security, and business requirements.</em></p><h3>Wrapping Up</h3><p>This was a small learning journey that I wanted to share with all of you. As a developer, I’m still learning, experimenting, and trying to keep pace with how quickly the AI landscape is evolving. Every week seems to bring a new framework, protocol, or idea and that’s both the exciting and challenging part of being in tech today.</p><p>If any of these thoughts resonate with you, or if you’re exploring Agents, MCP, A2A and Agentic AI yourself, feel free to reach out. I’d be happy to exchange ideas, learn from your experiences, or discuss the simple agent application we walked through in this article.</p><p>Until then, it’s time for me to move on to the next item on my ever-growing learning to-do list.</p><p><strong>See you in the next learning adventure.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wY0afllFjCVkSgiITGhxJA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd7987b8a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Developer’s New Role: From Coder to AI Manager]]></title>
            <link>https://medium.com/@sunandanbose17/the-developers-new-role-from-coder-to-ai-manager-64afecab3eb0?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/64afecab3eb0</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 17:43:06 GMT</pubDate>
            <atom:updated>2025-09-24T17:43:59.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2ognSfPTMvMAa75o0teqA.png" /></figure><p>Once, my job was my hands. My world was defined by tools like IntelliJ, Eclipse, and VS Code. I was a craftsman, spending my days in a workshop of code. I’d carefully debug lines, fix tangled knots in a project, and build everything from scratch. It was a hands-on life.</p><p>Then, a new tool arrived: Cursor. It was like bringing in a new intern, but this one was brilliant. Suddenly, I wasn’t just working; I was supervising. Cursor handled the small, messy jobs, the tedious setups, and the endless debugging. My hands were free. My role had changed from a maker to a manager. This shift is reshaping our world, and it’s all thanks to the revolutionary Model Context Protocol (MCP).</p><h3><strong>Lets have a intro of the “AI WORLD”</strong></h3><p><strong>Cursor AI:</strong></p><p>Think of it as a familiar friend who’s learned some new tricks. It’s a code editor built on top of VS Code — a forked version, to be precise. It has all the features you love about VS Code, but it’s been supercharged with AI functionality that acts like a co-pilot, helping you write and manage code faster and smarter than ever before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcayjE3oqg2vGpWzDa0mPg.png" /></figure><p><strong>MCP Server (Model Context Protocol):</strong></p><p>So, how does this brilliant intern get its work done? The secret is a system called the MCP Server. Think of it as the intern’s personal assistant. When you ask Cursor, “Can you do the task in Jira ticket #456,” the MCP Server connects to Jira for bug details, talks to your Git repository to find the relevant code, and might even query your company’s database to get the full picture. It’s the bridge that allows the AI to gather all the necessary context in one seamless action.</p><p>The best part? This isn’t some complex, secret server you have to build. It’s more like installing a new app on your phone. For most popular tools like Jira, Confluence, and Git, the MCP server is already built and waiting for you. All you do is click a button to install it and provide a token for a quick, one-time authentication. Then you’re done, and your new assistant is ready to work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6IgW-WjuPRWi6FLq8DHgA.png" /></figure><h3><strong>A Day in Developers Life:</strong></h3><p>Here’s my new routine. I open two chat windows in Cursor. Each chat window is a new agent. I use the first one like a supervisor, giving it the bigger picture tasks and making sure the work is on track. The second one is my helper; it handles the little jobs and works out the fine details. While my two AI assistants are busy, I can sit back and get caught up on office gossip. It’s amazing how much more I can get done while doing less.</p><p>To start the day, I’ll tell my supervisor AI something like,</p><blockquote>Hey, here’s Jira ticket #123. Can you figure out what needs to be done, look at the code, and give me a step-by-step plan? Make sure to include what tests we should run to be sure we don’t break anything. Oh, and also add a spot for feedback so we can keep track of everything.</blockquote><p>It’s that easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLwiHVbnpT4gAVLCqMLa3Q.png" /></figure><p>The supervisor gives me a super detailed plan. The prompt is so good that anyone, even someone new to the project, could follow it. Then, I give this plan to my second helper AI. The helper does all the work, but it’s not perfect. It can still make mistakes or “hallucinate.” That’s why the feedback section is so important — it’s where the helper tells me what it did and what’s left, so I can double-check everything.</p><p>Once the helper is done, I’ll take that feedback and send it back to the supervisor chat window. The supervisor then evaluates the work and, if it finds a mistake, gives me a new, corrected prompt with all the steps that need fixing. If the work is perfect, then great — the task is complete and I’m ready for the next one.</p><h3>Automating the Final Steps</h3><p>Most developers hate this part. The last bit of work feels like a chore. Once the helper is done, I tell Cursor,</p><blockquote>“Verify the changes one more time. Everything okay? Then push it to Git and create a pull request on GitHub”</blockquote><p>I also tell it who to add as a reviewer. Cursor does this work for me with perfection.</p><p>Then, I tell Cursor to add the documentation of the changes to the given Confluence page, and it does that task for me too. The documentation of the change is added exactly where it’s required.</p><h3>The Feedback Loop</h3><p>Now, someone reviews my pull request and leaves comments. This is where I go back to my supervisor AI. I ask it to look at the comments on github and figure out if they’re valid. If they are, it gives a new prompt to the helper AI, and the whole process starts all over again until the task is complete.</p><h3>The Game-Changer</h3><p>All these tasks are made easy because of the MCP Server. It’s what connects all the different systems, like Jira, Confluence, and GitHub. This changed documentation from being a boring chore to something as simple as saying, “Hey, intern, document this part nicely.” The MCP Server truly changes the game; it can even connect to databases and various other external systems.</p><h3>So, Are Developers Obsolete?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjDuSuW7z9MhY9Ei8rModQ.png" /></figure><p>If Cursor is doing all the work, why are developers even needed? It’s not that simple. While the MCP server is amazing, the AI isn’t perfect; it can still “hallucinate” or misunderstand a task. You have to set rules and teach it how to do things, which can be a long process. This has me worried as a developer. I’ve noticed I’m not enjoying debugging anymore — I just want the AI to give me the fix in simple English. It’s a scary feeling. And am I really being productive while the AI works? The answer is often no, as I find myself just babysitting the AI and scrolling through my phone.</p><h3>Questions for my community(Developers):</h3><p>So, what are your thoughts? I have a few questions for other developers who might be experiencing the same thing.</p><ul><li>How are you coping with losing your ability to do basic debugging and bug fixes?</li><li>How are you utilizing these AI tools in a better way?</li><li>What are you doing to make use of the time you saved by having your “intern” (Cursor agent) do the tasks?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64afecab3eb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making AI Useful at Work: My Journey with LLMs and Vector DBs]]></title>
            <link>https://medium.com/@sunandanbose17/making-ai-useful-at-work-my-journey-with-llms-and-vector-dbs-1126e1543edb?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1126e1543edb</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 10:44:10 GMT</pubDate>
            <atom:updated>2025-08-07T16:38:22.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXQqdHwCCclq1kMyQaESVQ.jpeg" /></figure><p>As the buzz around AI grew louder, I found myself, a Java developer, caught in a wave of uncertainty. With tools like Cursor becoming increasingly intelligent, the thought kept gnawing at me — what if it starts writing my code better than I can? Would there still be a place for me in this fast-evolving tech landscape?</p><p>Instead of letting the fear paralyze me, I decided to take control. I began carving out just 20 minutes a day, sometimes a video, sometimes a small task — to dip my toes into the world of AI. I wasn’t trying to master it overnight, just staying consistent with baby steps.</p><p>The more I learned, the more curious I became. I started hearing the term “RAG” (Retrieval-Augmented Generation) and it felt like a fascinating bridge between traditional software skills and the world of intelligent systems. It felt like the kind of tech I could build, not just admire from afar.</p><p>Today, I’ve actually built something using RAG. It might not be world-changing yet, but it’s real, and I made it. This blog is my way of sharing that journey — from fear to building.</p><p>So before we start with the actual problem, let’s start with the 3 basic pillars: <strong>LLMs</strong>, <strong>embeddings</strong>, and <strong>vector databases</strong>. Understanding these will make the rest of the journey clearer and much more intuitive.</p><h3>The buzzword: LLM</h3><p><strong>What is an LLM?</strong><br>A Large Language Model (LLM) is a type of AI model trained on huge volumes of text data, books, websites, code, and more. It learns patterns, grammar, facts, and even reasoning to understand and generate human-like text.</p><p><strong>How does it work?</strong><br>At its core, it predicts the next word in a sentence based on the words that came before. It’s just a very smart guesser, but trained on billions of examples.</p><p><strong>How is an LLM created?</strong><br>You start with a neural network architecture like a Transformer. Then, you feed it massive datasets (like Common Crawl or Wikipedia), and let it learn by adjusting its internal weights using a process called gradient descent.</p><p><strong>How is it trained?</strong><br>The model sees tons of text, tries to predict missing or next words, and gets rewarded when it’s right or corrected when it’s wrong. This loop runs across thousands of GPUs for weeks or even months, until the model becomes good enough to answer questions, write essays, or even code.</p><h3>Embeddings🤔</h3><p><strong>What is an embedding?</strong><br>Embeddings are a way to represent words, sentences, or documents as numbers, so that computers can understand and work with their meaning.</p><blockquote><em>example:<br></em>Imagine you’re assigning values based on meaning:<br>* The first few dimensions capture general concepts (like human vs object).<br>* The next might capture gender (male/female).<br>* Another might capture fame or importance.<br>So you could have:</blockquote><blockquote>* “king” → [1 (human), 1 (male), 1 (famous)] → [0.25, 0.13, 0.89, …]<br>* “queen” → [1 (human), 0 (male), 1 (famous)] → [0.27, 0.14, 0.91, …]<br>* “man” → [1 (human), 1 (male), 0 (not famous)] → [0.20, 0.10, 0.60, …]<br>* “banana” → [0 (not human), 0, 0] → [0.01, -0.45, 0.02, …]</blockquote><p>While the actual values are more complex and high-dimensional (like 384 or 768 numbers), this simplified version helps explain how embeddings carry meaning.</p><p><strong>Why is it useful?<br></strong>This allows the model to compare meanings. If two pieces of text are similar in meaning, their embeddings will be close together. This is how search engines or AI tools understand that “How to start Java” is similar to “Beginner Java guide.<br>Even more impressively, embeddings help where traditional keyword search fails. For example, if someone searches for “I want to build Android apps,” embeddings can match it to posts like “Learning mobile development with Kotlin” — even though no words are shared.</p><p><strong>Who creates embeddings?</strong><br>LLMs like OpenAI’s models or BERT can generate embeddings. When you input a piece of text, the model converts it into a high-dimensional vector that captures its meaning. Each LLM may create slightly different embeddings because it was trained differently or focuses on different language patterns.<br>Also, embeddings from different LLMs may vary in quality or style. So choosing the right model for embedding generation is crucial.</p><h3>Vector Database😵‍💫</h3><p><strong>Why do we need it?<br></strong>Embeddings are just numbers long lists of them. When you have thousands (or millions) of these, you need a smart way to store and search through them quickly. That’s where vector databases come in.</p><p><strong>What does a Vector DB do?</strong><br>It stores all those embeddings in a way that makes it easy to find the closest match. For example, if you search “Learn Java basics”, it finds texts/questions with embeddings closest to that i.e., most semantically similar.</p><p><strong>How is it useful?</strong><br>Instead of searching for exact keyword matches, vector DBs help retrieve answers that actually match the meaning of your question. Tools like FAISS, Pinecone, and Weaviate are built exactly for this.</p><p>Example:</p><blockquote>Say you want to find posts similar to “I want to build Android apps”. A normal SQL search won’t help much unless someone wrote that exact sentence.</blockquote><blockquote>But with embeddings and a vector DB, it will return posts like:</blockquote><blockquote>- “Kotlin for mobile development”<br>- “Where to start with Android Studio”</blockquote><blockquote>Because those embeddings are nearby in vector space, they carry similar meanings, even if the words are different.</blockquote><blockquote>You can think of it like Google Search but powered by understanding, not just matching words.</blockquote><p>So now some questions:</p><p><strong>Can everyone create their own LLM?<br></strong>Not really. Training a powerful LLM from scratch is super expensive. You need mountains of data, thousands of GPUs, and months of time. We’re talking millions of dollars.</p><p>But here’s the good part: you don’t need to. Companies like OpenAI, Meta, and Google have already trained great models.</p><p>You can either:</p><ul><li><strong>Fine-tune</strong> an open-source model on your domain-specific data.</li><li>Use <strong>RAG</strong> to keep the model frozen but provide it external knowledge at query time.</li></ul><h3><strong>Fine-tuning</strong></h3><p><strong>Fine-tuning</strong> means taking a pre-trained LLM and training it further on your data, so it adapts to your tone, content, or specific domain.</p><ul><li>Cost: High (needs GPUs and training time)</li><li>Speed: Slow (days or weeks)</li><li>When to use: If your app needs the model to change its behavior or learn specific patterns</li></ul><h3><strong>RAG</strong></h3><p>means you leave the LLM(consider chat-gpt) as-is but give it smart context retrieved from your data at runtime.</p><p>ChatGPT (or any LLM) can easily tell you what quantum mechanics is because that information is already part of its training data.<br>But if you ask it, “What is the premium value of <em>my</em> insurance policy?”, it can’t help — because that data isn’t public, and GPT has no idea about your specific policy.<br>Now, imagine you upload your insurance policy document. GPT can then scan it and give you an answer.<br>But what if that document is 100MB long? Feeding the whole document to GPT is:</p><ul><li>Costly (in tokens)</li><li>Inefficient</li><li>Risky (LLMs can lose context when fed too much data)</li></ul><p>Instead, what if someone could hand-pick <strong>only the relevant section</strong> from your document say, the part that talks about your premium and give just that piece to GPT?<br>That’s where <strong>RAG</strong> comes in.<br>RAG means: Retrieve the relevant content, then use it as context to Generate an answer.<br>It’s like having an assistant who knows where to find the right page in a 500-page book, and shows just that page to GPT so it can focus and answer you better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDJkJmT8j5wfwlZALrdFPQ.jpeg" /></figure><h3>Problem Statement &amp; Scenario(Finally😁)</h3><p>In our team, we handle multiple old projects. These projects come with a ton of documentation technical endpoint docs, architectural diagrams, flowcharts, internal notes basically everything you’d need to understand the system. The problem? It’s overwhelming.</p><p>Whenever a new person joins the team, they face a flood of documents. Even experienced developers struggle to connect the dots or find what they’re looking for. It’s easy to get lost, and it takes time before anyone feels confident navigating the project.</p><h3>Solution:</h3><p>So we thought — what if we built a small AI-powered help system for our team?<br>A new joinee (or even an old one) could simply ask questions about the project in plain English — no need to feel awkward, no need to dig through outdated Confluence pages.<br>They could ask:<br>- What does the payment service do?<br>- Which API is used for user onboarding?<br>- Show me the architecture flow for the login module.</p><p>And the system would answer in simple terms or in technical depth, depending on what the person prefers.</p><h3>Step1: Structure the document for embedding</h3><p>The idea was simple: break our documentation and files into small, meaningful chunks, generate embeddings for each of those chunks, and store them in a Vector Database.</p><pre># Example<br>{<br>  &quot;documentTitle&quot;: &quot;Your Confluence Page Title&quot;,<br>  &quot;url&quot;: &quot;https://your-confluence-page-url&quot;,<br>  &quot;lastUpdated&quot;: &quot;2025-08-07T14:32:00Z&quot;,<br>  &quot;chunks&quot;: [<br>    {<br>      &quot;chunkId&quot;: &quot;section-1&quot;,<br>      &quot;heading&quot;: &quot;1. Introduction&quot;,<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;content&quot;: &quot;This section introduces the purpose of the document and high-level system architecture.&quot;<br>    },<br>    {<br>      &quot;chunkId&quot;: &quot;section-2&quot;,<br>      &quot;heading&quot;: &quot;2. API Overview&quot;,<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;content&quot;: &quot;This section describes the available APIs and authentication methods.&quot;<br>    },<br>    {<br>      &quot;chunkId&quot;: &quot;section-3&quot;,<br>      &quot;heading&quot;: &quot;2.1 Get User Endpoint&quot;,<br>      &quot;type&quot;: &quot;code&quot;,<br>      &quot;language&quot;: &quot;bash&quot;,<br>      &quot;description&quot;: &quot;Example usage of the GET /user endpoint.&quot;,<br>      &quot;codeSnippet&quot;: &quot;curl -X GET https://api.example.com/user -H \&quot;Authorization: Bearer &lt;token&gt;\&quot;&quot;<br>    }<br>  ]<br>}</pre><h3>Step 2: Generate Embeddings</h3><p>Install dependencies</p><pre>pip install sentence-transformers faiss-cpu requests</pre><pre>import requests<br>import json<br>import faiss<br>import numpy as np<br>from sentence_transformers import SentenceTransformer<br><br># Initialize the embedding model<br>model = SentenceTransformer(&#39;you can choose any model that fits your need and configuration&#39;)<br><br>def fetch_document_from_cloud(url):<br>    response = requests.get(url)<br>    response.raise_for_status()<br>    return response.json()<br><br>def generate_embeddings(document):<br>    embeddings = []<br>    metadata = []<br>    vectors = []<br><br>    for chunk in document.get(&quot;chunks&quot;, []):<br>        if chunk[&quot;type&quot;] == &quot;text&quot;:<br>            text_to_embed = f&quot;{chunk[&#39;heading&#39;]}\n{chunk[&#39;content&#39;]}&quot;<br>        elif chunk[&quot;type&quot;] == &quot;code&quot;:<br>            text_to_embed = f&quot;{chunk[&#39;heading&#39;]}\n{chunk[&#39;description&#39;]}\n{chunk[&#39;codeSnippet&#39;]}&quot;<br>        else:<br>            continue<br><br>        embedding = model.encode(text_to_embed)<br>        embeddings.append(embedding)<br>        vectors.append(embedding.astype(&#39;float32&#39;))<br>        metadata.append({<br>            &quot;chunkId&quot;: chunk[&quot;chunkId&quot;],<br>            &quot;heading&quot;: chunk[&quot;heading&quot;],<br>            &quot;documentTitle&quot;: document.get(&quot;documentTitle&quot;),<br>            &quot;url&quot;: document.get(&quot;url&quot;),<br>        })<br><br>    return np.array(vectors), metadata<br><br>def store_in_faiss(vectors, metadata):<br>    dimension = vectors.shape[1]<br>    index = faiss.IndexFlatL2(dimension)<br>    index.add(vectors)<br><br>    return index, metadata<br><br>def process_document(url):<br>    document = fetch_document_from_cloud(url)<br>    vectors, metadata = generate_embeddings(document)<br>    index, references = store_in_faiss(vectors, metadata)<br><br>    return index, vectors, references<br><br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    cloud_url = &quot;https://example.com/confluence-doc.json&quot;  # Replace with actual URL<br>    index, embeddings, refs = process_document(cloud_url)<br>    print(f&quot;Indexed {len(embeddings)} chunks.&quot;)<br>    print(&quot;Example Reference Metadata:&quot;)<br>    print(json.dumps(refs[0], indent=2))</pre><h3>Step 3: Get Similar Documents matching your query</h3><pre>import faiss<br>import numpy as np<br>from sentence_transformers import SentenceTransformer<br><br># Load the same embedding model used earlier<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br><br>def search_similar_chunks(query, index, metadata, top_k=3):<br>    &quot;&quot;&quot;Embed the query and find top_k similar chunks using FAISS index.&quot;&quot;&quot;<br>    query_embedding = model.encode([query]).astype(&#39;float32&#39;)<br>    distances, indices = index.search(query_embedding, top_k)<br><br>    results = []<br>    for i in range(top_k):<br>        idx = indices[0][i]<br>        score = distances[0][i]<br>        chunk_info = metadata[idx]<br>        results.append({<br>            &quot;score&quot;: float(score),<br>            &quot;chunk&quot;: chunk_info<br>        })<br>    return results<br><br>def build_prompt(query, results):<br>    &quot;&quot;&quot;Construct a prompt using retrieved chunks and user query.&quot;&quot;&quot;<br>    context_sections = []<br>    for res in results:<br>        heading = res[&quot;chunk&quot;].get(&quot;heading&quot;, &quot;&quot;)<br>        context_sections.append(f&quot;## {heading}\n&quot;)<br><br>    context_str = &quot;\n&quot;.join(context_sections)<br><br>    prompt = f&quot;&quot;&quot;You are a helpful assistant with access to the following documentation context:<br><br>{context_str}<br><br>Answer the following question using the above context:<br><br>{query}<br>&quot;&quot;&quot;<br>    return prompt</pre><h3>Step 4: Execute the query on LLM</h3><p>You can actually use chatgpt or deploy your LLM model on AWS sagemaker or your local system.</p><pre>import os<br>import openai<br>import requests<br>import boto3<br>import json<br><br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)  # Or set it manually<br><br>def call_chatgpt(prompt):<br>    &quot;&quot;&quot;Use OpenAI ChatGPT to get response.&quot;&quot;&quot;<br>    response = openai.ChatCompletion.create(<br>        model=&quot;gpt-4&quot;,  # or &quot;gpt-3.5-turbo&quot;<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>        ],<br>        temperature=0.3,<br>        max_tokens=512<br>    )<br>    return response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]<br><br><br>def call_local_llm(prompt, host=&quot;http://localhost:11434/api/generate&quot;):<br>    &quot;&quot;&quot;Send prompt to a locally hosted model (Ollama-style API).&quot;&quot;&quot;<br>    payload = {<br>        &quot;model&quot;: &quot;llama3&quot;,  # or whatever your model name is<br>        &quot;prompt&quot;: prompt,<br>        &quot;stream&quot;: False<br>    }<br>    res = requests.post(host, json=payload)<br>    if res.ok:<br>        return res.json().get(&quot;response&quot;)<br>    else:<br>        return f&quot;Error: {res.status_code} - {res.text}&quot;<br><br><br>def call_sagemaker_llm(prompt, endpoint_name):<br>    &quot;&quot;&quot;Send prompt to a SageMaker-hosted model.&quot;&quot;&quot;<br>    client = boto3.client(&#39;sagemaker-runtime&#39;, region_name=&quot;us-west-2&quot;)<br><br>    payload = {<br>        &quot;inputs&quot;: prompt<br>    }<br><br>    response = client.invoke_endpoint(<br>        EndpointName=endpoint_name,<br>        ContentType=&quot;application/json&quot;,<br>        Body=json.dumps(payload)<br>    )<br><br>    result = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>    return json.loads(result)[&quot;generated_text&quot;] if &quot;generated_text&quot; in result else result</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgcZk9ElD-AxjbZ2akboNg.jpeg" /></figure><h3>Conclusion</h3><p>This blog was a simple doorway into the world of AI where language models, embeddings, and vector databases come together to solve real problems. AI is more accessible than ever and there’s no better time to dive in.</p><p><strong>Make your Day 1 today.</strong> This is the next big shift, and I’m learning too so there are many parts I have made in this. Feel free to connect, share your thoughts, and help me grow as we explore this space together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1126e1543edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Quiet Road]]></title>
            <link>https://medium.com/@sunandanbose17/beyond-the-quiet-road-de0687744924?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0687744924</guid>
            <category><![CDATA[adventure]]></category>
            <category><![CDATA[thriller]]></category>
            <category><![CDATA[suspense]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 07:25:56 GMT</pubDate>
            <atom:updated>2024-09-12T12:24:35.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2JVb4yxFAxnrPHGbtwPtg.png" /></figure><p>I’m a software engineer working in Bangalore, where late-night work and deployments are pretty normal. It was Tuesday the 17th of October, 2023. We had to push some changes to production, and the whole thing took longer than expected. By the time I left the office, it was 2:20 AM.</p><p>The streets were empty. It looked like it had rained earlier, and a cold wind was blowing. Normally, at this hour, you’d see people grabbing tea or coffee, but tonight, there was no one around — not even a stray dog. It made me feel uneasy. I started thinking, “What if I get robbed?”</p><p>I sped up on my scooty, trying to get home as fast as I could. On the way, I had to pass through a stretch of road in Whitefield. It’s a strange area, with no buildings on either side, just trees and jungle. I’ve gone through it many times, but that night, it felt different. The air was colder than usual, and I couldn’t shake off a bad feeling, like something wasn’t right.</p><p>I rode faster, wanting to get out of there. After crossing that stretch, I finally reached an area with some flats and a society nearby. That’s when, out of nowhere, a group of dogs started barking and chasing me. It all happened so fast, and I panicked. I hit the accelerator, but didn’t notice a speed bump ahead. My scooty skidded, and I fell hard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5W5I0lvvZ03fgsc7Z0Q4A.png" /></figure><p>The dogs scattered as soon as I fell, but I was left there on the ground, my elbow hurt and bleeding. I couldn’t even lift my scooty. Nearby, I saw a house just a few steps away. Limping, I made my way to it, hoping to find help. The gate was open, and I could hear music playing from inside. Relieved, I thought someone must be awake.</p><p>I rang the doorbell. No answer. I rang it again, two, three times. Still nothing. I knocked on the door, and to my surprise, it was open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgU3ZM9tgPT86---BEoAxw.png" /></figure><p>I hesitated for a moment but then called out, “Koi hai andar? I need help.” The living room was empty, with the TV on but no one in sight. I shouted a few more times, but there was no response. Suddenly, I heard a loud crash from outside, the sound was deafening. I ran back to the road to check, and to my horror, someone had crashed their bike into my scooty. Both vehicles were smashed, and the rider was lying on the ground, bleeding heavily.</p><p>I panicked. The man was unconscious, bleeding badly, and there was no one around to help. I screamed for help, but the street was still empty.</p><p>Desperate, I ran back to the house. This time, I went inside, shouting for anyone who could hear me. No one was there. I searched the ground floor, but it was empty. I hurried upstairs, noticing a door slightly open. Terrified but with no other choice, I peeked inside.</p><p>There, sitting on the floor, was a girl staring at the wall. Her face was blank, like she wasn’t even aware of my presence. I stuttered, “Please, I need your help! bahar ek admi ka accident ho gya hai, he could die!”</p><p>She didn’t respond. She just kept staring at the wall. The room was dimly lit, and I couldn’t see what she was looking at. I repeated my plea, but instead of answering, she started crying.</p><p>Confused, I turned to see what she was looking at. My heart stopped. There was a man lying on the floor, covered in blood. Then I turned back and noticed the girl’s left hand — she was holding a knife. She was just staring at the dead body and crying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrK9mriYYEo0H7tYaLiOVQ.png" /></figure><p>I froze. I was in a room that was a part of a murder and a man who is bleeding outside. I thought to run away from the place. I didn’t want to be a part of all this. “I am a simple man” I kept murmuring this. I rushed outside to run away only then I noticed that I can’t run away also as my scooty was damaged in the accident. I was injured so I couldn’t drag my scooty from there also. I started crying because at that point I realised I am in a very big mess. I was shivering with all these things happening and nothing I could have done to avoid this.<br>I was so scared that I woke up and realised it was a very bad dream.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0687744924" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis to the Rescue: Upgrading Our Notification System]]></title>
            <link>https://medium.com/@sunandanbose17/redis-to-the-rescue-upgrading-our-notification-system-d8b28b768f06?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b28b768f06</guid>
            <category><![CDATA[event-management]]></category>
            <category><![CDATA[notification-service]]></category>
            <category><![CDATA[alertservice]]></category>
            <category><![CDATA[redis-stream]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Sun, 26 May 2024 17:18:04 GMT</pubDate>
            <atom:updated>2024-05-27T12:23:40.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*058tb7tVkf8zxP0u-WkPhQ.gif" /></figure><h3><strong>Current Dynamics and Challenges:</strong></h3><p>In our system, whenever a crash happens in any product, an event is triggered. The product team needs to be alerted about these events. For example, if 1,000 such events occur across all users within 5 minutes, an alert should be triggered. We also need to send daily or hourly alerts with information about the events received during those periods.</p><p>Our system used Java’s built-in data structures like TreeMap and LinkedList to handle this data and manage notifications, keeping only the latest 2 days of data. However, as the volume of events increased, we started experiencing Java heap memory issues.</p><p>We realized this setup isn’t scalable. Simply increasing Java heap space is not an ideal solution, nor is regularly restarting the application to prevent heap space from growing too much.</p><p>We need a more robust and scalable approach to handle the growing amount of data and ensure efficient alerting without running into memory issues.</p><h3>Redis: A Promising Solution, but Challenges Arise</h3><p>We thought Redis could be a great replacement since we already had data structured in TreeMap with key-value pairs, and all we needed was to move this data outside of internal storage. Redis seemed like an excellent choice — it was fast and reliable.</p><p>Initially, we seamlessly transitioned to Redis, creating key-value pairs and storing our data. Everything seemed to work well at first. However, we soon realized our mistake. Managing too many keys became overwhelming. The system became bloated, and accumulating keys based on time thresholds became a significant issue, especially under heavy production loads.</p><p>After facing these challenges, we had to reassess our approach. Ultimately, we decided to revert to the previous method of using Java’s internal memory, despite its shortcomings. While this solution wasn’t perfect, it at least functioned reliably. However, the process was slow and cumbersome, prompting us to reconsider our entire approach.</p><h3>Redis Streams: A Potential Solution Emerges</h3><p>As we delved into the issue, we stumbled upon Redis Streams — a feature designed precisely for tackling similar challenges. It sparked our interest, prompting us to go deeper into this new territory.</p><p>After some research, we realized that Redis Streams could indeed address our needs perfectly. However, we encountered a minor setback: Redis Streams lacked Time-To-Live (TTL) functionality. Despite this limitation, we remained undeterred. We believed that we could overcome this obstacle later. Our priority was to implement the solution effectively. We were confident that we could devise a workaround for the TTL issue once our system was up and running.</p><h3>Concepts:</h3><p>As we worked to improve our system, Redis Streams emerged as a promising solution. Here are some key concepts about Redis Streams that helped us build a more efficient system:</p><h4>What is Redis Stream?</h4><p>Redis Stream is a powerful data structure introduced in Redis 5.0 that allows you to manage and process streams of data efficiently. It is designed to handle high-throughput scenarios, making it ideal for applications like ours that require real-time data processing and alerting.</p><p>Redis Streams can be thought of as a message queue<em>(Redis stream as an append-only data structure, however Redis streams are represented in memory, so we are also able to delete entries)</em>, where each entry consists of a unique ID and associated fields with values. It supports appending new entries, querying specific ranges of entries. Streams are inherently ordered, meaning the entries are stored and accessed in the order they were added.</p><p>Example:</p><p>Redis Streams store data as a series of entries in a key, each identified by a unique ID. The unique ID consists of two parts: a millisecond timestamp and a sequence number to ensure uniqueness even for multiple entries added in the same millisecond. The format of the unique ID is timestamp-sequence</p><pre>&quot;stream-key&quot;:<br>  &quot;1692632086370-0&quot;:<br>    &quot;name&quot;<br>    &quot;John&quot;<br>  &quot;1692632094485-0&quot;:<br>    &quot;name&quot;<br>    &quot;Alice&quot;</pre><p><a href="https://redis.io/docs/latest/commands/xadd/"><strong>XADD:</strong></a></p><p>XADD is the command used to add new entries to a Redis Stream. The time complexity of XADD is O(1), meaning it operates in constant time, making it very efficient even with large volumes of data.</p><pre>XADD key [NOMKSTREAM] [&lt;MAXLEN | MINID&gt; [= | ~] threshold<br>  [LIMIT count]] &lt;* | id&gt; field value [field value ...]<br><br>XADD stream-key * name John<br>XADD stream-key * name Alice<br>XADD stream-key * name Bob</pre><p>Each XADD command adds a new entry to the stream stream-key. The * symbol tells Redis to generate a unique ID automatically.<br><a href="https://redis.io/docs/latest/commands/xadd/"><em>[Official Documentation of XADD]</em></a></p><p><strong>XRANGE:</strong></p><p>XRANGE allows us to retrieve a range of entries from a Redis Stream. This command helps in querying specific segments of the stream. The time complexity of XRANGE is O(N), where N is the number of elements in the stream.</p><pre>XRANGE key start end [COUNT count]<br><br>XRANGE somestream 1526985054069 1526985055069 // specifc entries<br>XRANGE somestream - + // all entries</pre><p><a href="https://redis.io/docs/latest/commands/xrange/"><em>[Official Documentation of XRANGE]</em></a></p><p><strong>XDEL:</strong></p><p>XDEL is used to delete specific entries from a Redis Stream, and returns the number of entries deleted. This is useful for managing and maintaining the stream’s data. The time complexity of XDEL is O(1) for each entry deleted, making it efficient for stream maintenance.</p><pre>XDEL key id [id ...]</pre><h3>Let’s Discuss the Code</h3><p>Our <strong>Event service</strong> is built as a Spring Boot application that exposes an API to fetch events. We use the Spring Redis starter dependencies for integrating with Redis, but you can also use other Redis clients. For instance, I’ve used Jedis before, and it’s an excellent option too.</p><p>By using Spring Boot and Spring Redis starter, we can easily manage our Redis connections and operations within our application, ensuring a smooth and efficient workflow. If you prefer, Jedis is also a great choice for interacting with Redis directly.</p><p><strong>EventService:</strong></p><pre>@Service<br>public class EventService {<br><br>    @Autowired<br>    private StringRedisTemplate redisTemplate;<br><br>    public void createEvent(Event event) {<br>        ObjectRecord&lt;String, String&gt; record = StreamRecords.newRecord()<br>                .ofObject(event.toString())<br>                .withStreamKey(getStreamKey(event.getProduct()));<br>        redisTemplate.opsForStream().add(record);<br>    }<br><br>    private String getStreamKey(String product) {<br>        return &quot;crash-events-&quot; + product.toLowerCase();<br>    }<br>}</pre><h3>Building the Alert Service:</h3><p>We successfully inserted events into our application. Now, let’s work on the Notification Service.</p><p>Note: It’s best to use the Observer Design Pattern here, as it will make the service more efficient.</p><p>In our implementation, I’ve added a scheduler that runs every 10 seconds. I chose to use a scheduler because the actual application has much more functionality and constraints. For simplicity, I’ve removed those additional constraints in this example.</p><p>AlertService:</p><pre>@Configuration<br>@EnableScheduling<br>public class AlertService {<br>    @Scheduled(fixedRate = 10000)<br>    public void crashThresholdAlert() {<br>        List&lt;String&gt; products = getProducts();<br><br>        for (String product : products) {<br>            String prefix = &quot;alert.threshold.&quot; + product.toLowerCase() + &quot;.&quot;;<br>            Integer threshold = //Fetch Threshold limit from the config files.<br>            int duration = //Fetch Duration time from the config files.<br>            String unit = //Fetch time metric unit from the config files.<br><br>            ChronoUnit chronoUnit = ChronoUnit.valueOf(unit.toUpperCase());<br>            Integer eventsCount = eventService.getEventsCount(duration, chronoUnit, product);<br>            print(product + &quot; : &quot; + eventsCount);<br>            synchronized (pauseAlertOnProducts) {<br>                print(&quot;ALERT stopped for products: &quot; + pauseAlertOnProducts);<br>                if (eventsCount &gt;= threshold &amp;&amp; !stopAlertOnProducts.contains(product)) {<br>                    print(&quot;ALERT: &quot; + product + &quot; has crossed the threshold of &quot; + threshold + &quot; in last &quot; + duration + &quot; &quot; + unit);<br>                    // TODO: Send actual alert instead of printing<br>                    pauseAlertOnProducts.add(product);<br><br>                    scheduler.schedule(() -&gt; {<br>                        synchronized (pauseAlertOnProducts) {<br>                            print(&quot;Removing alert for &quot; + product);<br>                            pauseAlertOnProducts.remove(product);<br>                        }<br>                    }, duration, TimeUnit.valueOf(unit));<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>The crashThresholdAlert method checks if any product has exceeded its crash threshold within a specified time frame. For each product, it fetches the alert threshold, duration, and unit from a property service and retrieves the event count. If the count exceeds the threshold and alert hasn&#39;t been paused for the product, it sends an alert message and haults alert for the product for a given time duration.</p><p><strong>EventService:</strong></p><pre>@Service<br>public class EventService {<br><br>    private StringRedisTemplate redisTemplate;<br><br>    public Integer getEventsCount(Integer time, ChronoUnit unit, String product) {<br>        Instant now = Instant.now();<br>        String epochTime = String.valueOf(now.minus(time, unit).toEpochMilli());<br><br>        return getEventsCount(epochTime, &quot;+&quot;, product);<br>    }<br><br>    public Integer getEventsCount(String from, String now, String product) {<br>        Range&lt;String&gt; range = Range.closed(from, now);<br><br>        List&lt;MapRecord&lt;String, Object, Object&gt;&gt; records =<br>                redisTemplate.opsForStream().range(getStreamKey(product), range);<br>        return records != null ? records.size() : 0;<br>    }<br>}</pre><p>I’m only explaining the CrashThreshold here. Other types of alerts will work in a similar way to this threshold alert.</p><h3>Implementing TTL Functionality in Redis Streams</h3><p>Now, let’s address how to implement TTL (Time-To-Live) functionality in Redis Streams.</p><p>We discovered a useful command called XTRIM. Here&#39;s a bit about how it works:</p><ul><li>XTRIM: This command trims the stream to keep it within specified limits.</li><li>MAXLEN: Trims the stream to a maximum length by removing the oldest entries. For example, XTRIM mystream MAXLEN 1000 keeps only the latest 1000 entries.</li><li>MINID: Trims entries with IDs less than a specified minimum ID. For example, XTRIM mystream MINID 1653660588123-0 removes all entries with IDs less than 1653660588123-0.</li></ul><p>Since Redis streams store data sequentially by timestamp, we can use XTRIM to delete stream IDs below a certain timestamp, effectively implementing a TTL-like functionality. The catch is that this needs to be run manually by us, unlike TTL which Redis applies automatically.</p><p><strong>Remove Id from Stream:</strong></p><pre>private void removeExpiredEvents(String product) {<br>        executorService.submit(() -&gt; {<br>            try {<br>                Instant now = Instant.now();<br>                String epochTime = String.valueOf(now.minus(2, ChronoUnit.DAYS).toEpochMilli());<br><br>                List&lt;RecordId&gt; recordIds = redisTemplate.opsForStream().range(getStreamKey(product), Range.closed(&quot;-&quot;, epochTime))<br>                        .stream()<br>                        .map(MapRecord::getId)<br>                        .collect(Collectors.toList());<br>                logger.info(&quot;Removing expired events: &quot; + recordIds.size());<br><br>                if (!recordIds.isEmpty()) {<br>                    redisTemplate.opsForStream().delete(getStreamKey(product), recordIds.toArray(new RecordId[0]));<br>                }<br>            } catch (Exception e) {<br>                e.printStackTrace();<br>            }<br>        });<br>        executorService.shutdown();<br>    }</pre><p>After setting everything up, we found that the Spring Redis dependency doesn’t support the MINID functionality with XTRIM. It only allows setting MAXLEN.</p><p>To work around this, we extracted all the record IDs using XRANGE and then deleted the IDs using XDEL. While XTRIM with MINID would have been ideal, this approach also works well for our needs.</p><p>Note: If you’re using Jedis, you can use XTRIM MINID directly.</p><h3>Conclusion: Reflecting on the Alert and Notification Service Journey</h3><p>With the completion of the Alert and Notification Service, it feels like the solution was simple. However, the journey of discovering this solution, going back and forth between learning and implementing, was truly enjoyable.</p><p>Throughout this process, I’ve learned a lot, and I hope to continue encountering such challenges in the future. It’s these challenges that push us to grow and improve.</p><p>If you have any feedback or would like to connect, feel free to reach out to me on <a href="https://www.linkedin.com/in/sunandan-bose/">LinkedIn</a>. I’m always open to learning and collaborating with others.</p><p>Thank you for joining me on this journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b28b768f06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring swift identification of offensive posts in online platforms]]></title>
            <link>https://medium.com/@sunandanbose17/ensuring-swift-identification-of-offensive-posts-in-online-platforms-126bce761b3e?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/126bce761b3e</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Fri, 03 May 2024 17:04:12 GMT</pubDate>
            <atom:updated>2024-05-03T18:05:26.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m75N2HCA7275PRns8HVAOg.png" /><figcaption>Identification of Offensive Posts in social media</figcaption></figure><h3><strong>Problem Statement:</strong></h3><p>The rule is that every post on social media needs to be checked to make sure it’s okay. That means no bad words, offensive pictures, or mean stuff. We also want to make sure it’s easy for people to use the app. So when someone is making a post, we don’t want to slow them down with these checks. We’ll do the checks later, not right when they’re making the post.</p><h3><strong>Constraints:</strong></h3><ol><li>The check for offensive content in posts should happen without slowing down creating posts.</li><li>This check needs to happen at a different thread, not the one in which someone’s making a post.</li><li>It had to be done by a different team, not the one creating posts.</li><li>Because of security and network, the UI app can’t directly talk to this team.</li><li>We need to figure out a different way so that reporting offensive posts can happen quickly, within 5–10 seconds, and be fail-safe if something goes wrong.</li></ol><h3><strong>Approach:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*sYO-Nq0f8EkOFZuTfMxp6g.png" /></figure><ol><li><strong>UI App:</strong> When someone wants to make a post, the app they’re using won’t stop them to check the content. Instead, it will quickly start a process in the background.</li><li><strong>API Gateway:</strong> This is like a door that the UI app knocks on. It receives the request from the app and then directs it to the right place. In this case, it sends the task to a lambda function.</li><li><strong>Lambda Function: </strong>Think of this as a tiny, specialized program that jumps into action when called. Its job here is to tidy up the event a bit and then put it in a queue. It does this quickly and efficiently.</li><li><strong>Moderation Service:</strong> This team is responsible for making sure posts are okay to stay on public platform. They’re watching the queue on which the lambda function posts content. When a new event pops up (like a newly created post, or any update on a post), they grab it and start analyzing it and report it if necessary.</li></ol><p>So, the UI app doesn’t wait around for the post to be checked before moving on. Instead, it hands off the task quickly and the moderation team handles it separately, keeping everything running smoothly. And if there are any hiccups along the way, like a server going down, the system is designed to keep going without breaking.</p><h3><strong>Discovering the unknowns:</strong></h3><ol><li><strong>Why use a API Gateway and not access lambda directly?</strong></li></ol><p>We used API Gateway before Lambda to add an extra layer of control and safety. API Gateway helps manage requests and sends them to the right Lambda function. Here’s why it’s useful:</p><ul><li>Security: It checks requests for security before they go to Lambda, keeping our system safe, allowing only authorized systems.</li><li>Routing and Versioning: We can organize our APIs better, making updates easier without changing the Lambda functions directly.</li><li>Scalability: It helps handle lots of requests smoothly, spreading them out to keep things running smoothly.</li></ul><p>In short, using API Gateway before Lambda makes our serverless apps safer, more flexible, and able to handle lots of users without crashing.</p><p><strong>2. Why Use a Queue? <br></strong>To make sure everything gets handled in order and nothing gets lost. If the moderation service has any problem. The the data will be safe in a queue.<br>Also here we needed asynchronous processing, decoupling the generation of tasks from lambda function to their execution in the moderation service.</p><p><strong>3. Redis Queue vs AWS Simple Queue Service (SQS):</strong> <br>Technical considerations that influenced our decision-making process.<br>- Integration: AWS SQS aligns seamlessly with our existing AWS infrastructure.<br>- Setup and Management: Configuring AWS SQS, is more simple than setting up Redis Queue.<br>- Cost Considerations: Redis Queue offers advanced features and flexibility, its deployment on AWS incur higher setup and operational costs compared to AWS SQS.</p><p>We already have a Redis setup in our account but we are thinking of moving out of it, because of high setup cost. This is the reason we considered comparing AWS SQS with Redis Queue.</p><p><strong>4. Why use Lambda function over server based service?<br>- </strong>Event-driven Architecture: Lambda functions excel in event-driven architectures, triggered by diverse events like HTTP requests, enabling smooth integration with AWS services.<br>- Reduced operational overhead: Lambda simplifies infrastructure management, minimizing operational tasks like server setup and maintenance, streamlining development and enabling to prioritize application logic over infrastructure concerns.<br>- Scalability and Cost: Lambda functions provide automatic scaling, crucial for handling varying workloads efficiently, coupled with a cost-effective pay-as-you-go model, reducing expenses by eliminating the management of idle server resources.<br>Lambda here is doing just a small job, and we’re still testing it out. If we get a lot more users later on, we might switch to a regular server service.</p><h3><strong>Conclusion:</strong></h3><p>I found working on this feature really interesting because it was more about planning how things fit together than writing the actual code. I learned a lot about building pipelines from start to finish and making sure they can handle lots of work without slowing down or failing. I hope you found it interesting too! If you have any questions or want to connect, feel free to reach out to me on <a href="https://www.linkedin.com/in/sunandan-bose/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=126bce761b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Cloud Infrastructure: Harnessing CloudFront, S3, WebACL, and CloudFormation for Seamless…]]></title>
            <link>https://medium.com/@sunandanbose17/efficient-cloud-infrastructure-harnessing-cloudfront-s3-webacl-and-cloudformation-for-seamless-73ad6b247669?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/73ad6b247669</guid>
            <category><![CDATA[cloud-hosting]]></category>
            <category><![CDATA[static-web-hosting]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 10:12:40 GMT</pubDate>
            <atom:updated>2024-04-20T10:24:21.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Cloud Infrastructure: Harnessing CloudFront, S3, WebACL, and CloudFormation for Seamless UI Application Hosting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Df0SsRTsqK_NbJuTG3v0g.jpeg" /></figure><h3><strong>Issue:</strong></h3><p>I had to set up a system to host static websites in my project using S3 and CloudFront. Part of this involved linking the S3 bucket and the logging bucket with CloudFront. The main problem I encountered was the lack of clear instructions for some tasks. So, I decided to write down all the steps I took to do everything.</p><p>Before we begin, let me explain the AWS Resources I used:</p><ul><li><strong>CloudFront</strong>: CloudFront is a content delivery network (CDN) service provided by AWS. It helps deliver content (like web pages, videos, or other files) to users globally with low latency and high transfer speeds by caching content at edge locations around the world.</li><li><strong>S3</strong>: S3 stands for Simple Storage Service. It is an object storage service provided by AWS, designed to store and retrieve any amount of data from anywhere on the web. It’s commonly used for backup and storage of large files, static website hosting, and application data storage.</li><li><strong>CloudFront Origin Access Identity</strong>: CloudFront Origin Access Identity (OAI) is a special CloudFront user identity. It allows CloudFront to access the content stored in private Amazon S3 buckets. This helps secure the content by ensuring that users can only access it through CloudFront, not directly from the S3 bucket.</li><li><strong>WAF v2 ACL</strong>: WAF stands for Web Application Firewall. WAF v2 ACL (Access Control List) is a feature of AWS WAF that allows you to control access to your web applications by creating rules to block or allow web traffic based on predefined conditions.</li><li><strong>BucketPolicy</strong>: A Bucket Policy is a set of permissions attached to an S3 bucket that defines who can access the bucket and under what conditions. It’s needed to control access to the S3 bucket, including permissions for CloudFront to access the content.</li><li><strong>Route 53</strong>: Route 53 is a scalable and highly available Domain Name System (DNS) web service provided by AWS. It translates human-readable domain names like example.com into IP addresses that computers use to identify each other on the internet. Route 53 is needed to manage domain names and route internet traffic to AWS resources like CloudFront distributions or S3 buckets.</li><li><strong>AcmCertificate: </strong>AcmCertificate is a resource managed by AWS Certificate Manager (ACM). It provides SSL/TLS certificates to enable secure connections between clients and servers over HTTPS. These certificates help ensure data exchanged between users and your website or application is encrypted and secure.</li></ul><p><strong>CloudFormation or Teraform?</strong></p><p>We stuck with AWS CloudFormation templates because we’ve already been using CloudFormation to set up other AWS resources in the project.</p><p>CloudFormation templates are used to define and deploy the infrastructure and resources in AWS in a consistent and repeatable way, ensuring that the project’s infrastructure is managed effectively. Although Terraform could be an option, we’re constrained by the project requirements.<br>Ref: <a href="https://www.toptal.com/terraform/terraform-vs-cloudformation#:~:text=What%20is%20the%20difference%20between,wide%20range%20of%20cloud%20vendors.">CloudFormation vs Terraform?</a></p><h3><strong>Let’s Start:</strong></h3><p>Let’s begin by creating S3 resources because that’s the first step in the process.</p><p><strong>Create S3 bucket:</strong><br>This CloudFormation resource creates an S3 bucket named “project-ui-bucket” for hosting user interface (UI) files. It ensures encryption of objects stored in the bucket using AES256 encryption. The “DeletionPolicy” and “UpdateReplacePolicy” are set to “Retain”, indicating that even if the stack is deleted or updated, the S3 bucket and its contents will be retained for safety.</p><pre>&quot;S3UIBucket&quot;: {<br>    &quot;Type&quot;: &quot;AWS::S3::Bucket&quot;,<br>    &quot;Properties&quot;: {<br>        &quot;BucketName&quot;: &quot;project-ui-bucket&quot;,<br>        &quot;BucketEncryption&quot;: {<br>            &quot;ServerSideEncryptionConfiguration&quot;: [<br>                {<br>                    &quot;ServerSideEncryptionByDefault&quot;: {<br>                        &quot;SSEAlgorithm&quot;: &quot;AES256&quot;<br>                    }<br>                }<br>            ]<br>        },<br>        &quot;Tags&quot;: [<br>            {<br>                &quot;Key&quot;: &quot;Domain&quot;,<br>                &quot;Value&quot;: &quot;ui-deployment-resource&quot;<br>            }<br>        ]<br>    },<br>    &quot;DeletionPolicy&quot;: &quot;Retain&quot;,<br>    &quot;UpdateReplacePolicy&quot;: &quot;Retain&quot;<br>}</pre><p><strong>Creating a S3 bucket for Logging</strong>:</p><p>Since we’re setting up S3 buckets, let’s create a Logging S3 bucket as well. This bucket is necessary to keep track of and store detailed data about requests made to your CloudFront distribution. By logging this information, we can analyze traffic, keep an eye on performance, and fix any problems that might occur during content delivery.</p><p>Creating the bucket for logging in CloudFront was tough because it needed ACL access, which we couldn’t provide due to project limits. So, in making the S3 bucket, we made sure to block public access to ACLs using “PublicAccessBlockConfiguration”. Also, with “OwnershipControls”, we set rules to manage object ownership. In this case, “ObjectOwnership” is set to “ObjectWriter”, meaning the uploader’s account becomes the owner of the object.</p><pre>&quot;LoggingBucket&quot;: {<br>    &quot;Type&quot;: &quot;AWS::S3::Bucket&quot;,<br>    &quot;Properties&quot;: {<br>        &quot;BucketName&quot;: &quot;project-logging-bucket&quot;,<br>        &quot;PublicAccessBlockConfiguration&quot;: {<br>            &quot;BlockPublicAcls&quot;: false<br>        },<br>        &quot;OwnershipControls&quot;: {<br>            &quot;Rules&quot;: [<br>                {<br>                    &quot;ObjectOwnership&quot;: &quot;ObjectWriter&quot;<br>                }<br>            ]<br>        },<br>        &quot;BucketEncryption&quot;: {<br>            &quot;ServerSideEncryptionConfiguration&quot;: [<br>                {<br>                    &quot;ServerSideEncryptionByDefault&quot;: {<br>                        &quot;SSEAlgorithm&quot;: &quot;AES256&quot;<br>                    }<br>                }<br>            ]<br>        },<br>        &quot;Tags&quot;: [<br>            {<br>                &quot;Key&quot;: &quot;Domain&quot;,<br>                &quot;Value&quot;: &quot;ui-deployment-resource&quot;<br>            }<br>        ]<br>    },<br>    &quot;DeletionPolicy&quot;: &quot;Retain&quot;,<br>    &quot;UpdateReplacePolicy&quot;: &quot;Retain&quot;<br>}</pre><p><strong>Create CloudFrontOriginAccessIdentity:</strong></p><pre>&quot;CloudFrontOriginAccessIdentity&quot;: {<br>  &quot;Type&quot;: &quot;AWS::CloudFront::CloudFrontOriginAccessIdentity&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;CloudFrontOriginAccessIdentityConfig&quot;: {<br>      &quot;Comment&quot;: {<br>        &quot;Fn::Sub&quot;: &quot;CloudFront OAI&quot;<br>      }<br>    }<br>  }<br>}</pre><p><strong>Create S3 Bucket Policy:</strong></p><p>An S3 Bucket Policy is a document that specifies who can access the objects stored in an Amazon S3 bucket and under what conditions.</p><p>The below policy allows the CloudFront Origin Access Identity to retrieve objects from the bucket using the “s3:GetObject” action. This policy ensures that only the CloudFront distribution associated with the specified Origin Access Identity can access the objects in the bucket, ensuring security for the UI assets served through CloudFront.</p><p><strong>S3CanonicalUserId</strong>: S3CanonicalUserId is a unique identifier assigned to an AWS account. It’s used to designate ownership of objects stored in an Amazon S3 bucket.</p><pre>&quot;S3UIBucketPolicy&quot;: {<br>  &quot;Type&quot;: &quot;AWS::S3::BucketPolicy&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;Bucket&quot;: {<br>      &quot;Ref&quot;: &quot;S3UIBucket&quot;<br>    },<br>    &quot;PolicyDocument&quot;: {<br>      &quot;Statement&quot;: [<br>        {<br>          &quot;Action&quot;: [<br>            &quot;s3:GetObject&quot;<br>          ],<br>          &quot;Effect&quot;: &quot;Allow&quot;,<br>          &quot;Resource&quot;: &quot;{<br>            &quot;Fn::Join&quot;: [<br>              &quot;&quot;,<br>              [<br>                &quot;arn:aws:s3:::&quot;,<br>                {<br>                  &quot;Ref&quot;: &quot;S3UIBucket&quot;<br>                },<br>                &quot;/*&quot;<br>              ]<br>            ]<br>          },<br>          &quot;Principal&quot;: {<br>            &quot;CanonicalUser&quot;: {<br>              &quot;Fn::GetAtt&quot;: [<br>                &quot;CloudFrontOriginAccessIdentity&quot;,<br>                &quot;S3CanonicalUserId&quot;<br>              ]<br>            }<br>          }<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p><strong>Ref</strong> tags in CloudFormation templates are used to reference other AWS resources within the same template, enabling dynamic insertion of resource values.<br><strong>Fn::Join</strong> tags in CloudFormation templates are used to concatenate strings or values together</p><p><strong>Create WAF:</strong></p><p>I’ve crafted a WAF ACL to carefully control access, permitting only specific IP ranges to interact with our system.</p><pre>&quot;MyIPSet&quot;: {<br>  &quot;Type&quot;: &quot;AWS::WAFv2::IPSet&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;Name&quot;: &quot;MyIPSet&quot;,<br>    &quot;Scope&quot;: &quot;REGIONAL&quot;,<br>    &quot;IPAddressVersion&quot;: &quot;IPV4&quot;,<br>    &quot;Addresses&quot;: [<br>      &quot;198.0.2.0/24&quot;,<br>    ]<br>  }<br>},<br>&quot;WebACL&quot;: {<br>  &quot;Type&quot;: &quot;AWS::WAFv2::WebACL&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;Name&quot;: &quot;MyWebACL&quot;,<br>    &quot;Scope&quot;: &quot;REGIONAL&quot;,<br>    &quot;DefaultAction&quot;: {<br>      &quot;Allow&quot;: {}<br>    },<br>    &quot;VisibilityConfig&quot;: {<br>      &quot;SampledRequestsEnabled&quot;: true,<br>      &quot;CloudWatchMetricsEnabled&quot;: true,<br>      &quot;MetricName&quot;: &quot;MyWebACLMetric&quot;<br>    },<br>    &quot;Rules&quot;: [<br>      {<br>        &quot;Name&quot;: &quot;BlockIPSet&quot;,<br>        &quot;Priority&quot;: 0,<br>        &quot;Action&quot;: {<br>          &quot;Block&quot;: {}<br>        },<br>        &quot;Statement&quot;: {<br>          &quot;IPSetReferenceStatement&quot;: {<br>            &quot;ARN&quot;: {<br>              &quot;Fn::GetAtt&quot;: [<br>                &quot;MyIPSet&quot;,<br>                &quot;Arn&quot;<br>              ]<br>            }<br>          }<br>        },<br>        &quot;VisibilityConfig&quot;: {<br>          &quot;SampledRequestsEnabled&quot;: true,<br>          &quot;CloudWatchMetricsEnabled&quot;: true,<br>          &quot;MetricName&quot;: &quot;BlockIPSetMetric&quot;<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p><strong>Creating CloudFront Distribution:</strong></p><p>This CloudFormation template sets up a CloudFront distribution, fine-tuning settings like logging, aliases, error responses, cache behavior, origins, SSL certificate, and tags. Additionally, OriginPath directs CloudFront to search for index.html within a specific location inside the associated S3 bucket. To complete the setup, you’ll need to obtain a certificate and add it to the template, but for security reasons, the certificate ARN isn’t included here.</p><pre>&quot;CloudFrontDistribution&quot;: {<br>  &quot;Type&quot;: &quot;AWS::CloudFront::Distribution&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;DistributionConfig&quot;: {<br>      &quot;Logging&quot;: {<br>        &quot;IncludeCookies&quot;: &quot;true&quot;,<br>        &quot;Bucket&quot;: {<br>          &quot;Fn::Join&quot;: [<br>            &quot;&quot;,<br>            [<br>              {<br>                &quot;Ref&quot;: &quot;LoggingBucket&quot;<br>              },<br>              &quot;.s3.amazonaws.com&quot;<br>            ]<br>          ]<br>        },<br>        &quot;Prefix&quot;: &quot;cloudfront/&quot;,<br>      },<br>      &quot;Aliases&quot;: [<br>        &quot;&lt;specify your cloudfront alias here&gt;&quot;<br>      ],<br>      &quot;WebACLId&quot; : {<br>        &quot;Ref&quot;: &quot;WebACL&quot;<br>      },<br>      &quot;CustomErrorResponses&quot;: [<br>        {<br>          &quot;ErrorCode&quot;: 404,<br>          &quot;ResponsePagePath&quot;: &quot;/error.html&quot;,<br>          &quot;ResponseCode&quot;: &quot;404&quot;,<br>          &quot;ErrorCachingMinTTL&quot;: 10<br>        }<br>      ],<br>      &quot;DefaultCacheBehavior&quot;: {<br>        &quot;TargetOriginId&quot;: {<br>          &quot;Ref&quot;: &quot;S3UIBucketName&quot;<br>        },<br>        &quot;SmoothStreaming&quot;: &quot;false&quot;,<br>        &quot;AllowedMethods&quot;: [ &quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot; ],<br>        &quot;CachedMethods&quot;: [ &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot; ],<br>        &quot;Compress&quot;: &quot;true&quot;,<br>        &quot;DefaultTTL&quot;: 60<br>        &quot;ForwardedValues&quot;: {<br>          &quot;QueryString&quot;: &quot;false&quot;,<br>          &quot;Cookies&quot;: {<br>            &quot;Forward&quot;: &quot;none&quot;<br>          },<br>          &quot;Headers&quot;: [<br>            &quot;Origin&quot;,<br>            &quot;Access-Control-Request-Method&quot;,<br>            &quot;Access-Control-Request-Headers&quot;<br>          ]<br>        },<br>        &quot;ViewerProtocolPolicy&quot;: &quot;https-only&quot;<br>      },<br>      &quot;DefaultRootObject&quot;: &quot;index.html&quot;,<br>      &quot;Enabled&quot;: true,<br>      &quot;HttpVersion&quot;: &quot;http2&quot;,<br>      &quot;Origins&quot;: [<br>        {<br>          &quot;DomainName&quot;: {<br>            &quot;Fn::Join&quot;: [<br>              &quot;&quot;,<br>              [<br>                {<br>                  &quot;Ref&quot;: &quot;S3UIBucket&quot;<br>                },<br>                &quot;.s3.amazonaws.com&quot;<br>              ]<br>            ]<br>          },<br>          &quot;Id&quot;: {<br>            &quot;Ref&quot;: &quot;S3UIBucketName&quot;<br>          },<br>          &quot;S3OriginConfig&quot;: {<br>            &quot;OriginAccessIdentity&quot;: {<br>              &quot;Fn::Join&quot;: [<br>                &quot;&quot;,<br>                [<br>                  &quot;origin-access-identity/cloudfront/&quot;,<br>                  {<br>                    &quot;Ref&quot;: &quot;CloudFrontOriginAccessIdentity&quot;<br>                  }<br>                ]<br>              ]<br>            }<br>          },<br>          &quot;OriginPath&quot;: &quot;/ui/latest/dist&quot;<br>        }<br>      ],<br>      &quot;PriceClass&quot;: &quot;PriceClass_All&quot;,<br>      &quot;ViewerCertificate&quot;: {<br>        &quot;AcmCertificateArn&quot;: {<br>          &quot;Ref&quot;: &quot;certificateArn&quot;<br>        },<br>        &quot;SslSupportMethod&quot;: &quot;sni-only&quot;,<br>        &quot;MinimumProtocolVersion&quot;: &quot;TLSv1.2_2021&quot;<br>      }<br>    },<br>    &quot;Tags&quot;: [<br>      {<br>        &quot;Key&quot;: &quot;Domain&quot;,<br>        &quot;Value&quot;: &quot;ui-deployment-resource&quot;<br>      }<br>    ]<br>  }<br>}</pre><p><strong>Create Route53 Record Set:</strong></p><p>This CloudFormation resource creates a Route 53 record set, which is used to map a domain name to a specific destination. It’s configured with properties such as the hosted zone ID, the CNAME alias mentioned in CloudFront, the record type (in this case, “A” for an IPv4 address), and an alias target pointing to the CloudFront distribution. This allows users to access your website or application using the specified domain name, which is then directed to the CloudFront distribution for content delivery.</p><pre>&quot;DNSRecord&quot;: {<br>  &quot;Type&quot;: &quot;AWS::Route53::RecordSet&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;HostedZoneId&quot;: &quot;&lt;Specify your hosted zone id here&gt;&quot;,<br>    &quot;Name&quot;: {<br>      &quot;Ref&quot;: &quot;&lt;CNAME Alisas mentioned in cloud front&gt;&quot;<br>    },<br>    &quot;Type&quot;: &quot;A&quot;,<br>    &quot;AliasTarget&quot;: {<br>      &quot;HostedZoneId&quot;: &quot;Z2FDTNDATAQYW2&quot;,<br>      &quot;DNSName&quot;: {<br>        &quot;Fn::GetAtt&quot;: [<br>          &quot;CloudFrontDistribution&quot;,<br>          &quot;DomainName&quot;<br>        ]<br>      },<br>      &quot;EvaluateTargetHealth&quot;: false<br>    }<br>  }<br>}</pre><p>For future CloudFront conquerors! Quick tip: when you’re crafting your AWS Route 53 DNS records for CloudFront, make sure to use “HostedZoneId”: “Z2FDTNDATAQYW2”. Trust me, I learned the hard way after wandering down the wrong path and losing some quality time. It’s like mistaking your car keys for your house keys — both important, but they unlock different doors!</p><h3>APPLICATION HOSTED SUCCESSFULLY!!!</h3><p>Just wanted to share my adventure in setting up UI Application Hosting using CloudFormation on AWS. It was like navigating a maze blindfolded — my first time with CloudFormation and UI hosting! Spent hours in research, so I decided to jot it all down. Hope this helps someone out there, like a treasure map in the jungle of AWS! Feel free to share your thoughts and feedback. And hey, if you’re lost in the cloud like I was, let’s connect on <a href="https://www.linkedin.com/in/sunandan-bose/">LinkedIn</a> and figure it out together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ad6b247669" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Work Distribution: Scaling Your Systems with Redis Queue]]></title>
            <link>https://medium.com/@sunandanbose17/efficient-work-distribution-scaling-your-systems-with-redis-queue-e3df81b040a9?source=rss-4f70a5247ac3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3df81b040a9</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[distributed]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sunandanbose]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 10:30:19 GMT</pubDate>
            <atom:updated>2024-03-31T10:30:58.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Q2PmQA00V1U3TITbwvQJWQ.jpeg" /></figure><h3><strong>Problem:</strong></h3><p>In Java, I encountered a challenge where a job designed to handle numerous resources asynchronously resulted in only one instance processing all tasks, leaving other instances idle. This limitation hindered the scalability of my job processing system. To address this issue, I sought to develop a solution that could efficiently distribute the workload across multiple instances, enabling the utilization of all available resources effectively.</p><h3><strong>Limitations:</strong></h3><p>The utilization of Kafka or a Messaging Queue was constrained by an associated additional cost, presenting a limitation within the project’s budgetary considerations.</p><h3><strong>Initial Approach:</strong></h3><p>The initial strategy involved leveraging the Redis Pub/Sub system, primarily due to the project’s existing utilization of Redis, rendering its integration for this purpose straightforward. Upon preliminary examination, it became apparent that a Pub/Sub system or Messaging Queue was required, and Redis, with its built-in Pub/Sub feature, appeared to offer a viable solution with minimal implementation complexity.</p><p>However, an inherent limitation arose within the Redis Pub/Sub system. Upon message publication, all consumers would concurrently process the message, contrary to the desired behavior where each resource should be processed only once. Addressing this challenge proved elusive within Redis, as it lacked a mechanism to mark a message as read once consumed by a subscriber, thereby preventing subsequent consumers from processing it.</p><h3><strong>Redis Queue:</strong></h3><p>Following the limitations encountered with the Redis Pub/Sub system, the Redis Queue emerged as an apt alternative. The queuing mechanism facilitated the distribution of resources across multiple systems, thereby enhancing efficiency. Moreover, the inherent feature of the queue ensured that once a resource was consumed by one subscriber, it would not be redundantly processed by subsequent subscribers. This characteristic alleviated concerns regarding duplicate processing, thereby optimizing resource utilization within the distributed system.</p><p><strong>Producer:</strong></p><p>The API will primarily invoke the fetchResources method, which will operate asynchronously, with the API initiating the call and subsequently proceeding without awaiting the response. In essence, the API will function solely as a producer, triggering the fetchResources method to retrieve resources without waiting for the completion of the operation.</p><pre>@Autowired<br>private RedisTemplate&lt;String, String&gt; redisTemplate;<br>@Autowired<br>private ObjectMapper objectMapper;<br>private static final String REDIS_QUEUE_KEY = &quot;processResourcesJob&quot;;<br>record ResourceProcessDetails(String resource, String type){};<br><br>private void fetchResources(String type){<br>  List&lt;String&gt; resourceIdList = getResourceIdsFromS3(type);// fetching the resources from S3;<br>  for(int i = 0; i &lt; resourceIdList.size(); i++){<br>      String jsonBody = objectMapper.writeValueAsString(new ResourceProcessDetails(resource, type));<br>      redisTemplate.opsForList().leftPush(REDIS_QUEUE_KEY, jsonBody);<br>  }<br>}</pre><p><strong>Consumer:<br></strong>A consumer process is scheduled to execute every 30 seconds, tasked with inspecting the queue for any newly added items. Upon inspection, if the queue size is found to be non-empty, the consumer will proceed to dequeue an object from the queue and initiate the resource processing procedure accordingly. This systematic approach ensures timely resource consumption and processing, facilitating efficient utilization of available resources.</p><pre>@Component<br>public class ResourceConsumer { <br><br>  @Autowired<br>  private RedisTemplate&lt;String, String&gt; redisTemplate;<br>  @Autowired<br>  private ObjectMapper objectMapper;<br>  private static final String REDIS_QUEUE_KEY = &quot;processResourcesJob&quot;;<br><br>  @Scheduled(cron = &quot;*/30 * * * * *&quot;) // Run every 30 seconds<br>  public void processResource() {<br>    Long size = redisTemplate.opsForList().size(REDIS_QUEUE_KEY);<br>    while (size != null &amp;&amp; size &gt; 0 ) {<br>      try {<br>       String jsonBody = redisTemplate.opsForList().rightPop(REDIS_QUEUE_KEY);<br>       ResourceProcessDetails resourceProcessDetail = objectMapper.readValue(jsonBody, AssetProcessDetails.class);<br>       processAsset(resourceProcessDetail.resource, resourceProcessDetail.type);<br>       size = redisTemplate.opsForList().size(REDIS_QUEUE_KEY);<br>      } catch (Exception e) {<br>        throw new RuntimeException(e);<br>      }<br>    }<br>  }<br>}</pre><h3>Conclusion:</h3><p>This configured setup has significantly facilitated the scaling of resource processing across systems. In instances where the processing of particular resources requires prolonged durations, the elasticity of my cloud computing infrastructure allows for the seamless addition of additional instances. This augmentation enhances the overall efficiency of the processing operation, ensuring expedited execution while effectively managing resource utilization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3df81b040a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>