Actix Web

Overview

Rate limit actix-web routes with actix-trypema, the Trypema middleware for local, Redis and hybrid limits.

actix-trypema is actix-web middleware for Trypema. One middleware covers every backend: local limits for a single process, Redis limits shared exactly across instances, and hybrid limits shared through a local fast path.

Install

cargo add actix-trypema
# Redis and hybrid backends, plus the client that connects to Redis:
cargo add actix-trypema --features redis
cargo add redis --features tokio-comp,connection-manager

actix-trypema 0.2 needs trypema 3.1. actix-trypema re-exports trypema, so actix_trypema::trypema::{RateLimit, RateLimiterBuilder, WindowSize} is the trypema version that actix-trypema uses. A separate trypema dependency is optional. If you add one, it must be the same version as the one actix-trypema uses (3.1). Otherwise the types do not match. Optional features:

FeatureAdds
redisThe Redis and hybrid backends (two providers and four limiters), on tokio (the runtime actix-web runs on). It turns on trypema/redis-tokio.
jsonJsonResponder, a JSON body for rejections.
metricsDecision counters and a backend latency histogram through the metrics facade.

A first limiter

Sixty requests per minute per client IP, in one process:

use std::sync::Arc;

use actix_trypema::{
    TrypemaLimiter,
    extract::PeerIp,
    trypema::{RateLimit, RateLimiterBuilder, WindowSize, local::AbsoluteLocalRateLimiter},
};
use actix_web::{App, HttpServer, web};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Build the backend once, outside HttpServer::new, so every worker shares one limiter.
    let backend: Arc<AbsoluteLocalRateLimiter> = RateLimiterBuilder::local()
        .window_size(WindowSize::seconds_or_panic(60))
        .build()
        .expect("valid backend");

    let limiter = TrypemaLimiter::builder(backend)
        .namespace("ip")
        .extractor(PeerIp::default())
        .rate(RateLimit::per_minute_or_panic(60.0))
        .build()
        .expect("valid configuration");

    HttpServer::new(move || {
        App::new()
            .wrap(limiter.clone())
            .route("/", web::get().to(|| async { "hello" }))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

The 61st request within a minute gets 429 Too Many Requests with a retry-after header, and the handler never runs. Admitted responses carry x-ratelimit-limit: 60.

The building blocks

Every limiter is a backend plus three required choices:

ChoiceBuilder callLearn more
Where counts liveTrypemaLimiter::builder(backend) with a Trypema provider or limiter in an ArcBackends
Who a request is.extractor(..) or .extractor_fn(..)Client IPs, Keys and custom extractors
How much is allowed.rate(..) or .rate_fn(..)Limits
A name.namespace("ip"), matching [a-z0-9-]{1,32}below

The namespace keeps limiters that share a backend apart: a per-IP limiter and a login limiter both see the client 203.0.113.7, but count it under ip_r_203.0.113.7 and login_r_203.0.113.7. It also names the limiter in headers, outcomes, metrics and logs.

build() validates everything and returns a ConfigError instead of panicking at request time: a missing namespace, extractor or rate, an invalid namespace, or a fixed rate that admits less than one request per window.

What happens to a request

  1. Exclusions. If an exclude predicate matches, the request is forwarded and not counted.
  2. Key. The extractor names the client. If that fails, the key error policy decides; by default the request gets 400.
  3. Allow list. Keys passed to allow_keys are forwarded without counting.
  4. Rate and cost. A per-request rate and cost are resolved; a cost of 0 forwards without counting.
  5. Decision. The backend admits or rejects. Admitted requests reach the handler and get rate limit headers; rejected requests get 429 from the responder.

Build once, clone everywhere

HttpServer::new runs its closure once per worker thread. A backend built inside the closure gives every worker its own counters, multiplying the effective limit by the worker count. Build the backend and the limiter before HttpServer::new and clone the limiter into the closure; clones share one set of counters.

Where to wrap

  • App::wrap limits every route. web::scope(..).wrap(..) and web::resource(..).wrap(..) limit only their routes.
  • actix runs middleware in reverse registration order: the last .wrap sees the request first.
  • Put IP limiters outermost, before authentication, so unauthenticated floods are cut early. Put identity limiters (per user, per API key) inside the middleware that authenticates them.
  • If an exclusion matches on paths, register NormalizePath so it runs before the limiter.
use std::sync::Arc;

use actix_trypema::{TrypemaLimiter, extract::PeerIp};
use actix_trypema::trypema::{RateLimit, RateLimiterBuilder, WindowSize, local::AbsoluteLocalRateLimiter};
use actix_web::{App, web};

let backend: Arc<AbsoluteLocalRateLimiter> = RateLimiterBuilder::local()
    .window_size(WindowSize::seconds_or_panic(60))
    .build()?;

let per_ip = TrypemaLimiter::builder(backend.clone())
    .namespace("ip")
    .extractor(PeerIp::default())
    .rate(RateLimit::per_minute_or_panic(600.0))
    .build()?;

let login = TrypemaLimiter::builder(backend)
    .namespace("login")
    .extractor(PeerIp::default())
    .rate(RateLimit::per_minute_or_panic(5.0))
    .build()?;

let app = App::new()
    .wrap(per_ip) // every route: 600 per minute per IP
    .service(
        web::resource("/login")
            .wrap(login) // and /login: 5 per minute per IP on top
            .route(web::post().to(|| async { "ok" })),
    )
    .route("/", web::get().to(|| async { "home" }));

Upgrade from 0.1

In 0.2, the backend is trypema's own provider or limiter, in an Arc. The types Local, Redis and Hybrid are removed. Build the backend with trypema's RateLimiterBuilder, and give it to TrypemaLimiter::builder:

0.10.2
Local::new(window)?RateLimiterBuilder::local().window_size(window).build()?
Redis::new(connection, window)?RateLimiterBuilder::redis(connection).window_size(window).build()?
Hybrid::new(connection, window)?RateLimiterBuilder::hybrid(connection).window_size(window).build()?
Hybrid::configured(connection, window, |b| b.prefix(p))?RateLimiterBuilder::hybrid(connection).prefix(p).window_size(window).build()?
backend.provider().absolute().get(&key)backend.absolute().get(&key) on a provider, backend.get(&key) on a limiter
BackendErrorPolicy::Fallback(local) with local: LocalBackendErrorPolicy::Fallback(local) with local: Arc<LocalRateLimiterProvider>

Annotate the result of build() with the type: Arc<LocalRateLimiterProvider> for both strategies, or one limiter type such as Arc<AbsoluteHybridRateLimiter>. A single limiter runs its own strategy, so its builder has no strategy(..). The derived keys do not change. The changelog lists all changes.

Next

  • Client IPs: direct clients, X-Forwarded-For, Forwarded and CDN headers.
  • Keys and custom extractors: API keys, tenants, users, and writing your own extractor.
  • Limits: rates, plan tiers, request costs and strategies.
  • Backends: local, Redis and hybrid, and what happens when Redis fails.
  • Responses: headers and custom rejection bodies.
  • Observability: shadow mode, outcomes and metrics.
  • Performance: what the middleware costs per request.