Post

Precise FloodWait Handling in Pyrogram: Making sleep_threshold Work as Expected

Precise FloodWait Handling in Pyrogram: Making sleep_threshold Work as Expected

Background

When interacting with the Telegram API, developers often encounter rate limits, which result in FloodWait or FloodPremiumWait errors. These errors indicate that the client must wait a certain number of seconds before making further requests. Pyrogram, like many Telegram client libraries, provides a mechanism to automatically handle these waits in its invoke() method, using a parameter called sleep_threshold.

The Old Behavior

Previously, the relevant code in the invoke() method looked like this:

1
2
if amount > sleep_threshold >= 0:
    raise

This logic was intended to control whether the client should sleep (wait) for the duration specified by the FloodWait, or immediately raise the exception to the caller. The idea was:

  • If amount (the wait time) is greater than sleep_threshold and sleep_threshold is non-negative, raise the exception.
  • Otherwise, sleep for amount seconds and then continue.

However, this approach had a subtle flaw: when sleep_threshold was set to 0, the client would still sleep for the full FloodWait duration instead of raising the exception immediately. This was counterintuitive, especially for advanced bot developers who want to handle rate limits themselves and expect sleep_threshold=0 to mean “never sleep, always raise”.

The New Behavior

To address this, the condition was changed to:

1
2
if sleep_threshold < 0 or amount > sleep_threshold:
    raise

With this new logic:

  • If sleep_threshold is negative, the exception is always raised (never sleeps).
  • If sleep_threshold is zero, the exception is always raised (never sleeps), which is now intuitive and expected.
  • If sleep_threshold is positive, the client will only sleep if the required wait time (amount) is less than or equal to the threshold. If the wait time is longer, the exception is raised.

Why This Matters

This change gives developers precise control over how their bots handle rate limits:

  • Immediate Handling: Setting sleep_threshold=0 now guarantees that the client will never sleep for a FloodWait—the exception is always raised, allowing the developer to implement custom logic (such as queuing, user notifications, or distributed rate limit handling).
  • Custom Thresholds: Developers can set a positive sleep_threshold to allow the client to automatically handle short waits, but raise for longer ones.
  • Opt-out: Setting sleep_threshold to a negative value disables all automatic sleeping, always raising the exception.
This post is licensed under CC BY 4.0 by the author.