Redis-based rate limiting.
Rate-limiting is accomplished by creating an instance and calling the
method, which will increment the ongoing count for the provided key or, if
the limit has been reached, reject with a limit-exceeded error.
Check calls with the same key will be tracked together, regardless of which process the call was made in, assuming the same redis database is used by each process.
const RateLimiter = ;const RedizClient = ;const pasync = ;let client = /* redis config */;let limiter = client;// Check arguments take the form key, rate in Hz, max burst count.// At most one per 2 seconds.let limiter;// First check will resolve.// Second check will reject.// wait 2 seconds.// Third check will resolve.;// At most two at once, treating two per second as complete.// Note that different keys are tracked separately.let limiter;// First check will resolve.// Second check will resolve.// Third check will reject.// wait 1/2 second.// Fourth check will resolve.;
rediz-rate-limiter prefixes keys with 'rzrate:' before storing
them in redis. An additional prefix can be set by the
Keys with a different prefix will be separated from each other, even if they
are otherwise the same.
let limiter = client;// This instance will prefix keys with 'rzrate:asdf:'let otherLimiter = client prefix: 'asdf' ;// First check will resolvelimiter// Second check will also resolve because it has a different prefix.
Default Rate and Burst Count
A default rate and burst count for an instance can be set with the
constructor. These will be used if the corresponding options are omitted from
// At most two per 5 secondslet limiter = clientrate: 02burst: 2;limiter// Next check will reject;
Multiple Operations Per Check
opCount option allows you to specify multiple operations starting
at once. This is useful if you need to limit composite operations that consist
of several smaller operations together, based on the number of smaller
operations. Note that if the collection of ops would cause the burst count to
be exceeded, the check will fail without updating the 'in-progress' count. Thus,
none of the checked operations should be started in this case.
// At most 3 per 5 secondslet limiter = clientrate: 02burst: 3;limiter// Next check will reject, because 4 ops would exceed the burst of 3.;
Redis keys created by
rediz-rate-limiter expire based on the provided
completion rate, since there's no reason to track operations that are
considered finished. This can result in some unexpected behavior, however, if
the rate is changed from one
check call to the next.
let limiter = client;limiter// Wait 2 seconds// Will resolve, even though the rate changed to only one per 10 seconds.;