TSocial TSocial
Open in Telegram
Better in TelegramOpen in Telegram

Connect Your Backend to a Telegram Bot: A Practical Architecture

· 4 min read · 18+ readers

Connect Your Backend to a Telegram Bot: A Practical Architecture: TSocial guide cover card

A bot icon bot on its own is a chat interface. Most useful bots connect to a backend: a database of users and orders, an code icon API for content, a payment system. This guide describes a simple, reliable way to connect them. The ideas hold for any language and framework.

The three pieces

  1. Telegram. send icon (paper plane) Sends updates and receives your method calls.
  2. Bot service. A small program that receives updates, decides what they mean and calls Telegram back.
  3. Backend. Your database and business logic. It may be the same program as the bot service, or a separate API.

For a small project, one program can be all three. Separate them when different people or scaling needs appear.

Identify users correctly

Telegram gives every account a numeric id. That number is permanent and unique. Usernames can be changed or removed, so never use them as keys. Store:

  • telegram_id (a big integer, so use a 64-bit type).
  • first_name, username and language_code as optional, updatable fields.
  • created_at and last_seen_at.

On every update, upsert the user:

insert into users (telegram_id, username, first_name, last_seen_at)
values ($1, $2, $3, now())
on conflict (telegram_id) do update
set username = excluded.username, first_name = excluded.first_name, last_seen_at = now();

Chat ids for groups and channel megaphone icon channels are also integers and can be negative. Store them as 64-bit integers too.

Handle updates safely

  1. Verify the request. Check the webhook secret header. See webhook setup.
  2. Acknowledge fast. Return 200 quickly.
  3. De-duplicate. Keep the last handled update_id, or insert it into a table with a unique key and ignore repeats.
  4. Route. Look at which field exists: message, callback_query and so on.
  5. Act. Update the database, then call Telegram.

A small table helps:

create table processed_updates (update_id bigint primary key, seen_at timestamptz default now());

Prune it regularly.

Keep slow work off the request path

If a handler calls a slow API or generates a large file, push a job onto a queue and let a worker process it. The webhook handler only stores the update and returns. Queues can be as simple as a database table with a status column, or a managed queue service.

Sending messages from the backend

Your backend may need to message users when something happens: an order shipped, a post was approved. Calls go to sendMessage with the stored telegram_id as chat_id. Rules to follow:

  • The user must have started the bot, otherwise Telegram returns an error such as 403.
  • Handle 403 Forbidden: bot was blocked by the user by marking the user as unreachable and stopping further sends.
  • Respect rate limits. See rate limits and flood control.

Linking a web account to a Telegram user

If you also have a website or a Mini App icon (grid) Mini App, the safest way to link icon link accounts is to let Telegram prove who the user is:

  • In a Mini App, validate initData. See initData validation.
  • On a website, use the Login Widget. See Login Widget.
  • From the bot, send a one-time link containing a random token, and bind it to the Telegram id when the user presses Start with that token. See deep links.

Never trust a Telegram id sent by the browser without verification.

Configuration and secrets

Use environment variables for the bot token, webhook secret and database URL. Keep separate tokens for development and production bots, so testing never touches real users. See keeping your token safe.

Deploying without dropping updates

  • Telegram retries failed deliveries, so brief restarts are survivable.
  • With long polling, stop the old process before the new one starts, to avoid 409 errors.
  • Run database migrations before code that needs them.
  • Keep a way to roll back.

Monitoring

Log each update id, type and outcome. Watch getWebhookInfo for errors and pending counts. Alert on spikes in 5xx responses and on Telegram errors such as 429.

Quick checklist

  • Users stored by numeric telegram_id as 64-bit integers.
  • Updates verified, acknowledged quickly and de-duplicated.
  • Slow work moved to a queue.
  • Blocked users marked inactive.
  • Accounts linked only through verified Telegram data or one time tokens.
  • Separate dev and production bots.
  • Logs show update id, type and outcome.
  • Migrations run before dependent code is deployed.

Plan for growth

Start with one service and one database. When traffic grows, separate the webhook receiver from the workers, add a queue and index your user table by telegram_id. These steps are usually enough for a long time.

Frequently asked questions

Should the bot and the API be separate services?

Not at first. Split them when you need to scale or deploy them independently.

What database should I use?

Any reliable database works. Use one you can back up and query easily.

How do I handle two admins editing at once?

Use database transactions and optimistic checks, as in any web application.

Do I need a framework?

No, but a bot library helps with routing and types. See creating a bot step by step.

Related guides

More in Build on Telegram

All topics: Build on Telegram · Guide index · Explore Telegram · About TSocial

Connect Your Backend to a Telegram Bot: A Practical Architecture | TSocial