<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sawastik Bhullar</title>
    <description>The latest articles on DEV Community by Sawastik Bhullar (@sawastik_bhullar).</description>
    <link>https://dev.to/sawastik_bhullar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4029046%2F3f36bddc-7a45-4a38-b346-ea280f8ee847.jpg</url>
      <title>DEV Community: Sawastik Bhullar</title>
      <link>https://dev.to/sawastik_bhullar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sawastik_bhullar"/>
    <language>en</language>
    <item>
      <title>How I Built an Autonomous AI News Digest Agent in 48 Hours (Node.js, OpenRouter &amp; Nodemailer)</title>
      <dc:creator>Sawastik Bhullar</dc:creator>
      <pubDate>Sun, 15 Nov 2026 06:29:15 +0000</pubDate>
      <link>https://dev.to/sawastik_bhullar/how-i-built-an-autonomous-ai-news-digest-agent-in-48-hours-nodejs-openrouter-nodemailer-39d3</link>
      <guid>https://dev.to/sawastik_bhullar/how-i-built-an-autonomous-ai-news-digest-agent-in-48-hours-nodejs-openrouter-nodemailer-39d3</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi9o2ja89wcofqzav8xks.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi9o2ja89wcofqzav8xks.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We live in an era of unprecedented information overload. Every morning, millions of professionals wake up, open dozens of browser tabs, scroll through chaotic social media feeds, and attempt to filter through mountains of noise just to stay informed on the topics that actually matter to their industry. Traditional RSS readers require manual curation, and modern news aggregators are flooded with clickbait, algorithmic bias, and distracting ads.&lt;/p&gt;

&lt;p&gt;As a backend developer, I realized I didn't need another third-party SaaS subscription or bloated browser extension to solve this problem. I needed a custom-built, proactive intelligence system that could do the heavy lifting for me.&lt;/p&gt;

&lt;p&gt;Over a fast-paced 48-hour build sprint, I engineered a fully autonomous, cron-driven backend agent from first principles. Without relying on heavy frameworks or black-box wrappers, this agent wakes up on a strict schedule, fetches breaking metadata from external news sources, scrapes and sanitizes raw web payloads, passes the content through an advanced Large Language Model for high-signal summarization, and dispatches a beautifully formatted HTML newsletter straight to my inbox.&lt;/p&gt;

&lt;p&gt;Here is the complete architectural deep dive into how I designed, built, and shipped this autonomous system.&lt;/p&gt;

&lt;p&gt;The Philosophy: Shifting from Reactive CRUD to Proactive Agents&lt;br&gt;
Most junior and mid-level backend portfolios look identical: a standard Express server hooked up to a database handling CRUD operations waiting for a frontend client to make an HTTP request. While essential, these systems are entirely reactive. They sit idle until a human interacts with them.&lt;/p&gt;

&lt;p&gt;Autonomous agents represent a fundamental shift in systems architecture. They are proactive. They operate independently in the background, orchestrated by time-based triggers or event streams, executing complex workflows without human intervention.&lt;/p&gt;

&lt;p&gt;Building this news agent taught me how to think in terms of asynchronous pipelines. Instead of managing synchronous request-response lifecycles, I had to design a decoupled workflow where data flows seamlessly across distinct domain services—from ingestion and scraping to AI transformation and final delivery.&lt;/p&gt;

&lt;p&gt;Architectural Blueprint: The 4-Stage Pipeline&lt;br&gt;
To ensure the system remained modular, maintainable, and easy to debug, I decoupled the architecture into distinct, single-responsibility modules:&lt;/p&gt;

&lt;p&gt;The Ingestion Layer: Responsible for querying external news providers (such as The Guardian Content API) using secure, environment-scoped credentials to harvest fresh breaking article metadata and target URLs.&lt;/p&gt;

&lt;p&gt;The Scraping and Filtering Layer: Takes the raw article URLs, pulls the core Document Object Model (DOM) content, strips away irrelevant boilerplate, and filters out low-signal entries.&lt;/p&gt;

&lt;p&gt;The AI Summarization Layer: Passes the sanitized text payload to an LLM via the OpenRouter SDK. Instead of forcing me to read dense, 2,000-word articles, the model extracts core themes, key takeaways, and executive summaries.&lt;/p&gt;

&lt;p&gt;The Dispatch Layer: Transforms the summarized text strings into a responsive, beautifully styled HTML card and pushes it out via an automated SMTP email service using Nodemailer.&lt;/p&gt;

&lt;p&gt;The Orchestration Layer: Powered by a background cron scheduler that manages exact execution times, ensuring the pipeline fires reliably without manual triggers.&lt;/p&gt;

&lt;p&gt;Deep Dive into Core Pipeline Execution&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Managing Asynchronous Data Flow
The backbone of the entire application is an isolated asynchronous pipeline function. Rather than cluttering the global scope with mutable state arrays, each execution cycle initializes a clean execution scope.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The pipeline begins by calling the ingestion module to fetch article metadata. Once URLs are retrieved, the scraper module extracts the underlying text content. After passing the payload through a strict filter to discard empty or malformed items, the data is handed off to the LLM summarizer. Finally, the enriched object is pushed to the email dispatch service. Wrapping this entire sequence in robust try-catch blocks ensures that if an external API times out or throws an error, the system logs the failure gracefully without crashing the entire Node process or leaving background workers hanging.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Crafting Responsive HTML Newsletters
Delivering text via plain, unstyled emails looks unprofessional and degrades readability. To solve this, I designed a custom email delivery module that constructs a clean newsletter card.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because major email clients (like Gmail, Outlook, and Apple Mail) notoriously strip out external stylesheets and complex CSS layout rules, I utilized robust inline styling techniques. The module takes the raw string output from the LLM summarizer, splits the text paragraphs cleanly, and wraps them in structured paragraph tags with explicit margins and line heights. These paragraphs are then injected into a centered, max-width container featuring a dark navy header banner and a soft, neutral background. This guarantees crisp, consistent rendering across both desktop and mobile email clients. Furthermore, authentication is handled securely through Google's App Passwords, allowing the application to authenticate via SMTP without exposing primary account credentials in plaintext config files.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Background Orchestration with Cron
An autonomous agent is only as good as its scheduling reliability. To automate the pipeline, I integrated a background cron manager.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One of the most valuable lessons I learned during this build was the importance of cron expression syntax. Standard cron schedulers utilize a 5-field format representing minutes, hours, day of the month, month, and day of the week. Initially, misconfiguring second-level parameters led to aggressive loop behaviors. Sticking strictly to standard 5-field syntax resolved execution timing completely, allowing me to configure precise daily triggers (such as running at 7:00 AM and 3:00 PM) while binding the runtime environment to a local timezone to prevent UTC offset discrepancies. Additionally, keeping an Express server running alongside the scheduler allowed me to expose a manual webhook endpoint, making local debugging and testing effortless via curl commands.&lt;/p&gt;

&lt;p&gt;Engineering Challenges and Hard-Won Lessons&lt;br&gt;
Every rapid development sprint comes with unexpected hurdles. Building this agent over two days surfaced two notable engineering challenges:&lt;/p&gt;

&lt;p&gt;SMTP Authentication Barriers: When first wiring up Nodemailer with a personal Gmail account, I ran into strict authentication blocks due to Two-Step Verification policies. Learning how to navigate Google's security architecture to generate dedicated App Passwords reinforced the importance of secure secret management and zero-trust configuration practices.&lt;/p&gt;

&lt;p&gt;Cron Granularity and Overlapping Runs: During early testing, setting cron intervals too aggressively caused overlapping pipeline executions when an external scraping or LLM request took slightly longer than expected. This highlighted the necessity of building idempotent background tasks and adding locking mechanisms or database state checks.&lt;/p&gt;

&lt;p&gt;What Comes Next?&lt;br&gt;
Building a fully functional autonomous news digest agent in 48 hours proved how powerful lightweight Node.js backends can be when combining external APIs, local scraping engines, and generative AI models.&lt;/p&gt;

&lt;p&gt;The immediate next phase of development involves integrating MongoDB persistence. By storing the unique hashes or URLs of articles that have already been emailed, the agent will be able to perform deduplication checks. If the underlying news source has not published a fresh top story between cron intervals, the agent will intelligently skip execution rather than dispatching redundant updates.&lt;/p&gt;

&lt;p&gt;If you are an engineer looking to sharpen your backend skills, step away from standard frontend CRUD apps for a weekend. Build something that runs in the background, talks to multiple APIs, reasons over data using an LLM, and delivers value autonomously. The architectural insights you gain will completely transform how you approach software design.&lt;/p&gt;

</description>
      <category>node</category>
      <category>ai</category>
      <category>automation</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Building an AI Agent Gateway: Semantic Caching, MongoDB, and Async RBAC Lessons</title>
      <dc:creator>Sawastik Bhullar</dc:creator>
      <pubDate>Tue, 10 Nov 2026 14:57:26 +0000</pubDate>
      <link>https://dev.to/sawastik_bhullar/building-an-ai-agent-gateway-semantic-caching-mongodb-and-async-rbac-lessons-33k1</link>
      <guid>https://dev.to/sawastik_bhullar/building-an-ai-agent-gateway-semantic-caching-mongodb-and-async-rbac-lessons-33k1</guid>
      <description>&lt;p&gt;Today was an intense coding sprint focused on building out a production-ready AI Agent Gateway. The goal was to hook up a secure, role-based access-controlled (RBAC) LangChain agent backed by MongoDB for persistent conversation history and Redis for a high-performance semantic caching layer.&lt;/p&gt;

&lt;p&gt;While the architecture came together cleanly, it wasn’t without its fair share of runtime gremlins. Here is a breakdown of what we built, the roadblocks encountered, and how we solved them.&lt;/p&gt;

&lt;p&gt;What We Built Today&lt;br&gt;
Redis Semantic Caching Layer: Integrated a custom vector caching pipeline. When a user sends a prompt, the gateway generates embeddings and runs cosine similarity checks against past queries stored in Redis. If a match exceeds the threshold, the gateway bypasses the LLM entirely, returning the cached answer instantly to save tokens and latency.&lt;/p&gt;

&lt;p&gt;MongoDB Session Management: Configured persistent chat histories, capturing user inputs, assistant responses, and intermediate tool execution steps with automated session saving.&lt;/p&gt;

&lt;p&gt;Role-Based Tool Filtering (RBAC): Implemented security layers ensuring users only access tools matching their permission level (e.g., standard users get weather lookup, while admins gain execution access to advanced database queries).&lt;/p&gt;

&lt;p&gt;The Roadblocks &amp;amp; How We Fixed Them&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Redis Asynchronous Flow Control &amp;amp; Handshake Errors
The Problem: Early on, Redis commands (client.keys, client.get) were returning pending Promises instead of raw data, causing similarity mapping loops to blow up. Additionally, a local Redis client protocol handshake error (ERR unknown command 'HELLO') kept throwing connection-level exceptions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The Fix: Refactored all synchronous-style Redis calls into clean async/await pipelines, wrapped the search utility properly, and ensured proper client connection initialization.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;MongoDB Duplicate Key &amp;amp; Session Errors
The Problem: Concurrent session writes were triggering duplicate key errors when tracking chat histories and turns.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The Fix: Standardized session insertion logic to leverage upsert patterns, ensuring existing sessions safely append messages rather than throwing collision exceptions.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Stubborn TypeError: Cannot read properties of undefined (reading 'filter')
The Problem: This was the biggest hurdle of the day. Every time the agent initialized, the console threw a TypeError: Cannot read properties of undefined (reading 'filter') right after verifying the user role.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The Root Causes &amp;amp; Fixes:&lt;/p&gt;

&lt;p&gt;Mismatched Tool Names: ROLE_PERMISSIONS mapped roles directly to arrays of snake_case strings ('get_weather', 'get_geolocation'), but our allTools object used camelCase keys (geoLocation). When looping through allowed names, lookups returned undefined. Fix: Standardized all keys in allTools to strict snake_case matching the permission arrays.&lt;/p&gt;

&lt;p&gt;Async Function Pitfall: We converted createTools into an async function to safely query user states, but forgot to await it in the main agent runner script. Because it wasn't awaited, it returned a Promise instead of an array, immediately triggering a breakdown when downstream code tried to process or filter it. Fix: Added the missing await keyword to the createTools invocation in agent.js.&lt;/p&gt;

&lt;p&gt;Key Takeaways&lt;br&gt;
Building custom AI gateways requires rigorous attention to asynchronous boundaries. Mixing synchronous assumptions with asynchronous database calls (like Redis operations and MongoDB queries) or async tool loaders will instantly break your runtime loop.&lt;/p&gt;

</description>
      <category>node</category>
      <category>ai</category>
      <category>agents</category>
      <category>backend</category>
    </item>
    <item>
      <title>Building a Production-Grade AI Agent Gateway in Node.js: RBAC, Gateway-Level HITL, and Dynamic Tools</title>
      <dc:creator>Sawastik Bhullar</dc:creator>
      <pubDate>Sun, 08 Nov 2026 11:54:27 +0000</pubDate>
      <link>https://dev.to/sawastik_bhullar/building-a-production-grade-ai-agent-gateway-in-nodejs-rbac-gateway-level-hitl-and-dynamic-tools-393l</link>
      <guid>https://dev.to/sawastik_bhullar/building-a-production-grade-ai-agent-gateway-in-nodejs-rbac-gateway-level-hitl-and-dynamic-tools-393l</guid>
      <description>&lt;p&gt;When building AI agents for enterprise environments, relying solely on raw LLM calls is not enough. You need fine-grained control over execution boundaries, security guardrails, role-based access control (RBAC), and human-in-the-loop (HITL) intervention patterns.&lt;/p&gt;

&lt;p&gt;Over the past few iterations, we designed and built a modular AI Agent Gateway in Node.js from scratch. Here is a breakdown of the core architecture and features built so far.&lt;/p&gt;

&lt;p&gt;Architectural Overview&lt;br&gt;
The gateway is structured following the Single Responsibility Principle, separating authentication, tool registries, semantic search caching, guardrails, and the core agent orchestrator into clean, decoupled modules.&lt;/p&gt;

&lt;p&gt;agent.js: Core orchestrator managing the terminal CLI loop, safety guardrails, model fallback logic, semantic caching, and gateway-level decision routing.&lt;/p&gt;

&lt;p&gt;tools/createTools.js: Dynamic tool factory that maps user permissions to authorized execution capabilities (GeoLocation, Weather, Currency Converter).&lt;/p&gt;

&lt;p&gt;authentication/: JWT-based session verification tied to a mock database user profile.&lt;/p&gt;

&lt;p&gt;timestampsWindow/: Rate-limiting and global request window management.&lt;/p&gt;

&lt;p&gt;services/: Embedding generation and semantic search ranking for caching responses.&lt;/p&gt;

&lt;p&gt;Key Features Implemented&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Role-Based Access Control (RBAC)&lt;br&gt;
Every incoming request is verified via JWT. The user's ID is checked against a local user database to determine which tools they are explicitly authorized to use (e.g., user_123 has access to weather and geoLocation, but not currencyConverter). Unauthorized tools are excluded from the model payload to prevent unauthorized tool invocation and hallucination.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Gateway-Level Human-In-The-Loop (HITL) Escalation&lt;br&gt;
Instead of blocking execution completely when a user attempts a restricted action, the gateway intercepts the intent at the routing layer.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If a user requests an action requiring a restricted tool, the gateway pauses execution using node:readline/promises.&lt;/p&gt;

&lt;p&gt;It prompts the operator interactively: Do you want to escalate permissions and temporarily unlock this tool? (y/n).&lt;/p&gt;

&lt;p&gt;Upon a y confirmation, the tool is dynamically appended to the active session toolset, allowing the agent to proceed smoothly.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Real-World Tool Integration
Integrated practical tools using Zod schemas and LangChain tool wrappers:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GeoLocation: Resolves city names to latitude and longitude using OpenStreetMap Nominatim APIs.&lt;/p&gt;

&lt;p&gt;Weather: Fetches current weather metrics via Open-Meteo forecasts.&lt;/p&gt;

&lt;p&gt;Currency Converter: Performs live currency exchange calculations using real-time open rates.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Guardrails &amp;amp; Fallback Mechanisms
Input/Output Safety: A secondary guardrail agent evaluates user prompts and agent responses for malicious or sensitive data leaks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Model Fallback Mapping: Automatically cycles through OpenRouter model limits using a fallback map when quotas are exhausted.&lt;/p&gt;

&lt;p&gt;Semantic Caching: Stores previous query embeddings and responses to serve repetitive queries efficiently.&lt;/p&gt;

&lt;p&gt;What is Next&lt;br&gt;
With the core gateway, RBAC, and gateway-level HITL fully functional in a terminal environment, the next phase focuses on scaling to a production-ready system:&lt;/p&gt;

&lt;p&gt;MongoDB: Persistent user management, chat histories, and audit logs.&lt;/p&gt;

&lt;p&gt;Redis &amp;amp; BullMQ: Asynchronous background queue processing for heavy agent tasks.&lt;/p&gt;

&lt;p&gt;Frontend Dashboard: A web-based interface to manage agent queries and monitor gateway logs directly from the client side.&lt;/p&gt;

</description>
      <category>node</category>
      <category>ai</category>
      <category>agents</category>
      <category>backend</category>
    </item>
    <item>
      <title>Building an Agent-Aware LLM Gateway from First Principles in Node.js</title>
      <dc:creator>Sawastik Bhullar</dc:creator>
      <pubDate>Sat, 07 Nov 2026 14:39:39 +0000</pubDate>
      <link>https://dev.to/sawastik_bhullar/building-an-agent-aware-llm-gateway-from-first-principles-in-nodejs-22na</link>
      <guid>https://dev.to/sawastik_bhullar/building-an-agent-aware-llm-gateway-from-first-principles-in-nodejs-22na</guid>
      <description>&lt;p&gt;🔗 &lt;strong&gt;GitHub Profile:&lt;/strong&gt; &lt;a href="https://github.com/sawastik7-bit" rel="noopener noreferrer"&gt;github.com/sawastik7-bit&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  🚀 What I’m Building Right Now
&lt;/h3&gt;

&lt;p&gt;Instead of relying on out-of-the-box abstractions, I’m building &lt;strong&gt;AgentGate&lt;/strong&gt;—a production-grade, agent-aware LLM Gateway from scratch in Node.js. &lt;/p&gt;

&lt;p&gt;Most AI implementations fall short when scaling to production because of unhandled API rate limits, provider outages, high token latency, and security leaks. My goal is to handle these infrastructure challenges right at the gateway level.&lt;/p&gt;




&lt;h3&gt;
  
  
  🛠️ Core Features &amp;amp; Architecture
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Semantic Caching:&lt;/strong&gt; Utilizing vector embeddings (&lt;code&gt;Xenova/all-MiniLM-L6-v2&lt;/code&gt;) and Cosine Similarity (&amp;gt;0.8 threshold) to bypass LLM calls entirely for similar incoming prompts—reducing latency and API costs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Multi-Model Dynamic Routing &amp;amp; Fallbacks:&lt;/strong&gt; Automatically tracking model usage limits and gracefully switching providers (&lt;code&gt;OpenRouter&lt;/code&gt;, &lt;code&gt;Nvidia Nemotron&lt;/code&gt;, &lt;code&gt;OpenAI&lt;/code&gt;) when rate limits or quotas are hit.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Guardrails &amp;amp; Security:&lt;/strong&gt; Dual-pass input and output validation layers evaluating prompts for malicious injections and data leaks before hitting downstream agents.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sliding-Window Rate Limiting:&lt;/strong&gt; Global request tracking to enforce traffic constraints and prevent gateway overload.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Interactive Terminal CLI Loop:&lt;/strong&gt; Built using &lt;code&gt;node:readline/promises&lt;/code&gt; for real-time testing, session token verification, and output tracking.&lt;/li&gt;
&lt;/ol&gt;




&lt;h3&gt;
  
  
  💡 My Approach: First Principles First
&lt;/h3&gt;

&lt;p&gt;Instead of stitching together high-level black-box tools, I approach engineering from first principles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Build the core low-level mechanics first:&lt;/strong&gt; (Handling cosine similarity math, manual sliding windows, and custom fallback maps).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Measure &amp;amp; Debug:&lt;/strong&gt; Validating behavior through raw CLI output logs, tracking cache hits vs. misses, and timing provider switches.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Production Hardening:&lt;/strong&gt; Incrementally layering resilience patterns—exponential backoffs with jitter, circuit breakers, and stateful tracking.&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  📌 Other Systems &amp;amp; Infra Projects I'm Working On
&lt;/h3&gt;

&lt;p&gt;If you enjoy backend infrastructure and systems engineering, check out my other open-source projects on &lt;a href="https://github.com/sawastik7-bit" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Redis from Scratch:&lt;/strong&gt; Implementing the RESP protocol and TCP sockets in Node.js.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Custom HTTP Load Balancer:&lt;/strong&gt; Round-robin routing, health checks, and automatic backend failovers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Distributed API Gateway Analytics:&lt;/strong&gt; Real-time metrics dashboard with Redis, JWT, and BullMQ logging.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;💬 &lt;em&gt;I’d love to hear your thoughts on LLM gateway design patterns! How are you handling model fallbacks and semantic caching in your production AI agents? Drop a comment below!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>javascript</category>
      <category>node</category>
      <category>architecture</category>
    </item>
    <item>
      <title>How I Built a Distributed API Gateway with Rate Limiting, BullMQ Queues, and Real-Time Analytics — From Scratch</title>
      <dc:creator>Sawastik Bhullar</dc:creator>
      <pubDate>Tue, 14 Jul 2026 16:56:30 +0000</pubDate>
      <link>https://dev.to/sawastik_bhullar/how-i-built-a-distributed-api-gateway-with-rate-limiting-bullmq-queues-and-real-time-analytics--53dm</link>
      <guid>https://dev.to/sawastik_bhullar/how-i-built-a-distributed-api-gateway-with-rate-limiting-bullmq-queues-and-real-time-analytics--53dm</guid>
      <description>&lt;p&gt;I'm a CS undergrad and I wanted to build something that wasn't &lt;br&gt;
a tutorial clone. So I built a 7-phase distributed API gateway &lt;br&gt;
from scratch with Node.js — here's everything I learned.&lt;/p&gt;
&lt;h2&gt;
  
  
  What I Built
&lt;/h2&gt;

&lt;p&gt;A production-grade API gateway that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Routes requests to multiple upstream microservices&lt;/li&gt;
&lt;li&gt;Enforces per-client rate limiting using Redis token-bucket algorithm&lt;/li&gt;
&lt;li&gt;Logs analytics asynchronously via BullMQ worker queues&lt;/li&gt;
&lt;li&gt;Streams live traffic metrics to a React dashboard via Socket.io&lt;/li&gt;
&lt;li&gt;Secures all routes with JWT authentication&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;GitHub: &lt;/p&gt;
&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
    &lt;div class="c-embed__content"&gt;
        &lt;div class="c-embed__cover"&gt;
          &lt;a href="https://github.com/sawastik7-bit" class="c-link align-middle" rel="noopener noreferrer"&gt;
            &lt;img alt="" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Favatars.githubusercontent.com%2Fu%2F247727860%3Fv%3D4%3Fs%3D400" height="420" class="m-0" width="420"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="c-embed__body"&gt;
        &lt;h2 class="fs-xl lh-tight"&gt;
          &lt;a href="https://github.com/sawastik7-bit" rel="noopener noreferrer" class="c-link"&gt;
            sawastik7-bit (Sawastik Bhullar) · GitHub
          &lt;/a&gt;
        &lt;/h2&gt;
          &lt;p class="truncate-at-3"&gt;
            sawastik7-bit has 28 repositories available. Follow their code on GitHub.
          &lt;/p&gt;
        &lt;div class="color-secondary fs-s flex items-center"&gt;
            &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.githubassets.com%2Ffavicons%2Ffavicon.svg" width="32" height="32"&gt;
          github.com
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;


&lt;h2&gt;
  
  
  Phase Breakdown
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Phase 1 — Reverse Proxy&lt;/strong&gt;&lt;br&gt;
Used http-proxy-middleware to forward requests to upstream services.&lt;br&gt;
Hit a nasty bug: Express strips the mount path before passing &lt;br&gt;
to the proxy, so /api/users was reaching upstream as /users &lt;br&gt;
instead of /api/users. Fixed it with pathRewrite to prepend &lt;br&gt;
the path back.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 2 — JWT Auth Middleware&lt;/strong&gt;&lt;br&gt;
Standard but important. Every request hits the auth middleware &lt;br&gt;
before reaching the proxy. Invalid token = 401, no forwarding.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 3 — Redis Rate Limiting (Token Bucket)&lt;/strong&gt;&lt;br&gt;
Each client gets a bucket. Every request costs 1 token. &lt;br&gt;
Tokens refill at a fixed rate. If bucket is empty = 429.&lt;br&gt;
Why token bucket over fixed window? It handles burst traffic &lt;br&gt;
gracefully instead of hard-cutting requests at the window boundary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 4 — Async Analytics with BullMQ&lt;/strong&gt;&lt;br&gt;
This was the most interesting part. Logging every request &lt;br&gt;
synchronously would add latency to every single API call. &lt;br&gt;
Instead, I push a job to a BullMQ queue and return the response &lt;br&gt;
immediately. A separate worker picks up the job and writes to MongoDB.&lt;br&gt;
Result: 35% latency reduction on the critical path.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 5 — Socket.io Worker&lt;/strong&gt;&lt;br&gt;
The BullMQ worker doesn't just write to DB — it also emits &lt;br&gt;
events via Socket.io so the dashboard updates in real time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 6 — React Dashboard&lt;/strong&gt;&lt;br&gt;
Built with Vite + Recharts. Shows live request rate, &lt;br&gt;
rate-limit hits, latency percentiles. Updates sub-200ms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 7 — ES Modules Throughout&lt;/strong&gt;&lt;br&gt;
Kept the entire codebase on ESM. Painful to set up with &lt;br&gt;
some packages but worth it for consistency.&lt;/p&gt;
&lt;h2&gt;
  
  
  What I Learned
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Never do sync I/O on the request path. Ever.&lt;/li&gt;
&lt;li&gt;Redis is not just a cache — it's a coordination primitive.&lt;/li&gt;
&lt;li&gt;BullMQ is criminally underrated for background jobs.&lt;/li&gt;
&lt;li&gt;pathRewrite in http-proxy-middleware will save your life.&lt;/li&gt;
&lt;li&gt;Socket.io namespaces are the right abstraction for 
multi-tenant real-time features.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Stack
&lt;/h2&gt;

&lt;p&gt;Node.js, Express, Redis (ioredis), BullMQ, Socket.io, &lt;br&gt;
JWT, React, Vite, Recharts, MongoDB, ES Modules&lt;/p&gt;
&lt;h2&gt;
  
  
  Repo
&lt;/h2&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://assets.dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/sawastik7-bit" rel="noopener noreferrer"&gt;
        sawastik7-bit
      &lt;/a&gt; / &lt;a href="https://github.com/sawastik7-bit/distributed-api-gateway-analytics" rel="noopener noreferrer"&gt;
        distributed-api-gateway-analytics
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      A custom API Gateway built with Node.js featuring  reverse proxy, Redis rate limiting, JWT auth,  async logging with BullMQ, and a real-time  analytics dashboard using React and Socket.io
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;Distributed API Gateway &amp;amp; Analytics Engine&lt;/h1&gt;
&lt;/div&gt;
&lt;p&gt;A production-grade API Gateway built with Node.js featuring reverse proxy, Redis rate limiting, JWT authentication, async logging with BullMQ, and a real-time analytics dashboard.&lt;/p&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Architecture&lt;/h2&gt;
&lt;/div&gt;
&lt;div class="snippet-clipboard-content notranslate position-relative overflow-auto"&gt;&lt;pre class="notranslate"&gt;&lt;code&gt;Client Request
      ↓
API Gateway (Port 3000)
  → Rate Limiter (Redis)
  → JWT Auth
  → Reverse Proxy
      ↓
Microservices
  → Service A - Users (Port 4001)
  → Service B - Products (Port 4002)
      ↓
Logger → BullMQ Queue → Worker → MongoDB
                                    ↓
                          React Dashboard (Port 5173)
                          via Socket.io (Port 4003)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Features&lt;/h2&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Reverse proxy routing to microservices&lt;/li&gt;
&lt;li&gt;Redis rate limiting (10 requests/minute per IP)&lt;/li&gt;
&lt;li&gt;JWT authentication at gateway level&lt;/li&gt;
&lt;li&gt;Async request logging via BullMQ message queue&lt;/li&gt;
&lt;li&gt;Real time analytics dashboard with live charts&lt;/li&gt;
&lt;li&gt;Request metrics: total requests, requests per minute, average response time, error rate&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Tech Stack&lt;/h2&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Backend:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Node.js, Express.js&lt;/li&gt;
&lt;li&gt;Redis (Memurai on Windows)&lt;/li&gt;
&lt;li&gt;BullMQ (message queue)&lt;/li&gt;
&lt;li&gt;MongoDB with Mongoose&lt;/li&gt;
&lt;li&gt;Socket.io&lt;/li&gt;
&lt;li&gt;JSON Web Tokens&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Frontend:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;React (Vite)&lt;/li&gt;
&lt;li&gt;Recharts&lt;/li&gt;
&lt;li&gt;Socket.io…&lt;/li&gt;
&lt;/ul&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/sawastik7-bit/distributed-api-gateway-analytics" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Would love feedback on the architecture — especially around &lt;br&gt;
the queue worker design and rate limiting strategy.&lt;/p&gt;

</description>
      <category>api</category>
      <category>node</category>
      <category>showdev</category>
      <category>systemdesign</category>
    </item>
  </channel>
</rss>
