Providers

Redis

Best-effort distributed rate limiting backed by Redis 7.2+.

The Redis provider stores limiter state in Redis and evaluates operations through Redis-backed logic.

Three paper-craft rate-limiter topologies showing local state, direct shared Redis state, and local state synchronized to Redis.
Local keeps state in one process; Redis centralizes every call; hybrid periodically synchronizes local state to Redis.

Why choose Redis

  • limits are shared across processes and servers
  • each decision sees current remote state as directly as this crate offers
  • no local sync lag between admission and persistence

What to expect

  • methods are async
  • keys use RedisKey
  • every check performs Redis I/O
  • behavior is best-effort distributed, not strictly linearizable
  • reads, conditional updates, and lifecycle mutations run through atomic Lua scripts

Build it

Create a Redis connection manager, then pass it to RateLimiterBuilder::redis(connection). Set a RedisKey prefix when multiple applications share one Redis deployment. The complete setup is in the Redis quickstart.

use std::sync::Arc;
use trypema::RateLimiterBuilder;
use trypema::redis::{RedisKey, RedisRateLimiterProvider};

let provider: Arc<RedisRateLimiterProvider> = RateLimiterBuilder::redis(connection)
    .prefix(RedisKey::try_from("my-service")?)
    .build()?;

RedisRateLimiterProvider::builder(connection) is a shortcut for the same builder. Its build() needs no annotation.

Build one strategy directly

When the application uses one strategy only, build that limiter directly: annotate the result of build() with the limiter type. The limiter does not load the Lua scripts of the other strategy.

use std::sync::Arc;
use trypema::{RateLimiterBuilder, WindowSize};
use trypema::redis::{AbsoluteRedisRateLimiter, RedisKey};

let limiter: Arc<AbsoluteRedisRateLimiter> = RateLimiterBuilder::redis(connection)
    .prefix(RedisKey::try_from("my-service")?)
    .window_size(WindowSize::minutes_or_panic(1))
    .build()?;

For the suppressed limiter, annotate Arc<SuppressedRedisRateLimiter>. A limiter with a prefix uses the same Redis keys as the strategy of a provider with the same prefix, so the two share state. The limiter runs its own cleanup loop; see Directly built limiters. The provider and each limiter return the window they were built with from window_size().

Operational notes

  • Redis 7.2+ is required
  • enable exactly one of redis-tokio or redis-smol
  • all cooperating instances should use the same limiter settings for the same namespace
  • unknown reads return zero values without creating per-key Redis state

Best fit

Choose Redis when shared state matters more than per-request latency.

If the Redis round-trip becomes the bottleneck, hybrid is usually the next step.