ClassBuddy

Built with

React 18ViteTypeScriptTailwind CSSRedux ToolkitTanStack QueryFastAPIPythonPostgreSQLNeonDBSQLAlchemyAlembicRedisWebSocketsInngestLangChainLangGraphGoogle Gemini 2.5 FlashTavily Search APIOAuth 2.0 (PKCE)SlowAPIRazorpayCloudinaryDocker

ClassBuddy 🎓 — Next-Gen AI EdTech & Real-Time Classroom Ecosystem

LicenseLicense OAuth2OAuth2 ReactReact TypeScriptTypeScript ViteVite FastAPIFastAPI TailwindCSSTailwindCSS PostgreSQLPostgreSQL RedisRedis InngestInngest LangChainLangChain DockerDocker

Project Links & References:
🔗 Web Repository: GitHub - ClassBuddy
📱 Android Client: GitHub - ClassBuddy Mobile App
🌐 Domain: Multi-Agent AI Systems, Distributed Real-Time Microservices, EdTech, Cloud Architecture


📌 Executive Overview

ClassBuddy is a modern, enterprise-grade educational ecosystem engineered to connect educators and learners through autonomous AI agents, distributed low-latency messaging, automated assignment evaluation, and built-in subscription monetization.

Designed from the ground up to solve the architectural bottlenecks of AI-native web applications, ClassBuddy features a custom-built OAuth 2.0 PKCE Authorization Server (eliminating third-party auth vendors), a LangGraph multi-agent self-refining loop, an Inngest event-driven background job engine with Cron automation, a Redis-backed distributed WebSocket mesh, and real-time token streaming via Server-Sent Events (SSE).


💻 Tech Stack for Portfolio (Comma-Separated)

🏷️ Categorized by Engineering Domain:

  • Frontend Architecture: React 18.3, Vite 7.1, TypeScript 5.8, Tailwind CSS 4.1, Redux Toolkit, Redux Persist, TanStack Query v5, Radix UI Primitives, Lucide Icons, Recharts, React MD Editor, Axios
  • Backend & Core API: FastAPI 0.109 (Async Python 3.10+), SQLAlchemy 2.0, Alembic Migrations, PostgreSQL (Neon Cloud Serverless), SlowAPI (Token Bucket Rate Limiting), WebSockets, Server-Sent Events (SSE)
  • Authentication & Identity: Custom Standalone OAuth 2.0 Server, RFC 7636 PKCE (S256 Challenge Verifier), Refresh Token Family Rotation, HttpOnly Strict Cookies, Mobile Bearer Tokens, PyJWT
  • Autonomous AI & Agentic Systems: LangChain, LangGraph State Machines (Planner ➔ Research ➔ Generator ➔ Evaluator ➔ Improver ➔ Saver), Google Gemini 2.5 Flash, Hugging Face Hub, Tavily Search API
  • Asynchronous Jobs & Distributed Systems: Inngest Serverless Event Bus, Inngest Cron Schedulers, Redis 7 (Pub/Sub Broker & KV Caching), Cloudinary CDN, Razorpay Payments API, Docker, Docker Compose

🏗️ System Design Architecture

ClassBuddy decouples compute-heavy agentic execution, high-concurrency WebSocket messaging, and transactional relational operations into an event-driven, resilient architecture:

Loading diagram...

⚡ Comprehensive Deep-Dive: Core System Features

🔐 1. Custom OAuth 2.0 Authorization Server (PKCE)

ClassBuddy operates as an independent, standalone RFC 7636 compliant OAuth 2.0 Authorization Server with zero reliance on paid external providers (e.g., Clerk, Auth0).

  • Proof Key for Code Exchange (PKCE): Utilizes S256 code challenges and verifiers, safeguarding against authorization code interception attacks.
  • Dual Client Transport Architecture:
    • Web Client (classbuddy-web): Implements strict HttpOnly, SameSite=Lax/Strict, Secure cookies (access_token, refresh_token), immunizing the browser from XSS token extraction.
    • Android Mobile Client (classbuddy-android): Interacts via standard Authorization: Bearer <token> headers and JSON payloads.
  • Token Rotation & Family Revocation: Employs automated refresh token rotation. If an expired or already-consumed refresh token is replayed, the system instantly revokes the entire token family, neutralizing token hijackers.
  • OIDC Endpoints:
    • POST /api/v1/oauth/authorize/login: Validates credentials and yields single-use PKCE authorization codes.
    • POST /api/v1/oauth/token: Exchanges authorization codes or refresh tokens for active sessions.
    • POST /api/v1/oauth/revoke: Revokes refresh tokens and clears client cookies.
    • GET /api/v1/oauth/userinfo: Delivers cryptographically verified user claims.

⚙️ 2. Event-Driven Background Engine & CRON Schedulers (Inngest)

To prevent server thread starvation during heavy AI and database operations, ClassBuddy integrates Inngest as an asynchronous serverless background execution engine.

A. Asynchronous Assignment Question Synthesis (fn_id: generate-assignment-questions)

  • Event Trigger: assignment/question.generate dispatched upon teacher request.
  • Step 1 (ai-generate-assignment-questions): Asynchronously executes assignment_graph with Gemini 2.5 Flash, extracting structured questions in JSON format.
  • Step 2 (db-update-assignment-questions): Idempotently commits AssignmentQuestion records to PostgreSQL and resets assignment.is_generating = False.
  • Resilient Fallback (reset-generating-state-on-error): On unexpected LLM or DB failures, Inngest triggers an automated step to reset is_generating to False, preventing UI hang.

B. Mock Interview Preparation Generator (fn_id: generate-interview-questions)

  • Event Trigger: interview/prep.create triggered by student submission.
  • Step 1 (ai-generate-questions): Calls interview_graph to produce dynamic, role-specific technical questions.
  • Step 2 (db-update-questions): Commits the questions to the database and marks InterviewPrep.status = Status.COMPLETED.
  • Step 3 (db-update-error): Fallback error handler sets status to Status.ERROR if generation or validation fails.

C. Student Career Intelligence & Weekly Cron Engine (fn_id: generate-student-industry-insight)

  • Dual Trigger Strategy:
    1. User-Invoked Event: student/industry.generate for immediate on-demand profile generation.
    2. CRON Scheduler: inngest.TriggerCron(cron="0 0 * * 0") runs every Sunday at midnight UTC to refresh insights for all enrolled students.
  • Step Execution Pipeline:
    • fetch-refresh-targets: Queries all eligible student profiles across PostgreSQL.
    • ai-research-{user_id}: Runs industry_graph to analyze emerging market trends and required skills.
    • db-sync-{user_id}: Persists the updated skill matrices into the StudentInsight entity.
    • clear-cache-{user_id}: Automatically purges stale cache keys in Redis (student_insights:{user_id}) to ensure instant read consistency.
Loading diagram...

🤖 3. Autonomous Multi-Agent AI System (LangGraph)

Rather than relying on basic single-turn prompts, ClassBuddy uses stateful, cyclic multi-agent graphs built on LangGraph with integrated critique-and-refine loops:

  • Cyclic Architecture: Planner ➔ Research ➔ Generator ➔ Evaluator ➔ Improver ➔ Saver
    • Planner: Deconstructs syllabus topics into logical pedagogical units.
    • Research: Queries the Tavily Search API for up-to-date facts and verified external citations.
    • Generator: Drafts extensive Markdown notes with formulas and code examples.
    • Evaluator: Critiques the generated draft against clarity, depth, and academic rubrics.
    • Improver: Iteratively rewrites weak sections identified by the Evaluator before finalizing.
    • Saver: Commits the clean Markdown document into PostgreSQL.
  • AI Evaluation Engine (ai_evaluator.py): Grades student code submissions and free-text assignments, outputting line-by-line feedback and rubric scoring.
  • Progressive Token Streaming (/api/v1/ai-stream): Utilizes Server-Sent Events (SSE) paired with a custom useAIStream React hook to render LLM responses progressively with zero perceptual latency.
Loading diagram...

💬 4. Distributed Real-Time Communication Mesh (WebSockets + Redis Pub/Sub)

  • High-Concurrency WebSocket Gateway: Custom connection manager handling active student and teacher connections per classroom group (groupMessage.py).
  • Redis Pub/Sub Distribution: Enables horizontal scaling across multiple container instances; messages published on any node are instantly broadcast across the entire cluster.
  • Data Reliability & History: Every message frame is asynchronously persisted to PostgreSQL before broadcasting, with cursor-based infinite scroll loading on the frontend.
Loading diagram...

🏫 5. Teacher Group Onboarding & Access Control

  • Onboarding Guard (require_teacher_group): Strict backend dependency enforcing group creation before accessing teacher tools. Restricted calls return HTTP 403:
    json
    {
      "detail": "Teacher must create a group before accessing this feature.",
      "code": "TEACHER_GROUP_REQUIRED"
    }
  • Status Endpoint: GET /api/v1/teacher/group-status returns {"has_group": bool, "group_count": int} to conditionally render onboarding banners vs. active dashboards.
  • Single Group Policy: Enforces a strict 1-group limit per teacher account (400 Bad Request on duplicate creation).

💰 6. Native Monetization & Tier Management (Razorpay)

  • Tier Management: Teachers can configure up to 3 subscription tiers per classroom group with customizable pricing.
  • End-to-End Payment Flow: Integrated with Razorpay APIs supporting automated order creation, cryptographic webhook validation (X-Razorpay-Signature), and automatic membership activation.
  • Revenue Telemetry: Teacher dashboards feature real-time charts tracking gross volume, recurring subscribers, renewal rates, and payment logs.

📁 7. Centralized Media & Document Management (Cloudinary)

  • Unified upload pipeline (docsupload.py) supporting lecture slides, PDFs, code snippets, and student submissions via the Cloudinary Python SDK.
  • Provides authenticated asset URLs, thumbnail generation, and bandwidth-optimized CDN delivery.

📊 8. Insight Dashboards & Career Intelligence

  • Teacher Analytics: High-level views of assignment completion rates, student grade distributions, and revenue metrics.
  • Student Career Hub: Visual radar charts depicting skill mastery, weekly performance reviews, and AI-curated technology learning paths.

💡 Engineering Challenges & Solutions

Technical ChallengeRoot CauseEngineering SolutionMeasurable Impact
LLM Hallucinations in Educational GuidesSingle-turn prompts lack factual grounding and formatting consistencyDesigned a 6-node LangGraph cyclic graph (Planner ➔ Research ➔ Generator ➔ Evaluator ➔ Improver ➔ Saver) with Tavily web grounding100% cited references, eliminated shallow content, and ensured structured Markdown
High Latency & HTTP Thread StarvationAI generation and analytics computation take 5–15 seconds, blocking server threadsMigrated all heavy workloads to Inngest background event workers with step-level memoizationReduced transactional API response time to < 120ms
Weekly Data Staleness for StudentsStudents need updated market and skill insights without manual button clicksConfigured an Inngest Cron trigger (0 0 * * 0) that runs every Sunday at midnight and purges Redis cacheAutomated zero-touch updates for 100% of active student profiles
WebSocket Split-Brain across Server PodsTraditional in-memory socket lists only broadcast to clients on the same physical serverImplemented a Redis Pub/Sub message broker syncing channels across all running FastAPI instancesSub-50ms message delivery across multi-pod cluster deployments
Token Theft & Security Across Web & MobileStoring JWTs in browser localStorage leaves applications vulnerable to XSSArchitected a custom OAuth 2.0 PKCE server using HttpOnly Strict cookies for web and Bearer tokens for mobileNeutralized XSS token theft and automated token-family replay revocation