Skip to main content

PerKey

Struct PerKey 

Source
pub struct PerKey<K, C = SystemClock>
where C: Clock,
{ /* private fields */ }
Available on crate feature std only.
Expand description

A throttle that keeps independent state per key.

Each distinct key — a tenant, a user, an API token — gets its own token bucket with the same configured rate, so one noisy key cannot spend another’s budget. State lives in a sharded concurrent map: keys are spread across shards by hash, each shard has its own lock, and an existing key’s acquire takes only a shard read lock plus the bucket’s own atomic accounting, so unrelated keys never contend and throughput scales with cores.

Memory is bounded by eviction (see Eviction): idle keys expire and a hard cap bounds the total, so a flood of unique keys reaches a ceiling instead of growing without limit. Eviction is lazy and per-shard — it runs while inserting a new key, never on a background thread or the steady-state path. The default policy is bounded (Eviction::default).

Like Throttle, the headline acquire waits; the try_* variants do not.

§Examples

use throttle_net::PerKey;

// 100 requests per second, per tenant.
let limiter: PerKey<String> = PerKey::per_second(100);
limiter.acquire(&"tenant:42".to_string()).await?;

Implementations§

Source§

impl<K> PerKey<K, SystemClock>
where K: Eq + Hash + Clone + Send + Sync + 'static,

Source

pub fn per_second(rate: u32) -> Self

Creates a per-key limiter giving every key rate units per second, driven by the OS monotonic clock and the default Eviction policy.

§Examples
use throttle_net::PerKey;

let limiter: PerKey<u64> = PerKey::per_second(10);
assert!(limiter.try_acquire(&42));
Source

pub fn per_duration(amount: u32, period: Duration) -> Self

Creates a per-key limiter giving every key amount units every period.

§Examples
use std::time::Duration;
use throttle_net::PerKey;

// 1000 units per minute, per key.
let limiter: PerKey<String> = PerKey::per_duration(1000, Duration::from_secs(60));
Source§

impl<K, C> PerKey<K, C>
where K: Eq + Hash + Clone + Send + Sync + 'static, C: Clock + Clone,

Source

pub fn with_clock<C2>(self, clock: C2) -> PerKey<K, C2>
where C2: Clock + Clone,

Replaces the time source, for deterministic tests with a ManualClock. The store is rebuilt empty around the new clock.

§Examples
use std::sync::Arc;
use std::time::Duration;
use clock_lib::ManualClock;
use throttle_net::PerKey;

let clock = Arc::new(ManualClock::new());
let limiter = PerKey::<&str>::per_second(1).with_clock(clock.clone());

assert!(limiter.try_acquire(&"k"));
assert!(!limiter.try_acquire(&"k"));
clock.advance(Duration::from_secs(1));
assert!(limiter.try_acquire(&"k"));
Source

pub fn with_eviction(self, eviction: Eviction) -> Self

Sets the memory-bound policy (idle TTL and/or hard key cap).

§Examples
use std::time::Duration;
use throttle_net::{Eviction, PerKey};

let limiter: PerKey<String> = PerKey::per_second(100)
    .with_eviction(Eviction::capacity(50_000).with_idle(Duration::from_secs(300)));
Source

pub fn with_shards(self, shards: usize) -> Self

Sets the shard count (rounded up to a power of two, at least one).

More shards reduce contention between unrelated keys at the cost of a little memory. The store is rebuilt empty.

§Examples
use throttle_net::PerKey;

let limiter: PerKey<u64> = PerKey::per_second(100).with_shards(64);
assert_eq!(limiter.shard_count(), 64);
Source

pub fn capacity(&self) -> u32

The per-key capacity (burst ceiling): the configured amount.

Source

pub fn shard_count(&self) -> usize

The number of shards (a power of two).

Source

pub fn len(&self) -> usize

The number of keys with live state across all shards.

A momentary, advisory snapshot — useful for tests and metrics, not a synchronization point.

Source

pub fn is_empty(&self) -> bool

Returns true if no key currently has live state.

Source

pub fn try_acquire(&self, key: &K) -> bool

Attempts to take one token for key without waiting.

§Examples
use throttle_net::PerKey;

let limiter: PerKey<&str> = PerKey::per_second(1);
assert!(limiter.try_acquire(&"a"));
assert!(!limiter.try_acquire(&"a"));
assert!(limiter.try_acquire(&"b")); // a different key is independent
Source

pub fn try_acquire_with_cost(&self, key: &K, cost: u32) -> bool

Attempts to take cost tokens for key without waiting.

Source

pub fn peek(&self, key: &K, cost: u32) -> Decision

Reports whether cost tokens would be granted for key now, without taking them — and without creating state for an unseen key.

Source

pub fn available(&self, key: &K) -> u32

Current tokens available for key. An unseen key reports the full capacity, since acquiring would create a fresh bucket.

Source§

impl<K, C> PerKey<K, C>
where K: Eq + Hash + Clone + Send + Sync + 'static, C: Clock + Clone,

Source

pub async fn acquire(&self, key: &K) -> Result<(), ThrottleError>

Available on crate feature runtime only.

Takes one token for key, waiting until one is available.

§Errors

Returns ThrottleError::CostExceedsCapacity when the per-key capacity is zero.

§Examples
use throttle_net::PerKey;

let limiter: PerKey<String> = PerKey::per_second(100);
limiter.acquire(&"tenant:7".to_string()).await?;
Source

pub async fn acquire_with_cost( &self, key: &K, cost: u32, ) -> Result<(), ThrottleError>

Available on crate feature runtime only.

Takes cost tokens for key, waiting until they are available.

§Errors

Returns ThrottleError::CostExceedsCapacity when cost exceeds the per-key capacity, so the request can never be granted.

Auto Trait Implementations§

§

impl<K, C> Freeze for PerKey<K, C>
where C: Freeze,

§

impl<K, C> RefUnwindSafe for PerKey<K, C>
where C: RefUnwindSafe,

§

impl<K, C> Send for PerKey<K, C>
where K: Send,

§

impl<K, C> Sync for PerKey<K, C>
where K: Send + Sync,

§

impl<K, C> Unpin for PerKey<K, C>
where C: Unpin,

§

impl<K, C> UnsafeUnpin for PerKey<K, C>
where C: UnsafeUnpin,

§

impl<K, C> UnwindSafe for PerKey<K, C>
where C: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<E> WithErrorCode<E> for E

Source§

fn with_code(self, code: impl Into<String>) -> CodedError<E>

Attach an error code to an error
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more