jhurliman / node-rate-limiter

A generic rate limiter for node.js. Useful for API clients, web crawling, or other tasks that need to be throttled
MIT License
1.51k stars 135 forks source link

HTTP Limit headers #27

Closed jeanpsv closed 8 years ago

jeanpsv commented 8 years ago

I would like to set the HTTP headers:

something like this:

var RateLimiter = require('limiter').RateLimiter;
var limiter = new RateLimiter(150, 'hour', true);
console.log(limiter.limit()); // 150
console.log(limiter.reset()); // 58 (seconds elapsed)

Can I do something like that?

jhurliman commented 8 years ago

You could do something similar, but those exact headers would be tricky with node-rate-limiter. The reason is because token buckets (which node-rate-limiter uses under the hood) do continuous rate limiting; there is no concept of a fixed period of time before the throttle resets. You could implement this yourself on top of the rate limiter by initializing

var limiter = new RateLimiter(150, 'hour', true);

as well as recording the time when the limiter started, and starting a one hour timer that would reinitialize the rate limiter (and start time and reset timer). Then Limit would be 150, Remaining would be limiter. getTokensRemaining(), and Reset would be one hour minus the number of seconds that have elapsed since the start time.

jeanpsv commented 8 years ago

Ok. Thank you for the response.