A simple rate limiter using libsql | turso
npm install libsql-ratelimiterA flexible rate-limiting library built on top of libSQL, providing multiple algorithms (fixed window, sliding window, and token bucket) to control how frequently actions can be performed.
``bash`
npm install libsql-ratelimiter
Environment variables can be used to set the configuration:
`env`
LIBSQL_URL=
LIBSQL_AUTH_TOKEN=
`typescript
import { createRateLimiter } from 'libsql-ratelimiter';
async function example() {
const rateLimiter = await createRateLimiter({
url: 'file:./path/to/rate-limit.db', // process.env.LIBSQL_URL
// ...other config like authToken LIBSQL_AUTH_TOKEN can be used
});
// Check if it's initialized
console.log('Is initialized?', rateLimiter.isInitialized());
// Limit requests using the fixed window algorithm
const result = await rateLimiter.limit({
key: 'someUser',
limit: 5, // requests
window: 60, // seconds
algorithm: 'fixed', // 'fixed', 'sliding', or 'token'
});
console.log('Fixed window result:', result);
// Close the client when done
rateLimiter.close();
}
`
Creates and returns a new RateLimiter instance.
Checks if a given request identified by options.key should be allowed under the specified algorithm. Returns a RateLimitResult object containing:
- success: whether the request is allowedlimit
- : max capacityremaining
- : remaining limitreset`: milliseconds until limit resets
-
Returns a boolean indicating if the underlying table is set up.
Closes the underlying client connection.