Telegram clone: channels, bots and big file sharing
Build what makes Telegram different: public broadcast channels with view counts, a bot platform where developers create bots with tokens and webhooks, and resumable uploads for large files.
Educational project inspired by Telegram. Skills101 is not affiliated with Telegram. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Per-chat sequence numbers for reliable syncing
- ◆Designing a developer API with tokens and webhooks
- ◆Resumable chunked uploads with checksums
- ◆Approximate counting with Redis HyperLogLog
What you’ll build
- ✓Public channels with @usernames, subscribers and post views
- ✓Bot platform: create bot, token, sendMessage API, webhooks
- ✓Resumable uploads of files up to 2 GB
- ✓Public channel preview pages and search
Before you start
What you need
- •Node.js, Express, React and SQL basics.
- •Do the WhatsApp guide first, or be comfortable with Socket.IO rooms.
- •PostgreSQL and Redis via Docker.
How it fits together
- 1Chats (private, group, channel) live in PostgreSQL; each message gets the next sequence number of its chat.
- 2Clients sync by asking “messages in chat X after seq N”; Socket.IO only signals that something new exists.
- 3Bots are users with a hashed token. Developers call your Bot API over HTTPS; your server POSTs updates to their webhook.
- 4Large files are uploaded in 5 MB chunks that can resume after a failure, then joined and checked with SHA-256.
Project structure
relay/
├─ server/
│ ├─ chats.ts # seq allocation, channels
│ ├─ views.ts # HyperLogLog views
│ ├─ botapi.ts # /bot/:token/:method
│ ├─ webhooks.ts # delivery + retries
│ └─ uploads.ts # chunked uploads
├─ web/ (React)
└─ examples/quiz-bot/ # a bot written against YOUR APIStep-by-step guide
Step 1
Plan the three big features
Goal: A v1 focused on channels, bots and large files, with your own name.
Normal chat is covered in the WhatsApp guide. Here, focus on three things: (1) channels: one-to-many broadcasts with thousands of subscribers; (2) a bot platform: other developers build bots on your app; (3) large file sharing that survives bad networks.
Name it (“Relay”). Public links look like
/c/<username>. Add “Educational project inspired by Telegram. Not affiliated.” to the README.Write the bot API surface now:
getMe,sendMessage,setWebhook,getUpdates. Keeping it small and well documented is better than copying everything.✅ Check it works
You have a one-page spec with the Bot API methods and their JSON.
Step 2
Chats with sequence numbers
Goal: Every message has a per-chat number, so clients always know exactly what they are missing.
Timestamps can tie and clocks can drift. A per-chat sequence (1, 2, 3…) is exact: if a client has message 1500 and the chat's latest is 1503, it fetches 1501–1503. Telegram uses a similar idea.
Allocate the number atomically:
UPDATE chats SET last_seq = last_seq + 1 WHERE id = $1 RETURNING last_seq, then insert the message with that seq, in one transaction. The row lock makes concurrent senders get different numbers. Add UNIQUE (chat_id, seq).The socket event becomes tiny:
{ chatId, seq }. Clients that are behind callGET /chats/:id/messages?after=<seq>.server/chats.tsexport async function postMessage(chatId: string, senderId: string, body: string) { const client = await pool.connect() try { await client.query('BEGIN') const { rows } = await client.query('UPDATE chats SET last_seq = last_seq + 1 WHERE id = $1 RETURNING last_seq', [chatId]) if (!rows.length) throw new Error('no such chat') const seq = rows[0].last_seq await client.query('INSERT INTO messages (chat_id, seq, sender_id, body) VALUES ($1, $2, $3, $4)', [chatId, seq, senderId, body]) await client.query('COMMIT') io.to('chat:' + chatId).emit('new', { chatId, seq }) return seq } catch (e) { await client.query('ROLLBACK') throw e } finally { client.release() } }✅ Check it works
20 concurrent posts to one chat produce seq 1–20 with no gaps or duplicates.
Step 3
Channels: broadcast, subscribers and roles
Goal: Admins post, subscribers read, and posting to 10,000 subscribers is as cheap as posting to 10.
A channel is a chat with type CHANNEL. Members have roles: OWNER, ADMIN (can post), SUBSCRIBER (read only). Check the role on the server before posting.
Do not copy a post into every subscriber's inbox (“fan-out on write”); for big channels that is thousands of writes per post. Store the post once; subscribers read the channel by seq. Online subscribers in the
chat:<id>room get the tinynewevent.The subscriber count is a counter column updated when people join or leave, not a
COUNT(*)on every page view.✅ Check it works
A subscriber trying to post gets 403; a post appears for all open subscriber tabs within a second.
Step 4
Count post views with HyperLogLog
Goal: Each post shows “👁 12.4K” unique views without storing a row per view.
Counting unique viewers exactly needs a set of every viewer per post, which grows huge. Redis HyperLogLog estimates unique counts using about 12 KB per key, no matter how many viewers, with about 0.8% error. That is ideal for view counters.
When a post scrolls into view (IntersectionObserver, at least 50% visible for 1 second), the client reports it; the server runs
PFADD views:<postId> <userId>. Reading isPFCOUNT.Batch reports: the client collects seen post ids and sends them every 5 seconds.
server/views.tsapp.post('/api/views', requireUser, async (req, res) => { const ids: string[] = Array.isArray(req.body.postIds) ? req.body.postIds.slice(0, 100).map(String) : [] const multi = redis.multi() for (const id of ids) multi.pfAdd('views:' + id, req.user.id) await multi.exec() res.json({ ok: true }) }) export async function viewCounts(postIds: string[]) { const counts = await Promise.all(postIds.map((id) => redis.pfCount('views:' + id))) return Object.fromEntries(postIds.map((id, i) => [id, counts[i]])) }✅ Check it works
Viewing the same post 10 times from one account counts 1; from 3 accounts counts 3.
Step 5
Public usernames and preview pages
Goal: `/c/<username>` shows a public channel to anyone, even without an account, with a proper link preview.
Usernames: 5–32 characters, a–z, 0–9 and underscores, starting with a letter, unique case-insensitively. Block reserved words (admin, api, bot, support).
The preview page is server-rendered: channel name, description, subscriber count and the latest 20 posts, with Open Graph tags so the link looks good when shared on WhatsApp or LinkedIn.
Only PUBLIC channels have this page; private channels join by invite link with a random token.
✅ Check it works
Pasting the link into a chat app shows the channel name and description in the preview.
Step 6
Bot platform part 1: tokens and the Bot API
Goal: A developer can create a bot, get a token once, and call `sendMessage` with it.
Creating a bot creates a user with
is_bot = trueand a token like<botId>:<random>. Show the token once; store only its SHA-256 hash. If it leaks, the owner regenerates it.API calls look like
POST /bot/<token>/sendMessagewith JSON{ chat_id, text }. A middleware finds the bot by id, hashes the given token and compares withtimingSafeEqual.A bot may only message chats it belongs to or users who started a chat with it. Add rate limits (for example 30 messages per second per bot) and consistent JSON errors:
{ ok: false, error_code: 403, description: "bot is not a member" }.server/botapi.tsimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto' export const sha256 = (s: string) => createHash('sha256').update(s).digest() export function newToken(botId: string) { const token = botId + ':' + randomBytes(24).toString('base64url') return { token, hash: sha256(token).toString('hex') } // save hash, show token once } app.post('/bot/:token/:method', express.json(), async (req, res) => { const [botId] = req.params.token.split(':') const bot = await db.bot.findUnique({ where: { id: botId } }) const given = sha256(req.params.token) if (!bot || !timingSafeEqual(given, Buffer.from(bot.tokenHash, 'hex'))) { return res.status(401).json({ ok: false, error_code: 401, description: 'Unauthorized' }) } const method = BOT_METHODS[req.params.method] if (!method) return res.status(404).json({ ok: false, error_code: 404, description: 'Not Found' }) try { res.json({ ok: true, result: await method(bot, req.body) }) } catch (e: any) { res.status(e.status ?? 400).json({ ok: false, error_code: e.status ?? 400, description: e.message }) } })✅ Check it works
curl -X POST .../bot/<token>/getMereturns the bot; a wrong token returns 401.Step 7
Bot platform part 2: webhooks with retries (safely)
Goal: When a user messages a bot, your server POSTs the update to the bot's webhook, retrying on failure.
An “update” is JSON describing what happened:
{ update_id, message: { chat, from, text } }. Store updates in a table with a status. A worker POSTs each one to the bot's webhook with a secret header (X-Relay-Bot-Secret) so the bot can verify the request came from you.If the webhook fails or times out (5 seconds), retry with exponential backoff (10 s, 30 s, 2 min, 10 min) and give up after a day. Bots without a webhook use
getUpdates(long polling) instead.Security: the server fetches a URL supplied by a user, which can be abused to reach internal services (SSRF). Allow only
https://, resolve the hostname and refuse private and loopback addresses.server/webhooks.tsimport { lookup } from 'node:dns/promises' import net from 'node:net' function isPrivate(ip: string) { if (net.isIPv6(ip)) return ip === '::1' || ip.startsWith('fc') || ip.startsWith('fd') || ip.startsWith('fe80') const [a, b] = ip.split('.').map(Number) return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) } export async function safeWebhookUrl(raw: string) { const url = new URL(raw) if (url.protocol !== 'https:') throw new Error('Webhook must use https') const addrs = await lookup(url.hostname, { all: true }) if (addrs.some((a) => isPrivate(a.address))) throw new Error('Webhook host is not public') return url } const BACKOFF_S = [10, 30, 120, 600, 3600] export async function deliver(update: UpdateRow, bot: Bot) { try { const res = await fetch(await safeWebhookUrl(bot.webhookUrl!), { method: 'POST', body: JSON.stringify(update.payload), signal: AbortSignal.timeout(5000), headers: { 'Content-Type': 'application/json', 'X-Relay-Bot-Secret': bot.webhookSecret }, }) if (!res.ok) throw new Error('HTTP ' + res.status) await markDelivered(update.id) } catch { const delay = BACKOFF_S[Math.min(update.attempts, BACKOFF_S.length - 1)] await scheduleRetry(update.id, update.attempts + 1, delay) } }✅ Check it works
setWebhookwithhttp://localhost:3000orhttps://192.168.1.5is refused; a webhook that returns 500 is retried with growing delays.Step 8
Write a real bot against your own API
Goal: A separate small app (a quiz bot) that proves your platform works for developers.
Create
examples/quiz-bot: a tiny Express server with a/webhookroute. It checks the secret header, reads the message text and replies withsendMessage: “/start” sends a welcome, “/quiz” sends a question, an answer gets “✅ Correct” or the right answer.Deploy it separately (or run it with a tunnel) and register its URL with
setWebhook. Chat with it inside your app.Write short API docs (a Markdown page with every method, its parameters and an example). Good docs are part of building a platform.
examples/quiz-bot/index.tsconst API = 'https://relay.example.com/bot/' + process.env.BOT_TOKEN const send = (chat_id: string, text: string) => fetch(API + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id, text }) }) app.post('/webhook', express.json(), async (req, res) => { if (req.get('X-Relay-Bot-Secret') !== process.env.WEBHOOK_SECRET) return res.sendStatus(403) res.sendStatus(200) // answer fast, then work const msg = req.body.message if (!msg?.text) return if (msg.text === '/start') return send(msg.chat.id, 'Hi! Send /quiz for a question.') if (msg.text === '/quiz') return send(msg.chat.id, 'What is 2^10? Reply with a number.') return send(msg.chat.id, msg.text.trim() === '1024' ? '✅ Correct!' : '❌ It is 1024. Try /quiz again.') })✅ Check it works
Sending “/quiz” to your bot in the app gets a question back within a second or two.
Step 9
Resumable uploads for large files
Goal: A 1 GB file uploads in 5 MB chunks, resumes after a network drop, and is verified with SHA-256.
One big request fails completely if the network drops at 95%. Instead: (1)
POST /uploadswith name, size and SHA-256 → upload id; (2)PUT /uploads/:id/chunks/:indexfor each 5 MB piece; (3)GET /uploads/:idlists received chunks so a client can resume; (4)POST /uploads/:id/completejoins the chunks in order and checks the hash.The browser slices the file with
file.slice(start, end)and computes the hash with a streaming library (for example hash-wasm) becausecrypto.subtle.digestneeds the whole file in memory.Validate everything: chunk index within range, chunk size ≤ 5 MB, total size ≤ your limit, upload id belongs to the user. Delete unfinished uploads after 24 hours.
server/uploads.tsconst CHUNK = 5 * 1024 * 1024 app.put('/uploads/:id/chunks/:index', requireUser, express.raw({ limit: CHUNK, type: '*/*' }), async (req, res) => { const up = await getUpload(req.params.id, req.user.id) // null if not this user's const index = Number(req.params.index) if (!up || !Number.isInteger(index) || index < 0 || index >= Math.ceil(up.size / CHUNK)) return res.sendStatus(400) await fs.writeFile(path.join(TMP, up.id, String(index)), req.body) res.json({ ok: true }) }) app.post('/uploads/:id/complete', requireUser, async (req, res) => { const up = await getUpload(req.params.id, req.user.id) if (!up) return res.sendStatus(404) const parts = Math.ceil(up.size / CHUNK) const hash = createHash('sha256') const out = createWriteStream(path.join(FILES, up.id)) for (let i = 0; i < parts; i++) { const buf = await fs.readFile(path.join(TMP, up.id, String(i))) // throws if a chunk is missing hash.update(buf) if (!out.write(buf)) await once(out, 'drain') } out.end() if (hash.digest('hex') !== up.sha256) return res.status(422).json({ error: 'checksum mismatch' }) await markComplete(up.id) res.json({ ok: true }) })✅ Check it works
Start a 500 MB upload, turn Wi-Fi off halfway, turn it on and press Resume: it continues from the last chunk and the final checksum matches.
Step 10
Search, deploy and document
Goal: Search across your chats and public channels, a live deployment and developer docs.
Message search: PostgreSQL full-text search on messages, always filtered to chats the user is a member of. Public channel search by username and title for discovery.
Deploy API + Socket.IO + workers, PostgreSQL and Redis with Docker Compose behind Nginx (raise
client_max_body_sizeabove 5 MB for chunk uploads). Store completed files in object storage for production.README: the seq design, HyperLogLog trade-off, the bot API docs, the SSRF protection, the upload protocol diagram, and the not-affiliated note. Link the example bot repository.
✅ Check it works
A stranger can read your docs, create a bot and get it replying without asking you anything.
🚀 Make it stand out
- +Inline keyboards (buttons) in bot messages
- +Scheduled channel posts
- +Channel analytics: views per day and subscriber growth
- +Video streaming of uploaded files with HTTP range requests