Deploying a production Telegram bot with Grammy.js
From local polling to webhook-based production deploy on Fly.io with Postgres, sessions, and proper logging.
Grammy.js makes writing a Telegram bot pleasant. Deploying one properly takes a bit more thought. Here’s the setup I use for every production bot I ship.
From polling to webhooks
During development you’ll run your bot in long-polling mode. That’s fine for one user on localhost, but in production you want webhooks — they’re faster and avoid the “who’s connected” problem when you scale.
import { Bot, webhookCallback } from 'grammy';
import express from 'express';
const bot = new Bot(process.env.BOT_TOKEN!);
bot.command('start', (ctx) => ctx.reply('Hi!'));
const app = express();
app.use(express.json());
app.use(`/bot${process.env.BOT_TOKEN}`, webhookCallback(bot, 'express'));
app.listen(process.env.PORT ?? 3000);
Register the webhook once after deploy:
curl -X POST "https://api.telegram.org/bot$BOT_TOKEN/setWebhook" \
-d "url=https://your-app.fly.dev/bot$BOT_TOKEN"
Sessions that survive restarts
The built-in session middleware stores data in memory — fine for a prototype, a disaster in production. Use a real store:
import { session } from 'grammy';
import { PsqlAdapter } from '@grammyjs/storage-psql';
bot.use(session({
initial: () => ({ step: 'idle', cart: [] }),
storage: new PsqlAdapter({ /* ... */ }),
}));
Now when your Fly.io machine restarts at 4am, your users don’t lose their half-finished orders.
Deploy target: Fly.io
I’ve tried Railway, Render, Vercel, Heroku’s successors, and a few VPS providers. For Telegram bots, I keep coming back to Fly.io because:
- Persistent volumes for SQLite if you don’t want Postgres
- Cheap enough to run several bots on the free tier
- Multi-region if you need it later
- Their Postgres add-on is dead simple
A minimal fly.toml:
app = "my-bot"
primary_region = "fra"
[build]
dockerfile = "Dockerfile"
[http_service]
internal_port = 3000
force_https = true
auto_stop_machines = false # keep it warm — webhooks need fast response
auto_start_machines = true
min_machines_running = 1
Note auto_stop_machines = false. If Fly puts your machine to sleep, Telegram will hit a cold webhook, time out, and start disabling your bot. Always keep at least one machine warm.
Logging and error handling
Two things that make maintenance sane:
bot.catch((err) => {
console.error(`Error in ${err.ctx?.update?.update_id}:`, err);
// Forward to Sentry, Axiom, or a logging bot
});
bot.use(async (ctx, next) => {
const start = Date.now();
await next();
console.log(`[${ctx.update.update_id}] handled in ${Date.now() - start}ms`);
});
Wire the error handler to its own Telegram logging channel. You’ll be grateful when something breaks at 3am and you don’t have to SSH anywhere to find out what happened — it’s already in your logs channel.
Health checks
Add a simple /healthz endpoint so Fly’s health checks have something to ping:
app.get('/healthz', (_req, res) => res.json({ ok: true, uptime: process.uptime() }));
That’s the whole production setup. About 200 lines of code from empty folder to deployed bot that can handle thousands of users. Grammy + Fly + Postgres is hard to beat.