rate limit a endpoint in rocket in rust

To rate limit an endpoint in Rocket in Rust, you can utilize the RateLimiter request guard provided by the rate crate. Here's an example implementation:

First, add the rate crate to your Cargo.toml:

[dependencies]
rocket = "0.5.0"
rate = "0.1.0"
47 chars
4 lines

Next, implement the rate-limited endpoint in your Rocket application:

main.rs
#[macro_use] extern crate rocket;
use rocket::tokio::sync::Mutex;
use rocket::Request;
use rate::RateLimiter;

// Create a rate limiter with a window of 60 seconds and a max of 100 requests
// allowed during that window.
static RATE_LIMITER: RateLimiter = RateLimiter::new(100, 60);

#[get("/rate-limited-endpoint")]
async fn rate_limited_endpoint() -> &'static str {
    "Hello, rate limited endpoint!"
}

#[rocket::main]
async fn main() {
    rocket::build()
        .manage(Mutex::new(RATE_LIMITER))
        .mount("/", routes![rate_limited_endpoint])
        .launch()
        .await
}
590 chars
23 lines

In the above example:

  • RATE_LIMITER is a static instance of RateLimiter with a window of 60 seconds and a maximum of 100 requests allowed.
  • The rate_limited_endpoint function is the endpoint that you want to rate limit.
  • Inside the main function, we initialize Rocket and pass the RATE_LIMITER to it using manage.

By having the RATE_LIMITER as a request guard, the requests made to the rate_limited_endpoint will be rate-limited based on the configuration provided.

Remember to adjust the configuration values of the RateLimiter to match your desired rate-limiting settings.

related categories

gistlibby LogSnag