redis-sliding-rate-limiter
Version:
Flexible and performant rate limiter based on sliding window algorithm with arbitrary precision
104 lines (103 loc) • 3.11 kB
TypeScript
/// <reference types="node" />
import { Unit } from './lua';
export type SendCommand = (...args: any[]) => any;
export type Call = (command: string, args: (string | Buffer | number)[]) => any;
export interface RedisClientWrapper {
sendCommand?: SendCommand;
call?: Call;
}
export interface RateLimiterOptionsWindow {
/**
* Window unit (second, minute, hour, etc)
*/
unit: Unit;
/**
* Window size in number of units (eg 1 second, 10 minutes, 2 hour, etc)
*/
size: number;
/**
* Specify the granularity of the window, i.e. with which precision elements would expire in the current window.
* Must be less or equal than window unit.
*/
subdivisionUnit?: Unit;
}
export interface RateLimiterOptions {
/**
* Client object from any of the following libraries:
* - https://www.npmjs.com/package/redis
* - https://www.npmjs.com/package/ioredis
*/
client: RedisClientWrapper;
/**
* Rate limiter window properties
*/
window: RateLimiterOptionsWindow;
/**
* Number of requests allowed in the window (eg 10 requests per 1 second)
*/
limit: number;
/**
* How many requests are allowed to exceed the limit expressed as a fraction of the limit, rounded down.
* Example: with limit=10 and limitOverheadFraction=0.1, 10% of the requests (1) will be allowed to exceed the limit.
* Default is zero.
*/
limitOverhead?: number;
/**
* Optional name for this limiter
*/
name?: string;
}
export interface RateLimiterResponse {
/**
* Number of remaining requests that can be performed in the current window
*/
remaining: number;
/**
* Whether the request is allowed or not
*/
allowed: boolean;
/**
* Epoch (milliseconds) at which the first element will expire in the current window
*/
firstExpireAtMs: number;
/**
* Epoch (milliseconds) at which the current window will expire
*/
windowExpireAtMs: number;
}
export declare class RateLimiter {
private _strategy;
private _tag;
private _client;
private _windowUnit;
private _windowSize;
private _windowSubdivisionUnit;
private _limit;
private _limitOverheadFraction;
private _limitOverhead;
private _window;
private _windowExpireMs;
private _name;
constructor(options: RateLimiterOptions);
private _updateWindow;
private _updateWindowExpiration;
get client(): RedisClientWrapper;
set client(v: RedisClientWrapper);
get windowUnit(): Unit;
set windowUnit(v: Unit);
get windowSize(): number;
set windowSize(v: number);
get windowSubdivisionUnit(): Unit;
set windowSubdivisionUnit(v: Unit);
get limit(): number;
set limit(v: number);
get limitOverheadFraction(): number;
set limitOverheadFraction(v: number);
get limitOverhead(): number;
get window(): number;
get windowExpireMs(): number;
get name(): string;
set name(v: string);
toString(): string;
get: (key: any) => Promise<RateLimiterResponse>;
}