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.