Initial /start Command Delay in Telegram Bot Hosted on Vercel

I created a Telegram bot using Node.js and Telegraf that I deployed on Vercel. This bot features a referral system that verifies a user’s registration status through my backend API.

Currently, I am encountering a major issue where the first invocation of the /start command, after the bot has been idle, results in a significant delay in response. Subsequent commands are processed swiftly and without delay.

This initial lag disrupts my referral registration process because:

  • A user activates the referral link and sends the /start command.
  • The bot takes a long time to reply.
  • The user is registered while waiting for the response.
  • When the bot eventually processes the /start command, the referral association is lost.
const { Telegraf } = require('telegraf');
const fetch = require('node-fetch');
require('dotenv').config();

const botInstance = new Telegraf(process.env.BOT_TOKEN);

botInstance.start(async (context) => {
  const inviterCode = context.startPayload;
  const userId = context.from.id.toString();
  const displayName = context.from.username || 'Anonymous';
  const hasPremium = context.from.is_premium || false;

  if (!inviterCode) {
    await context.replyWithPhoto(
      { url: 'https://example.com/welcome.jpg' },
      {
        caption: '🎉 **Join Our Community** 🎉',
        parse_mode: 'Markdown',
        reply_markup: {
          inline_keyboard: [
            [{ text: 'Follow Channel', url: 'https://t.me/mychannel' }],
            [{
              text: 'Open App',
              web_app: { url: 'https://myapp.vercel.app' }
            }]
          ]
        }
      }
    );
    return;
  }

  try {
    const checkUser = await fetch(
      `${process.env.API_BASE}/users/${userId}`
    );

    if (!checkUser.ok) {
      await fetch(
        `${process.env.API_BASE}/invite`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            newUserId: userId,
            inviterCode: inviterCode,
            premium: hasPremium,
            name: displayName
          })
        }
      );
    }
  } catch (err) {
    console.log('Registration failed:', err);
  }

  await context.replyWithPhoto(
    { url: 'https://example.com/success.jpg' },
    {
      caption: '✅ **Welcome Aboard** ✅',
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: 'Join Channel', url: 'https://t.me/updates' }],
          [{
            text: 'Start App',
            web_app: { url: 'https://webapp.vercel.app' }
          }]
        ]
      }
    }
  );
});

const initializeBot = async (expressApp) => {
  const webhook = await botInstance.telegram.getWebhookInfo();
  
  if (!webhook.url) {
    await botInstance.telegram.setWebhook(
      `${process.env.DOMAIN}/webhook/${process.env.BOT_TOKEN}`
    );
  }

  expressApp.post(`/webhook/${process.env.BOT_TOKEN}`, (request, response) => {
    botInstance.handleUpdate(request.body, response);
  });
};

module.exports = initializeBot;

After the first slow response, the bot functions well. I suspect this delay may be due to Vercel’s serverless architecture entering a sleep state, but I am unsure how to resolve the timing issue for referrals. Has anyone else experienced similar challenges with their Telegram bots on Vercel?

Yeah, that’s a classic cold start problem with Vercel’s serverless functions. When your bot sits idle, the function shuts down and takes time to spin back up on the first request. I hit the same issue with my payment bot and found a workaround that worked for me. Set up a simple ping to keep your function warm during busy hours. Use a cron job to hit your webhook every 10-15 minutes without actually triggering the bot logic. For the referral timing, try a queue system to store referral data before processing it. Even if the first response is slow, you won’t lose the referral connection. I used Redis and it fixed most of my timing issues. If your bot gets decent traffic, you might want to switch to Railway or Render for always-on hosting - kills cold starts completely.

Cold starts kill referrals. I had the same issue - fixed it by storing the referral code in session storage right away, then processing it once the bot’s warmed up. Also throw maxDuration: 30 in your vercel config so you don’t timeout on slow starts.

Cold starts are definitely your problem. Had the same issue with my referral bot - the delay was killing conversions. Here’s what fixed it: restructure your webhook handler to acknowledge Telegram’s request immediately, then handle the referral logic async. Stops those timeout issues dead. I also used Vercel’s edge config (or just a simple JSON file) to cache the referral payload before the backend processes it. The trick is separating the instant response from database operations. You could even move just the webhook endpoint to Cloudflare Workers - way faster cold starts - while keeping your main logic on Vercel. Store the referral data temporarily and process it once your main function warms up.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.