Building NewTube: Full-Stack Video Platform with Mux & tRPC
Architectural breakdown of NewTube: zero-server media ingestion with Mux, webhook asset migration to Uploadthing, Upstash QStash AI workflows, and Drizzle ORM on Neon PostgreSQL.
Media Ingestion
Direct-to-Mux
Background Jobs
Upstash QStash
Database
Neon Serverless PG
Type Safety
100% tRPC + Zod
1. The Serverless Compute Dilemma: Decoupling Media Bytes from API Endpoints
Streaming multi-gigabyte video uploads through serverless Node.js API routes quickly leads to disaster: memory exhaustion, strict request payload caps, cold-start stalls, and exorbitant bandwidth egress costs.
For NewTube, our application runtime never buffers raw video bytes. Instead, the client invokes a protected tRPC mutation (videos.create) that asks Mux for a direct upload session. The serverless route merely initializes a pending video record in Neon PostgreSQL with a waiting status, returning the direct Mux upload URL so the client streams video chunks straight to Mux's global edge.
Decoupling video transport from serverless compute enables unlimited file sizes with zero server CPU overhead.
2. Webhook Orchestration & Dual-CDN Asset Archival
Once Mux finishes transcoding adaptive HLS streams (from 360p up to 1080p60) and generating automated English subtitles, it fires asynchronous webhooks back to Next.js. Every incoming payload is cryptographically validated using HMAC SHA-256 signatures via mux.webhooks.verifySignature() before any database mutation occurs.
Rather than leaving thumbnail and animated preview assets on ephemeral endpoints, our webhook handler intercepts video.asset.ready, downloads the generated assets, and immediately archives them to Uploadthing CDN via UTApi.uploadFilesFromUrl(). This dual-CDN strategy guarantees permanent, lightning-fast thumbnail delivery independent of Mux lifecycle states.
๐ Key Engineering Takeaways:
- โHMAC signature verification prevents spoofed webhook replay attacks.
- โAutomated Uploadthing migration protects against missing or expired thumbnails.
- โMux subtitle track webhooks (video.asset.track.ready) supply raw transcripts for AI pipelines.
3. Distributed AI Pipelines via Upstash QStash Workflows
A modern creator studio requires automated intelligence: SEO titles, detailed descriptions with timestamps, and custom thumbnails. Traditional queue workers (like BullMQ + Redis containers) require heavy persistent infrastructure incompatible with pure serverless platforms.
NewTube implements durable execution using @upstash/workflow/nextjs. When a creator triggers AI generation, QStash coordinates a multi-step background workflow that fetches the auto-generated transcript directly from Mux text tracks (stream.mux.com/.../text/*.txt), streams it to OpenRouter (deepseek/deepseek-chat) for SEO title synthesis, and invokes Hugging Face FLUX.1-schnell for 16:9 thumbnail rendering.
QStash Workflows provide durable execution with step-level retries and zero container management.
4. Relational Integrity: Composite Primary Keys & CTEs in Drizzle ORM
Instead of Prisma's Rust query engine which adds cold-start latency to serverless lambdas, Drizzle ORM compiles directly to clean SQL executed over Neon's HTTP connection pool.
To guarantee strict uniqueness without racing conditions, junction tables like video_reactions, subscriptions, and playlist_videos enforce composite primary keys at the database engine level. Complex feed queries leverage Common Table Expressions (db.$with) and sub-queries (db.$count) to fetch videos, creator profiles, view counts, and viewer like status in a single round-trip.
5. Production Hardening: Rate Limiting & Clerk User Synchronization
Public-facing APIs require defense-in-depth. We deployed Upstash Redis sliding window rate limiters (10 requests per 10-second window) to thwart scraping bots and reaction spam.
Authentication is handled by Clerk, with user lifecycle events (user.created, user.updated, user.deleted) synchronized into Neon PostgreSQL via verified webhooks. Combined with React Compiler (babel-plugin-react-compiler) automatically memoizing player and feed components, NewTube delivers buttery-smooth 60 FPS browsing with zero runtime type surprises.
๐ Key Engineering Takeaways:
- โSliding window rate limiters protect mutation procedures from API abuse.
- โClerk webhook synchronizations preserve foreign key references and cascade deletions.
- โDrizzle ORM + Neon HTTP driver eliminates serverless connection pool exhaustion.
โ Kuldeep Rajput โ๏ธ
Software Developer ยท building ambitious full-stack web apps