Kest

Search

Search the documentation

Security

Rate limiting

Limit how often one caller may ask, to stop abuse and protect your server.

Rate limiting says "at most N requests per minute from this caller". It stops password guessing on the login route, scrapers, a buggy client in a retry loop, and one heavy user starving everyone else. In NestJS this is @nestjs/throttler.

Kest.run<AppModule> { import(ThrottlerModule.forRoot { limit = 100; ttl = Duration.ofSeconds(60) }) }     // 100 requests per minute per caller
app.http(adapter) { useGuards(ThrottlerGuard::class) }

A caller over the limit gets 429 Too Many Requests with a Retry-After header telling them when to try again.

Different limits for different routes

Login and password reset need a stricter limit than a catalogue:

@Controller("/auth") @Throttle(limit = 5, ttlSeconds = 60)         // 5 requests a minute for everything in this controller
class AuthController {
    @Post("/login") fun login(...) = ...
    @Post("/forgot") @Throttle(limit = 3, ttlSeconds = 3600) fun forgot(...) = ...     // 3 per hour for this one
    @Get("/status") @SkipThrottle fun status() = "ok"              // exempt one route
}

Who is "one caller"?

By default the limit is counted per signed-in user (user:<id>), or per IP address when nobody is signed in. Change what identifies a caller with tracker, for example per API key or per tenant:

ThrottlerModule.forRoot {
    limit = 1000
    tracker = { ctx -> "key:" + (ctx.request.header("x-api-key") ?: ctx.http.ip) }
    ignoreUserAgents = listOf(Regex("kube-probe.*"))             // health probes are not limited
}

Behind a proxy or load balancer the IP seen by Kest is the proxy's, so make sure the real client address is available (forwarded header handling) or every user will share one limit.

Several instances: share the counters

By default each instance counts alone, so with three instances a caller can make three times the limit. Use Redis so all instances share one count (atomic Lua scripts):

ThrottlerModule.forRoot { limit = 100; storage = RedisThrottlerStorage(JedisPool("redis.internal", 6379)) }     // package throttler-redis

Layers

Rate limiting at the application is one layer. Also limit at the edge (a CDN, a reverse proxy, an API gateway) so floods never reach the JVM, and use resilience (@Bulkhead) to protect what your code calls.

Testing

Call the route limit + 1 times in a test and assert the last answer is 429 with Retry-After; use a tiny limit and ttl.

Read more