1

I want to test if the rate limiting of my site is working.

To do this I would like to send a controlled amount of requests. For example, exactly 100 requests per second, and probably save the responses.

From How can I perform parallel asynchronous HTTP GET requests with reqwest? and this gist I wrote the following:

# [dependencies]
# reqwest = { version = "0.11.6" }
# tokio = { version = "1.14.0", features = ["full"] }
# futures = "0.3.24"

use futures::stream::StreamExt;
use reqwest::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let paths: Vec<String> = vec![String::from("https://api.ipify.org/"); 50];

  let fetches = futures::stream::iter(paths.into_iter().map(|path| {
    let client = Client::new();
    let send_fut = client.get(&path).send();

    async move {
      let response = send_fut.await;

      match response {
        Ok(resp) => {
          println!("{}", resp.status());
        }
        Err(_) => println!("Error"),
      }
    }
  }))
  .buffer_unordered(100)
  .collect::<Vec<()>>();

  fetches.await;
  Ok(())
}


The point is that I dont know how to control how many request are executed per second.

Any idea will be welcome!

Herohtar
  • 5,347
  • 4
  • 31
  • 41
EmileC
  • 39
  • 4

1 Answers1

1

You can use the tokio::time::interval

use tokio::time;

async fn request() {
    println!("send request");
}

#[tokio::main]
async fn main() {
    let mut interval = time::interval(time::Duration::from_millis(10));
    for _i in 0..100 {
        interval.tick().await;
        request().await;
    }
}
gftea
  • 558
  • 3
  • 7
  • Would this work with asynchronous calls? Would this make 50 async calls that take 100ms each distributed in one second? – EmileC Oct 18 '22 at 19:47
  • 1
    no, this assume the total 100 calls can be finished in 1 sec. some calls may take more than 10ms, then the next tick() will return immediately. – gftea Oct 18 '22 at 19:54
  • Ah, thats the point. The idea is to make x calls in 1 sec. by equal intervals, regardless of how much takes each call. – EmileC Oct 18 '22 at 20:04