On this page
- Why automatic restart belongs to the service manager
- How to configure Docker restart policies
- Telegram polling, webhooks, and restart behavior
- The configuration that prevents restart storms
- Choosing the VPS for a restartable bot
- What We Got Wrong / What Surprised Us
- Practical Takeaways
- Try a VPS suited to the bot’s workload
- FAQ
Auto restart bot on VPS is best implemented with systemd or Docker, not a cron job. A systemd unit with Restart=on-failure, RestartSec=5s, and start-rate limits can recover a crashed process while stopping an endless crash loop. Docker Compose provides the equivalent unless-stopped policy for containerized bots.
- systemd: use
Restart=on-failurefor Python, Node.js, PHP, and Go bots running directly on Linux. - Docker: use
restart: unless-stopped, but remember that an unhealthy container does not restart unless its main process exits. - Telegram: updates are retained for up to 24 hours, so a short restart does not automatically mean lost messages.
- Safe defaults: a 5-second delay and a limit of 5 starts per 60 seconds reduce restart storms.
- VPS choice: the Hetzner CX22 was listed at €3.79 per month in June 2024, with 2 vCPUs, 4 GB RAM, and 40 GB storage; prices can change.
Compare VPS plans with real prices and testing data before deploying a bot, VPN, trading tool, or game server.
Why automatic restart belongs to the service manager
systemd supervises a Linux service independently of the SSH session, shell, terminal multiplexer, or user who launched the process. A bot started with python bot.py & can disappear after an exception, terminal disconnect, or reboot. A systemd unit starts it during boot and records stdout, stderr, exit status, and restart events in the journal.
systemd Restart=on-failure restarts a service after an unclean exit, signal, or timeout, while leaving a clean manual stop alone. The official systemd documentation recommends this mode for long-running services. systemd.service documentation also describes start-rate limiting through StartLimitIntervalSec and StartLimitBurst.
Minimal Python bot unit
[Unit]
Description=Telegram bot
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=simple
User=bot
WorkingDirectory=/opt/mybot
EnvironmentFile=/etc/mybot/bot.env
ExecStart=/opt/mybot/.venv/bin/python /opt/mybot/bot.py
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
Save the file as /etc/systemd/system/mybot.service. The WorkingDirectory variable prevents relative paths from breaking after boot. The virtual-environment path in ExecStart avoids dependence on the shell’s PATH.
sudo systemctl daemon-reload
sudo systemctl enable --now mybot.service
sudo systemctl status mybot.service
sudo journalctl -u mybot.service -n 100 --no-pager
sudo systemctl restart mybot.service
RestartSec=5s is a practical starting value, not a universal law. A bot that reconnects to an API immediately may need 10–30 seconds to avoid repeated connection bursts. A local worker with no external dependency may recover safely in 1–5 seconds.
How to configure Docker restart policies
Docker Compose restart=unless-stopped restarts a container after termination and continues doing so after the Docker daemon starts again, unless an administrator deliberately stopped the container. Docker documents four main policies: no, always, on-failure, and unless-stopped.
services:
telegram-bot:
image: ghcr.io/example/mybot:1.4.2
container_name: telegram-bot
restart: unless-stopped
env_file:
- .env
init: true
volumes:
- ./data:/app/data
logging:
driver: json-file
options:
max-size: "10m"
max-file: "5"
Docker restart policy reacts to container termination, not every application failure. A bot can remain alive while its polling loop is frozen, its database connection is broken, or its webhook handler returns errors. A Docker health check can detect a problem, but a health check alone does not restart an unhealthy container.
Health checks need an exit path
A health check is useful when it measures a real condition, such as a local HTTP endpoint or a heartbeat timestamp. The application or an external supervisor must then act on the failed condition. Otherwise Docker reports unhealthy while the process continues running.
services:
telegram-bot:
build: .
restart: unless-stopped
healthcheck:
test: ["CMD", "python", "/app/healthcheck.py"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
The interval variable here is 30 seconds, and retries is 3. Those values define detection behavior; they do not guarantee recovery. For a bot serving HTTP webhooks, place the health endpoint behind the same reverse proxy and TLS configuration used in production.
Valebyte helps compare VPS and dedicated-server options for bots, VLESS VPNs, forex tools, and game servers using published plan details and testing-oriented comparisons.
Telegram polling, webhooks, and restart behavior
Telegram Bot API supports two mutually exclusive update methods: getUpdates long polling and webhooks. A process using long polling normally reconnects after a network error, while a webhook bot depends on a reachable HTTPS endpoint, a valid certificate, and a supported port.
Telegram states that incoming updates are stored until the bot receives them, but not for more than 24 hours. That makes a short VPS restart less dangerous than a prolonged outage, provided the bot confirms updates correctly and does not lose its own database state.
Long polling is usually simpler for a single bot on a private VPS:
while True:
try:
run_polling()
except Exception:
logger.exception("Polling stopped")
time.sleep(10)
The internal time.sleep(10) is not a replacement for systemd. It handles a reconnectable application error; systemd handles process death, host reboot, and executable failure. Running both layers is reasonable, but each layer should have a defined job.
Webhooks need more infrastructure. Telegram’s official webhook guide lists ports 443, 80, 88, and 8443, requires TLS, and states that IPv4 support is required for webhook delivery. A restart can therefore affect both the bot process and the reverse proxy. Telegram’s webhook documentation is the authority for current delivery requirements.
For a bot that changes orders, trades, balances, or game state, automatic restart is not enough. Idempotency keys, update offsets, database transactions, and duplicate-event handling matter more than the restart command itself.
The configuration that prevents restart storms
StartLimitBurst=5 with StartLimitIntervalSec=60 means systemd will not repeatedly launch a process that fails five times inside one minute. Without a limit, a missing environment variable or invalid database URL can produce an endless loop of starts, log growth, API connection attempts, and confusing alerts.
[Unit]
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Restart=on-failure
RestartSec=15s
The non-obvious trade-off is that aggressive restarting can reduce reliability. A bot that starts, sends a duplicate job, crashes, and starts again may repeat the same side effect. A slower restart with a clear failed state gives an operator time to inspect logs and prevents a bad deployment from looking like a healthy service.
Keep secrets and logs separate
EnvironmentFile=/etc/mybot/bot.env keeps the Telegram token outside the unit file and application repository. Set ownership and permissions explicitly:
sudo chown root:bot /etc/mybot/bot.env
sudo chmod 640 /etc/mybot/bot.env
journald keeps service logs available through journalctl, but retention depends on host configuration. Docker’s JSON logging driver can also grow without limits, which is why the example uses a 10 MB maximum file size and 5 rotated files. Those are storage controls, not uptime controls.
Choosing the VPS for a restartable bot
VPS capacity should match the bot’s workload, not the restart mechanism. A simple Telegram polling process may use little CPU while a browser automation bot, LLM integration, image processor, or trading stack needs more memory and disk I/O.
| Workload | Useful deployment detail | Main risk |
|---|---|---|
| Single polling bot | systemd, virtual environment, local logs | Token or database misconfiguration |
| Webhook bot | systemd or Docker plus reverse proxy and TLS | Port, certificate, or DNS failure |
| Several bots | One unit or container per bot | Shared resources and unclear ownership |
| Trading or payment bot | Database transactions, idempotency, alerting | Duplicate side effects after recovery |
Hetzner’s June 2024 announcement listed the CX22 at €3.79 per month, excluding VAT, with 2 vCPUs, 4 GB RAM, 40 GB storage, 20 TB traffic, and one IPv4 address. That is a dated public reference, not a promise of the current tariff. Hetzner’s original CX plan announcement provides the stated specifications and date.
For current options, the Valebyte VPS catalog is useful when the decision depends on location, storage, dedicated resources, or a specific server purpose. Readers comparing a single-bot deployment can also review the VPS tariff guide for one bot and the cheap VPS comparison for bots.
What We Got Wrong / What Surprised Us
Automatic restart does not equal application recovery. The strongest practical signal is the difference between a dead process and a live-but-broken process. systemd can restart a process that exits; it cannot know that a bot has stopped processing messages while its PID remains active.
The common mistake is choosing Restart=always because it appears safer. For long-running bots, on-failure is usually more informative: a clean exit remains visible as a clean exit, and a broken process triggers recovery. Manual maintenance also becomes predictable because systemctl stop does not immediately fight the operator.
Another surprise is the role of state. A restart may be technically successful while the bot repeats a payment, places a duplicate trade, or processes the same queue item twice. The restart policy is only one part of reliability; the data model decides whether recovery is safe.
Practical Takeaways
- Create a dedicated service account and working directory. Expected outcome: fewer permission surprises and no dependency on a human SSH session. Time: 10–20 minutes. Difficulty: low.
- Deploy a systemd unit with
Restart=on-failureandRestartSec=5s. Expected outcome: recovery from process crashes and host reboots. Time: 15–25 minutes. Difficulty: low. - Add
StartLimitIntervalSec=60andStartLimitBurst=5. Expected outcome: a broken release fails visibly instead of restarting forever. Time: 5 minutes. Difficulty: low. - Use Docker Compose with
restart: unless-stoppedonly when the bot is containerized. Expected outcome: container recovery after daemon or VPS restarts. Time: 20–40 minutes. Difficulty: medium. - Test recovery deliberately. Run
sudo systemctl kill -s SIGKILL mybot.service, inspectsystemctl status, and verify a new process and fresh log entry. Time: 10 minutes. Difficulty: low. - Test the failure that matters. Stop the database, revoke a test token, or block the webhook endpoint in a staging environment. Expected outcome: proof that monitoring catches a live-but-broken bot. Time: 30–60 minutes. Difficulty: medium.
- Separate restart alerts from business alerts. Expected outcome: operators know whether the bot restarted, missed updates, or produced a duplicate side effect. Time: 30–90 minutes. Difficulty: medium.
For Telegram-specific deployment patterns, the auto-restart bot setup guide covers the surrounding VPS workflow. The Telegram bot VPS comparison is more relevant when server location, price, and resource allocation are the main decision.
Try a VPS suited to the bot’s workload
Valebyte is useful when the restart configuration is ready but the server still needs to match the job: a small polling bot, HTTPS webhook, forex tool, VLESS VPN, or game server. Compare plans and server types before committing to a provider whose CPU, location, or storage does not fit the workload.
Choose a VPS using real prices and testing-oriented comparisons, then deploy the bot with a restart policy you can verify.
FAQ
How do I automatically restart a bot on a VPS?
Create a systemd service with Restart=on-failure, reload systemd, enable the unit, and start it. Use Docker Compose with restart: unless-stopped if the bot runs inside a container.
Is systemd better than cron for restarting a bot?
Yes for long-running services. systemd supervises the process continuously, starts it during boot, records exit status, and supports restart delays and rate limits. Cron mainly runs commands on a schedule and may miss failures between scheduled checks.
Why does Docker show an unhealthy bot without restarting it?
Docker health checks report status but do not automatically terminate an unhealthy container. The application must exit, or an external supervisor must act on the failed health check, before a restart policy can recover the container.
Can Telegram lose messages while the bot restarts?
Telegram stores incoming bot updates until delivery, but its official Bot API documentation states that updates are not kept for more than 24 hours. Short restarts are therefore recoverable in many polling setups, but database state, duplicate processing, and webhook failures still require application-level handling.
slipjar.app
The slipjar.app team writes about hosting, servers and infrastructure in plain language.