GitHub RepositoryFastAPI · Redis · Lua · Scikit-LearnDistributed Systems Architecture

AI Rate Limiter Shield: Atomic Redis Lua & Sliding-Window Architecture

A high-throughput API gateway middleware designed to prevent race conditions during concurrent request surges, protect LLM endpoints from token exhaustion, and detect distributed botnets using Isolation Forest machine learning.

Architecture Summary: The AI Rate Limiter Shield enforces strict rate limits by encapsulating timestamp eviction (ZREMRANGEBYSCORE), cardinality checks (ZCARD), and request insertions (ZADD) into a single, atomic Redis Lua script. This eliminates network round-trips and guarantees that concurrent API threads never exceed rate thresholds due to read-modify-write race conditions.

1. The Concurrency Problem: Why Naive Redis Fails

In high-traffic distributed applications, multiple API gateway workers serve incoming requests simultaneously. If a rate limiter executes separate commands—reading a counter, validating the limit, and incrementing—a classic Time-of-Check to Time-of-Use (TOCTOU) race condition occurs:

Thread A: Reads Count = 99 (Threshold = 100) → Allowed
Thread B: Reads Count = 99 (Threshold = 100) → Allowed
Both execute write: Count becomes 101 → Rate limit breached!

Under heavy automated traffic or distributed DDoS attacks, thousands of requests can slip through during this race condition window, leading to backend database saturation and massive third-party API billing overages (especially on paid LLM token endpoints).

2. The Atomic Lua Solution

Redis executes Lua scripts as a single atomic operation. No other script or Redis command can execute while a script is running, completely eliminating concurrency race conditions.

-- Atomic Sliding Window in Redis Lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local clear_before = now - window

redis.call('ZREMRANGEBYSCORE', key, 0, clear_before)
local current_requests = redis.call('ZCARD', key)

if current_requests < limit then
  redis.call('ZADD', key, now, now .. '-' .. math.random(100000))
  redis.call('EXPIRE', key, math.ceil(window / 1000))
  return 1 -- Request Allowed
else
  return 0 -- HTTP 429 Too Many Requests
end

3. Anomaly Detection via Isolation Forest

In addition to strict sliding-window thresholds, the system incorporates an asynchronous anomaly detection pipeline built with Scikit-Learn's Isolation Forest algorithm. It models three feature vectors per client identifier:

  • Inter-Arrival Time Variance: Automated scrapers exhibit near-zero variance in request timing compared to human browsing jitter.
  • Endpoint Distribution Entropy: Crawlers systematically traverse directory structures, generating abnormally high entropy across path access patterns.
  • Payload Size Deviations: Sudden spikes in POST payload size indicate potential token stuffing or buffer exploit probes.

4. Performance & Benchmarks

Benchmarked on a local workstation environment (Redis 7 localhost loopback) with a 4-worker FastAPI setup using locust load generator under concurrent synthetic client requests:

0.62 ms
p99 Latency
5,200+
Req / Sec (Single Redis)
0.00%
Race Condition Breaches