Skip to content
Панель Розсилки Mail Cabinet Choose a plan

Deploy a Telegram Bot on a VPS: systemd, Nginx Webhook and Real RAM Use

Deploy a Telegram Bot on a VPS: systemd, Nginx Webhook and Real RAM Use

For a small Telegram bot on a VPS, start with long polling: it needs no domain, no certificate and no open ports. Run the bot as a systemd service (or under supervisord) with automatic restarts, and keep the token in a .env file with mode 600. Switch to a webhook behind nginx that checks the X-Telegram-Bot-Api-Secret-Token header when you run several bots or need instant delivery. 1 GB of RAM is enough: on our bench an aiogram 3.31 bot used 168-170 MB, a python-telegram-bot 22.8 bot 45 MB.

How we tested

  • RichHost test bench, an isolated container with 2 vCPU / 8 GB, Ubuntu 24.04, Python 3.12.3, nginx 1.24, PHP 8.3-FPM. October 2026. These are not RichHost production servers.
  • api.telegram.org is not reachable from the container (the proxy returns 403), so we wrote a local Bot API imitation on aiohttp: getMe, getUpdates, setWebhook, deleteWebhook, getWebhookInfo and sendMessage with JSON responses shaped as in the official docs. Error texts in the logs come from the imitation; the Telegram rules come from the documentation (checked 25.10.2026, Bot API 10.3).
  • Libraries from pip: aiogram 3.31.0 (aiohttp 3.14.5, pydantic 2.13.5), python-telegram-bot 22.8 (httpx 0.28.1), supervisor 4.3.0. The bot’s API address was replaced via TelegramAPIServer.from_base() and base_url().
  • Memory is VmRSS from /proc/PID/status at idle and after 1000 messages from 50 chats. Crashes were simulated with kill -9, a command that calls os._exit(1), and a broken token.
  • systemd is not running in the container (PID 1 is not systemd), so the unit file was only checked with systemd-analyze verify; the real restart test ran under supervisord.
$ curl -sS -m 15 https://api.telegram.org/
curl: (56) CONNECT tunnel failed, response 403

Long polling vs webhook: what the test showed

In long polling mode the bot calls getUpdates with a timeout, and Telegram keeps the request open until a message arrives. The logs show one request that waited 12 seconds and returned in the same millisecond the message arrived, while an empty request ended after exactly 30 seconds. The reply went out 6 ms after the incoming message (local network, no latency to Telegram servers).

The bench bot replied in Ukrainian, so the log lines contain Ukrainian text.

14:28:54.963 MOCK inject update_id=1 text='/start'
14:28:54.963 MOCK getUpdates offset=0 timeout=30 -> 1 update(s) after 0.82 s
14:28:54.977 MOCK sendMessage chat_id=555001 text='Привіт! Я працюю на VPS.'
14:29:06.975 MOCK inject update_id=2 text='друге повідомлення'
14:29:06.975 MOCK getUpdates offset=2 timeout=30 -> 1 update(s) after 12.00 s
14:29:06.981 MOCK sendMessage chat_id=555001 text='друге повідомлення'
14:29:36.989 MOCK getUpdates offset=3 timeout=30 -> 0 update(s) after 30.01 s

The main polling trap is two copies of the bot with one token, for example a manual run next to the service. The newer getUpdates terminates the older one, and both copies keep getting error 409:

ERROR aiogram.dispatcher: Failed to fetch updates - TelegramConflictError: Telegram server says
  - Conflict: terminated by other getUpdates request; make sure that only one bot instance is running
WARNING aiogram.dispatcher: Sleep for 1.000000 seconds and try again... (tryings = 0, bot id = 123456789)

In webhook mode Telegram sends a POST to your HTTPS address. The docs say plainly that getUpdates does not work while an outgoing webhook is set, so a polling bot must call deleteWebhook first (aiogram and python-telegram-bot do it on startup). We also tested a self-signed certificate: without uploading it in setWebhook, delivery failed with a certificate verification error; after the upload, updates arrived in 6-8 ms through nginx with TLS.

14:30:38.314 MOCK setWebhook url=https://bot.example.test:8443/tg secret=yes cert=no
14:30:39.373 MOCK webhook POST update_id=1 failed (... [SSL: CERTIFICATE_VERIFY_FAILED] ...), retry #1
# WEBHOOK_CERT set, the self-signed cert.pem is uploaded with setWebhook:
14:31:13.755 MOCK setWebhook url=https://bot.example.test:8443/tg secret=yes cert=uploaded
14:31:14.627 MOCK webhook POST update_id=1 -> 200 in 8.3 ms
14:31:14.937 MOCK webhook POST update_id=2 -> 200 in 6.8 ms
14:31:15.248 MOCK webhook POST update_id=3 -> 200 in 5.9 ms

$ curl -s http://127.0.0.1:18281/bot<TOKEN>/getWebhookInfo
{"ok": true, "result": {"url": "https://bot.example.test:8443/tg", "has_custom_certificate": true,
 "pending_update_count": 0, "max_connections": 40}}
$ curl -s http://127.0.0.1:18281/bot<TOKEN>/getUpdates
{"ok": false, "error_code": 409, "description": "Conflict: can't use getUpdates method while webhook
 is active; use deleteWebhook to delete the webhook first"}
Criterion Long polling Webhook
Domain and certificate not needed needed (Let’s Encrypt or self-signed)
Inbound ports none 443, 80, 88 or 8443
Bot process always running always running (Python) or one request per update (PHP)
Several bots on one server each holds its own request one nginx, different paths
Typical error 409: two bot copies 403/401: wrong secret, TLS error
When to choose getting started, one bot, no domain several bots, shared hosting, serverless

How much memory a bot really needs

The difference between libraries surprised us most. An echo bot on aiogram 3.31.0 used 168 MB right after start and 170 MB after a thousand messages; the same bot on python-telegram-bot 22.8 used 44-45 MB. Almost all of it is imports: a bare Python interpreter takes 8 MB, after import aiohttp and import pydantic 38 MB, and after from aiogram import Bot, Dispatcher 165 MB. Startup differs too: from launch to the first getUpdates aiogram took 3.2-3.3 s, python-telegram-bot 0.3-0.4 s (three runs each). Memory depends heavily on the version: in our test importing aiogram 3.22.0 took 108 MB, so measure your own build instead of trusting other people’s numbers.

Chart: a Telegram bot process on aiogram 3.31 uses 168-170 MB of RAM, on python-telegram-bot 22.8 45 MB, supervisord 20 MB
Measured on the RichHost test bench: bot process RSS from /proc/PID/status
$ grep VmRSS /proc/$(supervisorctl pid tgbot)/status
VmRSS:    172072 kB      # aiogram 3.31.0, polling, idle
VmRSS:    174368 kB      # the same process after 1000 messages from 50 chats
$ grep VmRSS /proc/$(cat ptb.pid)/status
VmRSS:     45632 kB      # python-telegram-bot 22.8, after 1000 messages
$ ps -o rss,cmd -C supervisord
  RSS CMD
20976 .../venv/bin/python3.12 ./venv/bin/supervisord -c supervisord.conf

What it means for sizing: the bot itself fits in 50-200 MB; the rest goes to the OS, nginx and a database if you have one (we did not measure those here). A 1 GB VPS is enough for one to three such bots, 512 MB is tight for aiogram with a database. Other things to check besides memory are covered in how to choose a VPS.

User, venv and the token in .env

Basic server setup (updates, SSH keys, firewall) is in our Ubuntu 24.04 VPS initial setup guide; here we cover only the bot. The bot runs as a separate system user without a login shell, with dependencies in a virtual environment pinned to an exact version:

sudo useradd --system --create-home --home-dir /opt/tgbot --shell /usr/sbin/nologin tgbot
sudo -u tgbot python3 -m venv /opt/tgbot/venv
sudo -u tgbot /opt/tgbot/venv/bin/pip install aiogram==3.31.0
sudo -u tgbot sh -c '/opt/tgbot/venv/bin/pip freeze > /opt/tgbot/requirements.txt'
sudo -u tgbot touch /opt/tgbot/.env && sudo chmod 600 /opt/tgbot/.env
openssl rand -hex 32        # WEBHOOK_SECRET: only A-Z a-z 0-9 _ - are allowed

The .env file is read both by systemd (EnvironmentFile) and by the shell (. ./.env in the supervisord command), so write values without quotes, spaces or variables; then both read them the same way. Add .env to .gitignore. If you use python-telegram-bot, turn off httpx INFO logs: we checked that at INFO level the library logs the full request URL including the token.

# /opt/tgbot/.env   owner tgbot, chmod 600, listed in .gitignore
BOT_TOKEN=123456789:AA-your-token-from-BotFather
BOT_MODE=polling
# webhook mode only:
WEBHOOK_URL=https://bot.example.com/tg
WEBHOOK_SECRET=paste-output-of-openssl-rand-hex-32
LISTEN_PORT=8081

Bot code: one file for both modes

This is the exact file we ran on the bench in polling and webhook modes. TG_API_BASE is only for the test with the local imitation; do not set it on a real server. If the bot runs in Docker, the restart policy replaces systemd: see Docker and Compose on a VPS.

import asyncio, logging, os, sys
from aiogram import Bot, Dispatcher, F
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
from aiogram.filters import CommandStart
from aiogram.types import FSInputFile, Message
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
from aiohttp import web

logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s",
                    level=logging.INFO, stream=sys.stdout)
TOKEN = os.environ["BOT_TOKEN"]
MODE = os.environ.get("BOT_MODE", "polling")
API_BASE = os.environ.get("TG_API_BASE")          # empty = api.telegram.org (we used a local mock)
dp = Dispatcher()

@dp.message(CommandStart())
async def start(m: Message):
    await m.answer("Hi! I am running on a VPS.")

@dp.message(F.text)
async def echo(m: Message):
    await m.answer(m.text)

def make_bot():
    s = AiohttpSession(api=TelegramAPIServer.from_base(API_BASE)) if API_BASE else None
    return Bot(TOKEN, session=s)

async def polling():
    bot = make_bot()
    await bot.delete_webhook()                     # getUpdates does not work while a webhook is set
    await dp.start_polling(bot, polling_timeout=30)

async def on_startup(bot: Bot):
    cert = os.environ.get("WEBHOOK_CERT")         # only for a self-signed certificate
    await bot.set_webhook(os.environ["WEBHOOK_URL"], secret_token=os.environ["WEBHOOK_SECRET"],
                          certificate=FSInputFile(cert) if cert else None)

def webhook():
    bot = make_bot()
    dp.startup.register(on_startup)
    app = web.Application()
    SimpleRequestHandler(dispatcher=dp, bot=bot,
                         secret_token=os.environ["WEBHOOK_SECRET"]).register(app, path="/tg")
    setup_application(app, dp, bot=bot)
    web.run_app(app, host="127.0.0.1", port=int(os.environ.get("LISTEN_PORT", "8081")))

if __name__ == "__main__":
    webhook() if MODE == "webhook" else asyncio.run(polling())

The systemd unit and what systemd-analyze showed

Compared with the usual example we added two things. MemoryMax=300M caps the bot with headroom above the measured 170 MB, so a memory leak cannot take the whole server. StartLimitBurst=5 within 60 seconds stops endless restarts if the bot dies right after start, for example because of a broken token.

# /etc/systemd/system/tgbot.service
[Unit]
Description=Telegram bot (aiogram)
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=simple
User=tgbot
Group=tgbot
WorkingDirectory=/opt/tgbot
EnvironmentFile=/opt/tgbot/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/tgbot/venv/bin/python /opt/tgbot/bot.py
Restart=on-failure
RestartSec=3
TimeoutStopSec=15
MemoryMax=300M
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/tgbot/data

[Install]
WantedBy=multi-user.target
$ systemd-analyze --version | head -1
systemd 255 (255.4-1ubuntu8.15)
$ systemd-analyze verify ./tgbot.service          # before the venv exists
tgbot.service: Command /opt/tgbot/venv/bin/python is not executable: No such file or directory
$ systemd-analyze verify ./tgbot-bench.service; echo "exit=$?"   # same unit, bench paths
exit=0
$ systemd-analyze verify ./broken.service         # deliberate typos
broken.service:3: Failed to parse service restart specifier, ignoring: sometimes
broken.service:4: Invalid memory limit '300X', ignoring: Invalid argument

systemd-analyze verify catches a missing ExecStart binary and invalid values, but reports syntax errors as warnings with exit code 0, so read the output, not just the exit code. Run it after creating the venv, then sudo systemctl daemon-reload and sudo systemctl enable --now tgbot. Logs: journalctl -u tgbot -f.

supervisord: a tested restart after a crash

Where there is no systemd (containers, some cloud images), supervisord does the same job. The exec in the command matters: without it SIGTERM goes to the shell instead of Python, and the bot does not shut down cleanly.

; /etc/supervisor/conf.d/tgbot.conf
[program:tgbot]
command=/bin/sh -c 'set -a; . /opt/tgbot/.env; set +a; exec /opt/tgbot/venv/bin/python /opt/tgbot/bot.py'
directory=/opt/tgbot
user=tgbot
autostart=true
autorestart=true
startsecs=5
startretries=3
stopsignal=TERM
stopwaitsecs=10
environment=PYTHONUNBUFFERED="1"
stdout_logfile=/var/log/tgbot/bot.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3
redirect_stderr=true

Test result: after kill -9 supervisord started a new copy within 1 s, the bot was ready 4.3 s after the crash, and a message sent during the downtime was not lost. Telegram keeps unread updates for up to 24 hours, and the bot received it on the next getUpdates. With a broken token supervisord gave up after four attempts and put the program into the FATAL state without further restarts; server monitoring has to tell you about it, otherwise the bot stays silent until someone notices.

$ kill -9 20912                                   # 14:33:53.144
14:33:53,153 WARN exited: tgbot (terminated by SIGKILL; not expected)
14:33:54,156 INFO spawned: 'tgbot' with pid 20968
14:33:57,447 INFO tgbot: mode=polling pid=20968                 (bot log)
14:33:57.461 MOCK sendMessage chat_id=555005 text='повідомлення під час падіння'   (mock log)
14:33:59,468 INFO success: tgbot entered RUNNING state, process has stayed up for > than 5 seconds (startsecs)
# /crash command -> os._exit(1)
14:34:01,308 WARN exited: tgbot (exit status 1; not expected)
14:34:02,310 INFO spawned: 'tgbot' with pid 20999
# BOT_TOKEN=broken-token -> TokenValidationError on every start
14:34:33,802 WARN exited: tgbot (exit status 1; not expected)
...
14:34:51,939 WARN exited: tgbot (exit status 1; not expected)
14:34:52,940 INFO gave up: tgbot entered FATAL state, too many start retries too quickly

Webhook behind nginx with a secret_token check

Pass secret_token to setWebhook (1-256 characters, only A-Z, a-z, 0-9, _ and -), and Telegram adds it to the X-Telegram-Bot-Api-Secret-Token header of every request. Check the header in nginx already, so foreign requests never reach Python. Installing nginx itself is covered in install LEMP on Ubuntu 24.04; certbot issues the certificate, see also SSL certificate on shared hosting.

# /etc/nginx/conf.d/tgbot-secret.conf   (http level, chmod 640)
map_hash_bucket_size 128;   # a 64-character secret does not fit the default bucket of 64
map $http_x_telegram_bot_api_secret_token $tg_secret_ok {
    default 0;
    "your-64-hex-secret" 1;
}

The map_hash_bucket_size line is not decoration: with a 64-character secret from openssl rand -hex 32 nginx 1.24 refused to start without it.

$ nginx -t
nginx: [emerg] could not build map_hash, you should increase map_hash_bucket_size: 64
server {
    listen 443 ssl;                 # Telegram: 443, 80, 88 or 8443 only
    server_name bot.example.com;
    ssl_certificate     /etc/letsencrypt/live/bot.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/bot.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    location = /tg {
        if ($tg_secret_ok = 0) { return 403; }
        limit_except POST { deny all; }
        client_max_body_size 1m;
        proxy_pass http://127.0.0.1:8081;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 60s;
    }
    location / { return 404; }
}

On the bench the same location blocks ran on port 18443 with a self-signed certificate. A wrong or missing secret is rejected by nginx with 403, GET also gets 403, other paths 404, and TLS 1.1 is refused. aiogram is the second line of defence: when nginx was bypassed, a request with the wrong secret got 401.

no header:     403
wrong secret:  403
GET + secret:  403
POST + secret: 200
other path:    404
TLS 1.1:       000 exit=35        # handshake refused, only TLS 1.2/1.3 allowed
# aiogram's own check when nginx is bypassed:
$ curl -s -w ' %{http_code}' -XPOST -H 'X-Telegram-Bot-Api-Secret-Token: wrong' http://127.0.0.1:18282/tg
Unauthorized 401

You can also allow /tg only from 149.154.160.0/20 and 91.108.4.0/22, the networks Telegram sends webhooks from according to its docs. Telegram warns that these ranges may change, so the secret remains the main protection.

Official Telegram rules worth knowing

Rule What the docs say Source
Webhook ports only 443, 80, 88 and 8443 Bot API, setWebhook
HTTPS and TLS webhook URL must be HTTPS, TLS 1.2 and later are supported, IPv6 is not supported for webhooks Webhooks guide
Self-signed certificate upload the public certificate as a file in the certificate parameter; the CN must match the domain or IP Webhooks guide
getUpdates and webhook getUpdates does not work while an outgoing webhook is set Bot API, getUpdates
Update storage unread updates are kept for no longer than 24 hours Bot API
Sending limits no more than 1 message per second in one chat, up to 20 per minute in a group, about 30 per second for bulk messages (up to 1000 with paid broadcasts) Bots FAQ
max_connections 1 to 100, default 40 Bot API, setWebhook

Checked on 25.10.2026; the latest entry in the changelog is Bot API 10.3 of August 24, 2026.

VPS, serverless or a PHP webhook on shared hosting

A webhook needs no resident process: each update is an ordinary HTTP request. That is why a simple PHP bot can live even on shared hosting. The docs let you answer a webhook with a method call right in the response: return JSON with a method field and Telegram executes it, with no outgoing request from your server. The catch: you cannot know whether that call succeeded.

<?php
// Telegram webhook on shared hosting: one update = one HTTP request, no resident process
$cfg = require __DIR__ . '/../config.php';          // outside public_html: ['secret' => '...']
$got = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if (!hash_equals($cfg['secret'], $got)) {
    http_response_code(403);
    exit;
}
$update = json_decode(file_get_contents('php://input'), true);
$msg = $update['message'] ?? null;
if (!$msg || !isset($msg['text'])) {                 // sticker, photo...: just confirm with 200
    http_response_code(200);
    exit;
}
$text = $msg['text'] === '/start' ? 'Hi! I am answering from PHP.' : $msg['text'];
// reply inside the webhook response: Telegram calls the method itself
header('Content-Type: application/json');
echo json_encode(['method' => 'sendMessage', 'chat_id' => $msg['chat']['id'], 'text' => $text],
                 JSON_UNESCAPED_UNICODE);
$ curl -i -XPOST -H "X-Telegram-Bot-Api-Secret-Token: $S" -d "$UPDATE" https://bot.example.test:18443/php-hook
HTTP/1.1 200 OK
Content-Type: application/json
{"method":"sendMessage","chat_id":42,"text":"curl test"}
# PHP check alone (nginx check off): wrong secret 403, no secret 403, correct 200, sticker 200
14:33:07.613 MOCK webhook POST update_id=6 -> 200 in 3.4 ms
14:33:07.613 MOCK sendMessage chat_id=555004 text='Привіт! Я відповідаю з PHP.'
php-hook incl. TLS handshake, n=100: min 3.3 ms, median 4.1 ms, p95 5.2 ms, max 8.4 ms

On the bench (nginx + PHP 8.3-FPM) the handler answered in 4.1 ms median including TLS, and the hash_equals check rejected foreign requests even with the nginx check removed. That matters on shared hosting, where the web server config is not yours. Such a handler needs PHP and HTTPS on port 443: RichHost shared hosting plans from A3 at $8 per month include free Let’s Encrypt SSL. We tested this code on the bench, not on RichHost production servers.

Situation Choose Why
Python or Node bot, background jobs, queues VPS, polling or webhook needs a resident process, 50-200 MB RAM per bot
Several bots on one server VPS, webhooks behind one nginx one port 443, different paths, no 409 between copies
Simple bot: replies, forms, notifications PHP webhook on shared hosting no process to babysit, SSL is already there
Rare requests, no wish to run a server serverless function with a webhook pay per call, but polling is impossible and cold starts happen
Mass broadcasts VPS with a queue the ~30 messages per second limit has to be spread over time

If you are still choosing between shared hosting and a server, compare the formats in what type of hosting your website needs.

Common errors

Symptom Cause Fix
409 Conflict: terminated by other getUpdates request two bot copies with one token systemctl status tgbot, pgrep -af bot.py, keep one
409 Conflict: can’t use getUpdates method while webhook is active an old webhook is still set deleteWebhook before polling
getWebhookInfo: pending_update_count keeps growing TLS, wrong port or 403 from nginx check last_error_message and the nginx access.log
nginx: could not build map_hash long secret in a map map_hash_bucket_size 128;
the bot restarts in a loop startup error (token, import) journalctl -u tgbot -n 50, StartLimitBurst or startretries
token in the logs httpx at INFO level WARNING level for the httpx logger, revoke the token in @BotFather

FAQ

How much RAM does a Telegram bot need?

On our bench the process itself used 45 MB (python-telegram-bot 22.8) or 168-170 MB (aiogram 3.31.0). Add memory for the OS and a database, so a 1 GB VPS is the practical minimum for one to three bots.

Are messages lost when the bot restarts?

No, as long as the downtime is shorter than 24 hours: Telegram keeps unread updates and the bot gets them after start. In our test a message sent during the crash was handled 4.3 s later.

Can I run a webhook on port 8080?

No, Telegram sends webhooks only to ports 443, 80, 88 and 8443. The bot can listen on any local port, such as 8081, while nginx accepts requests on 443 and passes them on.

systemd or supervisord?

On a regular Ubuntu VPS, systemd: it is already there, with a journal and resource limits. supervisord is handy in containers and wherever systemd is unavailable; it uses about 20 MB itself.

More on this topic

All articles
How to Connect via SSH from Windows, macOS and Linux: Step by Step
Hosting Guides and Tutorials27.09.2026

How to Connect via SSH from Windows, macOS and Linux: Step by Step

A step-by-step guide on how to connect via SSH from Windows, macOS and Linux with the terminal or PuTTY, set up key…

VPS Server Price in 2026: What 1-8 vCPU Cost (Price Guide)
General15.09.2026

VPS Server Price in 2026: What 1-8 vCPU Cost (Price Guide)

Real VPS prices for 1-8 vCPU plans from Ukrainian and European providers as of September 2026, what drives the cost, which extras…

VPS vs Dedicated Server: Signs You Have Outgrown Your VPS
VPS and Servers10.09.2026

VPS vs Dedicated Server: Signs You Have Outgrown Your VPS

When VPS can no longer handle the load, hosting providers stay silent about switching to a dedicated server. We break down when…