Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

telegram.error.TimedOut: Timed out — how to fix Telegram bot timeouts

telegram.error.TimedOut: Timed out in python-telegram-bot, TelegramNetworkError: HTTP Client says - Request timeout error in aiogram, and HttpError in grammY all mean the bot's request to the Bot API got no answer in time. Most often a file upload needs longer than the default timeout, or the connection, DNS or a proxy on the way to api.telegram.org is slow. Raise the timeouts for media, retry with backoff, and test the connection with curl.

By Livops team, the people who build and run LivopsUpdated

The errors, as each library raises them:

Library What you see
python-telegram-bot telegram.error.TimedOut: Timed out[2][3]
aiogram 3 aiogram.exceptions.TelegramNetworkError: HTTP Client says - Request timeout error[8][9]
grammY HttpError: Network request for 'sendVideo' failed![14][15]

python-telegram-bot has a second variant, TimedOut: Pool timeout: All connections in the connection pool are occupied. Request was *not* sent to Telegram. ...[3]. In grammY, the reason sits in the error’s error property — for a timeout, “Request to ‘sendVideo’ timed out after 500 seconds” — and is added to the message only when sensitiveLogs is on, which it is not by default[14][15].

This page explains what the timeouts are, the causes from the most common, and the fixes: longer timeouts for files, retries with backoff, and a curl check of the connection to api.telegram.org. It ends with how it looks on Livops.

What does the error mean?

Every Bot API call is an HTTPS request to https://api.telegram.org/bot<token>/METHOD_NAME[1]. The library gives each request a time limit, and when the limit passes with no answer, it stops waiting and raises. The defaults differ a lot:

Library Default limits
python-telegram-bot connect 5 s, write 5 s, read 5 s, pool 1 s; for requests that upload files, write is media_write_timeout, 20 s[3]
aiogram 3 60 s for the whole request[10][9]
grammY 500 s for the whole request (8 minutes 20 seconds)[15]

python-telegram-bot’s limits are per phase[3]: connect is the time to open a connection, write the time to send the request or upload the file, read the time to wait for Telegram’s answer, and pool the time to wait for a free connection in the bot’s own pool. They are short, so a slow phase trips them first; TimedOut is a subclass of NetworkError, and the original httpx exception is on __cause__[2].

A timeout does not tell you what happened to the request. It may never have reached Telegram, or Telegram may have done it and the answer was lost — which matters for retries below.

Causes, most common first

1. A file upload takes longer than the write timeout

sendVideo, sendDocument and the other upload methods take files up to 50 MB, and photos up to 10 MB[1]. Uploading tens of megabytes within python-telegram-bot’s 20-second media write timeout[3], or aiogram’s 60 seconds for the whole request[9][10], needs a fast uplink. If only the calls that send files time out while text messages go through, this is the cause. python-telegram-bot’s own wiki suggests passing a bigger write_timeout when sending big files[7].

2. A slow network path: DNS, the route, the connection

When connecting is what times out — or when every kind of call fails now and then — the problem is between your server and api.telegram.org: a slow DNS resolver, lost packets, a busy network. The curl check below shows which step is slow.

3. A proxy that is slow or down

All three libraries can send requests through a proxy, and a slow or dead proxy shows up as timeouts. python-telegram-bot takes the proxy from ApplicationBuilder().proxy(...), and its HTTP client also reads it from the HTTPS_PROXY or ALL_PROXY environment variables[3][4] — so a variable left in the environment applies even when the code mentions no proxy. aiogram takes it as AiohttpSession(proxy=...)[13]. grammY takes a proxy agent in baseFetchConfig, and its documentation says to set the agent’s own timeout, which closes stalled connections that grammY cannot close on its own[19].

4. A long-polling timeout longer than the client’s timeout

getUpdates takes a timeout in seconds for long polling; the default, 0, is short polling, which Telegram says is for testing only[1]. With long polling the request stays open while there are no updates, so the HTTP client’s read timeout must be longer than the polling timeout, or every quiet poll ends in a timeout.

The libraries take care of this: python-telegram-bot adds the long-polling timeout to the read timeout for getUpdates[5], aiogram sets the getUpdates request timeout to the session timeout plus polling_timeout[12], and grammY polls with 30 seconds by default[16] under its 500-second limit[15]. It bites hand-written polling loops: a client with a 10-second timeout and getUpdates?timeout=30 times out on every quiet poll.

The libraries also retry failed polls on their own. python-telegram-bot retries a timed-out getUpdates at once, and waits after other network errors, longer each time, up to 30 seconds[6]. aiogram logs Failed to fetch updates - TelegramNetworkError: HTTP Client says - Request timeout error, backs off and tries again, and logs Connection established when it works again[12]. grammY waits 3 seconds and retries[16]. A few such lines during a network hiccup are harmless; timeouts from calls in your handlers are yours to handle.

5. Too many requests at once: python-telegram-bot’s pool timeout

python-telegram-bot keeps a pool of connections, 256 by default for the bot’s requests[4]. With a finite pool timeout, sending more requests at once than there are connections raises TimedOut with the “Pool timeout” message — and that request was not sent to Telegram[3]. A broadcast that fires thousands of sends with asyncio.gather is the usual way to get there. Send in smaller batches, or change connection_pool_size and pool_timeout on the builder[4].

How to fix it

Check the connection to api.telegram.org with curl

Run this on the machine where the bot runs:

curl -sS -o /dev/null --connect-timeout 10 \
  -w 'dns %{time_namelookup}s  tcp %{time_connect}s  tls %{time_appconnect}s  total %{time_total}s  http %{http_code}\n' \
  "https://api.telegram.org/bot$BOT_TOKEN/getMe"

getMe is Telegram’s simple method for testing a bot’s token and needs no parameters[1]. The -w variables are the time until name resolving finished, until the TCP connection was made, until the TLS handshake finished, and the total, all in seconds since the start, plus the HTTP code[20]; --connect-timeout limits only the connection phase[20].

  • A large dns time: the resolver is slow. Try another one.
  • A large tcp or tls time, or no connection within 10 seconds: the network path or a proxy.
  • Fast numbers and http 200, but the bot still times out: the bot’s timeouts are too short for what it does, or the bot goes through a proxy that curl does not.
  • http 401: the token is wrong, not the network.

Keep the token out of anything you paste into a chat or an issue.

python-telegram-bot: raise the timeouts that fail

For every request, on the builder[4]:

app = (
    Application.builder()
    .token(TOKEN)
    .connect_timeout(10)
    .read_timeout(20)
    .write_timeout(20)
    .media_write_timeout(120)
    .build()
)

For one call — a large video, say — pass the timeouts to the method; the send_* methods take read_timeout, write_timeout, connect_timeout and pool_timeout[5]:

with open("clip.mp4", "rb") as f:
    await context.bot.send_video(chat_id, video=f, write_timeout=300, read_timeout=60)

Long polling has its own set: get_updates_read_timeout, get_updates_connect_timeout and the others, plus get_updates_proxy[4].

aiogram 3: a longer session timeout, or a longer one per call

from aiogram import Bot
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.types import FSInputFile

bot = Bot(TOKEN, session=AiohttpSession(timeout=120))   # every request

await bot.send_video(chat_id, FSInputFile("clip.mp4"), request_timeout=300)  # one call

The session’s timeout is the request timeout for the whole session, 60 seconds by default[10], and AiohttpSession passes it on[9]. Bot methods take request_timeout for a single call[11].

grammY: look inside HttpError, and retry with auto-retry

grammY’s 500-second limit is also the limit hard-coded in the official Bot API server, so raising it only makes sense with your own Bot API server[15]. So in grammY an HttpError is rarely about upload time: grammY’s documentation describes it as grammY being unable to contact the Bot API server, with the reason in the error property[17]. Without an error handler, grammY’s default one stops a bot started with bot.start()[17], so add one:

import { GrammyError, HttpError } from "grammy";

bot.catch((err) => {
  const e = err.error;
  if (e instanceof HttpError) console.error("Could not contact Telegram:", e.error);
  else if (e instanceof GrammyError) console.error("Error in request:", e.description);
  else console.error("Unknown error:", e);
});

The auto-retry plugin retries requests that fail with an HttpError too, not only rate limits and server errors, with exponential backoff starting at 3 seconds and capped at one hour[18]:

import { autoRetry } from "@grammyjs/auto-retry";

bot.api.config.use(autoRetry());

maxRetryAttempts limits the retries, and rethrowHttpErrors turns retries for network errors off[18].

Python: retry with backoff, and think about duplicates

python-telegram-bot’s TimedOut is a NetworkError[2]; aiogram raises TelegramNetworkError for timeouts and other client errors[8][9]. A small helper covers both:

import asyncio, random
from telegram.error import NetworkError          # aiogram: from aiogram.exceptions import TelegramNetworkError

async def with_retries(call, attempts=4, base=1.0):
    for i in range(attempts):
        try:
            return await call()
        except NetworkError:                       # aiogram: except TelegramNetworkError
            if i == attempts - 1:
                raise
            await asyncio.sleep(base * 2 ** i + random.random())

tg_file = await with_retries(lambda: context.bot.get_file(file_id))

Retry freely for calls that only read, such as getFile or getChat. For calls that send, a timeout may hide a message that was delivered, and a retry can post it twice; retry those only where a duplicate does no harm. The pool-timeout TimedOut is always safe to retry, because the request was not sent[3]. Rate limits are a different error with their own wait time; see 429 Too Many Requests.

Upload big files once, then send the file_id

A file that is already on Telegram’s servers can be sent again by its file_id, with no upload and no size limit[1]. Save the file_id from the Message your first upload returned and use it next time: the slow, timeout-prone step then happens once. The type cannot change on resend — a video stays a video[1]. More on file limits in Bad Request: file is too big.

On Livops

  • Where to look. The error lines are on the project’s Logs page; livops logs <service> -f follows them from the terminal (CLI), and get_logs over MCP returns up to 5000 lines. A timeout in a handler shows its traceback there; aiogram’s polling lines show the retries.
  • Timeouts as variables. Read the timeouts from environment variables — MEDIA_WRITE_TIMEOUT, say — and set them in Variables. Variables are passed to a service when it starts, so new values take effect on the next deploy, or at once if you restart the service. See Variables.
  • If a timeout stops the bot at start. An uncaught timeout in startup code — in post_init, say — ends the process, and the deploy fails as start_failed with the traceback on the Logs page. See The app did not start.
  • Large files in a bucket. A storage bucket holds uploads, reports and backups, and is private by default with temporary signed links (presigned URLs). A link in the message can replace an upload that keeps timing out.

A bot costs 19 credits a month (19,000 so’m); see Pricing.

Questions

What does telegram.error.TimedOut Timed out mean?

python-telegram-bot sent a request to the Bot API and one of its time limits ran out before the answer came: connecting, sending the request or file, waiting for the answer, or waiting for a free connection. The defaults are short, 5 seconds for most of them and 20 seconds for uploading a file, so a big upload or a slow connection is enough to hit them.

How do I increase the timeout in python-telegram-bot?

Set it on the ApplicationBuilder with connect_timeout, read_timeout, write_timeout and media_write_timeout, or pass write_timeout and read_timeout to a single call such as send_video. For long polling there are separate get_updates_ variants of the same settings.

How do I change the request timeout in aiogram 3?

aiogram's session allows 60 seconds per request by default. Create the bot with Bot(token, session=AiohttpSession(timeout=120)) to change it for every request, or pass request_timeout to a single method call, for example bot.send_video(..., request_timeout=300).

Why does sending a video time out when text messages work?

A text message is a small request; a video can be tens of megabytes that have to be uploaded within the write timeout, and python-telegram-bot allows 20 seconds for that by default. Raise the timeout for media, or upload the file once and resend it later by its file_id, which needs no upload.

Is it safe to retry after a timeout?

Not always. A timeout only means the answer did not arrive in time, so a message or file may already have been sent, and a retry can send it twice. Retry freely for reads such as getFile; for sends, retry only where a duplicate does no harm. python-telegram-bot's pool timeout is the exception: its message says the request was not sent at all.

Why does aiogram log Request timeout error while polling?

aiogram logs Failed to fetch updates with the error when a getUpdates request fails, waits with a growing backoff and tries again, and logs Connection established once a request succeeds. A few of these lines during a network hiccup are harmless; a steady stream means the server cannot reach api.telegram.org reliably.

How do I check whether my server can reach api.telegram.org?

Run curl against the getMe method with your bot token on the machine where the bot runs, and print curl's timing variables. The DNS, TCP connect and TLS handshake times show which step is slow, and the HTTP code shows whether the token works.

Sources

  1. Telegram Bot API — Making requests, getUpdates, getMe, Sending files (core.telegram.org). Checked .
  2. python-telegram-bot source — telegram/error.py (raw.githubusercontent.com). Checked .
  3. python-telegram-bot source — telegram/request/_httpxrequest.py (raw.githubusercontent.com). Checked .
  4. python-telegram-bot source — telegram/ext/_applicationbuilder.py (raw.githubusercontent.com). Checked .
  5. python-telegram-bot source — telegram/_bot.py (raw.githubusercontent.com). Checked .
  6. python-telegram-bot source — telegram/ext/_utils/networkloop.py (raw.githubusercontent.com). Checked .
  7. python-telegram-bot wiki — Handling network errors (github.com). Checked .
  8. aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Checked .
  9. aiogram source — aiogram/client/session/aiohttp.py (raw.githubusercontent.com). Checked .
  10. aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Checked .
  11. aiogram source — aiogram/client/bot.py (raw.githubusercontent.com). Checked .
  12. aiogram source — aiogram/dispatcher/dispatcher.py (raw.githubusercontent.com). Checked .
  13. aiogram documentation — Aiohttp session (docs.aiogram.dev). Checked .
  14. grammY source — src/core/error.ts (raw.githubusercontent.com). Checked .
  15. grammY source — src/core/client.ts (raw.githubusercontent.com). Checked .
  16. grammY source — src/bot.ts (raw.githubusercontent.com). Checked .
  17. grammY — Error Handling (grammy.dev). Checked .
  18. grammY — Retry API Requests (auto-retry) (grammy.dev). Checked .
  19. grammY — Proxy Support (grammy.dev). Checked .
  20. curl — man page (--connect-timeout, --write-out) (curl.se). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your bot

Got a question? — @livops_uz