wai-token-bucket-ratelimiter: A request rate limiting middleware using token buckets

[ apache, library, web ] [ Propose Tags ]

This package provides a WAI middleware to perform request rate limiting using the Token Bucket Algorithm.


[Skip to Readme]

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

  • No Candidates
Versions [RSS] 0.1.0.0, 0.1.0.1
Change log CHANGELOG.md
Dependencies base (>=4.16 && <5), clock (>=0.8.3 && <1), hashable (>=1.4 && <2), http-types (<1), unordered-containers (>=0.2.19.1 && <0.3), wai (>=3.0 && <4) [details]
License Apache-2.0
Author Aditya Manthramurthy
Maintainer aditya.mmy@gmail.com
Category Web
Home page https://github.com/donatello/wai-token-bucket-ratelimiter
Source repo head: git clone https://github.com/donatello/wai-token-bucket-ratelimiter.git
Uploaded by AdityaManthramurthy at 2023-06-07T18:11:14Z
Distributions
Downloads 76 total (9 in the last 30 days)
Rating 2.0 (votes: 1) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2023-06-07 [all 1 reports]

Readme for wai-token-bucket-ratelimiter-0.1.0.1

[back to package description]

wai-token-bucket-ratelimiter: WAI middleware to rate limit requests

This package provides a WAI middleware to perform request rate limiting using the Token Bucket Algorithm.

Quickstart

Adding rate limiting to your WAI app is as simple as:

rateLimitedApp :: (Request -> IO (ByteString, Rate)) -> Application -> IO Application
rateLimitedApp keyFunc = do
  rateLimitSettings <- newRateLimitSettings keyFunc
  return $ rateLimitMiddleware rateLimitSettings app

A rate is specified with the mkRate function that takes two parameters. These are:

  • burst amount: number of requests to allow initially and after a period of inactivity, and
  • averate rate: for example 5 requests every 2 seconds, specified as a pair (5, 2)

The special infRate value specified an infinite rate or rather no rate limit.

These are specified by your "key function":

keyFunc :: Request -> IO (ByteString, Rate)
keyFunc r = do
  let path = rawPathInfo r
      rate = case path of
        "/1" -> mkRate 5 (4, 1) -- burst=5, avg rate of 4 reqs per 1 second
        "/2" -> infRate
        _ -> mkRate 1 (1, 1) -- burst=1, avg rate of 1 req per 1 second
  return (path, rate)

In a real world case, the key function would most likely dependent on the client IP and the API endpoint.