View Source AbsintheRateLimiting.RateLimit (absinthe_rate_limiting v0.1.0)

Rate limiting middleware for Absinthe.

Usage

To use the rate limiting middleware, you must first configure Hammer. For example:

config :hammer,
  backend:
    {Hammer.Backend.ETS, [
      expiry_ms: 1000 * 60 * 60 * 4,
      cleanup_interval_ms: 1000 * 60 * 10
    ]}

See the Hammer documentation for more information.

The next step is to add the middleware to all queries that needs to be rate limited:

field :my_field, :string do
  middleware AbsintheRateLimiting.RateLimit
  resolve &MyApp.Resolvers.my_field/3
end

Configuration

The available configuration options are:

OptionDescriptionDefault Value
:scale_msInteger indicating size of bucket in milliseconds.60_000
:limitInteger maximum count of actions within the bucket. In other words, the maximum number of requests that are allowed in :scale_ms milliseconds.25
:resultThe result to return when the rate limit is exceeded.{:error, :too_many_requests}
:idThe name of the bucket, or a list of keys to fetch the name from the context or arguments. The bucket will always be scoped per field."default"
:id_sourceThe source of the ID, either :static, :context, or :arguments. When the source is :static, :id will be used as the name of the bucket. Otherwise, the Absinthe context or the arguments passed to the field respectively will be indexed using :id.:static

The default values can be configured in your config.exs:

config :absinthe_rate_limiting,
  scale_ms: 60_000,
  limit: 25,
  result: {:error, :too_many_requests},
  id: "default",
  id_source: :static

These values can be overridden for each field in the schema definition by passing them as options to the middleware:

field :my_field, :string do
  middleware AbsintheRateLimiting.RateLimit, limit: 10
  resolve &MyApp.Resolvers.my_field/3
end

Disabling rate limiting

Rate limiting can be disabled by setting the :active configuration option to false in your config.exs:

config :absinthe_rate_limiting,
  active: false

This will bypass the rate limiting middleware and allow all requests to pass through. This can be useful for testing or development environments.