⚡ Production Documentation

DisciplineOS

A personalized aspirant accountability platform engineered for UPSC, PSC, NEET, JEE, Coding & competitive exam students. Powered by AI, automation, and behavioral psychology.

Version1.0.0
Stackn8n · Telegram · OpenAI
TargetUPSC / NEET / JEE / PSC
ArchitectureMulti-tenant SaaS
01

Product Vision

DisciplineOS is not a study app. It is an accountability operating system — built to enforce, monitor, and sustain the behavioral discipline that high-stakes competitive exam aspirants need to succeed over months and years of preparation.

Traditional study platforms assume students are self-motivated. DisciplineOS assumes the opposite: that most aspirants need external structure, real-time feedback, intelligent nudges, and psychological pressure to stay on track.

🎯
Hyper-Personalization

No two students share the same automation schedule. Every message, reminder, and evaluation is tuned to each student's own wake time, habits, and goals.

🤖
AI Understanding

Natural language replies are parsed by OpenAI to extract topics studied, hours completed, emotional state, and productivity signals — no forms required.

🔥
Streak Psychology

Loss aversion, streak rewards, and weekly promotions/demotions create behavioral pressure that makes skipping study sessions feel costly.

📊
Behavioral Analytics

Long-term consistency tracking, burnout detection, weak subject heatmaps, and focus score trends surface insights that students can't see themselves.

⚙️
Full Automation

n8n workflows trigger Telegram messages, log data to Google Sheets/PostgreSQL, invoke OpenAI, compute scores, and update leaderboards — with zero manual intervention.

📈
Scalable SaaS

Built to grow from 10 students to 10,000. Multi-tenant architecture, per-user isolation, and a React dashboard allow admin and student access at scale.

Core Design Principle

💡 Every student must receive a personalized study accountability system based on their own wake-up time, study schedule, target hours, working style, consistency level, daily goals, and weak areas. The system must never send the same message to all students at the same time.
02

User Journey

The complete lifecycle of a student from onboarding to long-term accountability.

Day 0
Registration & Onboarding

Student fills onboarding form (HTML or Google Form). Provides name, Telegram username, phone, exam type, daily target hours, wake time, sleep time, preferred study slots, weak subjects, weekly goals, consistency level, and timezone. Data is auto-saved to Google Sheets / PostgreSQL and a unique user_id is assigned.

Day 0
Personalized Schedule Generation

The Personalized Automation Engine reads the student's profile and generates a unique daily schedule: morning accountability time (wake + 15 min), mid-day check-in times every 2 hours, evening review time, and night summary time. These schedules are stored per-student and drive all automation triggers.

Daily
Morning Accountability Check

Student receives a personalized Good Morning message on Telegram. Bot asks: today's target, focus subject, planned study hours, and energy level (1–5). Student replies in natural language. AI extracts structured data and logs it as the day's DailyPlan entry.

Every 2h
Mid-Day Progress Pings

Bot sends progress check-ins every 2 hours within the student's active window. Asks: completed topics, current focus level, break status, test performance. Student replies freely ("Completed Polity Chapter 3" / "Taking a 15-minute break"). AI logs structured FocusSession entries.

Evening
Night Review

Bot initiates end-of-day review. Asks: total hours studied, what was completed, what was skipped, tomorrow's plan, and overall mood. AI computes DailyScore (0–100) and updates StreakHistory. If the student fails the minimum threshold, streak is broken and penalty applied.

Weekly
Weekly Evaluation & Promotion

System evaluates the week: were target hours met on ≥4 days? Was 60%+ completion maintained? If yes → student advances to next week's schedule. If no → student repeats the same week. If 3+ failures → full streak reset. Leaderboard updated. AI generates a personalized weekly feedback report.

Ongoing
AI Coaching Interventions

AI monitors patterns across sessions: detects low consistency (3-day drops), burnout signals (energy < 2 for 2+ days), distraction patterns (short sessions, incomplete logs), and weak subject recurrence. Triggers motivational nudges, break recommendations, or adaptive plan suggestions.

03

Workflow Architecture

DisciplineOS is composed of five interconnected system layers. Each layer has a distinct responsibility and communicates via event-driven triggers.

User Layer
Telegram Bot
Onboarding Form
React Dashboard (future)
Automation
n8n Workflows
Cron Scheduler
Personalized Trigger Engine
AI Layer
OpenAI GPT-4 Parser
Intent Classifier
Coaching Engine
Processing
Score Calculator
Streak Engine
Weekly Evaluator
Leaderboard Updater
Data Layer
PostgreSQL (primary)
Google Sheets (MVP)
Redis (cache/queue)

Event Flow Overview

1
Student Sends Message → Telegram Webhook

Every student message triggers a Telegram webhook that n8n is subscribed to. n8n receives the payload with chat_id, user_id, and raw message text.

2
User Lookup + Context Fetch

n8n queries the Users table via chat_id to retrieve the student's profile, current streak, today's plan, and last activity timestamp.

3
AI Parsing (OpenAI)

The raw message + student context is sent to OpenAI GPT-4. The AI extracts: study_topic, duration_minutes, productivity_score (1–10), emotional_signal, break_type, test_score. Returns structured JSON.

4
Data Storage

Parsed data is written to IncomingMessages, StudyLogs, and FocusSessions tables. Running daily totals are updated in DailySchedules.

5
Score Computation

Score Calculator evaluates updated daily logs and computes the DailyScore. If study hours ≥ threshold or significant progress logged, streak eligibility flag is updated.

6
Response Generation

n8n triggers a follow-up Telegram message to acknowledge the update, provide encouragement or correction, and optionally ask the next check-in question.

04

Database Schema

Complete relational schema for DisciplineOS. All tables follow a PostgreSQL-first design with Google Sheets as the MVP fallback.

Users Table

FieldTypeKeyDescription
user_idUUIDPKUnique identifier, auto-generated on registration
full_nameVARCHAR(255)Student's full name
telegram_usernameVARCHAR(100)IDXTelegram @username for bot delivery
telegram_chat_idBIGINTIDXTelegram chat ID for sending messages programmatically
phoneVARCHAR(20)Phone number (optional)
exam_typeENUMUPSC / NEET / JEE / PSC / CODING / OTHER
daily_target_hoursDECIMAL(4,2)Student's self-declared daily study goal
wake_timeTIMEUsed to calculate morning accountability trigger
sleep_timeTIMEDefines end of active automation window
timezoneVARCHAR(50)IANA timezone string e.g. Asia/Kolkata
weak_subjectsTEXT[]Array of subject names
consistency_levelSMALLINTSelf-reported 1–5 at registration
current_streakINTEGERLive streak count (days)
longest_streakINTEGERHistorical best streak
statusENUMACTIVE / INACTIVE / AT_RISK / BANNED
created_atTIMESTAMPTZRegistration timestamp

DailySchedules Table

FieldTypeKeyDescription
schedule_idUUIDPKAuto-generated
user_idUUIDFK → UsersForeign key to student
dateDATEIDXSpecific date of this schedule
planned_hoursDECIMAL(4,2)Target hours declared in morning check-in
actual_hoursDECIMAL(4,2)Running total computed from StudyLogs
focus_subjectVARCHAR(100)Primary subject for the day
tasks_plannedINTEGERNumber of tasks declared
tasks_completedINTEGERCompleted tasks count (updated live)
completion_pctDECIMAL(5,2)tasks_completed / tasks_planned × 100
streak_qualifiedBOOLEANTrue if daily minimums are met
daily_scoreSMALLINTComputed 0–100 score
energy_levelSMALLINTMorning-declared 1–5

StudyLogs Table

FieldTypeKeyDescription
log_idUUIDPK
user_idUUIDFK → Users
schedule_idUUIDFK → DailySchedulesLinks to the day's schedule
subjectVARCHAR(100)AI-extracted subject name
topicTEXTSpecific topic studied
duration_minutesINTEGERDuration in minutes (AI-extracted)
productivity_scoreSMALLINTAI-assessed 1–10
raw_messageTEXTOriginal student message
logged_atTIMESTAMPTZWhen the log was recorded

StreakHistory Table

FieldTypeKeyDescription
streak_idUUIDPK
user_idUUIDFK → Users
streak_startDATEFirst day of streak
streak_endDATELast day (null if ongoing)
streak_lengthINTEGERNumber of qualifying days
end_reasonENUMDAILY_MISS / WEEKLY_PENALTY / MANUAL_RESET

Additional Tables

FocusSessions
  • session_id (PK), user_id (FK), schedule_id (FK)
  • start_time, end_time, duration_minutes
  • session_type: DEEP_WORK / BREAK / TEST / REVISION
  • focus_score (AI computed 1–10)
  • notes (AI-extracted summary)
WeeklyPerformance
  • week_id (PK), user_id (FK), week_start_date
  • total_hours, avg_daily_hours
  • days_met_minimum, completion_avg_pct
  • week_score (0–100), promoted (BOOLEAN)
  • ai_feedback (TEXT), leaderboard_rank
NightReviews
  • review_id (PK), user_id (FK), date
  • total_hours_actual, mood_score (1–5)
  • skipped_topics (TEXT[]), tomorrow_plan
  • ai_summary, ai_coaching_note
  • review_submitted_at (TIMESTAMPTZ)
Leaderboard
  • leaderboard_id (PK), user_id (FK)
  • week_rank, all_time_rank
  • discipline_score, focus_score, recovery_score
  • streak_badge, consistency_tier
  • updated_at (TIMESTAMPTZ)
05

Automation Flow Design

The automation engine is built on n8n. Each student has an independently scheduled set of workflows that fire based on their personal profile. No two students share the same cron schedule.

Personalized Trigger Calculation

// Pseudo-code: Calculate personalized trigger times function generateStudentSchedule(user) { const wake = parseTime(user.wake_time); // e.g. "06:00" return { morningPing: addMinutes(wake, 15), checkIn1: addMinutes(wake, 120), // +2h checkIn2: addMinutes(wake, 240), // +4h checkIn3: addMinutes(wake, 360), // +6h eveningNudge: subtractMinutes(user.sleep_time, 120), nightReview: subtractMinutes(user.sleep_time, 30), }; } // Example outputs: // Student A (wake 06:00): 06:15, 08:00, 10:00, 12:00, 20:00, 21:30 // Student B (wake 08:00): 08:15, 10:00, 12:00, 14:00, 20:00, 21:30

n8n Workflow Architecture

W1
Registration Intake Workflow

Triggered by: Google Form submission or HTTP POST from onboarding form. Actions: Parse form data → Create Users record → Generate DailySchedule template → Register personalized cron jobs in n8n → Send Welcome Telegram message with orientation instructions.

W2
Morning Accountability Workflow

Triggered by: Per-student cron (wake_time + 15 min). Actions: Fetch student profile → Generate personalized Good Morning message → Send via Telegram Bot API → Create empty DailySchedule record for today → Set session state = MORNING_PENDING.

W3
Inbound Message Processor

Triggered by: Telegram webhook on any message. Actions: Identify user by chat_id → Fetch current session_state → Route to appropriate sub-workflow (morning_response / check_in_response / night_review_response) → Call OpenAI parser → Store structured log → Compute running score → Send acknowledgment.

W4
Mid-Day Check-In Workflows (×3)

Triggered by: Three per-student crons (wake + 2h, 4h, 6h). Actions: Fetch today's DailySchedule → Check if student has already responded to last ping → If yes: send next question. If no: send gentle reminder + "Still studying?" message → Update PromptLogs.

W5
Night Review Workflow

Triggered by: Per-student cron (sleep_time - 30 min). Actions: Compile day summary from StudyLogs → Send review message asking final totals + mood + tomorrow plan → Set session_state = NIGHT_REVIEW → After response: compute DailyScore → Update StreakHistory → Check streak eligibility.

W6
Weekly Evaluation Workflow

Triggered by: Weekly cron every Sunday at 11:59 PM (per student timezone). Actions: Aggregate 7 days of DailySchedules → Compute WeeklyPerformance → Run streak penalty logic → Determine promotion/retention → Update Leaderboard → Send AI-generated weekly report via Telegram.

W7
Inactivity Watch Workflow

Triggered by: Global cron every 4 hours. Actions: Query all ACTIVE users → Check last_activity_at → If > 26 hours and no morning response: send re-engagement message → If > 48 hours: mark status = AT_RISK → If > 72 hours: notify admin and pause automation.

06

AI Processing Pipeline

OpenAI GPT-4 acts as the understanding layer between raw student messages and structured database records.

AI Parser — System Prompt Architecture

// OpenAI API call structure from n8n { "model": "gpt-4o", "system": "You are a study log parser for a competitive exam student. Extract structured data from the student's message. Return ONLY valid JSON. Fields: - subject: string or null - topic: string or null - duration_minutes: integer or null - activity_type: STUDY | BREAK | TEST | REVISION | PLANNING - productivity_score: 1-10 - emotional_signal: MOTIVATED | NEUTRAL | TIRED | STRESSED | BURNED_OUT - is_complete: boolean (did they finish what they started?) Student profile: {exam_type}, weak subjects: {weak_subjects}", "user": "Completed Polity Chapter 3 in 90 minutes. Feeling good!" } // Expected output: { "subject": "Polity", "topic": "Chapter 3", "duration_minutes": 90, "activity_type": "STUDY", "productivity_score": 8, "emotional_signal": "MOTIVATED", "is_complete": true }

AI Coaching Prompt Architecture

// Triggered when AI coaching analysis is needed { "system": "You are a study coach for {exam_type} aspirant {name}. Based on their last 7 days of study logs provided, detect: 1. Consistency trend (improving/declining/flat) 2. Subject imbalance (neglected vs over-studied) 3. Burnout risk (scale 1-5) 4. Distraction pattern (if any) Generate: one motivational nudge (2 sentences max), one actionable recommendation, and flag any urgent concern. Tone: direct, warm, like a strict but caring mentor.", "user": "7-day logs: {json_logs}" }

AI Processing Events

📥 Message Parsing

Every inbound Telegram message is parsed to extract structured study data. Fires on every student reply.

📊 Daily Score Reasoning

AI contextualizes the daily score: explains why the student scored X and what they should adjust tomorrow.

🔍 Weekly Pattern Analysis

Fires weekly. Detects multi-day trends: consistent weak spots, session length patterns, subject neglect.

🚨 Burnout Intervention

Fires when energy score ≤ 2 for 2+ consecutive days. Generates a special recovery message with revised lighter targets.

07

Streak Engine Logic

The streak system is the psychological core of DisciplineOS. It creates loss aversion, rewards consistency, and enforces minimum standards through a strict rule engine.

Daily Streak Qualification Rules

A student qualifies for the daily streak only if BOTH conditions are met: (1) actual study hours ≥ 5.0 hours, AND (2) task completion percentage ≥ 60%. If either condition fails, the day is marked as a streak miss.

Streak Calculation Algorithm

function evaluateDailyStreak(userId, date) { const day = getDailySchedule(userId, date); const hoursQualified = day.actual_hours >= 5.0; const completionQualified = day.completion_pct >= 60; const qualified = hoursQualified && completionQualified; updateDailySchedule(date, { streak_qualified: qualified }); if (qualified) { incrementStreak(userId); logStreakEvent(userId, 'QUALIFIED'); } else { breakStreak(userId, date); // saves current streak to StreakHistory resetCurrentStreak(userId); sendStreakLostMessage(userId, { hoursQualified, completionQualified }); } } function evaluateWeeklyPenalty(userId, weekStart) { const days = getWeekDays(userId, weekStart); const failedDays = days.filter(d => !d.streak_qualified).length; if (failedDays >= 3) { hardResetStreak(userId); // ALL accumulated streaks lost sendWeeklyResetPenaltyMessage(userId, failedDays); } }

Streak Status States

🔥
Active Streak
⚠️
At Risk
💔
Streak Lost
🔄
Recovery

Streak Visualization (30-day sample)

■ Qualified ■ Miss ■ At Risk

Recovery System

🔄 A student in recovery mode (status = AT_RISK) receives a lighter target for 2 days: only 3 hours required + 40% completion. If they qualify both days, they re-enter normal mode. This prevents complete abandonment after a bad week.

Weekly Progression Logic

Promoted → Next Week
  • Met daily minimum on ≥ 4 of 7 days
  • Average completion ≥ 60% for the week
  • No weekly penalty triggered
  • Receives "Level Up" badge and next week tasks
Retained → Repeat Week
  • Failed daily minimum on ≥ 4 days
  • Average completion < 60%
  • Repeats same week's syllabus/tasks
  • AI generates revised lighter schedule
08

Daily Accountability Logic

The daily cycle is a structured sequence of Telegram interactions designed to keep students accountable from morning to night.

Daily Score Formula

daily_score = ( (actual_hours / planned_hours) × 40 // 40% weight: hours + (completion_pct / 100) × 30 // 30% weight: tasks + (avg_productivity_score / 10) × 20 // 20% weight: focus quality + (night_review_submitted ? 10 : 0) // 10% weight: accountability ) clamped to [0, 100]

Daily Prompt Sequence

Morning
Good Morning Check-in

"Good morning [Name]! 🌅 Day [N] of your UPSC journey. What's your target for today? (Hours + focus subject + energy level 1-5)"

+2h
First Check-in

"[Name], first check-in! What have you covered so far? Any topics completed?"

+4h
Mid-Day Check-in

"Midday check! How's the focus? Any breaks taken? What's your current study count?"

+6h
Afternoon Check-in

"Afternoon update — are you on track for today's goal? Feeling any burnout?"

Evening
Evening Wind-Down Nudge

"2 hours left in your window. Final push — what's remaining on today's list?"

Night
Night Review

"Day complete! Final report: total hours? What did you nail? What did you skip? Mood? Tomorrow's plan? Your streak is [N] days 🔥"

Missed Check-in Escalation

1
First Reminder (15 min after prompt)

Gentle re-send: "Hey! Just checking — did you see my earlier message?"

2
Second Reminder (45 min after prompt)

Motivational pressure: "Your streak is at risk if you don't check in today. 5 minutes is all it takes."

3
Final Warning (90 min after prompt)

Loss framing: "No response yet. If your night review isn't submitted, today won't count toward your streak."

09

Weekly Evaluation Logic

Every Sunday night, the Weekly Evaluator runs per-student. It determines promotion, calculates week score, updates leaderboard, and generates AI feedback.

Week Score Formula

week_score = ( avg_daily_score × 0.5 // 50%: average of 7 daily scores + (days_met_minimum / 7) × 100 × 0.3 // 30%: consistency + (streak_maintained ? 20 : 0) // 20%: streak bonus )

Weekly Decision Matrix

Days Met MinimumAvg CompletionStreak StatusOutcome
5–7 days≥ 70%ActivePROMOTED + Bonus Badge
4 days≥ 60%ActivePROMOTED
4 days< 60%AnyRETAINED — Repeat Week
3 daysAnyAnyRETAINED + AT_RISK Flag
0–2 daysAnyAnyRETAINED + Full Streak Reset

Weekly AI Report Contents

Performance Summary
  • Total hours studied vs target
  • Best and worst performing subjects
  • Consistency score breakdown
  • Productivity trend (↑ ↓ →)
AI Coaching Insights
  • Subject neglect detection
  • Burnout risk assessment
  • Next week recommended adjustments
  • Motivational message with streak context
10

Leaderboard & Gamification

The gamification layer transforms daily discipline into a competitive, rewarding experience with ranks, badges, and meaningful scores.

Score Components

DS
Discipline Score
FS
Focus Score
CS
Consistency Score
RS
Recovery Score
discipline_score = (week_score × 0.4) + (streak_days × 0.3) + (focus_score_avg × 0.3) focus_score = avg(productivity_score) across all FocusSessions this week recovery_score = 100 - (streak_breaks_per_month × 15) // penalizes frequent resets

Streak Badges

🌱
Seedling

7-day streak. First milestone. "You've planted the seed of habit."

🔥
Ignition

21-day streak. Habit formation zone. "21 days of pure discipline."

Momentum

45-day streak. Unstoppable. "Nothing can stop your momentum now."

💎
Diamond

90-day streak. Elite level. "3 months of unwavering consistency."

🏆
Warrior

180-day streak. Rare. "Half a year. The true definition of discipline."

👑
Legend

365-day streak. One of a kind. "A year of daily discipline. You are unstoppable."

Burnout Detection Logic

function detectBurnout(userId) { const logs = getLast3DaysLogs(userId); const lowEnergy = logs.filter(d => d.energy_level <= 2).length >= 2; const decliningHours = logs[0].actual_hours > logs[1].actual_hours && logs[1].actual_hours > logs[2].actual_hours; const emotionalSignals = logs.filter(d => d.emotional_signal === 'BURNED_OUT' || d.emotional_signal === 'STRESSED' ).length >= 2; if (lowEnergy && (decliningHours || emotionalSignals)) { triggerBurnoutIntervention(userId); // send recovery message setLighterTargets(userId, days = 2); // reduce requirements } }
11

AI Coaching Layer

The AI coaching layer operates as a passive monitor that surfaces actionable insights when patterns emerge across days and weeks.

📉
Low Consistency Detection

Triggered after 3 consecutive below-minimum days. AI sends a pattern-awareness message: "You've missed your goal 3 days in a row. Here's a recovery plan."

😮‍💨
Burnout Detection

Monitors energy level + emotional signal across messages. When exhaustion patterns appear, AI reduces targets and recommends rest proactively.

🎯
Distraction Pattern Detection

Short sessions (<30 min), many break logs, low productivity scores for 2+ days → AI flags distraction and suggests focus techniques (Pomodoro, etc).

📚
Weak Subject Detection

Cross-references user-declared weak subjects against actual study logs. If a weak subject hasn't appeared in logs for 3+ days, AI nudges the student to address it.

🗺️
Adaptive Plan Generation

After a hard week, AI generates a revised week plan that redistributes topics based on what was missed, with realistic lower daily targets to rebuild momentum.

💬
Motivational Nudges

AI generates context-aware messages that reference the student's own streak, exam date, and progress — never generic. "You're 27 days from your UPSC Prelims target date."

12

Edge Cases

Edge CaseDetectionSystem Response
Student doesn't respond to morning pingNo incoming message within 2h of morning triggerSend 3-level escalation reminders. Mark day as AT_RISK after 3rd miss.
Student reports false hoursProductivity score inconsistent with claimed duration (AI flags anomalies)AI scores low for productivity, reducing overall daily score. Flag for admin review after 3 anomalies.
Timezone changeStudent updates timezone in profileRecalculate all cron triggers for that student. Do not restart streak.
Exam date passedexam_date field in Users crosses current datePause automation. Send congratulations + results check-in message. Offer new exam enrollment.
Student explicitly says they're sickAI detects health keywords (sick, fever, hospital, unwell)Grant a 1-day "health break" — day excluded from streak calculation. Max 2 per month.
Duplicate messages sentn8n workflow fires twice due to cron overlapIdempotency check on PromptLogs: if a prompt of the same type was sent within 30 min, skip second send.
OpenAI API failureAPI returns 500 or timeoutRetry 3×. If all fail: store raw message as-is in IncomingMessages with ai_processed = false. Reprocess in background queue within 1 hour.
Student sends unrelated messageAI classification: no study data extractedAI responds naturally ("Got it! Let me know when you start your next session.") — no log created.
Long inactivity (3+ days)last_activity_at > 72 hoursMark INACTIVE. Stop all pings. Send re-engagement message. Admin notification. Manual review required to reactivate.
13

Failure Recovery System

All critical system components have failure recovery paths designed to ensure no data is lost and no student is left in a broken state.

n8n Workflow Failures
  • All workflows wrapped in try/catch nodes
  • Failed executions logged to Errors table with payload
  • Dead Letter Queue for failed messages
  • Admin Telegram alert on 3+ failures in 1 hour
  • Automatic retry with exponential backoff (1s, 5s, 30s)
OpenAI Failures
  • Circuit breaker: disable AI if 5+ failures in 10 min
  • Fallback: store raw message, flag ai_processed = false
  • Batch reprocess job runs every 60 minutes
  • Graceful degradation: daily scores computed without AI if needed
Telegram API Failures
  • Retry up to 5× with 10-second intervals
  • Rate limit detection: queue messages with delay
  • Bot blocked: mark user as TELEGRAM_BLOCKED, pause automation
  • Log all send attempts in PromptLogs (sent/failed/queued)
Database Failures
  • PostgreSQL: daily automated backups to S3
  • Read replicas for leaderboard/analytics queries
  • Connection pool monitoring with auto-restart
  • Google Sheets: interim fallback for MVP phase
🔴 Critical: The Errors table must be monitored via a dashboard alert. Any unprocessed error older than 2 hours should trigger a PagerDuty/admin Telegram notification to prevent silent data loss.
14

Scalability Plan

Scaling Tiers

TierStudentsStackKey Changes
MVP1 – 50n8n + Google Sheets + OpenAIAll-in-one, single server, sheets as DB
Growth50 – 500n8n + PostgreSQL + RedisMigrate to PostgreSQL, add Redis queues, per-student cron optimization
Scale500 – 5000+ React Dashboard + Docker ComposeMulti-container deployment, read replicas, message queue for Telegram
Enterprise5000+Kubernetes + CDN + AnalyticsK8s autoscaling, tenant isolation, analytics data warehouse, admin portal

Performance Bottlenecks & Solutions

Cron Management (500+ students)
  • Replace individual crons with Redis-backed priority queue
  • n8n polls queue; workers pick up due tasks
  • Group students by timezone bucket (±30 min) for efficiency
  • Target: <2s message delivery latency per student
OpenAI Cost Optimization
  • Cache common phrase patterns (avoid redundant API calls)
  • Batch low-priority parsing jobs during off-peak hours
  • Fine-tune a smaller model on study log data over time
  • Target: 60% reduction in API spend by 1000 users
15

Security Considerations

🔐
Data Isolation

All student data is accessed via user_id. No cross-student data exposure. Row-level security enforced in PostgreSQL using RLS policies.

🔑
Secret Management

Telegram Bot Token, OpenAI API Key, and DB credentials stored in Docker secrets or HashiCorp Vault. Never in environment variables in production.

🛡️
Telegram Webhook Security

Telegram webhook verified via X-Telegram-Bot-Api-Secret-Token header. Webhook endpoint only accepts HTTPS requests from Telegram IP ranges.

🗂️
Data Retention

Raw messages purged after 90 days. Aggregated scores and streaks retained indefinitely. Students can request full data export (GDPR-ready structure).

🔒
n8n Access Control

n8n dashboard behind VPN or IP whitelist. All admin operations require 2FA. n8n credentials encrypted at rest using AES-256.

📋
Audit Logging

All admin actions (streak overrides, manual resets, status changes) logged to an immutable AuditLogs table with actor_id, action, and timestamp.

16

Production Deployment Architecture

MVP Deployment (Docker Compose)

# docker-compose.yml services: n8n: image: n8nio/n8n:latest ports: ["5678:5678"] environment: - N8N_ENCRYPTION_KEY="${N8N_SECRET}" - DB_TYPE=postgresdb volumes: [n8n_data:/home/node/.n8n] depends_on: [postgres, redis] postgres: image: postgres:16-alpine environment: - POSTGRES_DB=disciplineos - POSTGRES_PASSWORD="${DB_PASS}" volumes: [pg_data:/var/lib/postgresql/data] redis: image: redis:7-alpine command: redis-server --requirepass "${REDIS_PASS}" nginx: image: nginx:alpine volumes: [./nginx.conf:/etc/nginx/nginx.conf] ports: ["443:443"] depends_on: [n8n]

Infrastructure Stack

Current (MVP)
  • VPS: DigitalOcean / Hetzner (4GB RAM, 2 vCPU)
  • Docker Compose orchestration
  • n8n: automation engine + webhook receiver
  • PostgreSQL: primary data store
  • Redis: queues and caching
  • Nginx: reverse proxy + SSL (Let's Encrypt)
Future (Scale)
  • Kubernetes (K3s or EKS)
  • React Dashboard (Vercel / CloudFront)
  • PostgreSQL with read replicas (RDS)
  • Redis cluster for multi-node queuing
  • Analytics: ClickHouse + Metabase
  • CI/CD: GitHub Actions → Docker Hub → K8s
17

Future SaaS Expansion Plan

DisciplineOS is built from day one with multi-tenancy in mind. The path to a full SaaS product is incremental and implementation-ready.

SaaS Roadmap

Phase 1
Private Beta (0–50 students)

Manual onboarding via form. Single n8n instance. Google Sheets as database. Validate core accountability loop and streak psychology. Collect feedback aggressively.

Phase 2
Paid Cohorts (50–200 students)

Migrate to PostgreSQL. Add payment via Razorpay. Create batch enrollment (cohort model — 20 students per cohort). Build basic admin dashboard for monitoring student health scores. Introduce weekly leaderboard.

Phase 3
Self-Serve SaaS (200–2000 students)

Student self-registration portal. Subscription billing (₹499/month). React dashboard for students (streak calendar, score charts, weak subject heatmap). Admin panel for mentor intervention. Exam-specific personas (UPSC mode vs NEET mode).

Phase 4
Platform + Marketplace (2000+ students)

White-label offering for coaching institutes. Multi-mentor support (each mentor manages a group). AI study resource recommendations. Integration with YouTube playlists, PDFs, and test series. Mobile app (React Native). Analytics API for coaching institutes.

Monetization Model

💰
Student Subscription

₹299–₹799/month per student. Tiered based on features (basic accountability vs full AI coaching vs mentor support).

🏫
Institute License

₹50–₹150/student/month for coaching institutes using DisciplineOS as a white-label platform for their enrolled students.

🧑‍🏫
Mentor Marketplace

Platform commission (15–20%) on sessions booked between students and independent mentors discovered through DisciplineOS.

🚀 The strongest moat of DisciplineOS is its behavioral data. After 6 months of operation, the platform will hold the most granular competitive exam study behavior dataset in India — enabling highly accurate AI coaching, personalized performance prediction, and eventually, a study-outcome model that no competitor can replicate without years of data collection.

DisciplineOS

System Documentation v1.0 · Production-Grade · Built for Scale

n8n Automation Telegram Bot API OpenAI GPT-4 PostgreSQL Redis Docker