Skip to main content

Rate Limiting

See how to create rate-limiting rules for Athenna REST API application.

Introduction

Rate limiters ensure the fair usage of your http server by clients. It regulates the number of times a user can request your application in a given time-frame.

Basic usage

Athenna uses the @fastify/rate-limit plugin inside HttpKernel. All the configurations that @fastify/rate-limit supports can be set inside

Path.config('http.ts')

./src/config/http.ts

file in the rateLimit object:

Path.config('http.ts')
export default {
rateLimit: {
global: true,
max: 1000,
ban: null,
timeWindow: 1000 * 60,
cache: 5000,
allowList: [],
continueExceeding: false,
enableDraftSpec: false
}
}

Configuring for specific routes

In Athenna you can set specific options of rate limit for specific routes. You can also disable the global option of your rateLimit configuration in

Path.config('http.ts')

./src/config/http.ts

and set different rules in your routes:

Path.route('http.ts')
Route
.get('/hello', 'WelcomeController.show')
.rateLimit({ max: 1, timeWindow: '1 minute' }) 👈

Usage in route groups

You can also use the rateLimit() method in route groups. This will set the same configuration for all routes inside the group:

Path.route('http.ts')
Route.group(() => {
Route.get('/hello', 'WelcomeController.show')
}).rateLimit({ max: 1, timeWindow: '1 minute' }) 👈
warning

The rateLimit() method of route groups will never overwrite the already set methods of routes. Use it to create "defaults" configurations for all routes.

Usage in route resources

Same behavior as route groups, but for resources:

Path.route('http.ts')
// Set the same configurations for all routes of resource
Route.resource('/tests', 'WelcomeController').rateLimit({...})

// Set configuration only for that specific action of resource
Route.resource('/tests', 'WelcomeController').rateLimit('index', {...})
Route.resource('/tests', 'WelcomeController').rateLimit('store', {...})

Rate limit headers

The response will have the following headers if enableDraftSpec is true in rateLimit config or route:

HeaderDescription
ratelimit-limitHow many requests the client can make
ratelimit-remainingHow many requests remain to the client in the timewindow
ratelimit-resetHow many seconds must pass before the rate limit resets
retry-afterContains the same value in time as ratelimit-reset
tip

For more information on Rate limit headers, please consult the Meta article about rate limiters.

Disabling rate limiting

The HttpKernel class will automatically disable the plugin registration if the package does not exist, so to disable rate-limiting in Athenna you need to remove the @fastify/rate-limit package from your application:

npm remove @fastify/rate-limit

You can also disable by setting http.rateLimit.enabled to false:

Path.config('http.ts')
export default {
rateLimit: {
enabled: false
}
}