<?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: Aadarsh Singh</title>
    <description>The latest articles on DEV Community by Aadarsh Singh (@aadarshbabu).</description>
    <link>https://dev.to/aadarshbabu</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%2F1163385%2F96d3bd10-7001-491b-934e-39b046edd66b.jpeg</url>
      <title>DEV Community: Aadarsh Singh</title>
      <link>https://dev.to/aadarshbabu</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aadarshbabu"/>
    <language>en</language>
    <item>
      <title>Architecting for Zero: Building an Event-Driven, Scale-to-Zero AI Platform</title>
      <dc:creator>Aadarsh Singh</dc:creator>
      <pubDate>Sun, 27 Sep 2026 13:03:15 +0000</pubDate>
      <link>https://dev.to/aadarshbabu/architecting-for-zero-building-an-event-driven-scale-to-zero-ai-platform-4b93</link>
      <guid>https://dev.to/aadarshbabu/architecting-for-zero-building-an-event-driven-scale-to-zero-ai-platform-4b93</guid>
      <description>&lt;p&gt;Most modern AI applications follow an intuitive, straightforward pattern: the browser sends an HTTP POST, the API server invokes an LLM SDK, waits 15 seconds while streaming chunks back over the wire, and saves the result to a database.&lt;/p&gt;

&lt;p&gt;It works smoothly in development. But in production, this simple synchronous pattern quickly reveals its cracks:&lt;/p&gt;

&lt;p&gt;Vercel / Edge function timeouts abruptly cut off long-running multi-step agent graphs.&lt;br&gt;
Traffic spikes lock server threads, ballooning costs and stalling web traffic.&lt;br&gt;
Idle compute burns cash: keeping GPU-ready or high-memory container clusters running 24/7 when traffic fluctuates to zero overnight bleeds resources.&lt;br&gt;
Dropped client connections kill execution: if a user on mobile loses cell signal mid-generation, the entire inference is lost, wasting tokens and compute.&lt;br&gt;
When architecting Rewire—an AI platform orchestrating safety-critical cognitive reframing, Neo4j GraphRAG, and longitudinal mental health tracking—we set a clear architectural constraint:&lt;/p&gt;

&lt;p&gt;True Zero-Scale Economics: Baseline idle cost must be near $0/month, yet the system must instantly burst to handle concurrent multi-stage AI graphs without dropping tokens, exhausting database connections, or timing out web requests.&lt;/p&gt;

&lt;p&gt;Here is the high-level system architecture, the mechanics of our scale-to-zero pipeline, and the real-world pitfalls you encounter when taking this approach.&lt;/p&gt;

&lt;p&gt;The High-Level Topology&lt;br&gt;
Rewire is built as a decoupled monorepo (powered by Turborepo and pnpm). Instead of coupling user-facing authentication and rendering with heavy agentic inference, the architecture is split cleanly across an asynchronous message boundary:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                      ┌──────────────────────────────┐
                      │    User Browser / Client     │
                      └──────────────┬───────────────┘
                                     │ HTTP / SSE
                                     ▼
                      ┌──────────────────────────────┐
                      │  Next.js 16 BFF (apps/web)   │
                      │  Auth, tRPC, UI &amp;amp; SSE Stream │
                      └──────┬────────────────▲──────┘
         1. Enqueue Job      │                │ 4. Read Stream Events
         (Sub-100ms response)│                │    (XREAD with recovery)
                             ▼                │
                      ┌──────────────┐ ┌──────┴──────────────┐
                      │   AWS SQS    │ │    Redis Streams     │
                      │  (Job Queue) │ │   (ai:run:{runId})   │
                      └──────┬───────┘ └──────▲──────────────┘
         2. SQS Trigger      │                │ 3. Publish Tokens
            Event            ▼                │    &amp;amp; Deltas
                      ┌───────────────────────┴──────┐
                      │ NestJS AI Worker (apps/api)  │
                      │  AWS Lambda (Scale-to-Zero)  │
                      │  LangGraph + Neo4j GraphRAG  │
                      └──────────────┬───────────────┘
                                     │
                                     ▼
                      ┌──────────────────────────────┐
                      │ PostgreSQL (Prisma ORM)      │
                      │ Single Source of Truth       │
                      └──────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The system operates across three autonomous tiers:&lt;/p&gt;

&lt;p&gt;The Edge &amp;amp; BFF Tier (apps/web): Built with Next.js 16 (App Router), React 19, and Better Auth. It handles authentication, renders UI components, and serves as an ultra-fast gateway.&lt;br&gt;
The Elastic Queue &amp;amp; Stream Buffer: AWS SQS decouples ingestion from execution. Redis Streams (ai:run:{runId}) serves as an ephemeral, replayable token buffer.&lt;br&gt;
The AI Worker Tier (apps/api): A modular NestJS 11 application compiled into an AWS Lambda function triggered exclusively by SQS events. It drives LangGraph cognitive state machines, verifies clinical safety gates, and retrieves therapeutic context from Neo4j GraphRAG.&lt;br&gt;
Anatomy of an Asynchronous Interaction&lt;br&gt;
What does a message cycle look like when client requests never wait for an LLM?&lt;/p&gt;

&lt;p&gt;sequenceDiagram&lt;br&gt;
    autonumber&lt;br&gt;
    actor User as User Browser&lt;br&gt;
    participant Web as Next.js BFF (Vercel Serverless)&lt;br&gt;
    participant DB as PostgreSQL (Prisma)&lt;br&gt;
    participant SQS as AWS SQS&lt;br&gt;
    participant Worker as NestJS Worker (AWS Lambda)&lt;br&gt;
    participant Redis as Redis Streams&lt;br&gt;
    participant LLM as LLM Provider / Neo4j&lt;br&gt;
    User-&amp;gt;&amp;gt;Web: Send Prompt ("I'm feeling overwhelmed...")&lt;br&gt;
    Web-&amp;gt;&amp;gt;DB: 1. Persist User Message &amp;amp; AiRun(status: "queued")&lt;br&gt;
    Web-&amp;gt;&amp;gt;SQS: 2. Enqueue Lean Payload { runId, conversationId, userId }&lt;br&gt;
    Web--&amp;gt;&amp;gt;User: 3. Return { runId } immediately (&amp;lt; 100ms)&lt;br&gt;
    par Ephemeral Streaming&lt;br&gt;
        User-&amp;gt;&amp;gt;Web: GET /api/ai/runs/:runId/stream (SSE)&lt;br&gt;
        Web-&amp;gt;&amp;gt;Redis: XREAD from ai:run:{runId}&lt;br&gt;
    and Serverless Worker Execution&lt;br&gt;
        SQS-&amp;gt;&amp;gt;Worker: Trigger Lambda Event&lt;br&gt;
        Worker-&amp;gt;&amp;gt;DB: Update AiRun -&amp;gt; "running"&lt;br&gt;
        Worker-&amp;gt;&amp;gt;Redis: XADD run.started&lt;br&gt;
        Worker-&amp;gt;&amp;gt;Worker: Run LangGraph: Load Context -&amp;gt; Safety Triage -&amp;gt; Neo4j GraphRAG&lt;br&gt;
        loop Token Generation&lt;br&gt;
            LLM--&amp;gt;&amp;gt;Worker: Stream Token Chunk&lt;br&gt;
            Worker-&amp;gt;&amp;gt;Redis: XADD message.delta&lt;br&gt;
            Redis--&amp;gt;&amp;gt;Web: Event Delivered&lt;br&gt;
            Web--&amp;gt;&amp;gt;User: SSE Chunk Rendered in UI&lt;br&gt;
        end&lt;br&gt;
        Worker-&amp;gt;&amp;gt;DB: Commit Final Message &amp;amp; Mark AiRun "completed"&lt;br&gt;
        Worker-&amp;gt;&amp;gt;Redis: XADD run.completed&lt;br&gt;
        Web--&amp;gt;&amp;gt;User: Close SSE Connection&lt;br&gt;
    end&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Sub-100ms Handshake
When the user submits a prompt, the Next.js API route does not invoke LangGraph or call an AI model.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Instead, it validates the request using a shared Zod schema from packages/validation, writes the message and an AiRun record (flagged as queued) to PostgreSQL, and pushes an ultra-lean pointer payload to AWS SQS:&lt;/p&gt;

&lt;p&gt;{  "runId": "run_cuid123",  "conversationId": "conv_cuid456",  "messageId": "msg_cuid789",  "userId": "usr_cuid000"}&lt;br&gt;
The web server responds to the browser with { runId } in under 100ms. No gateway timeouts, no thread exhaustion, no risk of a 30-second multi-step graph stalling the front door.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Event-Driven Wake-Up
AWS SQS triggers the NestJS worker deployed on AWS Lambda. If there is zero traffic, zero Lambda instances are running.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When a job arrives, Lambda spins up, pulls authoritative context from PostgreSQL, and hands the state over to a deterministic LangGraph state machine:&lt;/p&gt;

&lt;p&gt;[START] &lt;br&gt;
   │&lt;br&gt;
   ▼&lt;br&gt;
[Load Context] ──► [Safety Triage] ──┬──► (Acute Risk) ──► [Crisis Helpline Flow] ──┐&lt;br&gt;
                                     │                                              │&lt;br&gt;
                                     └──► (Safe) ──► [Neo4j GraphRAG]               │&lt;br&gt;
                                                           │                        │&lt;br&gt;
                                                           ▼                        │&lt;br&gt;
                                                    [LLM Generation]                │&lt;br&gt;
                                                           │                        │&lt;br&gt;
                                                           ▼                        ▼&lt;br&gt;
                                                 [Response Verification] ◄──────────┘&lt;br&gt;
                                                           │&lt;br&gt;
                                                           ▼&lt;br&gt;
                                                    [Persist &amp;amp; END]&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Decoupled Streaming via Redis Streams
How does a serverless Lambda stream real-time text back to a browser without opening a direct WebSocket connection?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;As tokens arrive from the LLM, the Lambda worker pushes structured events (message.delta) into a dedicated Redis Stream: ai:run:{runId}.&lt;/p&gt;

&lt;p&gt;Meanwhile, the client connects to an SSE endpoint (/api/ai/runs/:runId/stream) served by Next.js. The SSE route reads from Redis Streams using XREAD and pipes events down to the client.&lt;/p&gt;

&lt;p&gt;Why Redis Streams Instead of Pub/Sub or WebSockets?&lt;br&gt;
Replayability &amp;amp; Resilient Reconnection: Redis Pub/Sub is fire-and-forget. If a user walks into an elevator and drops connection for 3 seconds, all missed tokens vanish. With Redis Streams, events are logged. When the client reconnects, it passes its Last-Event-ID, and the SSE handler resumes streaming exactly where it left off.&lt;br&gt;
Serverless Compatibility: Maintaining persistent, bidirectional WebSockets on serverless runtimes requires specialized gateway infrastructure (e.g., AWS API Gateway WebSockets). Redis Streams + SSE works over standard HTTP/2.&lt;br&gt;
Ephemeral Footprint: Each run’s stream has a short Time-to-Live (TTL). Once the run completes, the stream expires, keeping memory usage minimal.&lt;br&gt;
Why Scale-to-Zero?&lt;br&gt;
True Cost Elasticity: A startup or side project with sporadic traffic shouldn’t pay $150–$300/month for dedicated ECS/EKS clusters or container instances just to wait for user prompts. In this setup, idle compute cost is practically $0.&lt;br&gt;
Infinite Headroom for Spikes: If 500 users submit prompts simultaneously, SQS buffers the traffic cleanly. AWS Lambda scales out concurrently to process the jobs without bringing down the web tier.&lt;br&gt;
Protection Against Provider Outages: If an upstream LLM provider rate-limits or throttles requests, SQS handles exponential backoffs and dead-letter queueing (DLQ) without crashing the user’s browser session.&lt;br&gt;
Architectural Pitfalls &amp;amp; Trade-Offs&lt;br&gt;
While the zero-scale paradigm is cost-effective and resilient, it introduces non-trivial engineering trade-offs that every architect must evaluate.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The “Double Cold Start” Problem
When both your web tier (Next.js on Vercel) and your AI worker (NestJS on Lambda) scale to zero, an idle system encounters compounding cold starts:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next.js Serverless Function: ~300ms–800ms&lt;br&gt;
SQS Delivery Latency: ~50ms–200ms&lt;br&gt;
NestJS AWS Lambda Boot: 1,200ms–2,500ms (loading TypeScript metadata, Prisma engine, LangChain modules)&lt;br&gt;
While the user receives an immediate UI response acknowledging their message, their Time-to-First-Token (TTFT) after an idle period can reach 3–4 seconds.&lt;/p&gt;

&lt;p&gt;Mitigation: Optimize the Lambda bundle using esbuild/tree-shaking, minimize global module imports in NestJS, and use Lambda SnapStart or lightweight container provisioning if sub-second first-token response is mandatory.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Database Connection Flooding
Serverless workers scale horizontally with zero shared memory. When 100 SQS messages arrive at once:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;100 Lambda containers spin up in parallel.&lt;br&gt;
Each container attempts to open a connection pool via Prisma to PostgreSQL.&lt;br&gt;
PostgreSQL default max connection limit (e.g., 100–200 connections) is instantly saturated, causing Connection pool timeout errors.&lt;br&gt;
Mitigation: You cannot connect directly to vanilla Postgres from serverless workers at scale. You must place a connection pooler like AWS RDS Proxy, PgBouncer, or use serverless-native drivers (Prisma Accelerate / Neon Serverless Driver) to multiplex connections.&lt;/p&gt;

&lt;p&gt;Because i use the manage postgres database instance so there are no need to required PgBouncer on the top, pooler is associated to the layer of the database so our lambda can reuse the connection not make or create a new connection on each invocation.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Cost Inversion Point
Scale-to-zero is unbeatable at low to moderate traffic:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Monthly Active Workflows    Dedicated Server (Fargate / EKS)    Scale-to-Zero (Lambda + SQS + Redis)&lt;br&gt;
Low (0 – 10,000 runs) ~$80 – $200 / mo  ~$0 – $5 / mo&lt;br&gt;
Medium (100,000 runs)   ~$150 – $250 / mo ~$20 – $40 / mo&lt;br&gt;
Extreme Scale (10M+ runs)   ~$400 – $800 / mo ~$1,200 – $2,500+ / mo&lt;br&gt;
At millions of continuous requests per day, pay-per-invocation Lambda compute, SQS API calls, and Redis read/write operations surpass the predictable monthly cost of a well-tuned auto-scaling container cluster.&lt;/p&gt;

&lt;p&gt;The Verdict: When Should You Build This?&lt;br&gt;
The Decoupled Zero-Scale Architecture is the ideal blueprint if:&lt;/p&gt;

&lt;p&gt;✅ Your AI workloads involve multi-step reasoning, tool calls, or RAG that can exceed standard HTTP request timeouts.&lt;br&gt;
✅ Your application experiences variable or unpredictable traffic patterns, making dedicated 24/7 server clusters financially wasteful.&lt;br&gt;
✅ Resilience is paramount: client disconnections, mobile signal drops, or provider rate limits must never corrupt state or lose generated content.&lt;/p&gt;

&lt;p&gt;By strictly separating your fast web gateway from your heavy agent execution, and bridging them with a durable queue and an ephemeral stream, you get the best of both worlds: a lightning-fast user experience with zero idle infrastructure overhead.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://heyrewire.com" rel="noopener noreferrer"&gt;Visit HeyRewire platform&lt;/a&gt; &lt;/p&gt;

</description>
      <category>ai</category>
      <category>architecture</category>
      <category>cloud</category>
      <category>serverless</category>
    </item>
    <item>
      <title>Fluent UI 9 TextArea input field with useForm hook wher error happen it's loose my focus</title>
      <dc:creator>Aadarsh Singh</dc:creator>
      <pubDate>Sun, 17 Sep 2023 13:37:22 +0000</pubDate>
      <link>https://dev.to/aadarshbabu/fluent-ui-9-textarea-input-field-with-useform-hook-wher-error-happen-its-loose-my-focus-2652</link>
      <guid>https://dev.to/aadarshbabu/fluent-ui-9-textarea-input-field-with-useform-hook-wher-error-happen-its-loose-my-focus-2652</guid>
      <description>&lt;div class="ltag__stackexchange--container"&gt;
  &lt;div class="ltag__stackexchange--title-container"&gt;
    
      &lt;div class="ltag__stackexchange--title"&gt;
        &lt;div class="ltag__stackexchange--header"&gt;
          &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AoTUKOcU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/stackoverflow-logo-b42691ae545e4810b105ee957979a853a696085e67e43ee14c5699cf3e890fb4.svg" alt=""&gt;
          &lt;a href="https://stackoverflow.com/questions/77117993/fluent-ui-9-textarea-input-field-with-useform-hook-wher-error-happen-its-loose" rel="noopener noreferrer"&gt;
            Fluent UI 9 TextArea input field with useForm hook wher error happen it's loose my focus
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="ltag__stackexchange--post-metadata"&gt;
          &lt;span&gt;Sep 16 '23&lt;/span&gt;
            &lt;span&gt;Comments: 1&lt;/span&gt;
            &lt;span&gt;Answers: 0&lt;/span&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;a class="ltag__stackexchange--score-container" href="https://stackoverflow.com/questions/77117993/fluent-ui-9-textarea-input-field-with-useform-hook-wher-error-happen-its-loose" rel="noopener noreferrer"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oeieW07A--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/stackexchange-arrow-up-eff2e2849e67d156181d258e38802c0b57fa011f74164a7f97675ca3b6ab756b.svg" alt=""&gt;
        &lt;div class="ltag__stackexchange--score-number"&gt;
          1
        &lt;/div&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--h2-sXgSn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/stackexchange-arrow-down-4349fac0dd932d284fab7e4dd9846f19a3710558efde0d2dfd05897f3eeb9aba.svg" alt=""&gt;
      &lt;/a&gt;
    
  &lt;/div&gt;
  &lt;div class="ltag__stackexchange--body"&gt;
    
&lt;p&gt;I loose the focus when error happen the in textArea Component, and when i menualy all the foucs using ref.focus method it's ignore the previous type value and it's my new charector start in 0th position,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
import * as React from "react"
import {
  makeStyles,
  shorthands,
  useId,
  Input,
  Label,
  Field,&lt;/code&gt;&lt;/pre&gt;…
    
  &lt;/div&gt;
  &lt;div class="ltag__stackexchange--btn--container"&gt;
    &lt;a href="https://stackoverflow.com/questions/77117993/fluent-ui-9-textarea-input-field-with-useform-hook-wher-error-happen-its-loose" class="ltag__stackexchange--btn" rel="noopener noreferrer"&gt;Open Full Question&lt;/a&gt;
  &lt;/div&gt;
&lt;/div&gt;


</description>
    </item>
  </channel>
</rss>
