# Flood limits

The two limits every sender meets: vaegram's own pacing, and Telegram's `FLOOD_WAIT`.

Both exist so a busy client slows down instead of getting an account-limited `PEER_FLOOD` or a ban. The client paces itself; Telegram answers with a wait when something still goes too fast.

## Example

```rust
use vaegram::prelude::*;
use vaegram::session::{ChatRateLimits, RateCategory, RateLimits};

let limits = RateLimits::default()
    .limit(RateCategory::Message, 20.0, 30.0)
    .per_chat(ChatRateLimits::default());

let _bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
    .rate_limits(limits);
```

## vaegram's limiter

A call that goes through the limiter counts against one category bucket and the `Global` bucket. Categories are `Message`, `Media`, `Query`, `Admin`, `Bulk` and `Account`, chosen from the TL method name; `Client::invoke_for_chat` (and the client's own sends, edits, forwards and copies) also counts against that chat's bucket. File parts are not paced here.

Defaults:

- **A bot gets no limiter** unless `rate_limits` is set, so it goes at network speed.
- **A user account gets `RateLimits::user_account()`**: a message a second, a file every two seconds, a chat change a second, reads in bursts, and the per-chat limits below. Sending like a bot from a user account risks a ban, not just a wait.
- **Before login** the default limiter stands aside. It starts holding a user account back once `getMe` says the account is a user, and stays aside for a bot.

`RateLimits::default()` is the bots' pace: 20 messages a second, 30 in a burst, with no per-chat limits. It is not an unlimited preset, and `limit` refuses a rate that is not finite and above 0. A user account always gets a limiter; the closest to 0.3's none is a high finite rate per category with `no_per_chat()`.

### Per-chat limits

`ChatRateLimits::default()` gives a private chat one message a second with no burst, and a group, supergroup or channel the same plus at most 20 messages in any 60 seconds. Telegram answers `FLOOD_WAIT` above roughly those numbers, which is why they are the defaults.

- `private(rate, burst)`, `group(rate, burst)` and `group_per_minute(Option<u32>)` change them.
- The limiter keeps a bucket per chat by id, up to 10 000 chats; `max_tracked_chats` and `idle_ttl` control eviction.
- `no_per_chat()` takes chat limits off, and `per_chat(..)` puts them on a bot: `RateLimits::default().per_chat(ChatRateLimits::default())`.

```no_run
use vaegram::prelude::*;

# async fn f(bot: &Client) -> Result<()> {
if let Some(limiter) = bot.rate_limiter() {
    println!("global bucket {:.0}% used", limiter.congestion() * 100.0);
}
bot.send_message(7, "one").await?; // waits for chat 7's bucket
bot.send_message(7, "two").await?; // waits about a second more
# Ok(()) }
```

`Client::rate_limiter()` is `None` for an unlimited bot. `RateLimiter::available`, `try_acquire`, `try_acquire_chat`, `tracked_chats` and `update_limits` read or change it while the client runs.

## Telegram's flood waits

A flood wait is a `420` error whose name ends in a number of seconds: `FLOOD_WAIT_30`, `FLOOD_PREMIUM_WAIT_30`, `SLOWMODE_WAIT_30`. It arrives as `Error::Rpc`, and `Error::flood_wait()` reads the duration.

By default (`AutoSleep`) the session sleeps off waits of up to 60 seconds, at most 5 per call, and retries. A longer wait, or the sixth one, goes to the caller as `Error::Rpc`.

```no_run
use std::time::Duration;
use vaegram::prelude::*;

# async fn f(bot: &Client) -> Result<()> {
match bot.send_message(7, "hi").await {
    Ok(_) => {}
    Err(e) if e.is_flood_wait() => {
        let wait = e.flood_wait().unwrap_or(Duration::from_secs(1));
        eprintln!("Telegram says wait {wait:?}");
    }
    Err(e) => return Err(e),
}
# Ok(()) }
```

- `flood_sleep_threshold(d)` sets the longest wait slept off; `Duration::ZERO` surfaces every one.
- `max_flood_sleeps(n)` sets how many a call sleeps off; `0` surfaces every one.
- `retry_policy(NoRetries)` hands every failure to the caller, file parts included.
- A waited-off `FLOOD_WAIT` or `SLOWMODE_WAIT` also holds that chat's next message back by the wait, and no other chat's. The client does this itself for the calls it sends to one chat; raw calls can use `client.rate_limiter().unwrap().penalize_chat(id, wait)`.
- A file part gets four times the tries, since one part stands for a whole transfer.

`FLOOD_WAIT` is not the only account limit: `PEER_FLOOD` (code 400, no number) means the account messaged too many strangers. It is not a wait; `Error::is_peer_flood()` recognizes it, and retrying makes it worse.

A hard cap on volume is separate: `RateLimits::daily_limit(category, max)` allows `max` requests in any 24 hours. The count lives with the client, so a restart forgets it.

## Practical batching

- **Await each send to one chat.** The limiter queues waiters in order; firing a thousand sends at one chat with `join_all` does not go faster, it just parks a thousand tasks in memory.
- **Fan out across chats, not within one.** The per-chat buckets are independent; the global bucket is the ceiling.
- **Do not sleep before every send yourself.** The limiter already does it, and a manual sleep stacks on top. Sleep only where you must react to a surfaced `FLOOD_WAIT`.
- **A repeated update is not a reason to resend.** Redeliveries and catch-up can hand a handler an update twice; make the send idempotent or check the message cache instead of retrying blindly.
- **Keep the default retry settings for long-running bots.** They absorb normal waits; lower the threshold only when a scheduler must reschedule the work itself.
- **Watch `congestion()`.** A global bucket near 100% means the client is at its own ceiling, so more parallelism will not help.

## Common mistakes

- Expecting a bot to be paced by default. It is not; call `rate_limits(..)`.
- Setting `RateLimits::default()` on a user account to "remove limits". That is 20 messages a second from a person and is a ban risk.
- Matching on `Error::Rpc` and comparing `name == "FLOOD_WAIT_30"`. Use `is_flood_wait()` and `flood_wait()`; the number is split into `RpcError::value`.
- Retrying `PEER_FLOOD` on a timer. It is lifted by Telegram, not by waiting out a number.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/session/struct.RateLimits.html) for `RateLimits`, `ChatRateLimits` and `RateLimiter`.
- [Errors](/docs/errors.md) for `Error`, `RpcError` and retry policy.
- [Sending messages](/docs/sending-messages.md) for the calls that count against the limits.