typescriptadvanced
Sliding Window Rate Limiter
Implements sliding window rate limiting that distributes limits more evenly than fixed windows.
typescriptPress ⌘/Ctrl + Shift + C to copy
class SlidingWindowRateLimiter {
private windows = new Map<string, { current: number; previous: number; timestamp: number }>();
constructor(
private readonly limit: number,
private readonly windowMs: number
) {}
isAllowed(key: string): boolean {
const now = Date.now();
const windowStart = Math.floor(now / this.windowMs) * this.windowMs;
const entry = this.windows.get(key) || { current: 0, previous: 0, timestamp: windowStart };
if (entry.timestamp !== windowStart) {
entry.previous = entry.timestamp === windowStart - this.windowMs ? entry.current : 0;
entry.current = 0;
entry.timestamp = windowStart;
}
const elapsed = (now - windowStart) / this.windowMs;
const estimated = entry.previous * (1 - elapsed) + entry.current;
if (estimated >= this.limit) return false;
entry.current++;
this.windows.set(key, entry);
return true;
}
}
export { SlidingWindowRateLimiter };Use Cases
- API rate limiting
- DDoS protection
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Node.js Token Bucket Rate Limiter
Implement an in-memory token bucket rate limiter for controlling API request throughput.
Best for: Protecting APIs from abuse and DDoS
#nodejs#rate-limiting
typescriptintermediate
Webhook Handler with Signature Verification
Process incoming webhooks with HMAC signature verification, replay protection, and idempotency.
Best for: GitHub/Stripe webhook processing
#nodejs#webhook
typescriptadvanced
Edge Middleware Rate Limiter
Rate limit API requests at the edge using a sliding window counter with configurable thresholds.
Best for: API abuse prevention
#middleware#rate-limiting
typescriptintermediate
API Route Rate Limiting
Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.
Best for: API abuse prevention
#nextjs#api