Rate Limiting
Introduction
A rate limiter answers one question: has this key done this thing too many times recently? You use it to slow down password guessing, cap how often an API client can call an endpoint, or stop a background task from hammering an external service. The RateLimiter in @plinthjs/rate-limiter counts attempts per string key inside a time window, and the counter resets by itself when the window passes. For HTTP, the throttle middleware in @plinthjs/http applies a limiter to a route.
pnpm add @plinthjs/rate-limiterThe limiter keeps its counters in memory, inside the current process. If you run several server processes, each one counts separately.
Counting attempts
You choose the key. Anything that identifies "who is doing what" works, such as login|127.0.0.1 or send-mail|user:42.
import { RateLimiter } from '@plinthjs/rate-limiter'
const limiter = new RateLimiter()
limiter.hit('login|127.0.0.1') // => 1
limiter.hit('login|127.0.0.1') // => 2
limiter.attempts('login|127.0.0.1') // => 2
limiter.tooManyAttempts('login|127.0.0.1', 5) // => false
limiter.remaining('login|127.0.0.1', 5) // => 3
limiter.availableIn('login|127.0.0.1') // => 60 (seconds until the counter resets)hit(key, decaySeconds) records one attempt and returns the new count. The second argument is the window length in seconds and defaults to 60. The window starts at the first hit; later hits increase the count but do not extend the window. A window keeps the length it was opened with: hitting a key that has a live window with a different decaySeconds throws a RangeError rather than silently using the first value. Call resetAttempts(key) first to switch windows on purpose.
limiter.hit('export', 3600) // a one-hour windowReading the state
| Method | Returns |
|---|---|
attempts(key) | The number of hits in the current window (0 if none) |
tooManyAttempts(key, max) | true once the count has reached max |
remaining(key, max) | How many attempts are left, never below 0 |
retriesLeft(key, max) | The same as remaining |
availableIn(key) | Whole seconds until the key resets (0 if not limited) |
availableAt(key) | The reset moment as epoch milliseconds |
availableAt() also accepts a number of seconds instead of a key and returns the moment that far in the future, which is useful when you need a timestamp for a delayed action.
Resetting a key
clear(key) forgets the key straight away. Do this after a success, such as a correct login, so that earlier failures stop counting.
limiter.clear('login|127.0.0.1')
limiter.attempts('login|127.0.0.1') // => 0resetAttempts(key) does the same thing.
Running work only while under the limit
attempt(key, max, callback, decaySeconds) combines the check, the hit and the work. If the key is already at the limit it returns false without running your callback. Otherwise it records a hit and returns whatever your callback returns (the callback can be sync or async).
const result = await limiter.attempt('send-mail', 3, () => sendMail(), 60)
if (result === false) {
// three mails already went out in the last 60 seconds
}await limiter.attempt('m', 2, () => 'sent') // => 'sent'
await limiter.attempt('m', 2, () => 'sent') // => 'sent'
await limiter.attempt('m', 2, () => 'sent') // => falseThe hit is recorded before the callback runs, so a callback that throws still counts as an attempt.
TIP
Because attempt returns false when blocked, do not use it for a callback that can legitimately return false. Use tooManyAttempts and hit separately instead.
Named limiters
When the same limit is used in several places, register it once under a name with for(). The resolver returns a Limit.
import { Limit, RateLimiter } from '@plinthjs/rate-limiter'
const limiter = new RateLimiter()
limiter.for('uploads', () => Limit.perHour(100))
limiter.limiter('uploads') // => Limit { maxAttempts: 100, decaySeconds: 3600, key: '' }
limiter.limiter('unknown') // => undefinedThe Limit helpers build the common windows:
Limit.perMinute(60) // 60 attempts per minute
Limit.perMinutes(5, 20) // 20 attempts per 5 minutes
Limit.perHour(1000) // 1000 attempts per hour
Limit.perHour(10, 2) // 10 attempts per 2 hours
Limit.perDay(5000) // 5000 attempts per day
Limit.perDay(5, 2) // 5 attempts per 2 days
Limit.none() // unlimitedA Limit has maxAttempts and decaySeconds, and you can attach two more things to it:
by(key)sets a segment key, so one named limiter can count different callers separately.response(callback)stores a callback(payload, retryAfter) => responsethat your code can use to build a custom over-limit response.
limiter.for('api', (user?: { id: number; vip: boolean }) =>
user?.vip ? Limit.none() : Limit.perMinute(60).by(`user:${user?.id}`),
)The resolver receives the payload you pass when looking it up. Pass it to limiter(name, payload):
limiter.limiter('api', { id: 7, vip: false }) // => Limit { maxAttempts: 60, ..., key: 'user:7' }limiter.consume(name, payload) enforces a named limiter for you. It resolves the limits for the payload, checks all of them, records a hit on each only when none is exhausted, and returns { allowed, retryAfter, maxAttempts, remaining, response? }, where response is what the blocking limit's response() callback returned. limiter.resolve(name, payload) returns the limits with their counter keys if you want to drive them yourself. throttleUsing(limiter, name) binds a name to a plain (payload) => outcome function that an HTTP middleware can call with the request.
import { throttleUsing } from '@plinthjs/rate-limiter'
limiter.for('api', (req?: { ip: string }) => Limit.perMinute(60).by(req?.ip ?? 'anon'))
const check = throttleUsing(limiter, 'api')
const outcome = check(request)
if (!outcome.allowed) {
// respond 429 with Retry-After: outcome.retryAfter, or outcome.response when set
}The throttle middleware in @plinthjs/http still takes max and decaySeconds directly; use check above inside your own middleware to enforce a named limiter.
You can also read the Limit and apply it by hand:
const limit = limiter.limiter('uploads')
if (limit !== undefined) {
const key = `uploads|${userId}`
if (limiter.tooManyAttempts(key, limit.maxAttempts)) {
throw new Error(`Try again in ${limiter.availableIn(key)} seconds`)
}
limiter.hit(key, limit.decaySeconds)
}Applying several limits
A resolver can return an array of limits, for instance a short burst limit plus a daily cap. limiters(name, payload) returns every limit as an array (empty when the name is unknown), while limiter(name) returns only the first.
limiter.for('api', () => [Limit.perMinute(10).by('minute'), Limit.perDay(500).by('day')])
for (const limit of limiter.limiters('api')) {
const key = `api|${userId}|${limit.key}`
if (limiter.tooManyAttempts(key, limit.maxAttempts)) {
// reject: this limit is exhausted
}
}Check every limit first and hit them all only when none is exceeded, so a rejected request does not use up quota on the other limits.
Throttling routes
@plinthjs/http ships a throttle middleware that applies a limiter to requests. It is a plain middleware, so you attach it to a single route, a group, or the whole kernel. See Middleware and Routing.
import { RateLimiter } from '@plinthjs/rate-limiter'
import { Response, Router, throttle } from '@plinthjs/http'
const limiter = new RateLimiter()
const router = new Router()
router
.post('/login', () => Response.json({ ok: true }))
.middleware(throttle({ limiter, max: 5, decaySeconds: 60 }))When a client exceeds the limit, the middleware answers with status 429 and the JSON body { "message": "Too Many Attempts." }, plus these headers:
| Header | Value |
|---|---|
Retry-After | Seconds until the client may try again |
X-RateLimit-Limit | The configured max |
X-RateLimit-Remaining | Always 0 on a blocked response |
Under the limit, the middleware records a hit and passes the request on.
The options are:
| Option | Default | Meaning |
|---|---|---|
limiter | required | The RateLimiter that stores the counts |
max | 60 | Requests allowed per window |
decaySeconds | 60 | Window length in seconds |
key | client IP, method and path | A function (req) => string |
By default each client is limited separately for each route. Pass key to scope the limit differently, for example by the account being attacked rather than by IP address:
router
.post('/login', () => Response.json({ ok: true }))
.middleware(
throttle({
limiter,
max: 5,
key: (req) => String(req.input('email')),
}),
)The middleware prefixes the key with plinth-throttle: internally, so its keys never collide with keys you use for your own counters on the same limiter.
To see it work without a server, run a request through the kernel:
import { HttpKernel, Request } from '@plinthjs/http'
const kernel = new HttpKernel(router)
const send = () =>
kernel.handle(
new Request({
method: 'POST',
url: '/login',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ email: 'a@example.com' }),
}),
)
// with max: 1 and a key of the email, the second call is blocked
;(await send()).status // => 200
;(await send()).status // => 429throttle only needs hit, tooManyAttempts and availableIn, so any object with those three methods works as the limiter.
Testing
Everything that reads time takes an injected clock, so you never need to wait. Pass a now function that returns epoch milliseconds and move it forward yourself.
const clock = { at: 1_000_000 }
const limiter = new RateLimiter({ now: () => clock.at })
limiter.hit('k', 60)
limiter.availableIn('k') // => 60
clock.at += 60_000 // move past the window
limiter.attempts('k') // => 0
limiter.availableIn('k') // => 0Expired counters are discarded the next time the key is read or hit, so no cleanup is needed.