ClassBuddy 🎓 — Next-Gen AI EdTech & Real-Time Classroom Ecosystem
License
OAuth2
React
TypeScript
Vite
FastAPI
TailwindCSS
PostgreSQL
Redis
Inngest
LangChain
Docker
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 (
S256Challenge 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
S256code challenges and verifiers, safeguarding against authorization code interception attacks. - Dual Client Transport Architecture:
- Web Client (
classbuddy-web): Implements strictHttpOnly,SameSite=Lax/Strict,Securecookies (access_token,refresh_token), immunizing the browser from XSS token extraction. - Android Mobile Client (
classbuddy-android): Interacts via standardAuthorization: Bearer <token>headers and JSON payloads.
- Web Client (
- 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.generatedispatched upon teacher request. - Step 1 (
ai-generate-assignment-questions): Asynchronously executesassignment_graphwith Gemini 2.5 Flash, extracting structured questions in JSON format. - Step 2 (
db-update-assignment-questions): Idempotently commitsAssignmentQuestionrecords to PostgreSQL and resetsassignment.is_generating = False. - Resilient Fallback (
reset-generating-state-on-error): On unexpected LLM or DB failures, Inngest triggers an automated step to resetis_generatingtoFalse, preventing UI hang.
B. Mock Interview Preparation Generator (fn_id: generate-interview-questions)
- Event Trigger:
interview/prep.createtriggered by student submission. - Step 1 (
ai-generate-questions): Callsinterview_graphto produce dynamic, role-specific technical questions. - Step 2 (
db-update-questions): Commits the questions to the database and marksInterviewPrep.status = Status.COMPLETED. - Step 3 (
db-update-error): Fallback error handler sets status toStatus.ERRORif generation or validation fails.
C. Student Career Intelligence & Weekly Cron Engine (fn_id: generate-student-industry-insight)
- Dual Trigger Strategy:
- User-Invoked Event:
student/industry.generatefor immediate on-demand profile generation. - CRON Scheduler:
inngest.TriggerCron(cron="0 0 * * 0")runs every Sunday at midnight UTC to refresh insights for all enrolled students.
- User-Invoked Event:
- Step Execution Pipeline:
fetch-refresh-targets: Queries all eligible student profiles across PostgreSQL.ai-research-{user_id}: Runsindustry_graphto analyze emerging market trends and required skills.db-sync-{user_id}: Persists the updated skill matrices into theStudentInsightentity.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 customuseAIStreamReact 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-statusreturns{"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 Requeston 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 Challenge | Root Cause | Engineering Solution | Measurable Impact |
|---|---|---|---|
| LLM Hallucinations in Educational Guides | Single-turn prompts lack factual grounding and formatting consistency | Designed a 6-node LangGraph cyclic graph (Planner ➔ Research ➔ Generator ➔ Evaluator ➔ Improver ➔ Saver) with Tavily web grounding | 100% cited references, eliminated shallow content, and ensured structured Markdown |
| High Latency & HTTP Thread Starvation | AI generation and analytics computation take 5–15 seconds, blocking server threads | Migrated all heavy workloads to Inngest background event workers with step-level memoization | Reduced transactional API response time to < 120ms |
| Weekly Data Staleness for Students | Students need updated market and skill insights without manual button clicks | Configured an Inngest Cron trigger (0 0 * * 0) that runs every Sunday at midnight and purges Redis cache | Automated zero-touch updates for 100% of active student profiles |
| WebSocket Split-Brain across Server Pods | Traditional in-memory socket lists only broadcast to clients on the same physical server | Implemented a Redis Pub/Sub message broker syncing channels across all running FastAPI instances | Sub-50ms message delivery across multi-pod cluster deployments |
| Token Theft & Security Across Web & Mobile | Storing JWTs in browser localStorage leaves applications vulnerable to XSS | Architected a custom OAuth 2.0 PKCE server using HttpOnly Strict cookies for web and Bearer tokens for mobile | Neutralized XSS token theft and automated token-family replay revocation |
