Hybrid
The hybrid provider combines local admission speed with Redis-backed shared state.

Why choose Hybrid
- local-speed admission decisions
- much lower Redis load than pure Redis mode
- distributed limiting without paying a Redis round-trip on every request
What to expect
- methods are async, except
try_inc - keys use
RedisKey - local increments reach Redis within
SyncInterval - read-only calls answer from local state that is at most
AllowedLagold - an instance sees increments from other instances with a short delay
Timing settings
Three builder settings control how current the shared view is:
| Setting | Default | Controls |
|---|---|---|
sync_interval(SyncInterval) | 10 ms | how often local increments reach Redis |
allowed_lag(AllowedLag) | 1 second | maximum age of local state that answers a read-only call |
allowed_lag_applies_to_rejections(bool) | false | apply allowed_lag to the absolute rejection cache too |
- smaller values show changes from other instances sooner and increase Redis work
- larger values improve throughput and reduce Redis work
use std::sync::Arc;
use trypema::RateLimiterBuilder;
use trypema::hybrid::{AllowedLag, HybridRateLimiterProvider, SyncInterval};
use trypema::redis::RedisKey;
let provider: Arc<HybridRateLimiterProvider> = RateLimiterBuilder::hybrid(connection)
.prefix(RedisKey::try_from("my-service")?)
.sync_interval(SyncInterval::milliseconds_or_panic(10))
.allowed_lag(AllowedLag::milliseconds_or_panic(500))
.allowed_lag_applies_to_rejections(true)
.build()?;
Construct it with RateLimiterBuilder::hybrid(connection), or with the shortcut
HybridRateLimiterProvider::builder(connection), which needs no annotation. Background
synchronization always runs; stale-state cleanup is a separate optional loop. See the
Hybrid quickstart for a full setup.
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 create the state or the synchronization
worker of the other strategy.
use std::sync::Arc;
use trypema::RateLimiterBuilder;
use trypema::hybrid::{AbsoluteHybridRateLimiter, AllowedLag, SyncInterval};
use trypema::redis::RedisKey;
let limiter: Arc<AbsoluteHybridRateLimiter> = RateLimiterBuilder::hybrid(connection)
.prefix(RedisKey::try_from("ip-ban")?)
.sync_interval(SyncInterval::milliseconds_or_panic(10))
.allowed_lag(AllowedLag::milliseconds_or_panic(500))
.allowed_lag_applies_to_rejections(true)
.build()?;
For the suppressed limiter, annotate Arc<SuppressedHybridRateLimiter>. It does not use
allowed_lag_applies_to_rejections. 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 cleanup loop and the
synchronization worker of the limiter end at once after its last Arc drops; see
Directly built limiters.
The provider and each limiter return the window they were built with from window_size().
Read-only calls
The read-only calls are is_allowed and get_estimate on the absolute limiter, and
get_suppression_factor and get_estimate on the suppressed limiter.
- They answer from accepting local state only while it is younger than
allowed_lag. Older state is read from Redis again first. Concurrent calls for one key share that read. - A cached rejection answers until its retry time ends, which can be up to one window. With
allowed_lag_applies_to_rejections(true), an absolute rejection cache also reads Redis again once it is older thanallowed_lag. Thus a limit that another instance deletes or raises becomes visible within the lag.incandtry_inckeep the retry-time rule. - A suppressed key answers from its suppression cache until the
SuppressionFactorCachePeriodends.allowed_lag_applies_to_rejectionsdoes not apply to it. - They record no activity. A key in accepting state that is only checked becomes stale, and cleanup removes it. A rejected or suppressed key gets a new cache from Redis each time its cache ends, so cleanup keeps it while it is checked.
- A check of a key with no stored limit is allowed and creates no Redis key. The instance keeps a
small local entry that answers later checks until
allowed_lagpasses. Only the cleanup loop removes that entry, so keep cleanup running.
inc, try_inc, and get do not use allowed_lag.
Deciding without awaiting
try_inc(key, count) runs the local fast path synchronously. It takes a RedisKeyRef, a borrowed
key validated by the same rules as RedisKey, so the hot path validates without allocating. It
returns Ok(None), recording nothing, when the decision needs Redis (a new key, an expired
rejection cache, or exhausted local capacity); call inc then. Middleware on a hot path uses it to
skip async machinery on most requests.
let decision = match provider.absolute().try_inc(key.as_key_ref(), 1)? {
Some(decision) => decision,
None => provider.absolute().inc(&key, &rate, 1).await?,
};
Reading and priming counters
Both strategies expose reads, conditional updates, and lifecycle mutations. Hybrid variants coordinate local pending state with Redis:
get(key)reads Redis and overlays this instance's pending counts and declines.get_estimate(key)is a read-only call. It may answer from accepting local state that is younger thanallowed_lag, or from a rejection or suppression cache that has not ended; other state refreshes from Redis.- Conditional updates compare Redis history plus a protected snapshot of this instance's pending state. Comparator misses leave pending state untouched. Matches preserve increments racing after snapshot instead of dropping them.
- Lifecycle revisions prevent stale cached baselines from undoing a rate change, deletion, or clear. Pending work held by another instance may recreate a deleted or cleared key afterward.
use trypema::RateLimitComparator;
// Raise the window total to at least `used`; idempotent, safe to retry.
provider
.absolute()
.set_if(&key, &rate, RateLimitComparator::Lt(used), used)
.await?;
Best fit
Choose hybrid for high-throughput APIs where distributed visibility matters, but the pure Redis provider is too expensive on the hot path.
If you need every decision to read remote state directly, use Redis instead.

