{"slug": "how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools", "title": "How to Build a Sliding Window Rate Limiter in TypeScript for AI Agent Tools", "summary": "A developer published a zero-dependency TypeScript implementation of a sliding window rate limiter for AI agent tool calls, arguing that fixed-window counters let runaway retry loops burst through limits. The class tracks per-key timestamps in an in-memory Map, prunes expired entries, and returns a retryAfterMs value so clients can back off, with guidance to move the log to Redis sorted sets when running multiple replicas.", "body_md": "When an AI agent enters a retry loop on a failing tool call, a naive fixed window rate limiter won't save you.\n\nSuppose your limit is 50 requests per minute. A runaway loop fires 50 requests at 11:59:59 and another 50 at 12:00:01. The fixed counter resets at midnight, so 100 requests slip through inside a two-second burst.\n\nA sliding window log tracks the exact timestamp of every accepted call within the trailing window (for example, the last 60,000 milliseconds). Before executing a tool call, you prune expired timestamps and count what remains.\n\nHere is a clean, zero-dependency implementation in TypeScript:\n\n```\nexport interface RateLimitResult {\n  allowed: boolean;\n  remaining: number;\n  retryAfterMs: number;\n}\n\nexport class SlidingWindowLimiter {\n  private readonly windows = new Map<string, number[]>();\n\n  constructor(\n    private readonly maxRequests: number,\n    private readonly windowMs: number,\n  ) {}\n\n  check(key: string, nowMs = Date.now()): RateLimitResult {\n    const cutoff = nowMs - this.windowMs;\n    const timestamps = this.windows.get(key) ?? [];\n\n    while (timestamps.length > 0 && timestamps[0] <= cutoff) {\n      timestamps.shift();\n    }\n\n    if (timestamps.length >= this.maxRequests) {\n      const oldest = timestamps[0];\n      const retryAfterMs = Math.max(1, oldest + this.windowMs - nowMs);\n      this.windows.set(key, timestamps);\n      return { allowed: false, remaining: 0, retryAfterMs };\n    }\n\n    timestamps.push(nowMs);\n    this.windows.set(key, timestamps);\n\n    return {\n      allowed: true,\n      remaining: this.maxRequests - timestamps.length,\n      retryAfterMs: 0,\n    };\n  }\n}\n```\n\nIn-memory `Map` storage works well for a single Bun or Node worker, or inside a local MCP server process. Once you run multiple replicas behind a load balancer, move the timestamp log into Redis using a sorted set (`ZREMRANGEBYSCORE` + `ZCARD` + `ZADD` inside a Lua script or `MULTI` transaction).\n\nKey each bucket by both `agentKeyId` and `toolName` so a noisy read tool cannot starve critical write operations, and always return `retryAfterMs` in your tool error payload so well-behaved clients back off cleanly.\n\n💡 **Developer Infrastructure Note**: If your AI agent sends outbound emails over HTTP or MCP, rate limiters are only half the shield. [SadaSend](https://www.sadasend.com/?utm_source=devto&utm_medium=article&utm_campaign=dan_kestrel&utm_content=sliding-window-rate-limiter-typescript) enforces per-key spend guards, recipient allowlists, and active Port 25 bounce checks at the gateway.", "url": "https://wpnews.pro/news/how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools", "canonical_source": "https://dev.to/dev_kestrel/how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools-3m96", "published_at": "2026-12-05 05:05:47+00:00", "updated_at": "2026-12-05 05:13:55.933560+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools"], "entities": ["TypeScript", "Redis", "Bun", "Node.js", "SadaSend"], "also_reported_by": [], "takeaway": "A sliding window log that prunes timestamps older than the trailing window prevents fixed-window bursts, and keying buckets by both agentKeyId and toolName stops noisy read tools from starving write operations.", "recommendation": {"advice": "Rate-limit agent tool calls with a per-agentKeyId-and-toolName sliding window log and return retryAfterMs in error payloads; move the log to Redis sorted sets once you run multiple replicas.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools", "markdown": "https://wpnews.pro/news/how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools.md", "text": "https://wpnews.pro/news/how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools.txt", "jsonld": "https://wpnews.pro/news/how-to-build-a-sliding-window-rate-limiter-in-typescript-for-ai-agent-tools.jsonld"}}