1. System Overview & Problem Statement
Modern enterprise and educational ecosystems demand high-performance, real-time artificial intelligence interfaces that merge robust full-stack architecture with fluid user experiences. Gayatri Ai was engineered during an intensive 60-day engineering sprint at DBERT (Digital Blinc Education Research and Technology) to bridge the gap between heavy, asynchronous AI inferencing pipelines and responsive, reactive client applications.
The primary challenge addressed by this architecture is the systemic latency and state-synchronization bottlenecks inherent in traditional request-response web applications when interfacing with large language models and multi-modal generative pipelines. In production environments, unoptimized payload sizes, unmanaged database connection pools, and lack of resilient error boundary handling lead to cascading failures and degraded user trust. Gayatri Ai solves these challenges by implementing an event-driven, decoupled system design utilizing strict typing, connection multiplexing, and optimized caching layers.
Below are the foundational operational endpoints and verification links associated with this deployment:
- Production Source Code: https://github.com/sanskariladka-jay/Gayatri-AI.git
- Interactive Live Deployment: https://gayatri-ai.dbert.in
- DBERT Verified Credential: https://dbert.in/verify/CERT-DBERT-2026-FSD-051
- Pre-Screening Rubric Score: 75/100 (High Merit)
2. Architectural Blueprint & Technical Stack Decisions
Gayatri Ai adopts a decoupled, microservices-ready monolithic architecture designed for horizontal scalability. The technology stack was selected to guarantee zero memory leaks, type safety from the database schema up to the React client, and sub-millisecond route resolution.
- Frontend: Next.js 14 (App Router), TypeScript, Tailwind CSS, Zustand for atomic state management.
- Backend / API Gateway: Node.js, Express.js with custom middleware for rate-limiting, JWT authentication, and structured Pino logging.
- AI / Core Domain Engine: Python, FastAPI, LangChain integration, and asynchronous worker threads for non-blocking payload processing.
- Database & Caching: PostgreSQL (with Prisma ORM for type-safe schema migrations) and Redis for session caching and rate-limit token buckets.
- Infrastructure & CI/CD: Docker containerization, Nginx reverse proxy, and automated GitHub Actions deployment pipelines routed to the
gayatri-ai.dbert.incloud cluster.
System Data Flow Diagram
+-------------------------------------------------------------------------+
| CLIENT LAYER |
| Next.js 14 (App Router) / React / Tailwind / Zustand |
+-------------------------------------------------------------------------+
|
| HTTPS / WSS (JSON Payloads)
v
+-------------------------------------------------------------------------+
| API GATEWAY / NGINX |
| SSL Termination / Rate Limiting / Geo-Routing |
+-------------------------------------------------------------------------+
|
| Proxy Pass
v
+-------------------------------------------------------------------------+
| CORE BACKEND SERVICES |
| Node.js / Express (Auth, Middleware, Session Validation) |
+-------------------------------------------------------------------------+
| |
| ORM Queries | RPC / HTTP (Async Queue)
v v
+-----------------------+ +-------------------------------+
| PostgreSQL + Prisma | | FastAPI AI Engine |
| (ACID Transactions) | | (LangChain / Model Pipes) |
+-----------------------+ +-------------------------------+
^ ^
| |
+------------------ Redis ----------------+
(Token Bucket & Response Caching)3. Core Implementation & Engineering Highlights
To maintain production-grade reliability, Gayatri Ai implements rigorous validation schemas and asynchronous error management across both client and server boundaries.
3.1 Strict Input Validation and Schema Enforcement (Prisma & Zod)
To prevent injection attacks and malformed model requests, all incoming user interactions are validated at the API boundary using Zod schemas before being processed by the database or AI pipeline.
import { z } from 'zod';export const AIQuerySchema = z.object({ prompt: z.string().min(3, "Prompt must be at least 3 characters").max(2048, "Prompt exceeds maximum token length"), temperature: z.number().min(0.0).max(1.0).default(0.7), modelTag: z.enum(['gayatri-v1-standard', 'gayatri-v2-pro']), contextWindow: z.number().int().positive().optional(), });
export type AIQueryPayload = z.infer<typeof AIQuerySchema>; ```
3.2 Asynchronous Redis Caching & Rate Limiting Middleware
To protect backend resources from denial-of-service vectors and reduce LLM inference latency for repetitive queries, an atomic Redis token-bucket rate limiter was implemented.
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);export async function rateLimiterMiddleware(req, res, next) {
const identifier = req.headers['x-user-id'] || req.ip;
const windowKey = rate-limit:${identifier};
try { const currentRequests = await redis.incr(windowKey); if (currentRequests === 1) { await redis.expire(windowKey, 60); // 1-minute sliding window }
if (currentRequests > 60) { return res.status(429).json({ error: "Too Many Requests", message: "Rate limit exceeded. Please retry after 60 seconds.", retryAfter: await redis.ttl(windowKey) }); } next(); } catch (error) { // Fail open for caching errors, log internally console.error("Redis Rate Limit Error:", error); next(); } } ```
3.3 Robust Error Boundary and Custom Exception Handling (Express)
Global exception handlers ensure that unhandled rejections do not crash the Node.js event loop, returning standardized JSON responses instead.
export class AppError extends Error {
constructor(statusCode, message, isOperational = true) {
super(message);
this.statusCode = statusCode;
this.isOperational = isOperational;
Error.captureStackTrace(this, this.constructor);
}
}export const errorHandler = (err, req, res, next) => { const statusCode = err.statusCode || 500; const message = err.message || "Internal Server Error";
console.error([Error] ${new Date().toISOString()} - Status: ${statusCode} - Msg: ${message});
res.status(statusCode).json({ success: false, error: { code: statusCode, message: message, ...(process.env.NODE_ENV === 'development' && { stack: err.stack }) } }); }; ```
4. Engineering Hurdles, Edge Cases & Performance Tuning
Building Gayatri Ai exposed several nuanced production challenges that required architectural tuning:
- Handling LLM Stream Disconnections & Timeouts:
- Standard HTTP connections would frequently timeout during heavy model generation sequences. We resolved this by implementing Server-Sent Events (SSE) combined with client-side exponential backoff reconnection strategies, allowing users to maintain UI state without duplicate database writes.
- PostgreSQL Connection Pool Exhaustion under Load:
- Initial load tests revealed database connection spikes during concurrent AI chat history persistence. This was mitigated by configuring Prisma's connection pool limits (
connection_limit=20) alongside aggressive Redis query result caching for frequent user retrieval operations. - Rubric Compliance & Strict Type Synchronization:
- Meeting the rigorous standards of the DBERT 9-dimension evaluation rubric (resulting in the final 75/100 High Merit score) required exhaustive refactoring to eliminate implicit
anytypes in TypeScript, implement comprehensive unit test suites using Jest and Supertest, and eliminate unused dependency bloat across the Docker container images.
5. Deployment, Live Verification & Reflections
The deployment of Gayatri Ai to gayatri-ai.dbert.in served as the capstone verification for the DBERT Full Stack Development Fellowship. Operating under rigorous pre-screening and peer-review rubrics, the application underwent rigorous containerized validation, ensuring zero downtime during rolling updates.
Scoring 75/100 (High Merit) validated our adherence to clean code architecture, defensive programming paradigms, and scalable cloud deployment strategies. Key takeaways from this 60-day incubation sprint include: - The critical importance of validating client payloads at multiple architectural tiers (Zod at the edge, Prisma at the persistence layer). - Designing asynchronous boundaries to decouple heavy compute operations from real-time UI threads. - Embracing disciplined Git workflows and automated CI/CD pipelines to guarantee production stability.
Interested in building production AI & Full Stack systems with 1:1 mentorship and verified credentials? Explore the [DBERT AI Fellowship](https://lms.dbert.in).