Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Webhooks and Hosting

Hosting and Process Management for Bots

Run a bot reliably: environment config validation, health checks, graceful shutdown on SIGTERM, restart policies, systemd and Docker, and where each bot type can be hosted.

A bot that works on your laptop is not yet a bot that stays online. Hosting adds questions: where does the process run, what restarts it when it crashes, how does it learn its token, how do you deploy a new version without dropping messages? This lesson answers them in a platform-neutral way and builds the small pieces of code that make a bot a good citizen of any host.

Where can a bot live?

Bot type Needs Typical hosts
Discord gateway bot an always-on process with a WebSocket VPS, container service, home server, Raspberry Pi
Telegram long polling an always-on process, outbound HTTPS only the same, even behind a home router
Telegram webhook public HTTPS endpoint VPS behind nginx/Caddy, container platform, serverless
Discord interactions only public HTTPS endpoint serverless functions, edge workers, any web host

A gateway bot cannot run on pure "scale to zero" serverless because a sleeping function has no open socket. Webhook bots can, because a request wakes them.

Free tiers change often, so check current terms before committing. Whatever you pick, keep the bot portable: configuration in environment variables, data in a mounted folder or external database, no hard-coded paths.

Configuration from the environment

Tokens and settings should come from environment variables, never from source code (see token and secret safety). Validate them once at startup and fail loudly, so a typo shows up in the first second, not after the first user message.

Node.js A config loader that fails fast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Collecting all problems before throwing saves the "fix one, restart, find the next" loop. Printing only the first few characters of a secret is fine in logs; printing it whole is not.

Health checks

Platforms and load balancers need a cheap way to ask "are you alive?". Expose a tiny HTTP endpoint, even on a polling bot. Make it report something real, such as the time of the last successful poll, instead of always returning ok.

Graceful shutdown

Hosts stop your process with SIGTERM (and force-kill with SIGKILL after about 10 to 30 seconds). A good bot uses those seconds to stop taking new work, finish what is in flight, flush its database and close connections. Otherwise every deploy risks half-processed messages.

Node.js Health endpoint and graceful shutdown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The key idea: server.close() stops new connections but lets existing requests finish, and the counter lets you wait for background work that the server does not know about. For a polling bot, set a flag that makes the loop stop after the current batch.

Also handle the two last-resort events so a bug logs a clear line instead of dying silently:

NODE
process.on("unhandledRejection", (reason) => { console.error("unhandled rejection", reason); });
process.on("uncaughtException", (err) => { console.error("uncaught", err); process.exit(1); });

After an uncaught exception, the process state is unreliable. Exit and let the supervisor restart you.

Supervisors: who restarts the bot?

You never rely on "I will notice it is down". Use a supervisor that restarts on crash and starts on boot.

systemd unit (Linux VPS), read-only:

INI
[Unit]
Description=My bot
After=network-online.target

[Service]
User=bot
WorkingDirectory=/opt/mybot
EnvironmentFile=/etc/mybot.env
ExecStart=/usr/bin/node src/index.js
Restart=on-failure
RestartSec=5
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target

EnvironmentFile keeps secrets out of the repository and out of the unit file; set its permissions to 600.

Docker, read-only (see the Docker tutorial on this site for the details):

DOCKERFILE
FROM node:24-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY src ./src
USER node
ENV NODE_ENV=production
CMD ["node", "src/index.js"]

Run it with docker run -d --restart unless-stopped --env-file .env -v botdata:/app/data mybot. The volume keeps your SQLite file when the container is replaced.

Zero-downtime deploys

For a single polling or gateway process, a deploy means a few seconds of downtime. That is usually fine because Telegram holds undelivered updates for a while, but commands sent to a Discord bot while it is down simply fail for the user, so keep restarts quick. To go further:

  • Webhook bots can run two instances behind a proxy and replace them one at a time.
  • Discord gateway bots that reach thousands of servers must be sharded; Discord requires sharding at 2,500 guilds. Each shard is a separate connection, usually a separate process.
  • Never run two copies of a polling bot against the same token by accident. Telegram answers the second with 409 Conflict.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Discord gateway bot not run on a scale-to-zero serverless function?

    The gateway pushes events over an open connection; if the platform freezes the process, the connection is lost.
  2. 2. What should a bot do when it receives SIGTERM?

    Hosts send SIGTERM before a forced kill; use the grace period to finish cleanly.
  3. 3. Why validate all environment variables at startup?

    Failing fast with a clear message is far easier to debug than an obscure error later.
  4. 4. After an uncaughtException, the best action is:

    Program state may be inconsistent after an unexpected error; a restart gives a clean state.

Summary

  • Match the host to the bot type: always-on for gateway and polling bots, public HTTPS for webhooks.
  • Read configuration from the environment, validate it once and fail fast.
  • Expose a health endpoint that reports real liveness and handle SIGTERM with a graceful drain.
  • Let systemd or Docker restart the process; keep data on a volume.
  • Plan for sharding at scale and never run two pollers on one token.

Next: Token and secret safety