SPB Git
555 B · 10 lines typescript
1/** In-memory sliding-window limiter (single-process deployment). Keys are scoped by the caller. */2const buckets = new Map<string, number[]>();3export function rateLimit(key: string, max: number, windowMs: number) {4  const now = Date.now(); const arr = (buckets.get(key) ?? []).filter((t) => now - t < windowMs);5  if (arr.length >= max) { buckets.set(key, arr); return false; }6  arr.push(now); buckets.set(key, arr);7  if (buckets.size > 10000) for (const [k, v] of buckets) if (!v.some((t) => now - t < windowMs)) buckets.delete(k);8  return true;9}10
Files · main
Menu

Theme