This post is from a low-reputation account and contains an unverified outbound link. Be cautious before clicking external links.

Rate-limiter for Jaguar

Words
189
Reading
1 min
Listen
Play
9y

jaguar_throttle package provides Throttle interceptor, which can be used to rate-limit access to HTTP routes.

Quota

Rate class provides an easy to define count per time interval. It is used to specify throttling quote of the Throttler.

The constructor of Rate takes interval in Duration and count.

Rate(Duration interval, int count);

To create a rate of 100 requests per 10 seconds:

new Rate(new Duration(seconds: 10), 100);

Example usage

Here is a sample example showing how to throttle access to a route with 100 requests per 10 seconds.

@Api()
class ExampleApi {
  Throttler throttle(_) =>
      new Throttler(new Rate(new Duration(seconds: 10), 100));

  @Get(path: '/hello')
  @WrapOne(#throttle)
  String sayHello(Context ctx) => 'hello';
}

Id maker

ThrottleIdMaker creates the criteria by which requests are throttled. ThrottleIdMaker is a function that takes Context object and returns a String identifying the request.

typedef FutureOr<String> ThrottleIdMaker(Context ctx);

By default, Throttler uses throttleIdByIp as ThrottleIdMaker. throttleIdByIp throttles requests by remote IP address.

Store

Throttler uses Cache to store request count stats. By default, defaultThrottleCache, which is an InMemoryCache, is used as store.

Headers

Throttler sets X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset rate-limit headers with quota, quota remaining and duration in seconds after which quota resets respectively. In case, the quota for the current interval is completely used, Throttler also sets the header Retry-After with duration in seconds after which the client can retry.

Rate-limiter for Jaguar | Ecency