util::TokenBucket

A token bucket rate limiter.

Synopsis

Declared in <util/tokenbucket.h>

template<typename Clock>
class TokenBucket;

Description

Tokens are added at a steady rate (m_rate per second) up to a capacity cap (m_cap). Tokens are removed by calling decrement(), which returns false if the bucket is emptied.

Typical usage: bucket.increment(now); // refill based on elapsed time if (bucket.value() >= 1) bucket.decrement(1); // consume a token

Type Aliases

NameDescription
clock The clock type used to measure elapsed time.
duration The clock's duration type.
time_point The clock's point-in-time type, used for refill timestamps.

Member Functions

NameDescription
TokenBucket [constructor]Construct a token bucket with a given rate, initial balance, and capacity.
decrement Consume n tokens. Returns false if the balance dropped to/below the given floor.
increment Refill tokens based on elapsed time since last call. No refill occurs on the first call (establishes the time baseline).
value Current token balance.

Data Members

NameDescription
m_cap Maximum token balance
m_rate Tokens added per second