LectureAssist: AI-Powered Real-Time Lecture Q&A Platform
A real-time classroom collaboration platform featuring semantic question deduplication, multi-threaded local AI inference, and live file sharing.
Verified results and performance
Project details
- Role
- Full-Stack & Systems Engineer
- Timeline
- 2025
- Tracks
- software
Technologies and skills
Abstract
LectureAssist is a real-time collaborative Q&A platform engineered for university lecture halls. Built with React, Node.js, Express, PostgreSQL, and Socket.io, it allows students to join live lecture sessions and submit questions without interrupting the lecturer. The platform features an algorithmic NLP similarity engine for instant question deduplication and automatic upvote merging, a dedicated 4-worker thread pool offloading local Ollama (qwen:0.5b) inference from the Node event loop, and room-scoped WebSocket broadcasting for questions, upvotes, and in-session file sharing.
The Problem: Friction and Clutter in Large Lecture Halls
In large university lecture halls with over 100 students, fast-paced technical lectures present three fundamental engineering and usability challenges:
- Redundant and Cluttered Questions: When complex algorithms, operating system internals, or circuit diagrams are explained, multiple students inevitably formulate variations of the exact same question ("What is recursion?" vs "Can you explain recursive calls?"). Submitting multiple identical inquiries drowns out unique questions and overloads the lecturer.
- Event-Loop Bottlenecks: Offloading NLP parsing and AI generation directly to a standard single-threaded Node.js event loop blocks incoming HTTP requests, delays database queries, and disrupts WebSocket heartbeat pings.
- API Cost and Student Privacy: Relying on commercial cloud LLM APIs incurs recurring per-token costs and transmits internal university lecture discussions to external third-party servers.
"Core Concept: Ask once. Learn together. Stay focused. Provide a shared, low-latency question space that prevents duplicate inquiries while keeping the lecture flowing."
To solve this, I designed and built LectureAssist, an end-to-end real-time classroom platform with local AI inference, multi-threaded worker pools, algorithmic question deduplication, and database-level voting integrity.
System Architecture: End-to-End Flow
The system coordinates a mobile-friendly React frontend, an Express REST and WebSocket layer, an algorithmic text similarity pipeline, and a dedicated worker thread pool interfacing with self-hosted Ollama models.
[ Student / React Client ]
│
│ (POST /api/qa via JWT)
▼
[ Express API Router ]
│
▼
[ Semantic Deduplication Engine ]
├── Computes TF-IDF Cosine & Containment Overlap against active session questions
├── IF DUPLICATE (>= 0.68):
│ └── Auto-upvote existing QA in PostgreSQL ──> Socket.io Broadcast: "question_upvoted"
└── IF UNIQUE:
├── Save new QA to PostgreSQL ─────────────> Socket.io Broadcast: "new_question"
└── Enqueue to [ WorkerPool (4 Threads) ]
│
▼
[ ollamaWorker.js ]
│ (Calls Local Ollama: qwen:0.5b)
▼
Emit "question_answered" via Socket.io Room
Semantic Question Deduplication & Smart Merging
The Challenge
When students ask questions in natural language, identical conceptual doubts are phrased differently:
- "What is a binary search tree?"
- "Can you explain binary search trees with an example?"
- "How does a BST work?"
If every variation created a new entry, the question feed would rapidly clutter. However, rejecting the question outright frustrates the student.
The Hybrid Similarity Algorithm
Instead of relying on heavy external embedding services that introduce network latency, I developed a lightweight, multi-stage NLP similarity utility (similarity.js) combining four complementary metrics:
-
Stemming & Stop-Word Filtering: Removes conversational filler ("please", "explain", "sir", "tell me") and normalizes plurals and verbal suffixes using morphological stemming rules ("trees" -> "tree", "searching" -> "search").
-
TF-IDF Vector Cosine Similarity: Computes directional cosine similarity between term-frequency vectors:
TextCosine(A, B) = (A . B) / (||A|| * ||B||) -
Containment Overlap Coefficient: Explicitly addresses sub-phrase containment when a student embeds a short core concept inside verbose conversational text:
TextOverlap(A, B) = |A ∩ B| / min(|A|, |B|) -
Character Trigram Jaccard: Analyzes 3-character subword windows to provide spelling and typographical error tolerance.
Automated Action
If similarity satisfies threshold >= 0.68, the backend suppresses duplicate card creation, automatically records an upvote for the student on the existing question thread, and immediately broadcasts question_upvoted over Socket.io in under 15 ms.
// Hybrid similarity evaluation from backend/src/utils/similarity.js
async function findDuplicateQuestion(newQuestion, existingQuestions, threshold = 0.68) {
if (!existingQuestions || existingQuestions.length === 0) {
return { isDuplicate: false, matchedQuestion: null, similarity: 0 };
}
let highestSimilarity = 0;
let bestMatch = null;
// Evaluate embedding if Ollama vector service is reachable
const newEmb = await getOllamaEmbedding(newQuestion);
for (const item of existingQuestions) {
let score = 0;
if (newEmb) {
const itemEmb = await getOllamaEmbedding(item.question);
if (itemEmb) {
score = vectorCosine(newEmb, itemEmb);
}
}
const textScore = calculateTextSimilarity(newQuestion, item.question);
const finalScore = newEmb ? Math.max(score, textScore) : textScore;
if (finalScore > highestSimilarity) {
highestSimilarity = finalScore;
bestMatch = item;
}
}
return {
isDuplicate: highestSimilarity >= threshold,
matchedQuestion: highestSimilarity >= threshold ? bestMatch : null,
similarity: parseFloat(highestSimilarity.toFixed(3)),
};
}
Multi-Threaded Worker Pool for Local AI Inference
The Challenge
Generating responses with local models via Ollama (qwen:0.5b) requires 1 to 3 seconds of continuous inference time. Executing synchronous HTTP requests or heavy processing on the Express main thread blocks Node's event loop, creating server latency spikes and delayed WebSocket acknowledgments.
Implementation: Custom WorkerPool
I engineered an asynchronous worker thread pool (WorkerPool.js) using Node's native worker_threads:
- Maintains 4 persistent worker threads running
ollamaWorker.js. - Implements an internal FIFO task queue with dynamic worker dispatch.
- Correlates asynchronous responses with incoming callers using unique
messageIdcallbacks. - Emits
question_answeredover the lecture-specific Socket.io room once complete, without degrading Express REST throughput.
// Custom WorkerPool implementation from backend/src/utils/WorkerPool.js
const { Worker } = require('worker_threads');
const path = require('path');
class WorkerPool {
constructor(workerPath, numWorkers = 4) {
this.workers = [];
this.queue = [];
this.activeWorkers = new Map();
this.callbacks = new Map();
for (let i = 0; i < numWorkers; i++) {
const worker = new Worker(path.resolve(__dirname, workerPath));
this.setupWorkerHandlers(worker, i);
this.workers.push(worker);
}
}
setupWorkerHandlers(worker, id) {
worker.on('message', (result) => {
this.activeWorkers.delete(id);
const callback = this.callbacks.get(result.messageId);
if (callback) {
callback(result);
this.callbacks.delete(result.messageId);
}
if (this.queue.length > 0) {
const nextTask = this.queue.shift();
this.runTask(nextTask, id);
}
});
worker.on('error', (error) => {
console.error(`Worker \${id} error:`, error);
this.activeWorkers.delete(id);
});
}
executeTask(task) {
const availableWorkerId = this.workers.findIndex((_, id) => !this.activeWorkers.has(id));
if (availableWorkerId !== -1) {
this.runTask(task, availableWorkerId);
} else {
this.queue.push(task);
}
}
}
// Ollama task handler in backend/src/workers/ollamaWorker.js
parentPort.on('message', async (message) => {
const { type, questionId, question, messageId } = message;
if (type === 'generate_response') {
try {
const response = await axios.post(`\${OLLAMA_API_URL}/api/generate`, {
model: "qwen:0.5b",
prompt: question,
stream: false,
});
parentPort.postMessage({
type: 'response_generated',
questionId,
response: response.data.response,
messageId,
});
} catch (error) {
parentPort.postMessage({
type: 'error',
questionId,
error: 'Error processing local inference',
messageId,
});
}
}
});
Strict Per-User Upvoting with Relational Integrity
The Problem with Simple Counters
Naive applications store upvotes as a plain integer counter (upvotes = upvotes + 1). This allows malicious users to spam voting endpoints, artificially inflating questions.
Database-Level Unique Compound Constraint
To guarantee absolute voting integrity under concurrent race conditions, I introduced a dedicated join model (QuestionUpvote.js) in PostgreSQL with a composite unique index:
- Idempotent Toggle Logic: When an authenticated student clicks upvote, the system checks for an existing record. If found, the vote is safely removed and the count decrements. If not found, the record is created and the count increments.
- Client State: When questions are retrieved, an optional JWT authentication middleware attaches an instant
hasUpvoted: booleanattribute to each question object, giving each student immediate UI feedback.
// Compound database constraint in backend/src/models/QuestionUpvote.js
const QuestionUpvote = sequelize.define('QuestionUpvote', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
userId: {
type: DataTypes.UUID,
allowNull: false,
},
qaId: {
type: DataTypes.UUID,
allowNull: false,
},
}, {
indexes: [
{
unique: true,
fields: ['userId', 'qaId'],
},
],
});
Room-Based Real-Time Collaboration & File Sharing
- Lecture-Scoped Socket Rooms: The platform uses Socket.io rooms (
socket.join(lectureId)). Real-time events (new_question,question_answered,question_upvoted,file_shared) are isolated to active attendees of that specific lecture session. - In-Session File Sharing: Integrated Multer for multi-part file uploads paired with WebSocket event notifications, allowing lecturers to distribute slides and reference materials directly inside the live session.
Key Engineering Decisions and Interview Takeaways
- Why Worker Threads over Child Processes? Worker threads share memory space within the same Node.js process and have negligible instantiation overhead compared to spawning operating system child processes. This makes them ideal for managing I/O queues and AI worker pools.
- Why a Hybrid Text Similarity Algorithm? While dense embedding models are effective, calling external embedding APIs introduces latency and external dependencies. Engineering an algorithmic hybrid (TF-IDF cosine + containment overlap + character trigrams) delivers sub-millisecond deduplication directly in Node, with graceful fallback to Ollama embeddings when running.
- Why Compound Database Constraints?
Enforcing a composite
UNIQUE(userId, qaId)constraint at the PostgreSQL database level guarantees data integrity even under concurrent race conditions, preventing vote manipulation without relying solely on application-level locks.
Discuss this project
Have questions about the architecture or design decisions?