Rate Limiting
Same API as the core createRateLimit plugin, but backed by Redis using an atomic Lua script. Rate limits are enforced across all server instances with exactly one Redis roundtrip per consume() call.
When to use over the built-in plugin: The core rate limiter tracks tokens per-process, so a user could get N tokens on each of your M instances for N*M effective tokens. The Redis version enforces a single shared bucket, so limits hold regardless of which instance handles the request.
Setup
// src/lib/server/ratelimit.js
import { redis } from './redis.js';
import { createRateLimit } from 'svelte-adapter-uws-extensions/redis/ratelimit';
export const limiter = createRateLimit(redis, {
points: 10,
interval: 1000,
blockDuration: 30000
}); Usage
// src/hooks.ws.js
import { limiter } from '$lib/server/ratelimit';
export async function message(ws, { data, platform }) {
const { allowed } = await limiter.consume(ws);
if (!allowed) return; // drop the message
// ... handle message
} Options
| Option | Default | Description |
|---|---|---|
points | required | Tokens available per interval |
interval | required | Refill interval in ms |
blockDuration | 0 | Auto-ban duration in ms (0 = no ban) |
keyBy | 'ip' | 'ip', 'connection', or a function |
API
All methods are async (they hit Redis). The API otherwise matches the core plugin:
| Method | Description |
|---|---|
consume(ws, cost?) | Attempt to consume tokens. cost must be a positive integer. |
reset(key) | Clear the bucket for a key |
ban(key, duration?) | Manually ban a key |
unban(key) | Remove a ban |
clear() | Reset all state |
Was this page helpful?