Getting Started

Quickstart (Hybrid)

Combine local admission with periodic Redis synchronization.

Use hybrid provider when distributed visibility matters but per-request Redis I/O is too costly.

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.

Add dependencies

[dependencies]
trypema = { version = "3", features = ["redis-tokio"] }
redis = { version = "1", features = ["aio", "tokio-comp", "connection-manager"] }
tokio = { version = "1", features = ["full"] }

Build provider

use std::sync::Arc;
use trypema::{BucketSize, RateLimit, RateLimitDecision, RateLimiterBuilder, WindowSize};
use trypema::hybrid::{AllowedLag, HybridRateLimiterProvider, SyncInterval};
use trypema::redis::RedisKey;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let connection = redis::Client::open("redis://127.0.0.1:6379/")?
        .get_connection_manager()
        .await?;
    let provider: Arc<HybridRateLimiterProvider> = RateLimiterBuilder::hybrid(connection)
        .prefix(RedisKey::try_from("my-service")?)
        .window_size(WindowSize::minutes_or_panic(1))
        .bucket_size(BucketSize::milliseconds_or_panic(10))
        .sync_interval(SyncInterval::milliseconds_or_panic(10))
        .allowed_lag(AllowedLag::seconds_or_panic(1))
        .allowed_lag_applies_to_rejections(false)
        .build()?;

    let key = RedisKey::try_from("user_123")?;
    let rate = RateLimit::per_second_or_panic(10.0);
    assert!(matches!(
        provider.absolute().inc(&key, &rate, 1).await?,
        RateLimitDecision::Allowed
    ));

    Ok(())
}

Most admission calls use local state; background synchronization is always active. Local increments reach Redis within SyncInterval. Read-only calls such as is_allowed(...) and get_estimate(...) answer from local state that is at most AllowedLag old, then read Redis again. The values above are the defaults. Smaller values show changes from other instances sooner and increase Redis work. get(...) always reads Redis and overlays this instance's pending counts.

allowed_lag_applies_to_rejections(true) also bounds the absolute rejection cache by AllowedLag. See Read-only calls.

Redis 7.2+ and exactly one runtime feature are required, just as for the Redis provider.

Next steps