cd /news/ai-agents/how-to-build-a-sliding-window-rate-l… · home › topics › ai-agents › article
[ARTICLE · art-182265] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=· neutral

How to Build a Sliding Window Rate Limiter in TypeScript for AI Agent Tools

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.

recommendation

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.

more in playbook: Designing agent systems
by read2 min views10 publishedDec 5, 2026

When an AI agent enters a retry loop on a failing tool call, a naive fixed window rate limiter won't save you.

Suppose 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.

A 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.

Here is a clean, zero-dependency implementation in TypeScript:

export interface RateLimitResult {
  allowed: boolean;
  remaining: number;
  retryAfterMs: number;
}

export class SlidingWindowLimiter {
  private readonly windows = new Map<string, number[]>();

  constructor(
    private readonly maxRequests: number,
    private readonly windowMs: number,
  ) {}

  check(key: string, nowMs = Date.now()): RateLimitResult {
    const cutoff = nowMs - this.windowMs;
    const timestamps = this.windows.get(key) ?? [];

    while (timestamps.length > 0 && timestamps[0] <= cutoff) {
      timestamps.shift();
    }

    if (timestamps.length >= this.maxRequests) {
      const oldest = timestamps[0];
      const retryAfterMs = Math.max(1, oldest + this.windowMs - nowMs);
      this.windows.set(key, timestamps);
      return { allowed: false, remaining: 0, retryAfterMs };
    }

    timestamps.push(nowMs);
    this.windows.set(key, timestamps);

    return {
      allowed: true,
      remaining: this.maxRequests - timestamps.length,
      retryAfterMs: 0,
    };
  }
}

In-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).

Key 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.

💡 Developer Infrastructure Note: If your AI agent sends outbound emails over HTTP or MCP, rate limiters are only half the shield. SadaSend enforces per-key spend guards, recipient allowlists, and active Port 25 bounce checks at the gateway.

── more in #ai-agents 4 stories · sorted by recency
── more on @typescript 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-build-a-slidi…] indexed:0 read:2min 2026-12-05 · —