Skip to content

creichert/wai-middleware-throttle

Repository files navigation

WAI Request Rate Limiting Middleware

https://travis-ci.org/creichert/wai-middleware-throttle.svg?branch=master https://img.shields.io/badge/license-BSD3-green.svg?dummy

Rate Limit and Throttle WAI Requests

Examples

Default (IP address throttler)

main = do
  let expirationInterval = TimeSpec 3600 0 -- expire after an hour
      settings = defaultThrottleSettings expirationInterval
  th <- initThrottler settings
  let payload  = "{ \"api\", \"return data\" }"
      app = throttle th $ \_ f -> f (responseLBS status200 [] payload)
  Warp.run 3000 app

Custom throttler (like an Authorization header)

newtype MyData = MyData { unData :: Text } deriving (Eq, Ord, Show, Hashable)
extractData :: Request -> Either Response MyData
extractData = maybe (Left "No authorization header") (Right . decodeUtf8 . snd) $
  find ((== hAuthorization) . fst) . requestHeaders
main = do
  let expirationInterval = TimeSpec 3600 0 -- expire after an hour
      settings = defaultThrottleSettings expirationInterval
  th <- initCustomThrottler settings extractData
  let payload = "{ \"api\", \"return data\" }"
      app = throttle th $ \_ f -> f (responseLBS status200 [] payload)
  Warp.run 3000 app

Migration from Old API

In migrating from the old API to the new one, the following changes are required:

  • defaultThrottleSettings now takes another parameter for the expiration interval of the cache
  • initThrottler now takes the settings
    • initCustomThrottler now takes the settings and a function to extract the key that was previously a method in the RequestHashable class
  • throttle no longer takes the settings