Online Learning Platform (Byju’s / Khan Academy style)
High-Level Design: Online Learning Platform (Byju’s / Khan Academy style)
End-to-end HLD + LLD + Data Model + API interactions + S3 storage layout
1. Overview
Design an online learning platform that supports courses, video lessons, interactive quizzes, progress tracking, search & recommendations, offline downloads, payments (premium content), teacher/admin content management, analytics, and real-time notifications. The system should be multi-platform (web, iOS, Android), highly available, horizontally scalable, and secure.
Primary actors: Student (learner), Instructor/Content Creator, Admin, Payment Provider.
2. Goals & Non-goals
Goals
•Smooth video-first learning experience with adaptive streaming
•Low-latency search & recommendations
•Accurate progress tracking and analytics
•Scalable uploads and transcoding pipeline
•Secure DRM / offline usage model for paid content
Non-goals
•Live classroom features (large-scale live classes) — optional
•Full-fledged LMS features for enterprises (beyond scope)
3. Requirements
Functional
•User signup/login (email, OTP, OAuth)
•Browse courses, lessons, topics
•Play video lessons (adaptive streaming), captions, transcripts
•Quizzes, assessments, and instant grading
•Course progress, bookmarks, notes
•Search by topics, course, instructor
•Recommendations (personalized & trending)
•Upload content by instructors; admin moderation
•Payments for premium subscriptions & purchases
•Offline download for paid users
•Basic analytics dashboards for admins and instructors
Non-functional
•Availability: 99.9% for core operations
•Scalability: handle millions of users; 100k concurrent viewers
•Latency: <200ms API p99; video startup <2s
•Consistency: event-driven eventual consistency for analytics; strong consistency for payments & progress
•Security: HTTPS, encryption-at-rest, DRM for paid content
4. High-level Architecture
Components:
•Client (Web SPA / Mobile apps)
•API Gateway & Load Balancer
•Authentication & Authorization service
•Backend Microservices (or modular monolith) — User, Course, Content, Video, Quiz, Recommendation, Search, Payment, Notification, Analytics
•Datastores: Relational DB (Postgres/RDS) for OLTP, NoSQL (DynamoDB/Cassandra) for sessions & denormalized reads, Redis for caching, ElasticSearch for search
•Object Storage: S3 (video, thumbnails, transcripts) + CDN (CloudFront/Cloudflare)
•Video Processing: Transcoding workers (Fargate / ECS / Kubernetes Jobs) + HLS/DASH packaging
•Message Queues: Kafka / SQS for events, transcoding jobs, analytics piping
•Batch Processing: Spark / EMR for analytics & recommender training
•Monitoring & Logging: Prometheus, Grafana, ELK/Opensearch
(Clients) -> CDN -> API Gateway -> Services -> Datastore / S3 / Queue
5. Data Flow Highlights
1.Instructor uploads raw video to S3 (private).
2.Upload event published to queue → Transcoding service picks job → produces HLS/DASH renditions + thumbnails + captions → stores outputs in S3 (public or signed URL-enabled) and invalidates CDN cache.
3.Video metadata saved to Course/Content DB. Search index updated.
4.Student requests video → API returns signed CDN URL / streaming URL with token → CDN serves adaptive stream.
5.Playback events (play, pause, position) are pushed as events into queue → Analytics service consumes, updates progress counters and triggers recommendation updates.
6. Component Design
Client
•Web SPA (React) + Mobile SDKs. Handles playback using HLS player and offline encrypted storage for downloads.
•Local DB (SQLite / realm) on mobile to store downloaded content metadata & progress syncing.
API Gateway
•Rate-limits, authentication validation, request routing to internal services, throttling, and caching for public content metadata.
Auth Service
•JWT-based access tokens (short-lived) + refresh tokens.
•OAuth integration (Google, Apple).
•Role-based access (student, instructor, admin).
Content Service
•Manages courses, modules, lessons, metadata, captions, transcripts, tags, prerequisites.
•Exposes CRUD APIs for instructors & admin.
Video Service (Storage & Streaming)
•Manages video metadata, S3 paths, signed URL generation and DRM tokens.
•Triggers transcoding pipelines via messages.
Transcoding Pipeline
•Workers (k8s jobs / serverless) using FFmpeg producing multiple bitrates, HLS/DASH segments, thumbnails, VTT captions.
•Generates manifest files (.m3u8) and stores under S3 prefix.
•Stores renditions metadata (bitrate, resolution) in Video DB.
Quiz & Assessment Service
•Stores question banks, runs auto-grading logic, stores attempt history, calculates analytics (scores, mastery).
•Supports multiple question types: MCQ, fill-in, coding (optional).
Recommendation Service
•Hybrid model: collaborative filtering + content-based + business rules.
•Offline model training (Spark) and online features (user embeddings cached in Redis). API for top-N recommendations.
Search Service
•ElasticSearch index for course, lesson, instructor, and transcript search; supports fuzzy and semantic (if models used).
•Index updated asynchronously on content change.
Notification Service
•Push notifications (FCM/APNS) + email (SES) + in-app notifications.
Payment Service
•Integrates with Stripe / Razorpay. Handles subscriptions, coupons, refunds, webhooks, receipts.
•Stores transactions in relational DB with strong consistency.
Analytics Service
•Real-time metrics (Kafka → consumers → Redis or timeseries DB) and batch metrics for reporting.
•Dashboards for admin / instructor: course completion, retention.
DRM & Offline Downloads
•Use token-based signed URLs for streaming. For offline, encrypt video files with per-user keys, licensed via an entitlement server. Keys rotated and cached on device securely.
7. Storage Layout (S3)
S3 bucket structure (example):
s3://learning-platform-raw/ # raw uploads (private)
/instructor/<instructorId>/<uploadId>.mp4
s3://learning-platform-media/ # processed media
/videos/<videoId>/hls/master.m3u8
/videos/<videoId>/hls/720p/seg-00001.ts
/videos/<videoId>/thumbnails/0001.jpg
/videos/<videoId>/captions/en.vtt
s3://learning-platform-assets/
/course/<courseId>/cover.jpg
/transcripts/<videoId>.json
s3://learning-platform-exports/
/analytics/daily/2025-08-26/...
Bucket policies:
•Raw uploads private (signed URLs only).
•Media can be cached via CDN; signed URLs for paid content.
•Lifecycle rules: raw uploads -> move to Glacier after X days.
8. Data Model (DDL-like tables)
Primary choice: Relational DB (Postgres) for transactional data; ElasticSearch for search; NoSQL for wide/tall event stores.
Key tables (simplified):
users (id PK, email, name, role, password_hash, created_at, ...)
courses (id PK, title, short_desc, long_desc, language, level, instructor_id FK, price, is_published, created_at)
modules (id PK, course_id FK, title, position)
lessons (id PK, module_id FK, title, type [video/quiz/article], content_meta JSON, duration, position)
videos (id PK, lesson_id FK, s3_key, hls_master_path, duration, captions, size, transcoding_status)
quizzes (id PK, lesson_id FK, questions JSON)
user_progress (user_id FK, lesson_id FK, watched_seconds, completed boolean, last_watched_at)
user_course_enrollments (user_id FK, course_id FK, status, purchased_at, expires_at)
transactions (id PK, user_id FK, amount, currency, provider, provider_id, status)
events (id PK, user_id, event_type, payload JSON, created_at) — append-only for analytics
recommendations_cache (user_id PK, recs JSON, updated_at)
9. API Design (Representative Endpoints)
Note: Use REST or GraphQL; either is OK. Example REST endpoints:
Auth
•POST /api/v1/auth/signup — sign up
•POST /api/v1/auth/login — returns access & refresh token
Courses & Content
•GET /api/v1/courses — list / filter
•GET /api/v1/courses/{courseId}
•POST /api/v1/courses — instructor creates course
•POST /api/v1/courses/{courseId}/modules — add module
•POST /api/v1/lessons/{lessonId}/upload — returns signed S3 URL for upload
•GET /api/v1/lessons/{lessonId}/stream — returns signed CDN streaming URL
Playback & Progress
•POST /api/v1/progress — {userId, lessonId, position, eventType}
•GET /api/v1/progress/{userId}/courses/{courseId}
Quiz
•POST /api/v1/lessons/{lessonId}/submit-quiz — returns score & feedback
Search & Recs
•GET /api/v1/search?q=... — returns paginated results
•GET /api/v1/recommendations — returns personalized recs
Payments
•POST /api/v1/payments/subscribe — create subscription
•POST /api/v1/payments/webhook — payment provider webhook
Admin
•GET /api/v1/admin/analytics — aggregated metrics
Authentication via Authorization: Bearer <token>. Signed URLs for media access.
10. Low-level Design (LLD) Notes
Class/module decomposition (examples)
•VideoUploader — handles signed upload URLs, initial metadata write
•TranscodeManager — creates transcode jobs, retries, updates DB
•HLSManifestGenerator — builds master playlist from renditions
•PlaybackTokenService — mints short-lived tokens for CDN
•ProgressHandler — processes progress events (idempotent)
•RecommendationEngine — fetches cached embeddings and ranks items
Sequence — Playback flow
1.User clicks lesson → client calls GET /lessons/{id}/stream with auth
2.Server verifies entitlement (enrolled/paid) and issues signed CDN URL (or DRM license URL)
3.Client plays via HLS. Player periodically posts progress events to POST /progress.
4.ProgressHandler writes to Redis (fast) and enqueues event for analytics. Periodic job persists to Postgres.
Sequence — Upload & Transcode
1.Instructor requests upload URL → POST /lessons/{id}/upload → server returns pre-signed S3 URL + uploadId
2.Instructor uploads raw file directly to S3.
3.S3 sends event to queue (SNS/SQS/Kafka) including object key.
4.Transcoding workers pick job, update videos.transcoding_status to processing.
5.On success, workers write HLS artifacts to S3, update DB row to ready and push index update to ES.
11. Caching & Performance
•CDN for all media & static assets.
•Redis for session, rate-limiting, and caching frequently-read responses (course lists, recommendations).
•Use read-replicas for Postgres to offload reads.
•Use pagination and cursor-based APIs for large result sets.
12. Scalability & Availability
•Microservices behind autoscaling