#rate-limiting #actix-web #web-framework #web-services #limitation #web-server

actix-limitation

Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web

10 releases

0.5.1 Sep 16, 2023
0.5.0 Sep 16, 2023
0.4.0 Sep 10, 2022
0.3.0 Jul 11, 2022
0.1.2 Apr 11, 2020

#1846 in Web programming

Download history 140/week @ 2024-06-09 89/week @ 2024-06-16 166/week @ 2024-06-23 170/week @ 2024-06-30 283/week @ 2024-07-07 180/week @ 2024-07-14 289/week @ 2024-07-21 176/week @ 2024-07-28 291/week @ 2024-08-04 202/week @ 2024-08-11 192/week @ 2024-08-18 112/week @ 2024-08-25 155/week @ 2024-09-01 95/week @ 2024-09-08 95/week @ 2024-09-15 215/week @ 2024-09-22

566 downloads per month

MIT/Apache

55KB
919 lines

actix-limitation

Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web.
Originally based on https://github.com/fnichol/limitation.

crates.io Documentation Apache 2.0 or MIT licensed Dependency Status

Examples

[dependencies]
actix-web = "4"
actix-limitation = "0.5"
use actix_limitation::{Limiter, RateLimiter};
use actix_session::SessionExt as _;
use actix_web::{dev::ServiceRequest, get, web, App, HttpServer, Responder};
use std::{sync::Arc, time::Duration};

#[get("/{id}/{name}")]
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
    format!("Hello {}! id:{}", info.1, info.0)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let limiter = web::Data::new(
        Limiter::builder("redis://127.0.0.1")
            .key_by(|req: &ServiceRequest| {
                req.get_session()
                    .get(&"session-id")
                    .unwrap_or_else(|_| req.cookie(&"rate-api-id").map(|c| c.to_string()))
            })
            .limit(5000)
            .period(Duration::from_secs(3600)) // 60 minutes
            .build()
            .unwrap(),
    );
    HttpServer::new(move || {
        App::new()
            .wrap(RateLimiter::default())
            .app_data(limiter.clone())
            .service(index)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Dependencies

~17–27MB
~485K SLoC