Why Your Telegram Bot Dies on Vercel (And How to Fix It)
You wrote a perfect Python Telegram bot. It runs flawlessly on your local machine using bot.polling(). You push it to Vercel to host it for free, and... silence. It works for 10 seconds and then dies.
This is the "Hello World" of serverless frustration. The problem isn't your code; it's a fundamental misunderstanding of how platforms like Vercel work compared to your local computer.
The Problem: Serverless vs. Long-Polling
When you run a script locally, it is a "long-lived" process. It sits there, constantly asking Telegram, "Do I have new messages? Do I have new messages?" This is called polling.
Vercel, however, is serverless. It does not keep computers running for you 24/7. It only spins up a tiny function when a specific URL is visited, runs the code, and then kills it immediately to save resources. If you try to run an infinite polling loop on Vercel, the platform sees a function that won't finish and forcibly kills it (usually after 10-60 seconds).
The Solution: Webhooks
To fix this, we need to invert the relationship. Instead of your bot asking Telegram for updates, we tell Telegram: "Hey, whenever someone sends a message, YOU come and knock on MY door."
This is called a Webhook.
Step 1: Structure for Serverless
You can't just run a main.py loop. You need to expose a web route (like an API endpoint). If you are using libraries like python-telegram-bot or aiogram, you need to wrap them in a web framework like Flask or FastAPI.
Your directory structure should look like this:
/api
└── index.py <-- The entry point for Vercel
requirements.txt
vercel.json
Step 2: The Code Logic
In your index.py, you need to handle a POST request. When Telegram sends an update to your URL, your script should:
- Receive the JSON data.
- Process the update object.
- Send the logic to your bot instance.
- Crucial: Return a
200 OKstatus immediately.
If you don't return a 200 OK quickly, Telegram assumes you failed and will keep retrying, eventually spamming your bot into a crash loop.
Step 3: Setting the Webhook
Once deployed, you need to tell Telegram where your bot lives. You can do this with a simple browser command:
[https://api.telegram.org/bot](https://api.telegram.org/bot)<YOUR_TOKEN>/setWebhook?url=[https://your-project.vercel.app/api/index](https://your-project.vercel.app/api/index)
Why This Method Wins
By switching to webhooks, your bot becomes purely reactive. It consumes zero resources when no one is using it, meaning you will likely never exceed Vercel's free tier limits. It scales infinitely; whether 1 person or 1,000 people message your bot, Vercel just spins up more instances to handle the load instantly.
Stop polling. Start listening.



