📖 Part 1: How I Built a Telegram Bot That Downloads YouTube Music & Videos Up to 2 GB
In Part 1, I explored how media extraction works.
In Part 2, I expanded my Telegram bot beyond YouTube to Instagram and Twitter/X.
Three platforms. Three different architectures. Three different sets of technical challenges.
I thought I had solved the difficult problems.
Then I introduced payments.
And suddenly, the most interesting system to investigate wasn't YouTube, Instagram, or Twitter anymore.
It was my own backend.
Imagine someone pressing the payment confirmation button twice at exactly the same time.
Imagine a user submitting a transaction reference that another user has already claimed.
Imagine someone launching multiple 4K downloads simultaneously.
Or imagine my own storage cleaner deleting a video while Telegram is still uploading it.
None of these problems require a sophisticated attacker. Sometimes, two ordinary requests arriving at the wrong moment are enough to expose a serious architectural flaw.
So I started looking at my project differently.
Instead of asking, "How do I make this feature work?"
I started asking:
"What assumptions would I challenge if I wanted to break this system?"
This is Part 3.
And this time, we're going deep into backend engineering.
1. What My Bot Has Become
The project is no longer just a Telegram media downloader.
Here's what the current system handles:
- YouTube video downloads up to 2160p (4K).
- Original-quality Instagram and Twitter/X media.
- Native MTProto file delivery up to approximately 2 GB.
- UPI-based payments and premium subscriptions.
- Gmail-based payment reconciliation.
- Priority-based job scheduling.
- Atomic subscription quota management.
- Persistent conversational state.
- Automated storage management.
- Referral rewards and coupon redemption.
- Payment abuse detection.
- Hundreds of automated tests.
The interesting part?
I'm still using Python, SQLite, asyncio, FFmpeg, and Telegram.
No Kubernetes cluster. No unnecessary microservices. No complicated distributed infrastructure added just to make the technology stack sound impressive.
But simplicity in infrastructure doesn't mean simplicity in application logic.
2. Async Programming Doesn't Give You Unlimited Hardware
One of the biggest misconceptions about asynchronous programming is that it somehow makes an application capable of handling unlimited concurrent operations.
It doesn't.
Imagine running the bot on a server with 4 GB of RAM.
One user requests a 4K video.
Another requests a large audio file.
Five more users start downloads.
Every request competes for:
- CPU cycles.
- Available memory.
- Disk space.
- Network bandwidth.
- FFmpeg subprocess capacity.
An event loop can efficiently coordinate waiting operations. It cannot manufacture more physical resources.
A naive implementation might look like this:
async def handle_download(url): await download_media(url) The function is asynchronous.
But where is the resource control?
Where is the queue?
What prevents too many FFmpeg processes from running simultaneously?
That's where synchronization primitives become useful.
Here's a simplified example:
import asyncio download_slots = asyncio.Semaphore(4) upload_slots = asyncio.Semaphore(4) async def process_media(url): async with download_slots: file_path = await download_media(url) async with upload_slots: await upload_to_telegram(file_path) Notice that downloading and uploading use separate semaphores.
Once downloading finishes, the download slot becomes available even if the previous file is still being uploaded.
This creates a processing pipeline instead of making every operation compete for the same execution slot.
The real application adds scheduling, cancellation, user-level restrictions and task tracking around this concept.
Asyncio handles concurrency. Resource management prevents concurrency from destroying your server.
3. I Turned a Download Queue Into a Scheduling System
Originally, the simplest approach was FIFO.
First In, First Out.
Incoming Requests User A → User B → User C → User D ↓ Available Worker Then I introduced premium subscriptions.
Now the scheduler needs to distinguish between free users, premium users and administrators.
The problem becomes more interesting.
A priority queue is one possible way to represent this scheduling policy.
Here's a conceptual Python implementation:
import asyncio from itertools import count queue = asyncio.PriorityQueue() sequence = count() async def submit_job(user_id, url, premium=False): priority = 1 if premium else 2 await queue.put(( priority, next(sequence), user_id, url )) Lower priority values are processed first.
The sequence number preserves submission order among requests with equal priority.
But priority scheduling creates another potential problem: starvation.
If premium requests continuously arrive, free requests could wait indefinitely.
That is an architectural trade-off worth monitoring.
This is where Operating Systems concepts become surprisingly relevant.
CPU scheduling, starvation, resource allocation and synchronization are not just university examination topics.
They're real engineering problems.
I also needed a task registry capable of tracking multiple jobs belonging to the same user.
Consider the following mistake:
active_tasks[user_id] = task If that user starts a second job, the original task reference gets overwritten.
The first task might still be running, but the application has lost its reference.
A better conceptual structure is:
active_tasks[user_id][job_id] = task Now cancellation and cleanup can operate at individual job level.
A small change in data structure.
A significant change in system behavior.
4. Why Supporting 4K Isn't Just Adding Another Button
A 4K button takes seconds to add.
A reliable 4K processing pipeline is another story.
High-resolution adaptive media frequently arrives as separate streams:
Video Stream: 2160p, no audio Audio Stream: Audio, no video ↓ FFmpeg ↓ Playable MP4 File This is associated with adaptive streaming technologies such as MPEG-DASH.
If both streams use compatible codecs, FFmpeg can merge them without performing a complete re-encode.
For example:
ffmpeg -i video.mp4 -i audio.m4a \ -map 0:v:0 -map 1:a:0 \ -c copy \ -movflags +faststart \ output.mp4 The important argument is -c copy.
Instead of decoding and encoding every frame again, FFmpeg copies the compatible streams into the output container.
That can save considerable processing time.
The bot then chooses an appropriate delivery route based on file size.
| File size | Delivery route |
|---|---|
| Up to 48 MB | Standard Bot API |
| Larger files, up to 2 GB | Native MTProto, when configured |
| Large files without MTProto | Media segmentation fallback |
The backend makes the decision.
The user simply selects a resolution.
That's one of the principles I've learned from this project:
A good interface hides implementation complexity without hiding important limitations.
5. The Networking Problem: Why Move More Bytes Than Necessary?
When retrieving media, an application performs two fundamentally different operations.
First, it retrieves metadata.
Then it transfers the actual media.
Metadata might contain:
- Video title.
- Duration.
- Available resolutions.
- Audio formats.
- Stream information.
The metadata response might be measured in kilobytes.
The actual video might be measured in gigabytes.
Treating both operations identically is inefficient.
My architecture separates metadata retrieval from bulk media transfer and supports a configurable fallback network route for metadata operations.
The expensive media transfer can use an independent delivery path when permitted and available.
Consider this illustrative comparison:
Metadata request: 50 KB Media transfer: 1,000 MB Those workloads have completely different bandwidth requirements.
This separation makes it possible to reason about network costs more effectively.
Caching introduces another optimization.
If twenty users request the same media information, why retrieve identical metadata twenty times?
A short-lived cache reduces repeated work.
But a cache without an expiration policy or capacity limit eventually becomes another resource problem.
Every optimization creates a new responsibility.
6. I Added UPI Payments Without Making the Bot Trust Screenshots
Here's where things became particularly interesting.
I wanted users to support the project through UPI and unlock additional capabilities.
But there is an uncomfortable question behind every payment feature:
How does the application independently establish that money was actually received?
A screenshot is untrusted input.
A transaction reference entered by a user is also untrusted input.
Neither should automatically unlock a subscription.
So the bot creates an order before initiating the payment.
Conceptually, an order contains:
Order ID Telegram User ID Expected Amount Transaction Reference Creation Time Expiration Time Payment Status Fulfillment Status The user receives a UPI QR code.
After making the payment, they submit the transaction reference.
The application can then reconcile the transaction with an incoming payment notification, or an administrator can review it manually.
The system must check that the transaction belongs to the appropriate order and has not been processed previously.
The optional email-verification feature is disabled by default.
It is a payment reconciliation experiment, not a replacement for a payment provider's authenticated transaction API.
7. I Turned Gmail Into an Event Source
Normally, when a payment notification arrives in Gmail, a human opens it and reads it.
But from a backend perspective, an incoming notification is an external event containing potentially useful data.
The architecture connects several independent systems:
Telegram Bot ↓ UPI Payment Order ↓ Payment Provider ↓ Email Notification ↓ Gmail / IMAP ↓ Verification Service ↓ SQLite Order ↓ Subscription Activation The important part is the trust boundary.
An email cannot be trusted simply because it appears to come from a familiar sender.
The verification service considers authenticated sender information, transaction direction, expected amount, transaction reference and order timing.
The documented implementation includes DKIM, SPF and DMARC authentication checks as part of the validation process.
What are these technologies?
SPF: Helps establish whether a sending server is authorized to send email for a domain.
DKIM: Uses a cryptographic signature to authenticate selected parts of an email and verify their integrity.
DMARC: Defines alignment requirements and handling policies based on SPF and DKIM authentication.
These mechanisms improve email authenticity checking, but they don't independently establish that a payment has settled.
A reliable financial integration still needs trustworthy transaction-level evidence.
That distinction is important.
8. Twenty Users. One Inbox. A Concurrency Problem.
Now imagine twenty users requesting payment verification simultaneously.
Should the application open twenty independent IMAP connections and retrieve the same inbox contents twenty times?
That would waste resources and potentially hit provider limits.
Instead, the bot uses synchronized inbox retrieval and a short-lived shared snapshot.
This is related to a concurrency pattern called single-flight execution.
The idea is simple:
Request A ─┐ Request B ─┤ Request C ─┼── Shared Inbox Retrieval Request D ─┤ ↓ Request E ─┘ Cached Snapshot ↓ Independent Validation Multiple requests share an expensive retrieval operation.
Each order still undergoes its own validation.
Here's a simplified demonstration:
import asyncio import time lock = asyncio.Lock() snapshot = None expires_at = 0 async def get_inbox_snapshot(): global snapshot, expires_at async with lock: now = time.monotonic() if snapshot is not None and now < expires_at: return snapshot snapshot = await asyncio.to_thread(fetch_inbox) expires_at = time.monotonic() + 4 return snapshot The lock prevents overlapping refreshes.
The cache allows waiting requests to reuse a recent result.
The actual verification service also accounts for notifications that arrive slightly late.
What started as a payment feature became a practical lesson in network I/O, caching, locks and event processing.
9. The Race Condition Hiding Inside a Successful Payment
This is one of the most important backend concepts I encountered.
Consider two requests processing the same order:
Request A Request B Read order: pending Read order: pending Grant subscription Grant subscription Mark order paid Mark order paid Both requests believe they are doing the correct thing.
But the combined result is incorrect.
The problem is the gap between checking a condition and changing the associated state.
This is a race condition.
A safer design performs the state transition atomically inside the database.
For example:
UPDATE orders SET status = 'paid' WHERE id = ? AND status = 'pending'; The application checks how many rows were affected.
If one row changes, that request successfully claimed the state transition.
If zero rows change, the order is no longer eligible.
The real implementation also considers ownership, expiration, transaction uniqueness and fulfillment tracking.
A separate fulfillment marker helps prevent repeated subscription delivery.
This is related to idempotency.
Repeated requests must not create repeated unintended business effects.
However, marking an order as fulfilled and granting its subscription also need careful transaction boundaries and recovery behavior.
Atomic state changes are powerful, but they aren't magic.
10. Can Two Downloads Consume One Remaining Quota?
The same concurrency problem appears in premium subscriptions.
A user has exactly one HD download remaining.
Two download requests arrive simultaneously.
An unsafe implementation might do this:
remaining = await get_remaining_quota(user_id) if remaining > 0: await consume_quota(user_id) await start_download() The issue?
Both requests might read the same remaining quota before either updates it.
The application can instead use a conditional database update:
UPDATE user_subscriptions SET used = used + 1 WHERE user_id = ? AND used < daily_limit; Again, the number of affected rows determines whether the operation succeeded.
The current project uses atomic quota consumption and can refund the consumed quota when a download fails or is cancelled.
The lesson here is bigger than Telegram bots.
Whenever multiple requests modify shared business state, ask whether the database itself enforces the condition.
Application-level checks alone aren't always sufficient.
11. My Storage Cleaner Could Become My Own Enemy
Every media download creates temporary files.
Without cleanup, disk usage increases indefinitely.
The obvious solution is a periodic cleanup process.
Delete old temporary folders.
Simple, right?
Except a large video might still be uploading when its temporary directory becomes old enough to qualify for cleanup.
The cleaner sees an old folder.
The uploader sees an active job.
Both components believe they are correct.
The user receives an error because the file disappears.
This is a resource lifecycle problem.
The system needs to distinguish between:
- Abandoned temporary files.
- Files currently being processed.
- Files waiting for upload.
- Files associated with completed jobs.
The bot uses active-job tracking to protect directories still needed by ongoing operations.
Python's finally block also provides a reliable place for job-level cleanup.
async def process_job(job): try: await download(job) await upload(job) finally: await cleanup(job) A background sweeper handles abandoned files that normal cleanup couldn't remove.
Sometimes the component that breaks your application is another component of your own application.
12. When Restarting a Python Process Erases the Conversation
Telegram bots are event-driven applications.
Messages arrive independently.
Consider this interaction:
Bot: Enter your transaction reference. User: Wait, I'm opening my payment app. Server: Restarts. User: Sends transaction reference. What does that final message mean?
Is it a payment reference?
A search query?
A coupon code?
The application needs conversational context.
This is where a Finite State Machine becomes useful.
IDLE ↓ ORDER_CREATED ↓ AWAITING_REFERENCE ↓ VERIFYING_PAYMENT ↓ COMPLETED A Finite State Machine represents the current stage of an ongoing workflow.
But an in-memory state machine disappears when the process restarts.
The bot uses persistent SQLite-backed FSM storage so that relevant conversational state can survive process restarts.
Persistent state does not guarantee that interrupted downloads automatically resume.
It means the application can preserve and recover the conversational context it needs.
That difference matters.
13. I Made the Bot Work Without Opening the Bot
One of my favorite Telegram features is inline mode.
Instead of opening the bot directly, a user can search from another Telegram conversation.
Try typing:
@songsuperzxbot song_name The bot returns search results within the current chat.
A deep link can then transfer the selected media identifier into the bot's private conversation.
Conceptually:
Inline Search ↓ Search Results ↓ Selected Media ID ↓ Telegram Deep Link ↓ Bot Download Workflow Telegram can cache inline search results for a configured period.
That reduces repeated backend work for identical searches.
The current implementation also applies separate rate-limiting rules to inline queries.
Why?
Because typing inside an inline search field can generate multiple events before the user finishes entering a query.
A feature that feels instantaneous to the user can generate a surprising amount of backend traffic.
14. I Started Treating Every Input as Untrusted
The bot accepts URLs, Telegram messages, callback data, transaction references and media metadata.
Every one of these crosses a trust boundary.
So I started reviewing the system with a defensive mindset.
| Security concern | Defensive approach |
|---|---|
| SSRF | URL validation and restricted destinations |
| Duplicate payment processing | Unique transaction references and atomic state transitions |
| Unauthorized payment operations | Order ownership checks |
| Race conditions | Conditional database writes |
| Request flooding | Rate limiting and bounded concurrency |
| Command injection | Subprocess argument lists without shell interpolation |
| Credential leakage | Environment variables and log redaction |
| Unsafe temporary deletion | Active-job directory protection |
| State loss | Persistent storage |
One security improvement I particularly like is secret redaction inside logs.
It's easy to avoid printing a bot token directly.
It's harder to ensure that an unexpected exception doesn't accidentally reveal sensitive configuration through a traceback.
The logging system now includes redaction mechanisms for sensitive values.
The project also keeps TLS certificate verification enabled and uses escaped user-facing HTML.
None of this makes the application invulnerable.
For example, initial URL validation alone is not complete SSRF protection. Connection-time DNS resolution and redirect handling require additional review.
Security isn't a feature you permanently finish.
It's a continuous process of challenging assumptions.
15. Why I Still Use SQLite Instead of PostgreSQL
As the project grew, I could have introduced PostgreSQL, Redis and separate worker services.
But every new component introduces operational complexity.
For a single-instance application, SQLite remains a practical choice.
The project uses WAL mode and persistent database-backed workflows.
PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA synchronous = NORMAL; WAL stands for Write-Ahead Logging.
Instead of immediately modifying the main database file for every change, SQLite records updates in a separate write-ahead log.
This improves concurrency between readers and writers.
However, SQLite still has limitations around concurrent writes.
If the project eventually requires multiple application instances, distributed workers or significantly heavier write workloads, moving to a client-server database may become appropriate.
Until then, unnecessary infrastructure would solve problems I haven't established that I actually have.
Choose architecture based on requirements, not on how impressive the technology names sound.
16. The Update Nobody Sees: Automated Testing
When I published Part 2, the project had approximately 30 automated tests.
The current repository README reports:
228 passed in 23.01s The repository has also grown to 136 commits.
The test suite covers functionality and security-related behavior, including payment processing, quota handling, synchronization, validation and resource management.
You can inspect and run the tests yourself:
git clone https://github.com/chandan0000001/music-video_telegrambot.git cd music-video_telegrambot python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt pytest tests/ -v Passing tests don't prove that an application cannot be broken.
They establish that particular expected behaviors were checked under defined conditions.
The goal isn't to chase an impressive test count.
It's to make important assumptions executable.
17. Things I Would Improve Next
I don't want to pretend this architecture is perfect.
There are several areas worth exploring further:
- Stronger connection-time SSRF protections.
- Official payment-provider transaction verification.
- More comprehensive failure-recovery testing.
- Fair scheduling policies to reduce queue starvation.
- Better operational metrics and structured observability.
- Distributed worker architecture if actual demand justifies it.
- Continuous dependency security scanning.
Building a project teaches you how to make decisions.
Maintaining it teaches you how to question those decisions.
What I Actually Learned From This Project
I started with a Telegram bot that downloaded songs.
Then videos.
Then three different platforms.
Then payments, scheduling, authentication checks, database transactions, resource protection and persistent workflows.
Somewhere along the way, this project became my personal backend engineering laboratory.
Here's how the computer science concepts connect to real features:
| Computer Science | Practical implementation |
|---|---|
| Data Structures | Queues, hash maps, task registries |
| Operating Systems | Scheduling, subprocesses, resource management |
| Computer Networks | HTTP, IMAP, MTProto, TLS |
| DBMS | Transactions, constraints, WAL, atomic updates |
| Cybersecurity | Trust boundaries, authorization, input validation |
| System Design | Processing pipelines, caching, failure recovery |
| Software Engineering | Testing, documentation, maintainability |
The most valuable thing I learned wasn't how to download a video.
It was how many engineering decisions hide behind a single button.
Final Thoughts
In Part 1, I investigated media extraction.
In Part 2, I investigated the differences between three platforms.
In Part 3, I started questioning the architecture of my own application.
And that might have been the most valuable investigation of all.
Because the more I understand how systems fail, the better I become at building them.
Making a feature work is programming.
Making it behave correctly when users, networks, databases and processes don't cooperate is engineering.
Explore the Project
🤖 Telegram Bot: @songsuperzxbot
📦 GitHub Repository: music-video_telegrambot
👨💻 Developer: @coder_chandan
Use the bot only for media you own or have permission to download.
If you're a backend developer, security researcher or someone learning computer science, explore the source code.
I'd especially appreciate feedback on the scheduling architecture, payment verification and database concurrency.
The interesting part isn't the Telegram bot.
It's the entire system hiding behind it.
AI-assisted writing based on my project, implementation documentation and engineering decisions.






