Hotstar clone: live cricket streaming with live score
Stream a live match from a phone or laptop, show a ball-by-ball live scorecard that never spoils the video, a live viewer count and a moderated live chat.
Educational project inspired by JioHotstar. Skills101 is not affiliated with JioHotstar. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆How live streaming works: RTMP in, HLS out, and why there is a delay
- ◆Real-time updates with Socket.IO and Redis
- ◆Event-sourced scoring (store balls, compute the score)
- ◆Designing for thousands of viewers
What you’ll build
- ✓Live video with a “Go live” button that jumps to the latest point
- ✓Ball-by-ball scorecard updated by a scorer panel
- ✓Live viewer count
- ✓Live chat with slow mode and moderation
Before you start
What you need
- •JavaScript, Node.js and React basics.
- •Docker installed (for MediaMTX and Redis) and OBS Studio (free) on your laptop, or the free Larix Broadcaster app on your phone.
- •Something you are allowed to stream: your college or society match, your own screen or camera. Never restream TV or IPL broadcasts; they are copyrighted.
How it fits together
- 1Camera/phone → OBS or Larix sends RTMP → MediaMTX media server → HLS segments → viewers' browsers (hls.js).
- 2Scorer panel → Node.js API stores each ball as an event → Socket.IO pushes the new score to everyone in the match room.
- 3Redis keeps viewer counts and the last 50 chat messages, and lets several Node servers share Socket.IO rooms.
- 4Because video arrives 5–10 seconds late, each score update is delayed on the client by the player's measured latency.
Project structure
matchday-live/
├─ docker-compose.yml # mediamtx + redis
├─ server/
│ ├─ index.ts # Express + Socket.IO
│ ├─ score.ts # balls → score
│ ├─ chat.ts # rate limit + moderation
│ └─ viewers.ts
└─ web/ (React + Vite)
├─ src/LivePlayer.tsx
├─ src/Scorecard.tsx
├─ src/Chat.tsx
└─ src/ScorerPanel.tsx # admin onlyStep-by-step guide
Step 1
Understand live streaming and plan v1
Goal: You can explain RTMP, HLS and latency, and you have a v1 plan with your own app name.
Video-on-demand files are complete before anyone watches. Live is different: the camera produces video continuously. An encoder (OBS) pushes it to a media server over RTMP. The server cuts it into short HLS segments and keeps updating a playlist that only lists the last few segments (a “sliding window”). Viewers keep re-downloading the playlist to find new segments.
That pipeline causes delay: encoding, segment length and player buffering add up to roughly 5–30 seconds. Low-latency HLS reduces it to a few seconds by using smaller parts. Your scorecard, which arrives instantly over WebSocket, must account for this delay or it will spoil wickets before viewers see them (step 8).
v1: one live match page with video, scorecard, viewer count and chat, plus a scorer panel. Name it something like “MatchDay Live”; do not use Hotstar's name or logo.
✅ Check it works
You can draw the pipeline (camera → OBS → RTMP → MediaMTX → HLS → hls.js) from memory.
Step 2
Run a media server and go live from OBS
Goal: A live stream from your laptop or phone that plays in the browser.
MediaMTX is a free, single-binary media server that accepts RTMP and serves HLS with no configuration. Start it and Redis with Docker Compose.
In OBS: Settings → Stream → Service “Custom”, Server
rtmp://localhost:1935, Stream keylive. In Settings → Output set the keyframe interval to 2 seconds. On a phone, Larix Broadcaster can publish tortmp://<your-laptop-ip>:1935/liveon the same Wi-Fi.Open
http://localhost:8888/livein a browser; MediaMTX has a built-in test page. The playlist your app will use ishttp://localhost:8888/live/index.m3u8.docker-compose.ymlservices: mediamtx: image: bluenviron/mediamtx:latest ports: - "1935:1935" # RTMP in - "8888:8888" # HLS out redis: image: redis:7 ports: - "6379:6379"✅ Check it works
Wave at the camera; you see it in the browser a few seconds later.
⚠️ Common mistakes
- A long OBS keyframe interval (the default “auto” can be 8+ s) makes segments long and latency high.
- Windows Firewall can block port 1935 for the phone; allow it on private networks.
Step 3
Build the live player with a “Go live” button
Goal: A React player tuned for live, which shows how far behind live you are.
hls.js has live-specific settings.
lowLatencyMode: trueuses low-latency HLS parts when the server offers them.liveSyncDurationCount: 3keeps the player about three segments behind the newest one, a balance between delay and buffering.If a viewer pauses or the network stalls, they fall behind. Show a red “LIVE” badge when close to the live edge, and a “Go live” button otherwise that seeks to
hls.liveSyncPosition.hls.latencytells you how many seconds behind real time the viewer is. Expose it (via a callback) because the scorecard needs it in step 8.web/src/LivePlayer.tsximport Hls from 'hls.js' import { useEffect, useRef, useState } from 'react' export function LivePlayer({ src, onLatency }: { src: string; onLatency: (s: number) => void }) { const video = useRef<HTMLVideoElement>(null) const hlsRef = useRef<Hls | null>(null) const [behind, setBehind] = useState(0) useEffect(() => { const hls = new Hls({ lowLatencyMode: true, liveSyncDurationCount: 3 }) hlsRef.current = hls hls.loadSource(src) hls.attachMedia(video.current!) const timer = setInterval(() => { const lat = hls.latency || 0 onLatency(lat) setBehind(hls.liveSyncPosition ? hls.liveSyncPosition - video.current!.currentTime : 0) }, 1000) return () => { clearInterval(timer); hls.destroy() } }, [src, onLatency]) const goLive = () => { const pos = hlsRef.current?.liveSyncPosition if (pos) video.current!.currentTime = pos } return ( <div className="relative"> <video ref={video} autoPlay muted playsInline controls className="w-full bg-black" /> {behind > 8 ? <button onClick={goLive} className="absolute left-2 top-2 rounded bg-white px-2 text-sm">Go live</button> : <span className="absolute left-2 top-2 rounded bg-red-600 px-2 text-sm text-white">LIVE</span>} </div> ) }✅ Check it works
Pause for 30 seconds: the button shows “Go live”; clicking it jumps back to the live edge.
⚠️ Common mistakes
- Browsers block autoplay with sound; start muted and show an “unmute” button.
Step 4
Model the score as ball events
Goal: A scorer panel that records each ball, with undo, and a function that turns balls into the scoreboard.
Do not store “score = 145/3”. Store each ball as an event: runs off the bat, extras (wide, no-ball), wicket. The scoreboard is computed from the list. This is called event sourcing, and it makes “undo last ball” trivial: delete the last event and recompute.
Rules that matter: wides and no-balls add 1 extra run and do not count as legal deliveries, so they do not advance the over. Overs are written as completed overs plus legal balls in the current over (for example 12.4).
The scorer panel is a page with big buttons 0, 1, 2, 3, 4, 6, Wide, No-ball, Wicket and Undo, protected by an admin login. Each tap calls
POST /api/matches/:id/balls.server/score.tsexport type Ball = { runs: number; extra?: 'wd' | 'nb'; wicket?: boolean } export function score(balls: Ball[]) { let runs = 0, wickets = 0, legal = 0 for (const b of balls) { runs += b.runs + (b.extra ? 1 : 0) // wide / no-ball = 1 extra run if (b.wicket) wickets++ if (!b.extra) legal++ // only legal balls count in the over } const overs = Math.floor(legal / 6) + '.' + (legal % 6) const lastSix = balls.slice(-6).map((b) => (b.wicket ? 'W' : b.extra ? b.extra + (b.runs ? '+' + b.runs : '') : String(b.runs))) return { runs, wickets, overs, runRate: legal ? +(runs / (legal / 6)).toFixed(2) : 0, lastSix } }✅ Check it works
Write a unit test: balls [4, wd, 1, W, 6, 0, 0] give 12/1 in 1.0 overs (the wide is not a legal ball).
Step 5
Push the score live with Socket.IO
Goal: Every viewer's scorecard updates within a second of the scorer tapping a button.
Each match is a Socket.IO room (
match:<id>). When a viewer joins, send the full current score immediately; do not rely on them having received every earlier update. Sending full state (not just “+4”) means a viewer who reconnects after a network drop is instantly correct.When the scorer adds or undoes a ball, save it, recompute with
score(), and broadcast the new state with a server timestamp. The timestamp is used in step 8.Add the Redis adapter (
@socket.io/redis-adapter) now, even with one server. Then running two server processes later just works, because rooms are shared through Redis.server/index.ts (score part)io.on('connection', (socket) => { socket.on('join', async (matchId: string) => { socket.join('match:' + matchId) socket.emit('score', { ...score(await loadBalls(matchId)), at: Date.now() }) }) }) app.post('/api/matches/:id/balls', requireScorer, async (req, res) => { const ball = parseBall(req.body) // validate: runs 0-6, extra wd/nb, wicket boolean if (!ball) return res.status(400).json({ error: 'bad ball' }) await saveBall(req.params.id, ball) io.to('match:' + req.params.id).emit('score', { ...score(await loadBalls(req.params.id)), at: Date.now() }) res.json({ ok: true }) })✅ Check it works
Open the match in two browsers and the scorer panel in a third: taps appear in both viewers; refreshing a viewer shows the correct score immediately.
Step 6
Show a live viewer count
Goal: An accurate “12,340 watching” that does not overload the server.
Track viewers per match in Redis:
INCR viewers:<id>when a socket joins,DECRon disconnect. Redis is shared by all server processes, so the count is correct even with several servers.Do not broadcast the count on every join; during a big moment thousands join per second. Instead, broadcast it on a timer every 5 seconds per active match. Round large numbers (12.3K) like real apps.
Disconnects are not always clean (a phone loses signal). Socket.IO's ping timeout eventually fires
disconnect, so the count corrects itself within about a minute.server/viewers.tssocket.on('join', async (matchId: string) => { socket.data.matchId = matchId await redis.incr('viewers:' + matchId) }) socket.on('disconnect', async () => { if (socket.data.matchId) await redis.decr('viewers:' + socket.data.matchId) }) setInterval(async () => { for (const id of await activeMatchIds()) { const n = Number(await redis.get('viewers:' + id)) || 0 io.to('match:' + id).emit('viewers', Math.max(0, n)) } }, 5000)✅ Check it works
Open 5 tabs: the count shows 5 within 5 seconds; close 2 and it drops to 3.
Step 7
Add live chat with slow mode and moderation
Goal: A chat that stays usable and safe when many people type at once.
Store only the last 50 messages per match in a Redis list (
LPUSHthenLTRIM 0 49); new viewers get those 50 when they join. Older messages are not needed for a live chat.Slow mode: allow one message per user every 3 seconds using a Redis key with expiry (
SET chat:slow:<user> 1 EX 3 NX); if the key already exists, reject the message. Limit length to 200 characters and only allow logged-in users to send.React escapes text automatically, so never use
dangerouslySetInnerHTMLfor chat. Add a small blocked-words list and give moderators a delete button that broadcastschat:deletewith the message id.server/chat.tssocket.on('chat', async (text: string) => { const user = socket.data.user const matchId = socket.data.matchId if (!user || !matchId || typeof text !== 'string') return const clean = text.trim().slice(0, 200) if (!clean || hasBlockedWord(clean)) return const ok = await redis.set('chat:slow:' + user.id, '1', { EX: 3, NX: true }) if (!ok) return socket.emit('chat:error', 'Slow mode: wait 3 seconds') const msg = { id: crypto.randomUUID(), user: user.name, text: clean, at: Date.now() } await redis.lPush('chat:' + matchId, JSON.stringify(msg)) await redis.lTrim('chat:' + matchId, 0, 49) io.to('match:' + matchId).emit('chat', msg) })✅ Check it works
Sending 5 messages quickly only posts the first; a moderator deletion disappears from every open tab.
Step 8
Stop the scorecard from spoiling the video
Goal: Score updates appear at the same moment the viewer sees the ball in the video.
The score socket is near-instant but the video is 5–10 seconds behind. Without a fix, viewers see “WICKET” on the scorecard before the bowler has even run in. Real apps solve this by syncing data to the video timeline.
Each score message carries the server time
at. The player reportshls.latencyevery second (step 3). When a score arrives, waitlatencyseconds minus how long the message took to arrive, then show it.Keep it simple: a queue of pending updates and a timer. Add a toggle “Instant score (may spoil)” for people only following the score.
web/src/useSyncedScore.tsimport { useEffect, useRef, useState } from 'react' export function useSyncedScore(socket: Socket, latencyRef: { current: number }, instant: boolean) { const [score, setScore] = useState<Score | null>(null) const timers = useRef<number[]>([]) useEffect(() => { const onScore = (s: Score & { at: number }) => { const transit = Math.max(0, Date.now() - s.at) // ms already spent in transit const wait = instant ? 0 : Math.max(0, latencyRef.current * 1000 - transit) timers.current.push(window.setTimeout(() => setScore(s), wait)) } socket.on('score', onScore) return () => { socket.off('score', onScore); timers.current.forEach(clearTimeout) } }, [socket, latencyRef, instant]) return score }✅ Check it works
Hold a phone with a stopwatch in front of the camera; a scorer tap shows on the viewer's scorecard at the same time the tap appears in the video (within about 1 second).
⚠️ Common mistakes
- Comparing the server clock with a viewer's phone clock: they can differ by seconds. For better accuracy, send the server time on join and store the offset.
Step 9
Test with many viewers and plan for scale
Goal: Measured numbers for your demo and a clear explanation of how this scales to millions.
Load-test the socket server with Artillery's Socket.IO engine or a small Node script that opens 1,000 clients, joins a match and listens. Measure CPU, memory and the time from scorer tap to viewers receiving it.
Video scales differently from sockets: HLS is plain HTTP files, so a CDN can cache each segment once and serve it to millions. That is how large live events work. Sockets scale by running more Node processes behind a load balancer with the Redis adapter.
Enable recording in MediaMTX so the match can be replayed later, then convert the recording to VOD HLS with the FFmpeg command from the Netflix guide.
✅ Check it works
You have a small table in your README: number of clients, p95 update delay, CPU and memory.
Step 10
Deploy and demo a real match
Goal: A public link and a recording of a real (small) live match.
Run MediaMTX, Redis and the Node server on one small VPS with Docker Compose; put Nginx in front with HTTPS (browsers block mixed content). Serve the React build as static files.
Stream a real game: a college or society match from a phone with Larix. Have a friend score it on the scorer panel while others watch and chat.
In the README, add: the pipeline diagram, your latency numbers, the spoiler-sync explanation and “Educational project inspired by JioHotstar. Not affiliated.”
✅ Check it works
Friends on mobile data can watch, see a synced score and chat during a real match.
🚀 Make it stand out
- +Multiple camera angles as separate streams
- +Polls during the match (“Who wins?”)
- +Highlights: mark moments in the scorer panel and clip them with FFmpeg
- +Commentary audio track in Hindi