Skip to content

insidewhy/rxjs-ratelimiter

Repository files navigation

rxjs-ratelimiter

build status Known Vulnerabilities

An rxjs library to facilitate dealing with rate limited resources (say, external REST APIs). Great for use with @angular/http.

This library is fully tested using rxjs's marble testing and rxjs's TestScheduler to provide virtual time scheduling.

How to install

npm install -S rxjs-ratelimiter
yarn add rxjs-ratelimiter

How to use

This example uses angular 2:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import RateLimiter from 'rxjs-ratelimiter'

@Injectable()
export class RateLimitedApi {
  // allow at most 6 requests every 1000ms
  private rateLimiter = new RateLimiter(6, 1000)

  constructor(private http: Http) {}

  makeRequest(path: string): Promise<Response> {
    return this.rateLimiter.limit(
      this.http.get(`https://my.api/${path}`)
    ).toPromise()
  }
}

rateLimiter.limit returns an observable that rate limits the subscription to the passed observable. To understand how this works it is important to realise that cold observables create requests lazily (when subscribed to, not when instantiated). In this example the http request happens when the rate limiter passes a subscription through to the observable returned by this.http.get, not at the time that this.http.get is called.

Retrying requests

A consequence of the lazy nature of rate limited observable is that resubscriptions by operators chained from them (such as retry) will also be subject to rate limitation.

this.rateLimiter.limit(
  this.http.get(`https://my-api.co/`)
).pipe(retry())

This will produce an observable that will retry the HTTP request until it succeeds. The rate limiter also applies to the retries so at most one request can happen per second, less if the rate limiter is being used for other requests. To have the rate limiter apply to the initial request but not the retries the following modification can be made:

this.rateLimiter.limit(this.http.get(`https://some.api/`).pipe(retry()))

rxjs 5 support

Version 0.1.1 supports rxjs5. Versions 1.0.0 and onward will only support rxjs 6 (and later).