<?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 Aditya Rajbhar on Medium]]></title>
        <description><![CDATA[Stories by Aditya Rajbhar on Medium]]></description>
        <link>https://medium.com/@codebyaadi?source=rss-0d39dace4aa9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zC-lhtImK-Mu-MfAqs10gA.jpeg</url>
            <title>Stories by Aditya Rajbhar on Medium</title>
            <link>https://medium.com/@codebyaadi?source=rss-0d39dace4aa9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:52:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codebyaadi/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[I open-sourced Upzy: uptime monitoring and attack-surface security in one tool]]></title>
            <link>https://medium.com/@codebyaadi/i-open-sourced-upzy-uptime-monitoring-and-attack-surface-security-in-one-tool-18b3fd9e54f6?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b3fd9e54f6</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 19:41:01 GMT</pubDate>
            <atom:updated>2026-10-31T19:41:01.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP6d4fUnoas0NIkefLpqbQ.png" /></figure><p>Why I built it, how it works inside (Postgres job queue, SSRF-safe probes, an A–F grade), and what I learned taking a private repo public</p><p>Today I made Upzy public under the MIT license. It’s uptime monitoring and external attack-surface security for small teams, and it tries hard to tell you, in plain English, what’s wrong and exactly how to fix it.</p><p>This post covers why it exists, how it works inside, and what I learned getting a private codebase ready to be public.</p><h3>Why one tool for both</h3><p>Small teams usually end up with two tools. A cheap uptime pinger that knows nothing about what you expose, and (if they can afford it) a security scanner written for security teams, which reports problems in jargon and never tells you whether the site is even up.</p><p>I wanted one place that answers two questions: <em>is it up?</em> and <em>what am I exposing?</em> And for every problem, the change to make for my actual stack, not a link to an RFC.</p><p>Here’s what you see about a minute after adding a website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jgr3QdHc7oEWwF7iUdjCow.png" /></figure><h3>What it does</h3><p>Uptime. HTTP, TCP, DNS and SSL checks every minute, keyword and JSON assertions, multi-step API flows, and heartbeat monitors for cron jobs and workers. A slow-but-up service gets a “degraded” state instead of an incident.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Lfwdr1-ZtsOYdBqd0203TA.png" /></figure><p>Attack surface. Certificates and old TLS versions, security headers and cookies, SPF, DMARC, CAA and MTA-STS, DNSSEC, domain expiry, dangling DNS (subdomain takeover), new third-party scripts appearing on a page, and known CVEs for the software a site runs, enriched with CISA KEV and EPSS so they’re ranked by real-world risk.</p><p>A fix, not a report. Every finding comes with the change to make for the stack Upzy detected (nginx, Apache, Caddy, Cloudflare, Vercel and more), and a Verify fix button re-runs just that check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*biX8rvxjtVxoM9E5MJEQ9w.png" /></figure><p>A grade. Every site gets an A–F health score with a breakdown and a 90-day trend, so “are we OK?” has a one-letter answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*j-mto0YWR0zsXUqSimNUQA.png" /></figure><p>Status pages and alerts. Public status pages with 90 days of uptime and email subscribers. Alerts go to email, Slack, Discord, Microsoft Teams, PagerDuty, Opsgenie, GitHub issues or signed webhooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*0eX-or7LWtwtRfwEMPoGkA.png" /></figure><p>AI, opt-in. If you add your own provider key (Groq, OpenAI, Anthropic, Gemini or OpenRouter), it explains findings in plain English, suggests a likely cause when a monitor goes down and drafts postmortems. There’s also a read-only MCP server, so tools like Claude Code can ask “which monitors are down?” or “which findings should I fix first?”.</p><h3>How it works inside</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0K9ewdHAgAz_qQSpBvqWg.png" /></figure><p>The stack is Bun workspaces with Turborepo, an Elysia API, Drizzle on Postgres, better-auth, and Next.js 16 with shadcn/ui. A few design decisions I’m happy with:</p><h3>Postgres is also the job queue</h3><p>There’s no Redis or separate broker. Jobs are rows in a jobs table, and workers claim them with FOR UPDATE SKIP LOCKED, so two workers never get the same job:</p><pre>update jobs set state = &#39;running&#39;, attempts = attempts + 1, locked_at = now()<br>where id in (<br>  select id from jobs<br>  where queue = $1 and state = &#39;queued&#39; and run_at &lt;= now()<br>  order by run_at<br>  limit $2<br>  for update skip locked<br>)</pre><p>Instead of polling, an insert trigger sends a Postgres notification and the waiting worker wakes up through LISTEN (with a fallback to polling every second where LISTEN isn&#39;t available). One less service to run is a big deal when the goal is &quot;self-host it on one small VPS&quot;.</p><h3>One worker, several roles</h3><p>The worker runs roles: a scheduler that decides what’s due, a prober that runs uptime checks, a scanner for security checks, a notifier that delivers alerts, and a few more. An environment variable (WORKER_ROLES) picks which ones a process runs, so everything can live on one machine, or a role can move to another host that can reach Postgres.</p><h3>Blips don’t page you</h3><p>A monitor is only declared down after a number of consecutive failures (two by default), and any success resolves it. Being slow never opens an incident; it only shows “degraded”. It’s a small pure state machine, which made it easy to test every edge case, including maintenance windows.</p><h3>Targets are public only</h3><p>A monitoring tool that fetches any URL you give it is an SSRF tool if you’re careless. Upzy refuses loopback, private, link-local and cloud-metadata addresses, and it resolves and pins the address at connect time, so DNS rebinding can’t swap it afterwards.</p><h3>Passive until you prove ownership</h3><p>Without proof that you own a domain, scans only look at what any visitor can see: no logins, no guessing, no port scans. After you verify it with a DNS record or a file, scans also request a short fixed list of paths that should never be public (like /.env and /.git/HEAD) and test whether about a dozen risky ports (databases, RDP, Telnet) accept a connection. Findings record where something was found, never what was read.</p><h3>AI is fenced in</h3><p>The AI layer never has write access, and alerting never depends on it. Inputs are redacted and wrapped as untrusted data, output is schema-validated, and each organization has a daily token budget. It runs only on your own key, with no shared server key and no silent fallback to another provider.</p><h3>What I learned open-sourcing it</h3><p>The code was the easy part. Making a private repo safe to publish took more care than I expected. What I did:</p><ol><li>Split the private stuff out first. Plans, internal docs and notes moved to a separate private repo, so the public one only has what belongs there.</li><li>Audited every config and script for anything that shouldn’t be public, not just .env files.</li><li>Published from a clean snapshot with one squashed commit. A private repo’s history can contain things you deleted long ago. Starting the public repo from a single fresh commit means old history can’t leak anything.</li></ol><p>CI on the public repo runs format, lint, types, migrations (including a drift check), the full test suite against Postgres and the build, plus a separate workflow with gitleaks, OSV-Scanner and CodeQL.</p><h3>Try it</h3><ul><li>Code (MIT): <a href="https://github.com/codebyaadi/upzy-oss">github.com/codebyaadi/upzy-oss</a></li><li>Hosted version: <a href="https://upzy.codebyaadi.com/">upzy.codebyaadi.com</a> (early access, free)</li></ul><p>It runs locally with Bun and Docker in a few commands, and self-hosts on one small VPS with Docker Compose and Caddy. The README has the steps.</p><p>What’s next: DKIM key checks. A comment on my launch post asked about email authentication, and the first version is already written.</p><p>If you try it, I’d love to hear what it finds on your domain, and what it gets wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b3fd9e54f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jev and System One Models: What Is Under the Hood, and What Is Not Public]]></title>
            <link>https://medium.com/@codebyaadi/jev-and-system-one-models-what-is-under-the-hood-and-what-is-not-public-1b918cfcfbfc?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b918cfcfbfc</guid>
            <category><![CDATA[system-one-model]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[jevs]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 15:16:25 GMT</pubDate>
            <atom:updated>2026-10-04T15:16:25.277Z</atom:updated>
            <content:encoded><![CDATA[<p>“<em>A model that never writes a sentence, answers in about 100 ms, and tells your code how sure it is. Here is how it works, sorted into documented, inferred and unknown.”</em></p><p>On Sep 15, 2026, TypeSafe AI released <strong>Jev</strong>, the first of what it calls <strong>System One models</strong>. The pitch: chat models are used as functions inside software, and that is the wrong shape. You prompt for text, parse it, validate it, and hope it did not drift. Jev skips the text entirely.</p><p>TypeSafe has not published the model architecture, so this post separates three things: what the docs state, what I am inferring, and what nobody outside the company knows.</p><h3>The core idea: a function call, not a conversation</h3><p>TypeSafe’s one-line description is a frontier-intelligence function call: unstructured state in, typed probabilistic decisions out. The name comes from Kahneman’s fast “System 1” thinking, meaning quick judgments rather than long deliberation.</p><figure><img alt="System One Model vs LLM used as function" src="https://cdn-images-1.medium.com/max/1024/1*cE_xhcUfe050Eafx2QhxCw.png" /><figcaption>The parse-and-validate step disappears because the output space is defined before the call.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueL9LmcnksdQb7DxB853zQ.png" /></figure><h3>The API contract: state plus questions</h3><p>Every call has a state (text, JSON or an array of text) and a map of named <strong>questions</strong>. There are three question types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBUq1KKp8yBG7zxNKk5RrQ.png" /></figure><p>quickstart.py (from TypeSafe’s docs, trimmed)</p><pre>from typesafe_sdk import Choice, Noul, TypeSafeClient<br><br>client = TypeSafeClient()   # reads TYPESAFE_API_KEY, model defaults to jev-latest<br>r = client.system_one(<br>    state=&quot;Integration has failed for 3 days and I&#39;m losing sales. Help ASAP.&quot;,<br>    questions={<br>        &quot;department&quot;: Choice(<br>            instructions=&quot;Which team should handle this&quot;,<br>            criteria={&quot;billing&quot;: &quot;Payments&quot;, &quot;technical&quot;: &quot;Bugs or integrations&quot;,<br>                      &quot;sales&quot;: &quot;Pricing or accounts&quot;},<br>        ),<br>        &quot;is_urgent&quot;: Noul(instructions=&quot;The message conveys urgency&quot;),<br>    },<br>)<br>print(r.answers[&quot;department&quot;].choice, r.answers[&quot;department&quot;].confidence)<br>print(r.answers[&quot;is_urgent&quot;].noul)</pre><h3>What happens during one call</h3><p>The docs say Jev reads the state once and evaluates every question against it in parallel and in isolation. No answer becomes context for another, which is why adding questions barely changes latency and why docs call it “context-rot” free across questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRWXTFOd_aQILiPAIk3WMw.png" /><figcaption>Questions fan out from one shared read of the state and come back in a single response.</figcaption></figure><p>Documented limits for jev-1.13: 64k tokens per request, 32k for the state plus the longest question, text input only, up to 255 options per Choice, and 100K tokens/s plus 80 requests/s as rate limits that TypeSafe says are still adjusting.</p><blockquote><strong>My inference, not TypeSafe’s disclosure.</strong> A “parallel sampler” over a closed answer set most plausibly means a non-autoregressive pass: the model encodes the state, and each question reads out a probability distribution over its own options directly, instead of emitting tokens one at a time. That would explain the speed (no decode loop), the free output tokens, and the guaranteed schema, since the output space only contains valid answers. How the model actually does this is unpublished.</blockquote><h3>Training: RLCD instead of RLHF</h3><p>TypeSafe frames post-training as three paths. RLHF optimizes for answers humans prefer and produced chatbots. RLVR optimizes for verifiable rewards and produced reasoning models. <strong>RLCD</strong>, Reinforcement Learning for Calibrated Decisions, optimizes for probabilities that match reality.</p><p>Calibration is a statement about groups of predictions. Of all answers given 80% probability, about 80% should be right. It does not promise that any single answer is correct. TypeSafe argues RLHF can reward confident-sounding answers and narrows output diversity (“mode dropping”), which is the wrong trade for unattended automation.</p><p>Jev is not fine-tuned per customer and TypeSafe states it is not trained on customer requests. You customize behavior through the state and question wording, never through weights.</p><h3>Confidence: the part you build around</h3><p>Every Choice and Score answer includes the full probability distribution plus a confidence from 0 to 1 computed from its shape. For a Choice with <em>n</em> options:</p><pre>confidence = (p_max - 1/n) / (1 - 1/n)<br><br># docs example: probabilities 0.85 / 0.15 / 0.00 across 3 options<br># (0.85 - 1/3) / (1 - 1/3) = 0.775  -&gt; reported as 0.78</pre><p>Score uses the same idea but accounts for level order, so probability split across neighboring levels hurts less than a split across opposite ends. Noul has no confidence field, because its probability already carries it: near 0.5 means unsure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrAPWRB440XFU2dhA2rKCQ.png" /><figcaption>Thresholds should scale with risk. The docs use 0.5 as a floor and 0.9 for destructive actions, as an example only.</figcaption></figure><p>This is the architectural payoff. The model is a fuzzy if statement, and your code owns the branching, the weights and the thresholds.</p><h3>How to read the numbers</h3><ul><li><strong>Speed and price are checkable.</strong> The published latency is measured from the team’s laptops on the US West Coast, and the pricing is public, though TypeSafe admits it cannot prove it is not subsidized.</li><li><strong>“Cannot hallucinate” means schema validity.</strong> The output always fits your types. It does not mean every answer is right, and the docs say so. Wrong-but-well-formed answers still happen.</li><li><strong>The 193.6x faster and 444.6x cheaper figures</strong> come from TypeSafe’s own workflow evals, and the company says they sit at the high end of real-world gains. Reference answers are the average of two other labs’ flagship models, and the workflows were written by TypeSafe’s own team.</li><li><strong>Independent evidence is thin.</strong> One third-party deep dive notes TypeSafe chose not to publish public-benchmark results. Treat the claims as promising until you test your own data.</li></ul><h3>Where Jev struggles</h3><p>TypeSafe publishes a candid “jaggedness” list for jev-1.13. The recurring themes:</p><ul><li><strong>Literal reading.</strong> It answers the question as written, not as intended.</li><li><strong>Numbers and dates.</strong> It does not count or do arithmetic reliably, so extract parts with the model and compute in code.</li><li><strong>Large, noisy state.</strong> Accuracy drops with irrelevant context, so filter first.</li><li><strong>Adversarial text.</strong> Injected instructions inside the state can steer answers.</li><li><strong>Option order bias.</strong> It leans toward the first Choice option, so shuffle and re-check.</li><li><strong>No generation.</strong> Use a normal LLM when you need prose or code.</li></ul><h3>What is unknown</h3><ul><li>The model architecture, parameter count and how the parallel sampler works. TypeSafe has only said it is neither small nor an LLM.</li><li>The RLCD objective and training data sources. The FAQ entries on both are collapsed on the launch page.</li><li>Performance on public benchmarks and on non-English text, where English is the strongest.</li></ul><h3>Who should try it</h3><p>Jev fits routing, classification, scoring, extraction-by-selection, guardrails and real-time decisions where an LLM call is too slow or too loose. It does not fit open-ended generation. A sensible pattern is to use Jev for the many cheap gate decisions and call a large LLM only for the rare case that needs reasoning or writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b918cfcfbfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CDNs Work: The Real-World Magic Behind Every Fast App]]></title>
            <link>https://medium.com/@codebyaadi/how-cdns-work-the-real-world-magic-behind-every-fast-app-460ec2858fbb?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/460ec2858fbb</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 06:25:14 GMT</pubDate>
            <atom:updated>2025-09-21T06:25:14.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2YS3kr50M68aEvP9D5CUQ.png" /><figcaption>A futuristic illustration of global content delivery: glowing data streams moving between sleek server racks, edge nodes, and user devices across a dark world map. Vibrant neon lines (blue, purple, green) flow dynamically between servers and cities, symbolizing speed and connectivity. High-tech atmosphere, cinematic lighting, modern and minimal, wide banner format, no text.</figcaption></figure><p>You know that feeling, right? You’re trying to load a website, and the little spinner just… keeps spinning. It’s like waiting in a line that goes nowhere. Now, think about streaming a movie on Netflix or scrolling through the endless feed of products on Amazon. The content appears instantly, as if it’s already there.</p><p>That’s not a coincidence, and it’s definitely not just magic. It’s the <strong>Content Delivery Network (CDN)</strong>, and if you’re building anything for the web today, you need to understand it. A CDN is the secret sauce that makes the internet feel fast, even when your users are thousands of miles from your servers.</p><h3>So, What’s a CDN in Plain English?</h3><p>Imagine you’re running a massive, world-famous coffee shop (your <strong>origin server</strong>) in a single city, say, San Francisco. People from all over the globe love your coffee, but they have to wait for it to be shipped from that one single shop. The global demand is a nightmare for your operations.</p><p>A <strong>CDN</strong> is like you deciding, “Okay, this is getting ridiculous.” So you set up a bunch of smaller, more efficient coffee kiosks (<strong>CDN edge servers</strong>) in a bunch of other cities — London, Tokyo, Mumbai, São Paulo. Now, when someone in London wants a cup, they just walk to their local kiosk and get it instantly. No more waiting for a long, expensive cross-ocean shipment. That’s a <strong>content delivery network</strong>: a distributed system of servers that brings your content closer to your users.</p><h3>How a CDN Works Under the Hood</h3><p>Alright, let’s get a little more technical, but I promise it’s not that complicated. The whole system runs on three core ideas: caching, edge locations, and smart routing.</p><h4>1. The Caching Game</h4><p>The very first time a user requests a file — like a high-res product photo or a big JavaScript bundle — their request goes all the way back to your main server. But here’s the clever part: the <strong>CDN</strong> grabs a copy of that file and holds onto it. It caches the file. From that point on, any other user in the same city or region who asks for the same file gets it directly from the local <strong>edge server</strong>. Your main server gets to take a break, and your users get their content at warp speed.</p><h4>2. All About Those Edge Servers</h4><p>These <strong>edge servers</strong> are the workhorses of the network. They’re strategically placed in data centers all over the world, as close as possible to major population centers. The goal is to minimize the physical distance the data has to travel. As a developer, you know that physical distance equals network <strong>latency</strong>, and latency is the enemy of a good user experience. A <strong>CDN</strong> fights that battle for you, every single day.</p><h4>3. The Art of Smart Routing</h4><p>When a user’s browser requests a file from your site, the <strong>CDN</strong>’s intelligent routing system figures out which <strong>edge server</strong> is best for that user. It’s not just about what’s closest on a map. It also considers things like network congestion and server load to make sure the user is routed to the fastest, most available server. It’s a real-time traffic director for your data.</p><h3>Where CDNs Shine: A Few Real-World Examples</h3><ul><li><strong>Streaming (Netflix, Hotstar):</strong> Imagine trying to stream the Super Bowl live, with millions of people hitting one central server. It would crash instantly. <strong>CDNs</strong> cache the video segments and serve them from nearby locations, making sure everyone gets a smooth, buffer-free stream.</li><li><strong>E-commerce (Amazon, Flipkart):</strong> When a major sale hits, traffic spikes through the roof. The static content — product images, style sheets, and scripts — is a huge part of the page load. By serving this from a <strong>CDN</strong>, the site stays responsive even under extreme load, preventing slow-downs that would cost a business millions.</li><li><strong>Gaming:</strong> Ever downloaded a massive game update? <strong>CDNs</strong> ensure that a 50GB patch isn’t coming from a single server in the US. They distribute it globally, so you can get back to gaming faster.</li></ul><h3>The Big Wins: Why You Can’t Ignore CDNs</h3><ul><li><strong>Blazing-Fast Performance:</strong> This is the most obvious one. Lower <strong>latency</strong> and faster load times mean happier users and better SEO. Google actually factors page speed into its search rankings, so a <strong>CDN</strong> can directly help your site climb higher.</li><li><strong>Massive Scalability:</strong> Whether you’re dealing with a viral tweet that sends a traffic spike or a holiday sale, a <strong>CDN</strong> absorbs the shock, shielding your main server from being overwhelmed.</li><li><strong>Cost Savings:</strong> By offloading most of the traffic to the <strong>CDN</strong>’s network, you drastically reduce the bandwidth costs from your hosting provider. Trust me, those bills can add up.</li><li><strong>Enhanced Security:</strong> A <strong>CDN</strong> sits in front of your origin server, acting as a powerful line of defense against cyberattacks. Many providers offer built-in <strong>DDoS mitigation</strong> and Web Application Firewalls (WAFs), adding a critical layer of protection for your app.</li></ul><h3>Looking Ahead: CDNs Are Getting Smarter</h3><p>The evolution of CDNs is probably the most exciting part. They aren’t just for serving static files anymore. We’re seeing a push toward <strong>edge computing</strong>, where developers can actually run code right on the <strong>CDN’s edge servers</strong>. This opens up a world of possibilities, from real-time API processing to advanced personalization, all without a round trip to your origin server. It’s a game-changer for system architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=460ec2858fbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Gemini to CI/CD: Building and Testing a RAG API with FastAPI and GitHub Actions]]></title>
            <link>https://medium.com/@codebyaadi/from-gemini-to-ci-cd-building-and-testing-a-rag-api-with-fastapi-and-github-actions-d9ee32923979?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ee32923979</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 07:44:47 GMT</pubDate>
            <atom:updated>2025-08-31T07:44:47.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXj4Mtz2vbnypIgOhfMX6g.png" /></figure><p>The world is buzzing with applications powered by Large Language Models (LLMs) like Google Gemini. We see incredible demos, often born from the creative chaos of a Jupyter Notebook. But there’s a huge gap between a notebook and a robust, production-ready application. How do you ensure your brilliant RAG (Retrieval-Augmented Generation) logic doesn’t silently break with the next commit? How do you move from experimentation to engineering?</p><p>The answer lies in bridging the world of AI development with modern DevOps practices. In this tutorial, we’ll do exactly that. We will build a smart RAG API using Google Gemini and FastAPI. Then, we’ll go a step further and create a complete, automated CI (Continuous Integration) pipeline using GitHub Actions. This pipeline will test our application on every single push, ensuring its reliability and integrity while handling sensitive API keys with professional-grade security.</p><h4>What You’ll Learn</h4><ul><li><strong>Build a Core RAG Service:</strong> Combine a local knowledge base with Google Gemini to answer questions based on specific context.</li><li><strong>Expose it as an API: </strong>Wrap the RAG service in a fast, modern API using FastAPI.</li><li><strong>Write Meaningful Tests:</strong> Learn the critical skill of <em>mocking</em> external services like the Gemini API to create fast, reliable, and cost-effective tests.</li><li><strong>Automate Everything:</strong> Implement a full CI pipeline with GitHub Actions to lint and test your code automatically.</li><li><strong>Manage Secrets Securely:</strong> Learn the industry-standard way to handle API keys using GitHub Actions Secrets.</li></ul><h4>Prerequisites</h4><p>Before we begin, make sure you have the following tools installed and configured:</p><ul><li><strong>Python 3.9+</strong> and pip</li><li><strong>Git</strong> for version control</li><li>A <strong>GitHub account</strong></li><li>Your favorite <strong>code editor</strong> (e.g., VS Code)</li><li>A <strong>Google AI Studio API key</strong>. You can get one for free from <a href="https://aistudio.google.com/app/apikey">Google AI Studio</a>. Your API key must have permissions for both the Generative Model and the Embedding Model.</li></ul><h4>Step 1: Project Setup &amp; Virtual Environment</h4><p>First things first, let’s set up our project directory and a virtual environment. This is a critical best practice that creates an isolated space for our project’s Python packages, preventing conflicts with other projects on your system.</p><ol><li><strong>Create the Project Directory</strong></li></ol><p>Open your terminal and run the following commands:</p><pre>mkdir gemini-rag-api<br>cd gemini-rag-api</pre><p><strong>2. Create and Activate the Virtual Environment</strong></p><p>Next, create a virtual environment named venv and activate it.</p><ul><li>On macOS and Linux:</li></ul><pre>python3 -m venv venv<br>source venv/bin/activate</pre><ul><li>On Windows (Command Prompt):</li></ul><pre>python -m venv venv<br>venv\Scripts\activate</pre><p>You’ll know it’s active because your terminal prompt will be prefixed with (venv). All subsequent commands should be run inside this activated environment.</p><h4>Step 2: Architecting the RAG Service with Gemini</h4><p>Our RAG system will have two core components, both powered by Gemini: a Retriever and a Generator.</p><ol><li><strong>The Retriever</strong>: This component finds relevant information from our knowledge base. We’ll use a local text file for knowledge, the <strong>Gemini embedding model (</strong><strong>models/embedding-001)</strong> to create numerical vectors of our text, and an in-memory ChromaDB vector store for efficient search.</li><li><strong>The Generator</strong>: This is our generative LLM, <strong>Google Gemini (</strong>gemini-1.5-flash-002<strong>)</strong>. It will take the user&#39;s question and the retrieved context to generate a coherent answer.</li></ol><p>First, create a simple text file named knowledge_base.txt.</p><pre>Mars is the fourth planet from the Sun and is known as the Red Planet.<br>Jupiter is the largest planet in our solar system and is a gas giant.<br>The Sun is a G-type main-sequence star at the center of the Solar System.<br>The Earth&#39;s atmosphere is composed of about 78% nitrogen, 21% oxygen, and 1% other gases.</pre><p>Next, let’s build the Python service that orchestrates the RAG logic. Create a file named rag_service.py.</p><pre>import os<br>import google.generativeai as genai<br>from chromadb import Client as ChromaClient<br><br><br>class RAGService:<br>    def __init__(self):<br>        api_key = os.getenv(&quot;GEMINI_API_KEY&quot;)<br>        if not api_key:<br>            raise ValueError(&quot;GEMINI_API_KEY environment variable not set.&quot;)<br>        genai.configure(api_key=api_key)<br><br>        self.generative_model = genai.GenerativeModel(&quot;gemini-1.5-flash-002&quot;)<br>        self.embedding_model_name = &quot;models/embedding-001&quot;<br><br>        self.chroma_client = ChromaClient()<br>        self.collection = self.chroma_client.create_collection(name=&quot;knowledge_base&quot;)<br><br>        self._load_and_embed_knowledge_base()<br><br>    def _load_and_embed_knowledge_base(self):<br>        &quot;&quot;&quot;Loads the knowledge base from a file and stores embeddings.&quot;&quot;&quot;<br>        try:<br>            with open(&quot;knowledge_base.txt&quot;, &quot;r&quot;) as f:<br>                documents = [line.strip() for line in f.readlines() if line.strip()]<br><br>            print(f&quot;Embedding {len(documents)} document(s)...&quot;)<br>            response = genai.embed_content(<br>                model=self.embedding_model_name,<br>                content=documents,<br>                task_type=&quot;retrieval_document&quot;,<br>            )<br>            embeddings = response[&quot;embedding&quot;]<br><br>            self.collection.add(<br>                embeddings=embeddings,<br>                documents=documents,<br>                ids=[f&quot;id_{i}&quot; for i in range(len(documents))],<br>            )<br>            print(&quot;Knowledge base loaded and embedded successfully.&quot;)<br>        except Exception as e:<br>            print(f&quot;An error occurred while loading the knowledge base: {e}&quot;)<br><br>    def answer_question(self, question: str) -&gt; str:<br>        &quot;&quot;&quot;Answers a question using the RAG pattern.&quot;&quot;&quot;<br>        question_embedding_response = genai.embed_content(<br>            model=self.embedding_model_name,<br>            content=question,<br>            task_type=&quot;retrieval_query&quot;,<br>        )<br>        question_embedding = question_embedding_response[&quot;embedding&quot;]<br><br>        results = self.collection.query(<br>            query_embeddings=[question_embedding], n_results=2<br>        )<br>        context = &quot;\n&quot;.join(results[&quot;documents&quot;][0])<br><br>        prompt = f&quot;&quot;&quot;<br>        Using ONLY the following context, answer the question.<br>        If the context does not contain the answer, say &quot;I don&#39;t know&quot;.<br><br>        Context:<br>        {context}<br><br>        Question:<br>        {question}<br>        &quot;&quot;&quot;<br><br>        try:<br>            response = self.generative_model.generate_content(prompt)<br>            return response.text<br>        except Exception as e:<br>            print(f&quot;Error generating content with Gemini: {e}&quot;)<br>            return &quot;Sorry, I encountered an error while generating the answer.&quot;</pre><h4>Step 3: Building the FastAPI Endpoint</h4><p>Now we’ll expose our RAG service over the web using FastAPI. This part of our application doesn’t need to change; it simply calls the RAGService, regardless of its internal implementation.</p><p>Create a file named main.py.</p><pre>import os<br>from fastapi import FastAPI, HTTPException, status<br>from pydantic import BaseModel<br>from dotenv import load_dotenv<br>from rag_service import RAGService<br><br>load_dotenv()<br><br>if not os.getenv(&quot;GEMINI_API_KEY&quot;):<br>    raise RuntimeError(&quot;GEMINI_API_KEY not found in environment variables.&quot;)<br><br>app = FastAPI(<br>    title=&quot;Gemini RAG API&quot;,<br>    description=&quot;A simple API for a Retrieval-Augmented Generation service using Google Gemini.&quot;,<br>    version=&quot;1.0.0&quot;<br>)<br><br>try:<br>    rag_service = RAGService()<br>except Exception as e:<br>    raise RuntimeError(f&quot;Failed to initialize RAGService: {e}&quot;)<br><br>class QueryRequest(BaseModel):<br>    question: str<br><br>class QueryResponse(BaseModel):<br>    answer: str<br><br>@app.get(&quot;/&quot;, tags=[&quot;Health Check&quot;])<br>def read_root():<br>    return {&quot;status&quot;: &quot;ok&quot;}<br><br>@app.post(&quot;/query&quot;, response_model=QueryResponse, tags=[&quot;RAG&quot;])<br>async def query_rag(request: QueryRequest):<br>    if not request.question:<br>        raise HTTPException(<br>            status_code=status.HTTP_400_BAD_REQUEST,<br>            detail=&quot;Question field cannot be empty.&quot;<br>        )<br>    try:<br>        answer = rag_service.answer_question(request.question)<br>        return QueryResponse(answer=answer)<br>    except Exception as e:<br>        raise HTTPException(<br>            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,<br>            detail=f&quot;An internal error occurred: {e}&quot;<br>        )</pre><h4>Step 4: Writing Smart Tests for the AI API</h4><p>Automated tests are non-negotiable for robust applications. We will <strong>mock</strong> the external Gemini API calls to ensure our tests are fast, free, and completely deterministic. This allows us to validate our application’s logic in isolation.</p><p>Create a file named test_main.py.</p><pre>from fastapi.testclient import TestClient<br>from main import app<br><br>client = TestClient(app)<br><br><br>def test_read_root():<br>    &quot;&quot;&quot;Test the health check endpoint.&quot;&quot;&quot;<br>    response = client.get(&quot;/&quot;)<br>    assert response.status_code == 200<br>    assert response.json() == {&quot;status&quot;: &quot;ok&quot;}<br><br><br>def test_query_rag_with_mock(monkeypatch):<br>    &quot;&quot;&quot;Test the /query endpoint by mocking the RAG service.&quot;&quot;&quot;<br><br>    def mock_answer_question(question: str) -&gt; str:<br>        return &quot;This is a mocked Gemini response.&quot;<br><br>    monkeypatch.setattr(&quot;main.rag_service.answer_question&quot;, mock_answer_question)<br><br>    response = client.post(&quot;/query&quot;, json={&quot;question&quot;: &quot;What is Jupiter?&quot;})<br><br>    assert response.status_code == 200<br>    response_data = response.json()<br>    assert &quot;answer&quot; in response_data<br>    assert response_data[&quot;answer&quot;] == &quot;This is a mocked Gemini response.&quot;<br><br><br>def test_query_with_empty_question():<br>    &quot;&quot;&quot;Test that an empty question returns a 400 Bad Request error.&quot;&quot;&quot;<br>    response = client.post(&quot;/query&quot;, json={&quot;question&quot;: &quot;&quot;})<br>    assert response.status_code == 400<br>    assert response.json() == {&quot;detail&quot;: &quot;Question field cannot be empty.&quot;}</pre><h4>Step 5: Automating Everything with GitHub Actions</h4><p>Now for the automation. We’ll use a GitHub Actions workflow to run our tests on every code push. We will use <strong>GitHub Actions Secrets</strong> to securely manage our GEMINI_API_KEY without ever exposing it in our code.</p><p>First, create the necessary directories:</p><pre>mkdir -p .github/workflows</pre><p>Now, create the workflow file ci-pipeline.yml.</p><pre>name: Python CI Pipeline<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br>  pull_request:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - uses: actions/checkout@v4<br><br>    - name: Set up Python 3.9<br>      uses: actions/setup-python@v5<br>      with:<br>        python-version: 3.9<br><br>    - name: Install dependencies<br>      run: |<br>        python -m pip install --upgrade pip<br>        pip install -r requirements.txt<br><br>    - name: Lint with flake8<br>      run: |<br>        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics<br>        flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics<br><br>    - name: Test with pytest<br>      env:<br>        GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}<br>      run: |<br>        pytest</pre><p><strong>🚨 How to Add Your API Key to GitHub Secrets</strong></p><ol><li>On GitHub, go to your repository’s <strong>Settings</strong> tab.</li><li>In the sidebar, navigate to <strong>Secrets and variables</strong> &gt; <strong>Actions</strong>.</li><li>Click <strong>New repository secret</strong>.</li><li>Set the <strong>Name</strong> to GEMINI_API_KEY and paste your API key into the <strong>Secret</strong> field.</li><li>Click <strong>Add secret</strong>. Your workflow can now securely access this key.</li></ol><h4>Step 6: Final Project Setup</h4><p>To tie everything together, we need a requirements.txt file to manage our dependencies and a .gitignore file to keep our repository clean.</p><pre>fastapi<br>uvicorn[standard]<br>pydantic<br>python-dotenv<br>google-generativeai<br>chromadb<br>pytest<br>httpx<br>flake8</pre><p>The .gitignore file is crucial for preventing sensitive files (like your local .env file) from being committed.</p><pre># Python<br>__pycache__/<br>venv/<br>.env<br><br># IDEs<br>.vscode/<br>.idea/</pre><p><strong>Final Instructions</strong></p><ol><li><strong>Install Dependencies:</strong> Make sure your (venv) is active and run:</li></ol><pre>pip install -r requirements.txt</pre><p>2. <strong>Create Local Environment File:</strong> Create a file named .env in your project root. <strong>This file should NOT be committed to Git.</strong> Add your API key to it:</p><pre>GEMINI_API_KEY=&quot;YOUR_GOOGLE_AI_STUDIO_KEY_HERE&quot;</pre><p>3. Initialize Git and Push:</p><pre>git init<br>git add .<br>git commit -m &quot;Initial commit: Add RAG API with CI pipeline&quot;<br>git branch -M main<br># Add your remote repository from GitHub<br>git remote add origin https://github.com/YOUR_USERNAME/YOUR_REPO_NAME.git<br>git push -u origin main</pre><p>Once you push your code, navigate to the “Actions” tab of your repository on GitHub. You should see your workflow start automatically and pass with flying colors!</p><h4>Conclusion &amp; Next Steps</h4><p>Congratulations! 🎉 You’ve successfully built and engineered an AI application. You now have a RAG API powered entirely by Google Gemini, wrapped in a robust FastAPI server, and protected by a fully automated CI pipeline.</p><p>This setup is the foundation for building production-grade AI systems. From here, you can explore several exciting next steps:</p><ul><li><strong>Continuous Deployment (CD):</strong> Add another job to your workflow to automatically deploy your application to a cloud service.</li><li><strong>Persistent Vector Database:</strong> Replace the in-memory ChromaDB with a persistent solution like PostgreSQL with pgvector.</li><li><strong>Advanced Logging and Monitoring:</strong> Integrate logging to track requests, responses, and errors for real-world performance insights.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ee32923979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Large-Scale Systems Check If a Username or Email Exists]]></title>
            <link>https://medium.com/@codebyaadi/how-large-scale-systems-check-if-a-username-or-email-exists-8a4086ebff37?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a4086ebff37</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 14:48:40 GMT</pubDate>
            <atom:updated>2025-07-13T14:48:40.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykikCbLe5DIGkQesteMauQ.png" /><figcaption>Illustration of a distributed system architecture</figcaption></figure><h4>The Problem</h4><p>Whenever someone signs up on a platform like Google, Twitter, or Instagram, the system needs to answer a very simple question:</p><blockquote>Does this username or email already exist?</blockquote><p>Sounds trivial, right? Just run a SQL query:</p><pre>SELECT * FROM users WHERE email = &#39;user@example.com&#39;;</pre><p>But if you have <strong>billions of users</strong> and are handling <strong>millions of sign-ups or sign-ins every second</strong>, this tiny check can become very <strong>expensive and slow</strong>.</p><h4>Why not just hit the database?</h4><p>A typical relational or NoSQL database is designed to handle <strong>thousands of reads per second</strong>. But these big companies have to handle <strong>millions per second</strong>.</p><p>If every signup or login request hit the database:</p><ul><li>It would <strong>overload a database</strong>.</li><li>It would cost <strong>a lot in compute and IOPS.</strong></li><li>It would introduce <strong>latency.</strong></li></ul><h4>The Production Strategy</h4><p>At scale, engineers use a <strong>multi-layered approach</strong> to optimize this check.</p><p>Imagine it like airport security:</p><ol><li><strong>Bloom Filter at the door </strong>— Quickly rejects most obviously invalid requests.</li><li><strong>Cache (Redis/Memcached)</strong> — Checks exact matches for frequent lookups.</li><li><strong>Database </strong>— The final truth, but touched only if really necessary.</li></ol><p>This avoids bombarding the database unnecessarily.</p><h4>So how does this look in production?</h4><ol><li><strong>Bloom Filters: The fast rejector</strong></li></ol><p>A <strong>Bloom filter</strong> is a special data structure kept <strong>entirely in memory</strong>. It’s super small (can hold billions of items in a few GB).</p><p>It can quickly say:</p><ul><li>“This email definitely does not exist” (skip DB completely).</li><li>Or, “Hmm, it <strong>might exist</strong>” (check further).</li></ul><p>It <strong>never misses existing users</strong> (no false negatives), but it may sometimes give <strong>false positives</strong> (it says maybe, when actually not present).</p><p>This means we can reject <strong>most non-existing emails instantly</strong>, and check others more carefully.</p><p><strong>2. Redis / Memcached: The fast confirmer</strong></p><p>If the Bloom filter says, <strong>“maybe”</strong>, we then check an <strong>in-memory key-value store</strong> like Redis.</p><p>This:</p><ul><li>Stores exact usernames or emails.</li><li>Is <strong>millisecond-level fast</strong>.</li><li>Can handle <strong>millions of QPS</strong>.</li></ul><p><strong>3. The database: The final judge</strong></p><p>If Redis says <strong>not found</strong>, we go to the <strong>primary database</strong>, e.g. Spanner, MySQL, or DynamoDB.</p><p>Here:</p><ul><li>We guarantee correctness.</li><li>We ensure no duplicates via <strong>UNIQUE constraints</strong>.</li></ul><p>This is the <strong>most expensive step</strong>, so we try to avoid it unless absolutely needed.</p><h4>How writes update the system</h4><p>When a user successfully signs up:</p><ol><li>Insert user into the <strong>database</strong> (with unique constraint).</li><li>Asynchronously update Redis and Bloom filter.</li><li>Bloom filter may be periodically rebuilt from a fresh DB snapshot to keep false positive rates low.</li></ol><h4>A simplified flow</h4><ol><li>User tries to sign up with email.</li><li>Check Bloom filter in memory:</li></ol><ul><li>If NOT present → definitely does not exist. Allow immediately.</li><li>If MAYBE present → go to next step.</li></ul><p>3. Check Redis:</p><ul><li>If present → reject (already taken).</li><li>If not found → go to next step.</li></ul><p>4. Check database:</p><ul><li>If exists → reject.</li><li>If not → insert new record.</li></ul><p>5. Update Redis and Bloom filter in background.</p><h4>Why does this work so well?</h4><p><strong>Bloom Filter—</strong> Tiny &amp; lightning fast. (Handles ~99% of traffic) <br><strong>Redis</strong>— Accurate &amp; fast. (Handles ~1% of traffic) <br><strong>Database</strong> — Guarantees truth. (Handles ~0.1% of traffic)</p><p>This massively reduces the load on the database and keeps <strong>latency low for users</strong>.</p><h4>A few production tips</h4><p>✅ <strong>Always enforce unique constraint at the database level.</strong></p><ul><li>Bloom filters and caches can have errors, so only the DB can truly prevent duplicates.</li></ul><p>✅ <strong>Periodically rebuild Bloom filters.</strong></p><ul><li>As false positive rates grow, you want to refresh.</li></ul><p>✅ <strong>Use CDC (Change Data Capture)</strong> systems like Kafka or Debezium to keep Redis and Bloom filters updated in near real-time.</p><p>✅ <strong>Add metrics &amp; alerts</strong> on:</p><ul><li>Bloom filter false positive rates.</li><li>Redis hit/miss rates.</li><li>DB fallback frequency.</li></ul><h4>Real examples from big tech</h4><ul><li><strong>Google</strong> uses in-memory Bloom filters (and even more advanced techniques like Count-Min Sketches for different problems) to reduce database hits.</li><li><strong>Facebook</strong> uses large Redis clusters for name/email checks to handle their insane scale.</li><li><strong>Twitter</strong> relies on Redis + database sharding to ensure usernames are globally unique.</li></ul><h4>Why not just use Redis alone?</h4><ul><li>Redis with billions of emails needs lots of RAM (can be very expensive).</li><li>Bloom filters are tiny — you can store a billion emails in under ~1 GB with ~1% false positive probability.</li><li>So Bloom filters are a <strong>cost-effective way to pre-filter</strong> before hitting Redis.</li></ul><h4>A practical analogy</h4><ul><li><strong>Bloom filter</strong>: Like a guard who can instantly say, “Nope, this person isn’t even on any list.”</li><li><strong>Redis</strong>: Like checking a detailed guest list for exact match.</li><li><strong>Database</strong>: Like opening the vault to look at official records.</li></ul><h4>The golden takeaway</h4><p><strong>Use multiple layers.</strong> At scale, one system alone can’t handle it. A smart pipeline like this:</p><p>Bloom Filter → Redis → DB</p><p>saves costs, reduces latency, and keeps your systems snappy even under billions of users.</p><p><strong>TL;DR for SDEs:</strong></p><ul><li>Use <strong>Bloom filters</strong> to quickly reject obvious non-existing usernames.</li><li>Use <strong>Redis/Memcached</strong> to confirm hot lookups.</li><li>Rely on <strong>database unique constraints</strong> to guarantee correctness.</li><li>Keep all caches fresh with async pipelines (like Kafka + CDC).</li><li>Monitor false positive rates to keep the system reliable.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a4086ebff37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Balancing Multiple Node.js Containers with Nginx + Docker]]></title>
            <link>https://medium.com/@codebyaadi/load-balancing-multiple-node-js-containers-with-nginx-docker-b4b6069c501b?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4b6069c501b</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 12:02:20 GMT</pubDate>
            <atom:updated>2025-06-10T12:02:20.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7V_-f_xiXYb3hM1WB4IGYA.png" /></figure><p>When scaling a web application, <strong>handling high traffic</strong> is crucial. One of the simplest and most effective ways to do this is through <strong>load balancing</strong> — distributing traffic evenly across multiple backend servers.</p><p>In this tutorial, you’ll learn how to <strong>load balance multiple Node.js + TypeScript backend containers</strong> using <strong>Nginx as a reverse proxy</strong>, all managed with <strong>Docker Compose</strong>.</p><h4>What Is Load Balancing?</h4><p><strong>Load balancing</strong> is the process of distributing incoming network traffic across multiple backend servers. This ensures no single server becomes a bottleneck and improves the application’s availability and reliability.</p><h4>Why Use Load Balancing?</h4><p><strong>✅ Increased Scalability</strong> — More containers = more traffic capacity.</p><p><strong>✅ High Availability — </strong>If one backend fails, others can continue serving requests.</p><p><strong>✅ Better Performance — </strong>Prevents any one server from being overloaded.</p><h4>Architecture Overview</h4><p>Here’s what we’ll build:</p><pre>Client → Nginx (reverse proxy + load balancer)<br>                  ↓<br>     ┌────────────┬────────────┐<br>     │            │            │<br> backend-1   backend-2    backend-3 (Node.js)</pre><h4>Project Structure</h4><pre>project-root/<br>│<br>├── backend/<br>│   ├── src/<br>│   │   └── index.ts<br>│   ├── package.json<br>│   ├── tsconfig.json<br>│   └── Dockerfile<br>│<br>├── nginx/<br>│   └── default.conf<br>│<br>├── docker-compose.yml<br>└── README.md</pre><h4>Step 1: Create a Node.js + TypeScript Backend</h4><pre>mkdir backend &amp;&amp; cd backend<br>npm init -y<br>npm install express<br>npm install --save-dev typescript ts-node @types/node @types/express</pre><p>tsconfig.json</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;CommonJS&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;esModuleInterop&quot;: true<br>  },<br>  &quot;include&quot;: [&quot;src&quot;]<br>}</pre><p>src/index.ts</p><pre>import express from &#39;express&#39;;<br>const app = express();<br><br>const PORT = 3000;<br>const ID = process.env.CONTAINER_ID || &#39;unknown&#39;;<br><br>app.get(&#39;/&#39;, (_req, res) =&gt; {<br>  res.send(`Hello from container ${ID}`);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Container ${ID} running on port ${PORT}`);<br>});</pre><blockquote>The CONTAINER_ID will help us distinguish which container responds.</blockquote><h4>Step 2: Dockerize the Backend</h4><p>backend/Dockerfile</p><pre>FROM node:18<br><br>WORKDIR /app<br><br>COPY package*.json ./<br>RUN npm install<br><br>COPY . .<br><br>CMD [&quot;npx&quot;, &quot;ts-node&quot;, &quot;src/index.ts&quot;]</pre><h4>Step 3: Set Up Nginx as Load Balancer</h4><p>nginx/default.conf</p><pre>upstream backend_cluster {<br>    server backend1:3000;<br>    server backend2:3000;<br>    server backend3:3000;<br>}<br><br>server {<br>    listen 80;<br><br>    location / {<br>        proxy_pass http://backend_cluster;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>    }<br>}</pre><h4>Step 4: Docker Compose for Everything</h4><p>docker-compose.yml</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  backend1:<br>    build: ./backend<br>    container_name: backend1<br>    environment:<br>      - CONTAINER_ID=backend1<br>    networks:<br>      - app-network<br><br>  backend2:<br>    build: ./backend<br>    container_name: backend2<br>    environment:<br>      - CONTAINER_ID=backend2<br>    networks:<br>      - app-network<br><br>  backend3:<br>    build: ./backend<br>    container_name: backend3<br>    environment:<br>      - CONTAINER_ID=backend3<br>    networks:<br>      - app-network<br><br>  nginx:<br>    image: nginx:latest<br>    container_name: nginx-load-balancer<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf<br>    depends_on:<br>      - backend1<br>      - backend2<br>      - backend3<br>    networks:<br>      - app-network<br><br>networks:<br>  app-network:<br>    driver: bridge</pre><h4>Step 5: Run Everything</h4><pre>docker-compose up --build</pre><p>Now visit <a href="http://localhost/">http://localhost</a> multiple times or refresh the page. You’ll see different responses like:</p><pre>Hello from container backend1<br>Hello from container backend2<br>Hello from container backend3</pre><p>🎉 Success! Nginx is load balancing across your Node.js containers!</p><h4>How Nginx Load Balancing Works</h4><p>Nginx cycles through the listed servers in the upstream block (round-robin by default). Each request is forwarded to one of the containers, distributing load evenly.</p><h4>Optional: Other Load Balancing Strategies</h4><p>Nginx supports other strategies too:</p><pre>upstream backend_cluster {<br>    least_conn;     # Least number of active connections<br>    server backend1:3000;<br>    server backend2:3000;<br>    server backend3:3000;<br>}</pre><p>Or add weights:</p><pre>upstream backend_cluster {<br>    server backend1:3000 weight=3;<br>    server backend2:3000;<br>}</pre><h4>Recap</h4><p>We just:</p><p>✅ Built 3 identical Node.js backend containers<br>✅ Created an Nginx config to load balance them<br>✅ Used Docker Compose to manage it all</p><p>👏 <strong>Was this helpful?</strong> Smash that clap button and follow for more backend + DevOps tutorials!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4b6069c501b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Proxy with Nginx for a Node.js + TypeScript Backend (with Docker)]]></title>
            <link>https://medium.com/@codebyaadi/reverse-proxy-with-nginx-for-a-node-js-typescript-backend-with-docker-bc22c4d61a80?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc22c4d61a80</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Thu, 29 May 2025 12:07:57 GMT</pubDate>
            <atom:updated>2025-05-29T12:07:57.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD3KK5t1yt50HCPf8pnmeA.png" /></figure><p>In modern web architectures, a <strong>reverse proxy</strong> plays a crucial role in optimizing performance, improving security, and simplifying deployment. In this guide, you’ll learn what a reverse proxy is, why it matters, and how to set it up using <strong>Nginx</strong>, a <strong>Node.js + TypeScript</strong> backend, and <strong>Docker</strong>.</p><h4>What Is a Reverse Proxy?</h4><p>A <strong>reverse proxy</strong> is a server that sits between clients (like browsers) and your backend servers. Instead of clients accessing your backend directly, they make requests to the proxy server, which then forwards the request to the appropriate backend.</p><blockquote>Think of it as a gatekeeper that routes, filters, and manages traffic between the outside world and your internal services.</blockquote><h4>Why and When to Use a Reverse Proxy?</h4><p><strong>Security</strong></p><ul><li>Hides backend services from the public.</li><li>Allows rate limiting, blacklisting, and DDoS protection.</li></ul><p><strong>Performance</strong></p><ul><li>Enables caching and compression.</li><li>Reduces load on backend servers.</li></ul><p><strong>SSL Termination</strong></p><ul><li>Offloads HTTPS encryption from the backend.</li></ul><p><strong>Load Balancing</strong></p><ul><li>Distributes traffic among multiple backend servers.</li></ul><p><strong>When to Use It</strong></p><ul><li>When building <strong>microservices</strong></li><li>In <strong>production deployments</strong></li><li>When managing <strong>multiple services</strong></li><li>For <strong>handling SSL</strong> with ease</li></ul><h4>Project Overview</h4><p>We’ll build a simple Express app in <strong>Node.js with TypeScript</strong>, containerize it, and use <strong>Nginx</strong> as a reverse proxy using Docker.</p><pre>project-root/<br>│<br>├── backend/<br>│   ├── src/<br>│   │   └── index.ts<br>│   ├── tsconfig.json<br>│   ├── package.json<br>│   └── Dockerfile<br>│<br>├── nginx/<br>│   └── default.conf<br>│<br>├── docker-compose.yml<br>└── README.md</pre><p><strong>Step 1: Create the Backend (Node.js + TypeScript)</strong></p><ol><li>Init Project</li></ol><pre>mkdir backend &amp;&amp; cd backend<br>npm init -y<br>npm install express<br>npm install --save-dev typescript ts-node @types/node @types/express</pre><p>2. tsconfig.json</p><pre>// backend/tsconfig.json<br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;CommonJS&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;esModuleInterop&quot;: true<br>  },<br>  &quot;include&quot;: [&quot;src&quot;]<br>}</pre><p>3. Add server code</p><pre>// backend/src/index.ts<br>import express from &#39;express&#39;;<br><br>const app = express();<br>const PORT = 3000;<br><br>app.get(&#39;/&#39;, (_req, res) =&gt; {<br>  res.send(&#39;Hello from the Node.js + TypeScript backend!&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on http://localhost:${PORT}`);<br>});</pre><h4>Step 2: Dockerize the Backend</h4><p>Dockerfile</p><pre># backend/Dockerfile<br>FROM node:18<br><br>WORKDIR /app<br><br>COPY package*.json ./<br>RUN npm install<br><br>COPY . .<br><br>CMD [&quot;npx&quot;, &quot;ts-node&quot;, &quot;src/index.ts&quot;]</pre><h4>Step 3: Configure Nginx as Reverse Proxy</h4><p>nginx/default.conf</p><pre>server {<br>    listen 80;<br><br>    location / {<br>        proxy_pass http://backend:3000;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>    }<br>}</pre><blockquote>This tells Nginx to forward all requests to the backend service on port 3000.</blockquote><h4>Step 4: Docker Compose for Easy Setup</h4><p>docker-compose.yml</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  backend:<br>    build: ./backend<br>    container_name: node-backend<br>    ports:<br>      - &quot;3000:3000&quot;<br>    networks:<br>      - app-network<br><br>  nginx:<br>    image: nginx:latest<br>    container_name: nginx-reverse-proxy<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf<br>    depends_on:<br>      - backend<br>    networks:<br>      - app-network<br><br>networks:<br>  app-network:<br>    driver: bridge</pre><h4>Step 5: Run Everything</h4><pre>docker-compose up --build</pre><p>Navigate to <a href="http://localhost/">http://localhost</a> and you’ll see:</p><pre>Hello from the Node.js + TypeScript backend!</pre><p>Congrats! 🎉 Nginx is now proxying HTTP requests to your TypeScript backend.</p><h4>Recap: How the Reverse Proxy Works</h4><ol><li><strong>Browser</strong> makes a request to <a href="http://localhost/">http://localhost</a></li><li><strong>Nginx</strong> receives the request on port 80</li><li>Nginx <strong>forwards the request</strong> to the Node.js backend on port 3000</li><li>Backend responds, and Nginx passes the response <strong>back to the browser</strong></li></ol><p>📢 <strong>Found this useful?</strong> Clap 👏 and follow for more hands-on backend and DevOps tutorials!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc22c4d61a80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Authentication Using SSH: Why You Should Use It]]></title>
            <link>https://medium.com/@codebyaadi/github-authentication-using-ssh-why-you-should-use-it-b1c2e1c8f7af?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c2e1c8f7af</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 04:57:25 GMT</pubDate>
            <atom:updated>2025-03-31T04:57:25.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0_Wl9hCqfkm9XXvs-6fWA.png" /></figure><p>When working with GitHub, authentication is an essential step to securely push and pull code. While HTTPS-based authentication using personal access tokens (PATs) is common, SSH authentication offers a more secure and convenient alternative. This article will walk you through GitHub authentication using SSH, its benefits, and why you should consider switching to it.</p><h4>What is SSH Authentication ?</h4><p>Secure Shell (SSH) is a cryptographic network protocol that allows secure communication between client and a server. Instead of relying on passwords or access tokens, SSH authentication uses a pair of cryptographic keys (public and private keys) to establish a secure connection.</p><p>When you set up SSH authentication for GitHub, your private key remains on your local machine, while public key is added to your GitHub account. This allows secure authentication without need for entering credentials repeatedly.</p><h4>How to Set Up GitHub Authentication Using SSH</h4><p>Setting up SSH authentication for GitHub is a straightforward process. Follow these steps to configure it:</p><p><strong>Step 1: Check for Existing SSH Keys</strong></p><p>Before generating a new SSH key, check if you already have one:</p><pre>ls -al ~/.ssh</pre><p>If you see files like id_rsa and id_rsa.pub , an SSH key pair already exists.</p><p><strong>Step 2: Generate a New SSH key ( If needed )</strong></p><p>If you don’t have an existing key, generate a new one:</p><pre>ssh-keygen -t rsa -b 4096 -C &quot;you_email@example.com&quot;</pre><p>This command creates a new SSH key pair and stores them in the ~/.ssh directory. You will be prompted to enter the passphrase while generating key pair.</p><p><strong>Step 3: Add you SSH Key to the SSH Agent</strong></p><p>Start the SSH agent and add your new SSH key:</p><pre>eval &quot;(ssh-agent -s)&quot;<br>ssh-add ~/.ssh/id_rsa</pre><p><strong>Step 4: Add SSH key to GitHub</strong></p><p>Copy your public key and add it to GitHub:</p><pre>cat ~/.ssh/id_rsa.pub</pre><p>Go to GitHub → Settings → SSH and GPG keys → New SSH key, paste the copied key, and save it.</p><h4>Step 5: Test the Connection</h4><p>Run the following command to test the connection:</p><pre>ssh -T git@github.com</pre><p>If everything is set up correctly, you should see a message like:</p><pre>Hi username! You&#39;ve successfully authenticated, but GitHub does not provide shell access.</pre><h4>Benefits of Using SSH for GitHub Authentication</h4><ol><li>Stronger Security</li></ol><p>SSH authentication eliminates the need for passwords or personal access tokens, reducing the risk of credential theft. The use of public-private key pairs ensures secure communication.</p><p>2. Convenience and Automation</p><p>Once configured, SSH authentication allows you to interact with GitHub without entering credentials repeatedly. This is particularly useful when automating tasks, such as CI/CD pipelines.</p><p>3. No Expiry Issues</p><p>Unlike personal access tokens, which can expire and require regeneration, SSH keys remain valid unless manually revoked, making them more convenient for long-term use.</p><p>4. Prevents Man-in-the-Middle Attacks</p><p>SSH authentication ensures that you are connecting to the legitimate GitHub server, protecting against potential MITM attacks.</p><p>5. Better for Remote Servers</p><p>If you work on cloud-based development environments or remote servers, SSH authentication allows secure, passwordless Git interactions, improving workflow efficiency.</p><h4>Conclusion</h4><p>SSH authentication for GitHub provides a secure, seamless, and more efficient way to manage repositories. By using SSH keys instead of passwords or access tokens, you enhance security while simplifying access. Whether you’re an individual developer or part of a team, switching to SSH authentication is a smart move to improve your GitHub workflow.</p><p>So, if you haven’t already set up SSH authentication, now is the perfect time to do it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c2e1c8f7af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CSRF and How to Secure Your Express + TypeScript Server]]></title>
            <link>https://medium.com/@codebyaadi/understanding-csrf-and-how-to-secure-your-express-typescript-server-580c4db1a342?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/580c4db1a342</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 17:22:21 GMT</pubDate>
            <atom:updated>2025-02-06T17:22:21.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8cjiNmgL5yaWndjB" /><figcaption>Photo by <a href="https://unsplash.com/@fantasyflip?utm_source=medium&amp;utm_medium=referral">Philipp Katzenberger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks a user’s browser into executing unwanted actions on a trusted site where the user is authenticated. This can lead to unauthorized data modifications, financial transactions, and even account takeovers.</p><p>In this in-depth article, we will explore CSRF in detail, provide a real-world example of an attack, and implement CSRF protection in an Express.js server using TypeScript.</p><h4>What is CSRF ?</h4><p>CSRF exploits the trust a website has in a user’s browser. It typically occurs when:</p><ul><li>A user is logged into a web application.</li><li>The attacker tricks the user into visiting a malicious page.</li><li>The malicious page makes an unwanted request to the web application using the user’s active session.</li></ul><p>Since the request comes from an authenticated user’s browser, the server assumes it is legitimate and processes it.</p><h4>CSRF Attack Example</h4><p><strong>Scenario: Online Banking Application</strong></p><p>Imagine a banking application where users can transfer money using a simple form. The transfer request is processed via a POST request.</p><p>Legitimate Money Transfer Request</p><pre>POST /transfer HTTP/1.1<br>Host: bank.com<br>Cookie: session=abcdef123456<br>Content-Type: application/x-www-form-urlencoded<br><br>amount=1000&amp;to=attacker_account</pre><p>The server verifies the session and processes the transfer request accordingly.</p><p><strong>How an Attacker Exploits This</strong></p><p>An attacker crafts a malicious page:</p><pre>&lt;html&gt;<br>&lt;body&gt;<br>    &lt;form action=&quot;https://bank.com/transfer&quot; method=&quot;POST&quot;&gt;<br>        &lt;input type=&quot;hidden&quot; name=&quot;amount&quot; value=&quot;1000&quot;&gt;<br>        &lt;input type=&quot;hidden&quot; name=&quot;to&quot; value=&quot;attacker_account&quot;&gt;<br>    &lt;/form&gt;<br>    &lt;script&gt;document.forms[0].submit();&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>If an authenticated user visits this page, their browser automatically submits the form and initiates the transfer without their knowledge.</p><h4>Preventing CSRF in an Express + TypeScript Server</h4><h4>Implement CSRF Tokens</h4><p>A common and effective CSRF mitigation strategy is to use CSRF tokens. These tokens are unique per session and must be included in sensitive requests.</p><p>Install Dependencies</p><pre>npm install csurf cookie-parser express-session</pre><p><strong>Update Your Express Server</strong></p><p>Create an Express server with CSRF protection:</p><pre>import express, { Request, Response, NextFunction, ErrorRequestHandler } from &quot;express&quot;;<br>import csrf from &quot;csurf&quot;;<br>import cookieParser from &quot;cookie-parser&quot;;<br>import session from &quot;express-session&quot;;<br><br>const app = express();<br>app.use(express.json());<br>app.use(cookieParser());<br><br>// Session middleware (required for storing CSRF tokens)<br>app.use(<br>    session({<br>        secret: &quot;your_secret_key&quot;,<br>        resave: false,<br>        saveUninitialized: true,<br>        cookie: { secure: false },<br>    })<br>);<br><br>// CSRF Protection middleware<br>const csrfProtection = csrf({ cookie: true });<br>app.use(csrfProtection);<br><br>// Route to get CSRF token<br>app.get(&quot;/csrf-token&quot;, (req: Request, res: Response) =&gt; {<br>    res.json({ csrfToken: req.csrfToken() });<br>});<br><br>// Protected route<br>app.post(&quot;/transfer&quot;, csrfProtection, (req: Request, res: Response) =&gt; {<br>    res.send(&quot;Transfer successful&quot;);<br>});<br><br>// Error handling middleware<br>const errorHandler: ErrorRequestHandler = (<br>    err: any,<br>    req: Request,<br>    res: Response,<br>    next: NextFunction<br>): void =&gt; {<br>    if (err.code === &quot;EBADCSRFTOKEN&quot;) {<br>        res.status(403).json({ message: &quot;Invalid CSRF Token&quot; });<br>        return;<br>    }<br>    next(err);<br>};<br><br>app.use(errorHandler);<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><p><strong>Use SameSite Cookies</strong></p><p>To prevent unauthorized cross-site requests, configure SameSite=strict or SameSite=lax in cookies:</p><pre>app.use(<br>    session({<br>        secret: &quot;your_secret_key&quot;,<br>        resave: false,<br>        saveUninitialized: true,<br>        cookie: { secure: true, sameSite: &quot;strict&quot; },<br>    })<br>);</pre><p>This ensures cookies are only sent when navigating within the same site.</p><p><strong>Verify Origin Headers</strong></p><p>Validate the Origin and Referer headers to confirm that requests originate from a trusted source:</p><pre>app.use((req, res, next) =&gt; {<br>    const allowedOrigins = [&quot;https://yourdomain.com&quot;];<br>    const origin = req.headers.origin || req.headers.referer;<br>    if (origin &amp;&amp; !allowedOrigins.includes(origin)) {<br>        return res.status(403).json({ message: &quot;Request from untrusted origin&quot; });<br>    }<br>    next();<br>});</pre><p><strong>Testing CSRF Protection</strong></p><p>To test the CSRF protection, try the following:</p><ol><li>Start the Express server.</li><li>Use Postman or an API client to make a POST request to /transfer without a CSRF token – it should fail.</li><li>Retrieve the CSRF token from /csrf-token and include it in a subsequent request – it should succeed.</li><li>Try submitting a request from a different origin and verify that it is blocked.</li></ol><p><strong>Additional Security Measures</strong></p><ul><li><strong>Enable HTTPS:</strong> Always use HTTPS to encrypt communications and protect against man-in-the-middle attacks.</li><li><strong>Use Content Security Policy (CSP):</strong> Restrict allowed sources for scripts to prevent malicious scripts from executing.</li><li><strong>Educate Users:</strong> Warn users against clicking on suspicious links, especially when logged into sensitive applications.</li></ul><p><strong>Conclusion</strong></p><p>CSRF is a serious security risk, but with proper protection mechanisms such as CSRF tokens, SameSite cookies, and Origin verification, we can significantly reduce the risk of attacks in an Express + TypeScript application. Always ensure that state-changing operations are well-protected and educate users about avoiding malicious links.</p><p>By implementing these best practices, you can secure your web applications against CSRF and provide a safer experience for users.</p><p><strong>Further Reading</strong></p><ul><li><a href="https://owasp.org/www-community/attacks/csrf">OWASP CSRF Guide</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/CSRF">MDN Web Docs — CSRF</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=580c4db1a342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the JavaScript Event Loop: A Deep Dive]]></title>
            <link>https://medium.com/@codebyaadi/understanding-the-javascript-event-loop-a-deep-dive-7702b8da1e9b?source=rss-0d39dace4aa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7702b8da1e9b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aditya Rajbhar]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 17:50:56 GMT</pubDate>
            <atom:updated>2025-02-03T17:50:56.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ELQYV0BF-bSUkNpG" /><figcaption>Photo by <a href="https://unsplash.com/@karlp?utm_source=medium&amp;utm_medium=referral">Karl Pawlowicz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>JavaScript is a single-threaded, non-blocking, asynchronous language, and at the heart of this behavior lies the Event Loop. Understanding the Event Loop is crucial for writing efficient, performant, and scalable JavaScript applications. This article provides an advanced deep dive into the Event Loop, its mechanisms, and how it orchestrates asynchronous execution in JavaScript.</p><h3>The need for the Event Loop</h3><p>JavaScript executes in a single-threaded environment, meaning only one piece of code runs at a time. If JavaScript were purely synchronous, long-running operation like networks request or file reading would block the main thread, making the application unresponsive. The Event Loop is JavaScript’s solution to handle asynchronous operation efficiently while maintaining a single-threaded model.</p><h3>Key Components of the Event Loop</h3><p>To understand the Event Loop deeply, we need to break it down into its core components:</p><ol><li>Call Stack</li><li>Web APIs</li><li>Task Queues ( Macro-task Queue and Micro-task Queue )</li><li>Event Loop Mechanism</li></ol><h4>1. Call Stack</h4><p>The Call Stack is a LIFO ( Last In, First out ) data structure that keeps track of function execution in JavaScript. When a function is invoked, it is pushed onto the stack. When it completes execution, it is popped off the stack.</p><p>Example:</p><pre>function foo() {<br>  console.log(&quot;foo&quot;);<br>}<br><br>function bar() {<br>  foo();<br>  console.log(&quot;bar&quot;);<br>}<br><br>bar();</pre><p>Execution order:</p><ol><li>bar() is pushed onto the Call Stack.</li><li>foo() is pushed onto the Call Stack.</li><li>console.log(&quot;foo&quot;) executes and foo() is popped.</li><li>console.log(&quot;bar&quot;) executes and bar() is popped.</li></ol><h4>2. Web APIs</h4><p>Browser-provided Web APIs (like setTimeout , fetch , DOM events) allow asynchronous operations. When invoked, these APIs delegate tasks to the browser and do not block the Call Stack.</p><p>Example:</p><pre>console.log(&quot;Start&quot;);<br>setTimeout(() =&gt; console.log(&quot;Timeout&quot;), 0);<br>console.log(&quot;End&quot;);</pre><p>Expected Output:</p><pre>Start<br>End<br>Timeout</pre><p>Here, setTimeout delegates the callback to the browser API, allowing the Call Stack to continue execution without waiting.</p><h4>3. Task Queues</h4><p>There are two main types of task queues:</p><p><strong>Macro-task Queue</strong></p><ul><li>Also known as the <strong>Message Queue</strong>.</li><li>Includes setTimeout, setInterval, setImmediate (Node.js), and I/O tasks.</li><li>Tasks from this queue are executed after the Call Stack is empty and after all Micro-tasks have been executed.</li></ul><p><strong>Micro-task Queue</strong></p><ul><li>Also known as the <strong>Job Queue</strong>.</li><li>Includes Promises (.then()), MutationObserver, and queueMicrotask().</li><li>Microtasks have higher priority and execute before any macro-tasks in the next tick of the Event Loop.</li></ul><p>Example:</p><pre>console.log(&quot;A&quot;);<br>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);<br>Promise.resolve().then(() =&gt; console.log(&quot;C&quot;));<br>console.log(&quot;D&quot;);</pre><p>Expected Output:</p><pre>A<br>D<br>C<br>B</pre><p>Here, the microtask (Promise.then) executes before the macro-task (setTimeout).</p><h4>4. The Event Loop Mechanism</h4><p>The Event Loop continuously monitors the Call Stack and Task Queues. The process follows these steps:</p><ol><li>Execute all synchronous JavaScript code in the Call Stack.</li><li>Process all pending Microtasks before moving to Macro-tasks.</li><li>Pick the oldest Macro-task from the Macro-task Queue and execute it.</li><li>Repeat the cycle.</li></ol><h3>Behind the Scenes: How the Event Loop Works Internally</h3><p>To fully grasp the Event Loop, let’s explore its internal mechanisms:</p><p><strong>JavaScript Execution Context</strong></p><ul><li>When a script is run, a <strong>Global Execution Context (GEC)</strong> is created.</li><li>Every function call creates a new <strong>Function Execution Context (FEC)</strong>, which is pushed onto the Call Stack.</li><li>Each execution context has a <strong>Lexical Environment</strong> containing variables and scope references.</li></ul><p><strong>Interaction Between Call Stack and Web APIs</strong></p><ul><li>When a function like setTimeout is called, it is passed to the Web API environment, not the Call Stack.</li><li>Once the timer completes, the callback is queued in the <strong>Message Queue</strong>.</li></ul><p><strong>Microtasks vs Macrotasks Execution</strong></p><ul><li>The Event Loop prioritizes <strong>Microtasks</strong> over Macrotasks.</li><li>Microtasks execute after every synchronous operation, but before the next Macro-task.</li></ul><p><strong>Idle Time Processing</strong></p><ul><li>The browser optimizes performance by running background tasks, like rendering and garbage collection, during idle times.</li></ul><p><strong>Rendering Pipeline Considerations</strong></p><ul><li>The browser aims to render at <strong>60 FPS</strong>, meaning each frame should be processed in <strong>16.67ms</strong>.</li><li>Long synchronous tasks can block rendering, leading to performance issues.</li></ul><p>By understanding these deeper mechanisms, developers can optimize JavaScript execution and ensure a smooth, non-blocking experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7702b8da1e9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>