Token bucket rate limiter implementation.

Uses the token bucket algorithm to provide smooth rate limiting. Tokens are added at a constant rate, and each request consumes tokens.

Features:

  • Automatic token refill based on elapsed time
  • Burst support (can consume multiple tokens at once)
  • Per-key rate limiting
  • Blocking mechanism for abuse prevention
  • In-memory storage (suitable for single-instance deployments)
const limiter = new TokenBucketRateLimiter({
maxRequests: 100,
windowMs: 60000, // 100 requests per minute
keyPrefix: 'api'
});

// Check and consume
try {
const result = await limiter.consume('user:123');
console.log(`Remaining: ${result.remaining}`);
} catch (error) {
if (error instanceof RateLimitExceededError) {
console.log(`Rate limit exceeded. Retry after ${error.result.retryAfter}ms`);
}
}

// Block abusive key
await limiter.block('user:456', 300000); // Block for 5 minutes

Implements

  • RateLimiter

Constructors

Methods

  • Check if a request is allowed without consuming tokens

    Parameters

    • key: string

      Unique identifier for the rate limit (e.g., user ID, agent ID)

    Returns Promise<RateLimitResult>

    Rate limit result

  • Consume tokens from the rate limit

    Parameters

    • key: string

      Unique identifier for the rate limit

    • tokens: number = 1

      Number of tokens to consume (default: 1)

    Returns Promise<RateLimitResult>

    Rate limit result after consumption

    If rate limit is exceeded

  • Get current state for a key without modifying it

    Parameters

    • key: string

      Unique identifier for the rate limit

    Returns Promise<null | RateLimitResult>

    Current rate limit state, or null if no state exists

  • Block a key from making requests for a duration

    Parameters

    • key: string

      Unique identifier to block

    • durationMs: number

      Duration to block in milliseconds

    Returns Promise<void>