dust

Rate Limiting

Introduction

Rate limiting lets you cap how often an action can occur within a given time window. For example, you might allow each user to post 60 messages per minute. Once a user exceeds that limit, dust-framework rejects subsequent requests with a 429 Too Many Requests response.

Rate limits also help protect your application from brute-force login attempts, keep high-volume API clients from degrading performance for other users, and keep background jobs within third-party API quotas.

Cache configuration

dust-framework tracks rate limit attempts in your default cache store. The memory, database, and Redis stores all support rate limiting. Because the memory store is local to a single process and resets on restart, use it only for local development and tests. In production, use the database or Redis store so rate limit counters persist across deploys and are shared across all application servers.

Throttling routes

To limit how often clients can access a route, attach the Throttle middleware in your route file. For example, this route allows up to 60 messages per minute from each client:

rust
use dust::http::middleware::Throttle;pub fn routes(route: &mut Router) {    route        .post("/messages", messages::store)        .middleware(Throttle::per_minute(60));}

Alongside per_minute, Throttle offers per_second, per_hour, per_day, and per with a custom span such as Throttle::per(100, 5.minutes()). You can also construct a Throttle from a Limit with Throttle::new(limit).

Constructor Allows
Throttle::per_second(10) 10 requests per second
Throttle::per_minute(60) 60 requests per minute
Throttle::per_hour(1_000) 1,000 requests per hour
Throttle::per_day(10_000) 10,000 requests per day
Throttle::per(100, 5.minutes()) 100 requests per 5 minutes

Limits do not reset all at once at the end of a window. Instead, dust-framework uses a token bucket algorithm: a client can burst through its allowance immediately and then regains capacity steadily over time. With a limit of 60 requests per minute, a client that sends 60 requests in a few seconds can make its next request roughly one second later, and one more each second after that.

Because Throttle is standard middleware, you can apply it to route groups or middleware stacks. To rate limit every route in your API, append a throttle to the api middleware group in src/app.rs:

rust
.with_middleware(|middleware, _| {    middleware.api(|api| {        api.append(Throttle::per_minute(60));    });})

Routes configured with the same limit share a counter per client. For example, a client that sends 60 requests to /messages above has also exhausted its quota on any other route throttled at per_minute(60). To isolate a route under its own counter, give the throttle a bucket name:

rust
route    .post("/uploads", uploads::store)    .middleware(Throttle::per_minute(60).bucket("uploads"));

If a route sits inside multiple groups that each define a throttle, every throttle evaluates the request. To exclude a route from an inherited throttle, such as a health check endpoint polled by your monitoring service, use without_middleware:

rust
route.get("/status", status::show).without_middleware::<Throttle>();

How requests are counted

Throttles track a separate counter for each client. For authenticated users, dust-framework keys the counter by user ID so all of their requests share one limit across devices and IP addresses. For guests, dust-framework keys the counter by IP address as resolved by your trusted proxies.

dust-framework resolves the authenticated user from the session or from a request guard such as an ApiTokens guard. Because request guards authenticate inside Authenticate::via, attach Throttle after it so the throttle can identify the user rather than falling back to their IP address:

rust
use dust::auth::Authenticate;route    .get("/api/me", users::me)    .middleware(Authenticate::via::<ApiTokens>())    .middleware(Throttle::per_minute(60));

Several limits

Sometimes a single window isn't enough. For example, an export route might permit bursts of 10 exports per minute while capping total usage at 100 per day. Chain additional limits with and; a request is allowed only when it satisfies every limit:

rust
use dust::http::middleware::Throttle;use dust::rate_limit::Limit;route    .prefix("/exports")    .middleware(Throttle::per_minute(10).and(Limit::per_day(100)))    .group(|route| {        // ...    });

One limit for every client

Some limits protect your application globally rather than per user, such as capping total sign-ups per minute across all traffic. Call global to share one counter across every client, and assign a bucket name so it doesn't collide with other global throttles:

rust
route    .post("/signups", signups::store)    .middleware(Throttle::per_minute(1_000).bucket("signups").global());

Choosing a limit for each request

When the appropriate limit depends on the caller, such as offering higher API quotas on paid plans, write a #[middleware] function that constructs a Throttle dynamically and delegates to its handle method.

For example, suppose each User is a member of a Team whose plan sets api_requests_per_minute. This middleware calls by to share a per-team limit across all members of a signed-in user's team, and falls back to a lower per-IP limit for guests:

rust
use dust::auth::Auth;use dust::http::middleware::Throttle;use dust::http::{Middleware, Next, middleware};use dust::prelude::*;use crate::models::{Team, User};#[middleware]pub async fn throttle_api(    auth: Auth<User>,    request: Request,    next: Next,) -> dust::Result<Response> {    match auth.user().await? {        Some(user) => {            let team = Team::find_or_fail(user.team_id).await?;            Throttle::per_minute(team.api_requests_per_minute)                .by(format!("team:{}", team.id))                .handle(request, next)                .await        }        None => {            Throttle::per_minute(10)                .handle(request, next)                .await        }    }}

Whereas bucket names the feature or group of routes being counted, by chooses who the counter tracks in place of the authenticated user or IP address, and global shares one counter across all clients. You may combine bucket and by to keep separate counters per feature for the same key, or to carry over a team's usage when their plan limit changes.

Then attach throttle_api to your routes or route groups:

rust
use dust::routing::Router;use crate::http::middleware::throttle_api;use crate::http::handlers::projects;pub fn routes(route: &mut Router) {    route        .prefix("/api")        .middleware(throttle_api)        .group(|route| {            route.get("/projects", projects::index);            route.post("/projects", projects::store);        });}

Responses

dust-framework includes two headers on every response from a throttled route indicating the configured limit and remaining attempts:

text
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 42

Requests that exceed the limit never reach your handler. Instead, dust-framework returns a 429 Too Many Requests response with a Retry-After header indicating how many seconds the client should wait before retrying.

Because the 429 response is produced from a TooManyAttempts error, dust-framework renders JSON for API requests and an error page for browser requests. To render a custom response, such as a page showing the remaining wait time, register a renderer for TooManyAttempts in src/app.rs. dust-framework still attaches the rate limit headers automatically:

rust
use dust::prelude::*;use dust::rate_limit::TooManyAttempts;.with_errors(|errors, _| {    errors.render(|error: &TooManyAttempts, request, status| {        let seconds = error.retry_after().as_secs().max(1);        if request.wants_json() {            return None;        }        Some((status, view("errors.too-many-requests", data! { seconds })).into_response())    });})

Returning None for JSON clients keeps dust-framework's structured 429 body, so an API client still receives a machine-readable error. The custom view receives seconds, which it may show as "Try again in 42 seconds." retry_after() never returns zero, so max(1) keeps the message sensible.

Limiting your own code

Not every rate limit belongs on an entire route. You might limit a user to sending 5 messages per minute inside a broader handler, or throttle calls to a third-party API from a background job. For these cases, call the functions in dust::rate_limit directly. Each function accepts a key string identifying what you are limiting, such as messages: followed by the user's ID. Because each key tracks one counter, use distinct keys if you want to enforce multiple windows against the same action.

attempt records an attempt and checks whether it falls within the limit. It returns a nested result: the outer Result reports cache errors, while the inner Result returns Ok(Quota) when allowed or Err(TooManyAttempts) when throttled. In a handler, ?? unwraps both so a throttled call produces the same 429 response as Throttle:

rust
use dust::prelude::*;use dust::rate_limit::{self, Limit};pub async fn store(user: Authenticated<User>) -> dust::Result<Redirect> {    rate_limit::attempt(&format!("messages:{}", user.id), Limit::per_minute(5)).await??;    // Send the message...    Ok(Redirect::back())}

Counting only some attempts

Sometimes only failed attempts should count against a limit. On a login form, for example, you want to throttle repeated wrong passwords without counting successful logins. Call check to verify remaining capacity without incrementing the counter, call hit only when an attempt fails, and call clear to reset the counter on success.

This login handler allows 5 failed attempts per minute per email address and IP address, clearing the counter once the user signs in:

rust
use dust::auth::Auth;use dust::hash::Password;use dust::prelude::*;use dust::rate_limit::{self, Limit};use dust::validation::ValidRequest;#[dust::input]#[validate(anyone)]pub struct Login {    #[validate(required, email)]    email: String,    #[validate(required)]    password: Password,}pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> dust::Result<Redirect> {    let limit = Limit::per_minute(5);    let key = format!("login:{}|{}", login.email.to_lowercase(), login.request().ip());    rate_limit::check(&key, limit).await??;    if let Err(error) = auth.attempt(&login.email, &login.password).await {        rate_limit::hit(&key, limit).await?;        return Err(error);    }    rate_limit::clear(&key).await?;    Ok(Redirect::intended(dashboard::show, ()))}

The handler extracts ValidRequest instead of Valid so it has access to both the validated Login fields and the client's IP address on the underlying request.

Outside a request

Inside a queued job, propagating TooManyAttempts with ?? automatically releases the job back onto the queue until the rate limit allows it to run instead of failing the job. For example, this job stays within a mail provider's limit of 14 sends per second:

rust
use dust::prelude::*;use dust::queue::{Queueable, job};use dust::rate_limit::{self, Limit};#[derive(Queueable)]pub struct SendNewsletter {    pub user_id: i64,}#[job(retry_for = 1.hours())]impl SendNewsletter {    async fn handle(self) -> dust::Result<()> {        rate_limit::attempt("newsletter", Limit::per_second(14)).await??;        // Send the newsletter...        Ok(())    }}

Because a rate-limited job may be released many times before running, configure retry_for rather than a fixed tries count. If the next available slot falls past the job's retry_for window, dust-framework fails the job immediately with TooManyAttempts rather than letting it wait. To also cap genuine failures while allowing releases, configure max_errors as described in limiting errors.

If you want custom behavior when a job hits a rate limit, such as deleting it, match on the inner result instead of using ??:

rust
use dust::queue::Attempt;async fn handle(self, attempt: &Attempt) -> dust::Result<()> {    match rate_limit::attempt("newsletter", Limit::per_second(14)).await? {        Ok(_) => {            // Send the newsletter...        }        Err(_) => attempt.delete(),    }    Ok(())}

Testing

Each test runs with an isolated application and in-memory cache, so rate limit counters never leak between tests. To verify that limits recover as time passes, travel forward in time instead of sleeping:

rust
use dust::rate_limit::TooManyAttempts;use dust::testing::prelude::*;#[dust::test]async fn messages_are_throttled(app: Application) {    for _ in 0..60 {        app.post("/messages").await.assert_ok();    }    app.post("/messages")        .await        .assert_status(429)        .assert_header("x-ratelimit-remaining", "0")        .assert_error::<TooManyAttempts>();    app.travel(2.minutes());    app.post("/messages").await.assert_ok();}

Test requests originate from 127.0.0.1 by default. Use with_ip to simulate multiple guest clients, or acting_as to test per-user limits:

rust
app.post("/messages").with_ip([203, 0, 113, 7]).await.assert_ok();app.post("/messages").acting_as(&user).await.assert_ok();