# How do I limit how much data my program reads from an untrusted source?
Source: https://ruststudio.org/community/t/82/how-do-i-limit-how-much-data-my-program-reads-from-an-untrusted-source
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, input, denial-of-service | Views: 0

## Short answer
Wrap the reader in Read::take with your limit plus one byte, read into a buffer, and reject the input if the extra byte arrived. Never call read_to_end or read_to_string on an unlimited stream from a client, because a large or endless body will exhaust memory.

## Answer
## Answer
`read_to_end` and `read_to_string` keep reading until the source ends. A client who sends a very large body, or never stops, makes your program allocate until it runs out of memory: a denial of service with no bug in the parser at all.

Put the limit on the reader. `Read::take(n)` returns a reader that stops after `n` bytes. Ask for one byte more than you allow: if that byte arrives, the input was too big.

```rust title=src/main.rs
use std::io::{self, Cursor, Read};

/// Read at most `max` bytes. Fails if the source has more, instead of growing without limit.
fn read_limited<R: Read>(reader: R, max: usize) -> io::Result<Vec<u8>> {
    let mut buf = Vec::new();
    // Ask for one byte more than allowed: if we get it, the input was too big.
    reader.take(max as u64 + 1).read_to_end(&mut buf)?;
    if buf.len() > max {
        return Err(io::Error::new(io::ErrorKind::InvalidData, format!("input is larger than {max} bytes")));
    }
    Ok(buf)
}

fn main() {
    let small = Cursor::new(vec![b'a'; 10]);
    let large = Cursor::new(vec![b'a'; 5000]);
    println!("{:?}", read_limited(small, 1024).map(|v| v.len()));
    println!("{:?}", read_limited(large, 1024).map(|v| v.len()));
}
```

```text
Ok(10)
Err(Custom { kind: InvalidData, error: "input is larger than 1024 bytes" })
```

## How to do it
1. Pick a maximum for each kind of input from what the feature really needs (a login form needs bytes, not megabytes).
2. Apply it where the data is read, and again for anything that expands, such as decompression.
3. Return a clear error (HTTP 413 for web requests) and close the connection.
4. In a web framework, use its built-in body limit rather than reading the body yourself.
5. Combine with timeouts, so a client that sends one byte a minute cannot hold a connection forever.

## Common mistakes
- Checking `Content-Length` only. The header is claimed by the client and may be missing or wrong.
- Limiting the compressed size but not the size after decompression. A small file can expand enormously; limit the output of the decompressor with `take`.
- A limit on the total but not on the number of items, fields or nesting depth.

## Related questions
### What limit should I choose?
The smallest that serves the feature. You can raise it for the routes that need more; a global generous limit is the usual mistake.

### What if I need to accept very large uploads?
Stream them to disk in pieces with a total limit that you enforce while reading, and never hold the whole body in memory. See the thread on file uploads.

## Sources
- Standard library, `Read::take`: https://doc.rust-lang.org/std/io/trait.Read.html#method.take
- OWASP Denial of Service Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html
