Docs / Digging Deeper / Rate Limiting
Rate Limiting
Introduction
laraflare includes a simple to use rate limiting abstraction which, in conjunction with your application's cache, provides an easy way to limit any action during a specified window of time.
Note
If you are interested in rate limiting incoming HTTP requests, please consult the rate limiter middleware documentation.
Cache Configuration
Typically, the rate limiter utilizes your default application cache as defined by the default key within your application's cache configuration file. However, you may specify which cache store the rate limiter should use by defining a limiter key within your application's config/cache.ts configuration file:
default: envString('CACHE_STORE', 'database'),
limiter: 'kv', // [tl! add]
Basic Usage
The RateLimiter class may be used to interact with the rate limiter. The simplest method offered by the rate limiter is the attempt method, which rate limits a given callback for a given number of seconds.
The attempt method returns false when the callback has no remaining attempts available; otherwise, the attempt method will return the callback's result or true. The first argument accepted by the attempt method is a rate limiter "key", which may be any string of your choosing that represents the action being rate limited:
import { RateLimiter } from '@laraflare/framework';
const executed = await RateLimiter.attempt(
`send-message:${user.id}`,
5, // per minute
async () => {
// Send message...
},
);
if (! executed) {
return 'Too many messages sent!';
}
Note
The rate limiter's methods are asynchronous, since they read and write the cache:
awaitthem.
If necessary, you may provide a fourth argument to the attempt method, which is the "decay rate", or the number of seconds until the available attempts are reset. For example, we can modify the example above to allow five attempts every two minutes:
const executed = await RateLimiter.attempt(
`send-message:${user.id}`,
5, // per two minutes
async () => {
// Send message...
},
120, // decay rate
);
Manually Incrementing Attempts
If you would like to manually interact with the rate limiter, a variety of other methods are available. For example, you may invoke the tooManyAttempts method to determine if a given rate limiter key has exceeded its maximum number of allowed attempts per minute:
import { RateLimiter } from '@laraflare/framework';
if (await RateLimiter.tooManyAttempts(`send-message:${user.id}`, 5)) {
return 'Too many attempts!';
}
await RateLimiter.increment(`send-message:${user.id}`);
// Send message...
When rate limiting an endpoint that may receive many simultaneous requests, you may wish to check the value returned by the increment method instead of using tooManyAttempts and increment as separate operations. When using the redis or database cache stores, this value is incremented atomically, ensuring each concurrent request receives a unique count:
import { RateLimiter } from '@laraflare/framework';
const perMinute = 5;
if (await RateLimiter.increment(`send-message:${user.id}`) > perMinute) {
return 'Too many attempts!';
}
// Send message...
Note
Workers KV has no atomic counter: the
kvstore reads the value and writes it back, so concurrent requests may occasionally receive the same count. Use thedatabasestore where an exact count matters.
Alternatively, you may use the remaining method to retrieve the number of attempts remaining for a given key. If a given key has retries remaining, you may invoke the increment method to increment the number of total attempts:
import { RateLimiter } from '@laraflare/framework';
if (await RateLimiter.remaining(`send-message:${user.id}`, 5)) {
await RateLimiter.increment(`send-message:${user.id}`);
// Send message...
}
If you would like to increment the value for a given rate limiter key by more than one, you may provide the desired amount as the third argument to the increment method (the second is the decay rate in seconds):
await RateLimiter.increment(`send-message:${user.id}`, 60, 5);
Determining Limiter Availability
When a key has no more attempts left, the availableIn method returns the number of seconds remaining until more attempts will be available:
import { RateLimiter } from '@laraflare/framework';
if (await RateLimiter.tooManyAttempts(`send-message:${user.id}`, 5)) {
const seconds = await RateLimiter.availableIn(`send-message:${user.id}`);
return `You may try again in ${seconds} seconds.`;
}
await RateLimiter.increment(`send-message:${user.id}`);
// Send message...
Clearing Attempts
You may reset the number of attempts for a given rate limiter key using the clear method. For example, you may reset the number of attempts when a given message is read by the receiver:
import { RateLimiter } from '@laraflare/framework';
import type { Message } from '../Models/Message';
/**
* Mark the message as read.
*/
async read(message: Message): Promise<Message> {
await message.markAsRead();
await RateLimiter.clear(`send-message:${message.user_id}`);
return message;
}