Prevent Silent Telegram 429 Crashes and Lost Leads in Node.js grammY Bots

Deploying a customer intake or lead collection bot on Telegram seems straightforward until real users start interacting with it simultaneously. A developer writes a simple handler using bot.on('text'), relies on in-memory variables to track whether a user is answering a name or phone prompt, and tests it locally using polling. In a isolated environment, everything runs smoothly.

Once deployed to production, three critical failures emerge:

1. State Leakage: Storing multi-step input states in global objects causes User A's answer to overwrite User B's pending input when two people submit forms at the same time. 2. Insecure Endpoints: Switching from long polling to an open HTTP webhook endpoint allows anyone on the internet to POST fake payload data to your server and forge leads. 3. API Rate Limiting (HTTP 429): Sending notifications or multi-message updates to several leads at once hits Telegram Bot API limits (30 messages per second globally, 1 message per second per individual chat). Node.js unhandled rejections crash the process, leaving update queues stalled.

Here is how to design a production-grade lead intake bot using Node.js and the grammY framework that solves state management, webhook verification, and rate limiting safely.

Isolating Multi-Step Conversations with grammY Sessions

A common anti-pattern in Node.js Telegram bots is keeping track of user state using a global JavaScript object like const userState = {}. When Node processes asynchronous events, concurrent messages mutate this shared object. User A might be on step 2 (providing their phone number), while User B triggers /start and resets the step identifier for everyone.

To collect structured data cleanly, use @grammyjs/conversations. This plugin creates isolated step-by-step wizard functions per chat ID using grammY's session engine.

First, install the necessary packages:

npm install grammy @grammyjs/conversations dotenv

The code below configures grammY, attaches session middleware, registers a conversation plugin, and safely validates user responses before saving them to your data store.

// bot.js
require('dotenv').config();
const { Bot, session } = require('grammy');
const { conversations, createConversation } = require('@grammyjs/conversations');

const token = process.env.BOT_TOKEN;
if (!token) {
throw new Error('BOT_TOKEN environment variable is missing.');
}

const bot = new Bot(token);

// 1. Setup session middleware (required by conversations)
bot.use(session({ initial: () => ({}) }));

// 2. Register the conversation plugin
bot.use(conversations());

/**
* Multi-step lead intake conversation
*/
async function leadIntake(conversation, ctx) {
await ctx.reply('Welcome! What is your full name?');

// Wait for the next text message from THIS specific chat
const nameCtx = await conversation.waitFor('message:text');
const fullName = nameCtx.message.text.trim();

if (fullName.length < 2) {
await ctx.reply('Name is too short. Please restart with /lead.');
return;
}

await ctx.reply(`Thanks, ${fullName}. What is your business email address?`);

const emailCtx = await conversation.waitFor('message:text');
const email = emailCtx.message.text.trim();

// Basic format validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
await ctx.reply('That does not look like a valid email. Please restart with /lead.');
return;
}

// Simulate saving lead to your backend database
await conversation.external(async () => {
console.log('Saving lead to database:', { userId: ctx.from.id, fullName, email });
});

await ctx.reply('Thank you! Your information has been recorded.');
}

// 3. Define the conversation middleware
bot.use(createConversation(leadIntake));

// 4. Command trigger
bot.command('lead', async (ctx) => {
await ctx.conversation.enter('leadIntake');
});

bot.command('start', async (ctx) => {
await ctx.reply('Hi! Use /lead to submit your project details.');
});

// Fallback error handling
bot.catch((err) => {
console.error(`Error while handling update ${err.ctx.update.update_id}:`, err.error);
});

bot.start();

Inside the conversation function, conversation.waitFor('message:text') halts execution *only for the targeted conversation instance*. Under the hood, grammY handles context restoration when the user replies, keeping state isolated to ctx.from.id. Using conversation.external() ensures asynchronous database calls do not re-run unexpectedly if the conversation context is replayed.

Deploying an Express Webhook with Secret Token Verification

Long polling (bot.start()) works for development, but running multiple instances of a long-polling bot in production leads to 409 Conflict errors from Telegram. Switch to webhooks for scalable HTTP request processing.

Exposing an HTTP server without authentication introduces a security flaw: malicious actors can scan your domain and submit crafted payloads directly to your endpoint, bypassing Telegram's architecture completely.

Telegram provides a mechanism to verify incoming webhook requests: the X-Telegram-Bot-Api-Secret-Token header. When setting your webhook URL via the API, you pass a random string as the secret_token. Telegram includes this header in every payload POST request. Your Node.js server must verify this token before passing the payload to grammY.

npm install express

Here is the secure Webhook implementation using Express and grammY's built-in webhookCallback adapter:

// server.js
require('dotenv').config();
const express = require('express');
const { Bot, webhookCallback } = require('grammy');

const token = process.env.BOT_TOKEN;
const webhookSecret = process.env.WEBHOOK_SECRET;

if (!token || !webhookSecret) {
throw new Error('BOT_TOKEN or WEBHOOK_SECRET is missing from environment variables.');
}

const bot = new Bot(token);

bot.command('start', (ctx) => ctx.reply('Webhook mode active!'));
bot.on('message:text', (ctx) => ctx.reply(`Received: ${ctx.message.text}`));

const app = express();
app.use(express.json());

// Custom middleware to enforce Secret Token verification
app.use('/webhook', (req, res, next) => {
const incomingSecret = req.headers['x-telegram-bot-api-secret-token'];
if (incomingSecret !== webhookSecret) {
console.warn('Unauthorized webhook attempt detected. Invalid Secret Token.');
return res.status(403).json({ error: 'Access denied' });
}
next();
});

// Pass authenticated requests to grammY
app.post('/webhook', webhookCallback(bot, 'express'));

const PORT = process.env.PORT || 3000;
app.listen(PORT, async () => {
console.log(`Server listening on port ${PORT}`);

// Programmatically set webhook on launch (or set it manually via curl)
const webhookUrl = `${process.env.HOST_URL}/webhook`;
await bot.api.setWebhook(webhookUrl, {
secret_token: webhookSecret,
});
console.log(`Webhook successfully set to ${webhookUrl}`);
});

If an attacker tries to call your https://your-domain.com/webhook URL directly without the secret header matching process.env.WEBHOOK_SECRET, the middleware drops the connection with an HTTP 403 Forbidden response before grammY processes any data.

Intercepting and Handling Telegram 429 Rate Limits

Telegram limits how fast your bot can make API requests. If your app attempts to reply to hundreds of users at once or execute bulk actions, Telegram returns an HTTP 429 Too Many Requests error with a payload containing retry_after: N.

If your code lacks rate-limiting middleware, grammY throws a GrammyError. In a Node.js process without a custom error handler, this leads to unhandled promise rejections, dropped webhook payloads, and repeated retry delivery loops from Telegram's servers.

To prevent hitches, install the official grammY throttler plugin to queue outbound requests automatically:

npm install @grammyjs/transformer-throttler

Then attach the throttler plugin to your bot's API client instance *before* defining command logic or starting the bot:

// throttler-setup.js
const { Bot } = require('grammy');
const { apiThrottler } = require('@grammyjs/transformer-throttler');

const bot = new Bot(process.env.BOT_TOKEN);

// Configure outbound throttling rules compliant with Telegram API limits
const throttler = apiThrottler({
global: {
maxInInterval: 30, // Max 30 requests per second across all chats
interval: 1000,
},
outbound: {
maxInInterval: 1, // Max 1 message per second to a single chat
interval: 1000,
},
});

// Register API transformer
bot.api.config.use(throttler);

// Fallback Catch block for rare 429 surges exceeding queue capacity
bot.catch(async (err) => {
const ctx = err.ctx;
console.error(`Error handling update ${ctx.update.update_id}:`);
const e = err.error;

if (e.error_code === 429) {
const retryAfter = e.parameters?.retry_after || 1;
console.warn(`Hit 429 rate limit. Telegram requested waiting ${retryAfter} seconds.`);
// Here you can push failed updates to a Redis queue for execution after retryAfter seconds
} else {
console.error('Unknown API error:', e);
}
});

bot.command('broadcast', async (ctx) => {
ctx.reply('Processing request safely without hitting rate limits...');
});

By wrapping bot.api.config.use(throttler), any call to ctx.reply(), bot.api.sendMessage(), or bot.api.editMessageText() passes through an outbound token-bucket queue. If your application sends 10 messages to a single user in a split second, the transformer throttles the calls natively instead of triggering a server rejection.

Production Readiness: Timeouts, Idempotency, and Storage

Moving from a prototype to production requires defensive software design. Keep these rules in mind:

### Webhook Execution Timeouts Telegram expects your server to acknowledge webhooks with an HTTP 200 status code within 60 seconds. If your processing logic (such as generating a PDF report or reaching out to a third-party CRM) takes longer than 60 seconds, Telegram considers the delivery failed and will resend the exact same update repeatedly.

Always offload heavy processing to an asynchronous queue (like BullMQ or Celery) and return an immediate 200 response:

app.post('/webhook', (req, res, next) => {
// Pass to grammY callback; grammY calls res.sendStatus(200) internally when complete
webhookCallback(bot, 'express')(req, res, next);
});

### Update Idempotency Because Telegram retries webhooks on network timeouts, your application may receive the same update_id twice. If your lead generation workflow creates an invoice or sends an email notification, check the update_id against a deduplication store (like Redis with a short TTL) before processing business logic.

### Session Persistence The default session() middleware in grammY uses an in-memory map. If your Node.js application restarts, scales horizontally to multiple instances behind a load balancer, or runs inside Docker containers, in-memory sessions disappear. Use persistent storage layers like @grammyjs/storage-redis or @grammyjs/storage-free-redis so user state survives server redeployments.

Building Telegram integrations with validated multi-step input flows, secure webhook token verification, and proactive throttlers guarantees your Node.js application stays stable under heavy loads.

If you are expanding beyond standard conversational bots into custom web applications embedded inside Telegram, check out BotCreator — studio that ships Telegram bots / Mini Apps. For more low-level payload details on handling webhooks and bot APIs, refer to the documentation at

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.