Skip to content
NestRS

Rate limiting

Per-route rate limiting — a guard, a default limit from env, per-handler overrides via #[meta(Throttle::…)].

The throttler turns a unit of work into “at most N per window, per caller”. One ThrottlerModule import provides the in-memory counter (an InMemoryThrottler, a fixed-window store); one #[use_guards(ThrottlerGuard)] binds it wherever a guard binds; one #[meta(Throttle::per_minute(10))] overrides the limit for a single handler. Over the limit, an HTTP route answers 429 Too Many Requests with a Retry-After header, and the other edges answer through their own error frame.

ThrottlerGuard checks all four request-carrying edges, and each keys its bucket on the unit that edge addresses joined with the caller it can see: Rate-limit buckets.

#[meta(Throttle::…)] overrides the module default on every edge — beside a route, a #[query], a #[subscribe_message] or a #[tool], or on its host for all of them; a unit that pins none counts against ThrottlerConfig’s limit.

Bind it per route, or per controller. The app’s GlobalGuards works and reads the same #[meta(Throttle::…)] — the guard pool runs post-routing, see the request lifecycle — but it meters every route the pool reaches at the module default, which is a wider decision than rate limiting usually is.

A rate limit opens nothing. It identifies no one, so it covers no unit: a route, a message or an operation under ThrottlerGuard alone says #[public] or fails the boot, which names each. Beside an authentication guard, it needs nothing more.

Terminal window
cargo add nest-rs --features throttler

One replica, one counter. Across replicas each process keeps its own, so four pods let four times the configured rate through — the cross-process store is a second feature on the same page:

Terminal window
cargo add nest-rs --features redis-throttler

The adapter whose controller binds the guard imports the port, as it imports the module serving its edge:

crates/features/src/posts/http/module.rs
use nest_rs::core::module;
use nest_rs::throttler::ThrottlerModule;
use super::controller::PostsController;
use crate::posts::PostsModule;
#[module(
imports = [PostsModule, ThrottlerModule],
providers = [PostsController],
)]
pub struct PostsHttpModule;

That import is the whole wiring. It registers the shared store and the ThrottlerGuard that reads it, both as global infrastructure — so the guard resolves from any module that binds it, and nothing goes in a controller module’s providers. Listing ThrottlerGuard there as well is a duplicate registration and fails the boot naming it. Several adapters importing it share one store and one policy, and the app’s root imports nothing for them.

A root whose GlobalGuards lists the guard binds it too, so it imports ThrottlerModule itself: the pool stays armed whichever adapters the root lists.

The bare import reads ThrottlerConfig from <PREFIX>_THROTTLER__* over its defaults (60 requests per 60s window), which apply when nothing is set. ThrottlerModule::for_root(ThrottlerConfig { .. }), at the root, pins the limit in code, superseding the adapters’ bare imports — the pinned value is the base <PREFIX>_THROTTLER__* overlays, field by field, on the same dual-path rule the rest of the framework follows. The limit runs from 1 to a billion requests per window and the window from a second to a day, and a value outside either range fails the boot naming its variable.

Terminal window
NESTRS_THROTTLER__LIMIT=120
NESTRS_THROTTLER__WINDOW_SECS=60
# Not a throttler setting — the transport's, shared with `ClientIp`.
NESTRS_HTTP__TRUSTED_PROXIES=10.0.0.1,10.0.0.2
crates/features/src/posts/http/controller.rs
use nest_rs::http::controller;
use nest_rs::throttler::ThrottlerGuard;
#[controller(path = "/posts")]
#[use_guards(AuthnGuard, ThrottlerGuard)]
pub struct PostsController { /* … */ }

Every route on this controller now goes through the throttler. The default limit applies unless a handler overrides it. Each route’s OpenAPI document lists its 429 and the Retry-After it carries, wherever the guard is bound — the controller, the route, an alias, the global pool — #[public] routes included.

crates/features/src/posts/http/controller.rs
use nest_rs::http::{controller, routes};
use nest_rs::throttler::{Throttle, ThrottlerGuard};
use nest_rs::http::Json;
#[controller(path = "/posts")]
#[use_guards(AuthnGuard, ThrottlerGuard)]
pub struct PostsController { /* … */ }
#[routes]
impl PostsController {
#[post("/")]
#[meta(Throttle::per_minute(10))]
async fn create(&self, /* … */) -> Result<Json<Post>> { /* … */ }
#[get("/")]
async fn list(&self, /* … */) -> Result<Json<Vec<Post>>> { /* … */ }
}

#[meta] attaches the limit to the route; the guard reads it back through cx.reflector() at request time. create is capped at 10/min; list inherits the module default. Forms:

Form Meaning
Throttle::per_second(n) n requests per second
Throttle::per_minute(n) n requests per minute
Throttle::new(n, Duration::from_secs(s)) n requests per s seconds

A window must count something: Throttle::new refuses one under a millisecond — the Redis store’s resolution — which in a const is a compile error and in #[meta] fails the boot at the route. A zero window reset every bucket on every hit, so the limiter let everything through at any limit. <PREFIX>_THROTTLER__WINDOW_SECS=0, or a pinned window: Duration::ZERO, fails the boot naming the variable for the same reason.

On HTTP the client is the direct peer’s network, or, behind a proxy you list, the rightmost hop it did not write: Rate-limit buckets.

This is what an over-limit response looks like — the eleventh call in a minute, against the default window:

Terminal window
$ for i in {1..11}; do
curl -s -o /dev/null -w "%{http_code} retry=%{header.retry-after}s\n" \
-X POST http://localhost:3002/posts -H "Authorization: Bearer $TOKEN" -d '{...}'
done
200 retry=s
200 retry=s
… (8 more 200s)
429 retry=47s

Retry-After is the time until the window resets — clients respecting it back off cleanly and resume on the same window.

Alternative stores — Redis, and anywhere else

Section titled “Alternative stores — Redis, and anywhere else”

The counter sits behind a ThrottlerStore trait. InMemoryThrottler (fixed-window, process-local) ships with the module and covers a single replica. Across replicas each process would keep its own counter, so an app on four pods lets four times the configured rate through — which is why the cross-process store ships too.

InMemoryThrottler holds two tables of ten thousand buckets: one for WebSocket connections, one for every other caller. A client mints a connection each time it reconnects, so connections are counted apart and take no room another caller needs. Each table is cut into sixteen shards by a key’s hash, and a full shard first drops the buckets whose window has ended. Then the connections’ table drops its oldest bucket that never refused, and a refusal only when it holds nothing else, since a reconnect would open a fresh bucket anyway: past about ten thousand live connection buckets, the oldest that never refused start their count afresh. The other table drops its oldest bucket that never refused, and a shard holding refusals alone refuses a new caller for its unit’s window, so no flood of fresh addresses resets a denial (InMemoryThrottler).

Enable it at the top of this page, then:

apps/api/src/module.rs
use nest_rs::core::module;
use nest_rs::redis::RedisThrottlerModule;
use features::posts::PostsHttpModule;
#[module(imports = [
PostsHttpModule,
RedisThrottlerModule,
])]
pub struct ApiModule;

One line, at the root. ThrottlerModule, which the adapter imports, stays exactly as it was: it owns the policy (<PREFIX>_THROTTLER__* — the limit and the window are the throttler’s whatever store counts them) and the ThrottlerGuard that applies it. RedisThrottlerModule is a bare import that declares RedisThrottler as the dyn ThrottlerStore, which supersedes the port’s in-process default wherever the two fall in the app’s imports; it imports the RedisModule opening its connection (<PREFIX>_REDIS__URL), and an app that also queues shares that one RedisConnection with its producer. You add a line to move the counters off-process and remove none. A second vendor binding beside it is a named boot failure, never a silent last-one-wins.

Redis never holds a client. A bucket’s subject — the route and the client’s address, the field and the actor — is personal data, and Redis keeps what it counts where a replica, a backup or a SCAN reads it. So a store whose counters leave the process counts each bucket under a pseudonym: the first 128 bits of an HMAC-SHA256 of its subject, in hex (nestrs:throttler:buckets:3f9c…), keyed by <PREFIX>_THROTTLER__PSEUDONYM_KEY. Set it to the same 32 bytes or more on every replica, as a secret:

Terminal window
NESTRS_THROTTLER__PSEUDONYM_KEY_FILE=/run/secrets/throttler-pseudonym-key # openssl rand -base64 32

Without it the boot refuses, naming the store and the variable: replicas keyed apart would each count their own buckets in the shared store. Changing it starts every bucket afresh, which costs a window at most. A key under 32 bytes is refused too, without being repeated — HMAC-SHA256’s key is as strong as its length up to the hash’s size (RFC 2104 §3).

The counter is one Lua script — INCR, read the TTL with PTTL, set it with PEXPIRE on the first hit — so it is atomic across replicas with no check-then-act race. A window in its last millisecond, whose TTL Redis answers 0, has ended: the script deletes it with PEXPIRE … 0, so that hit opens the next window, as it would in process. A backend failure denies: a rate limiter that fails open is not a rate limiter. The store answers Redis’s error and the guard refuses the caller, as it does for any store that cannot count (below). Each command is bounded by the connection’s budget (<PREFIX>_REDIS__CONNECT_TIMEOUT_SECS, 10 s by default), well inside the guard’s own bound — the boot refuses a budget at or past it — so an outage reaches the guard’s line as Redis’s own error, with its cause.

The script is sent as EVALSHA, with a SCRIPT LOAD the first time Redis has not cached it, and Redis checks the commands inside it against the caller’s ACL as well. With the connection’s PING, which proves it at boot, and the SELECT of the database its URL names, a Redis user for the rate limiter is this rule and nothing more:

Redis ACL — rate limiter
ACL SETUSER <user> reset on ><password> ~nestrs:throttler:* +ping +select +evalsha +script|load +incr +pttl +pexpire

Under Sentinel and on a Cluster, the rule is created on every node and takes what its topology’s connection adds — see ACL on Sentinel and Cluster.

An app that also queues or fires scheduled jobs once gives the same user the queue’s and the schedule’s rules as well.

The server runs maxmemory-policy noeviction. A window carries an expiry, so a volatile-* or allkeys-* policy may evict a full one once the server reaches its maxmemory, and the next hit opens a fresh window: the client it denied gets through. The boot cannot read the policy, so it is the deployment’s to set, for every binding the server holds — see Eviction.

Any store that can count a window implements ThrottlerStore and binds it the way RedisThrottlerModule does: the contract, its binding, the net it answers under and why its failure always denies are on Writing a rate-limit store.

  • crates/nest-rs-throttler/ — ThrottlerModule, ThrottlerGuard, ThrottlerConfig, Throttle, InMemoryThrottler, ThrottlerStore, ThrottlerStoreError.
  • Configuration — <PREFIX>_THROTTLER__* follows the same env → struct dual path every module uses.
  • Guards — what #[use_guards(ThrottlerGuard)] binds, and the scopes it binds at.