Crates.io | upstash-ratelimit-rs |
lib.rs | upstash-ratelimit-rs |
version | 1.0.2 |
source | src |
created_at | 2024-03-22 17:17:28.573643 |
updated_at | 2024-03-30 06:25:38.507363 |
description | An unofficial Upstash rate limiting SDK in Rust |
homepage | https://github.com/sourabpramanik/upstash-ratelimit-rs |
repository | https://github.com/sourabpramanik/upstash-ratelimit-rs |
max_upload_size | |
id | 1182817 |
size | 91,066 |
A rate-limiting SDK built for the Rust ecosystem that uses in-memory data storage.
This rate limit SDK is inspired by the official TypeScript rate limit SDK created by Upstash team.
let connection_str = std::env::var("UPSTASH_REDIS_URL").unwrap_or_else(|_| panic!("Expecting UPSTASH_REDIS_URL to be set"));
let Ok(redis) = redis::Client::open(connection_str) else {
panic!("Failed to connect")
};
Create a client instance of the RatelimitConfiguration
using the Redis client:
Use the client configuration to create a new instance of any one of the three rate-limiting algorithms:
For example: Using the fixed window algorithm to limit 10 requests in 30 seconds of the window.
let client = RatelimitConfiguration::new(redis, true, Some(String::from("my-custom-prefix")));
let ratelimit = FixedWindow::new(client, 10, "30s");
In the above client configuration, using the Ephemeral cache to avoid making Redis calls if the request is already blocked and adding a custom prefix string will override the default prefix string,
Use the ratelimit
instance to call the limit function in any request calls to rate limit your requests:
let limit_response = state.ratelimit.limit("some-unique-identifier-like-ip", None).await;
By default every algorithm consumes one token per request, but if you want rate-limit the requests based on the payload size or any other factor, you can do so by providing the rate value to the limit function call:
let limit_response = state.ratelimit.limit("some-unique-identifier-like-ip", Some(10)).await;
This will consume 10 tokens in one request.
Check the examples directory