A Telegram Webhook on AWS Lambda or a Small Server
· 4 min read · 18+ readers

A webhook handler is a small HTTP endpoint. Two cheap and common ways to run one are an AWS Lambda function with a function URL and a small Node server on a virtual machine. This guide shows both, with the same safety checks. It describes the general shape, and you should read the current documentation of your cloud provider for exact setup steps and pricing. We do not run or recommend any particular account setup here.
What the endpoint must do
- Accept POST requests with a JSON body.
- Check the
X-Telegram-Bot-Api-Secret-Tokenheader against your stored secret. - Respond with a 2xx status quickly.
- Process the update, ideally after responding or through a queue.
- Never log the bot token or the secret.
See webhook setup for registering it with setWebhook.
Option A: AWS Lambda with a function URL
A Lambda function can have a function URL, which is an HTTPS address that invokes it directly. With a URL type that needs no AWS authentication, anyone can call it, so the secret header check is essential.
// index.mjs (Node.js runtime)
export const handler = async (event) => {
const method = event.requestContext?.http?.method;
if (method !== "POST") return { statusCode: 405, body: "" };
const got = event.headers?.["x-telegram-bot-api-secret-token"]; // header names arrive lowercase
if (!got || got !== process.env.WEBHOOK_SECRET) return { statusCode: 401, body: "" };
const update = JSON.parse(event.isBase64Encoded ? Buffer.from(event.body, "base64").toString() : event.body);
// Do very little here, push to a queue or handle a quick reply
await handleUpdate(update);
return { statusCode: 200, body: "ok" };
};
Points to remember:
- Set the secrets as environment variables or fetch them from a secrets service.
- Configure a timeout that is longer than your typical work but not huge.
- Use reserved concurrency to cap how many copies run at once, so a flood cannot overwhelm your database or exceed
Telegram limits.
- If handlers take long, send the update to a queue and let a second function process it.
- Cold starts can add delay on the first request. Keep the bundle small.
- Watch the logs for errors, but never print tokens.
Then register the function URL with setWebhook.
Option B: A small Node server
A tiny server on a virtual machine behind a reverse proxy gives you a constant process and no cold starts.
import http from "node:http";
import crypto from "node:crypto";
const secret = process.env.WEBHOOK_SECRET;
const ok = (a = "", b = "") => a.length === b.length && crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
http.createServer((req, res) => {
if (req.method !== "POST" || req.url !== "/telegram") return res.writeHead(404).end();
if (!ok(String(req.headers["x-telegram-bot-api-secret-token"] ?? ""), secret)) return res.writeHead(401).end();
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
res.writeHead(200).end("ok");
queue.push(JSON.parse(Buffer.concat(chunks).toString())); // processed by a worker loop
});
}).listen(3000, "127.0.0.1");
Run it under a process manager and put a reverse proxy in front for HTTPS. The proxy terminates TLS with a valid certificate and forwards to 127.0.0.1:3000. Limit the request body size.
Choosing
| Question | Lambda | Small server |
|---|---|---|
| Traffic is low or bursty | Great fit | Fine |
| You want zero server upkeep | Yes | No |
| You need long running jobs | Needs a queue | Easy |
| Predictable monthly cost | Usage based | Fixed |
| Cold start delay matters | Can matter | None |
Idempotency and retries
Telegram may deliver the same update twice, and functions may be retried. Record update_id in your database with a unique constraint and ignore repeats. This is especially important for payments and for anything that sends messages.
Rate limits
Parallel functions can send too fast. Use a queue with a concurrency limit, and handle 429 with retry_after. See rate limits.
Observability
- Log update id, type and result.
- Alarm on errors and on duration.
- Check
getWebhookInforegularly forlast_error_messageandpending_update_count.
Testing
Send a fake update to your endpoint with the right secret and with a wrong one. The wrong one must return 401. Then send a real message from a second account. See testing your bot.
Quick checklist
- HTTPS endpoint with a valid certificate or function URL.
- Secret header checked before any work.
- 200 returned quickly.
- update_id stored to ignore repeats.
- Concurrency capped to protect the database and Telegram limits.
- Errors and duration monitored.
- Secrets in the platform's secret store.
- Tested with a wrong secret and a real message.
Cost awareness
Serverless pricing is based on usage, so a bug that retries endlessly can cost more than expected. Set budgets and alarms, and test failure paths so that an error does not trigger a loop of retries.
Frequently asked questions
Do I need API Gateway for Lambda?
A function URL is one simple option. API Gateway or other front doors add features and cost. Choose according to your needs.
Can Lambda use a custom domain?
Yes, through a front door service. Check the documentation.
Is a free tier enough?
For a small bot it often is, but terms change. Check current limits.
What about Cloudflare Workers or other platforms?
The same rules apply: verify the secret header, reply fast and handle duplicates.
Related guides

Set Up a Telegram Webhook with HTTPS and a Secret Token
Register a webhook with setWebhook, protect it with secret_token, check getWebhookInfo, pick allowed_updates and handle retries, with a short Node example.

Host a Telegram Bot Cheaply: Options and Trade-offs
Where to run a Telegram bot for little money: your own computer, a small server, serverless functions and container platforms, with reliability and security tips.

Webhook vs Long Polling for Telegram Bots
Compare getUpdates long polling and setWebhook for Telegram bots: how each works, trade-offs, limits, when to switch and how to migrate safely.

Telegram Bot Rate Limits and Flood Control
Understand Telegram's bot limits: messages per second and per chat, 429 errors and retry_after, broadcasting safely, queues and backoff, with a Node example.

Connect Your Backend to a Telegram Bot: A Practical Architecture
How to wire a bot to your own backend: receiving updates, mapping Telegram users to accounts, queues, database design, idempotency and safe deploys.

Add a Bot as Channel Admin and Post to Your Channel
Give a bot posting rights in a Telegram channel, find the chat id, send posts with sendMessage, schedule them from code and fix common permission errors.
More in Build on Telegram
- Bot Privacy Mode and Group Admin Rights Explained
- BotFather Commands: What Each One Does
- Common Telegram Bot Errors and How to Fix Them
- Connect a Bot to Your Telegram Business Account (Chatbot Mode)
All topics: Build on Telegram · Guide index · Explore Telegram · About TSocial