Why we replaced our custom rate-limiter middleware with a 20-line Redis Lua token bucket
For a long time our API gateway used the classic Redis INCR + EXPIRE fixed-window counter to rate-limit agent tool calls. It looked fine on paper until a couple of aggressive coding loops started hitting our endpoints right at :59 seconds and again at :00 seconds—effectively pulling 2x their allowed burst in two seconds.
On top of that, doing GET -> check -> INCR in Python instead of atomically meant parallel requests from the same worker occasionally slipped past the cap together.
One atomic Lua script in Redis
Instead of pulling in a heavy gateway proxy, we moved the token bucket math straight into a tiny Redis Lua script so the read, refill, and deduct happen in a single atomic step:
lua-- KEYS[1] = bucket key, ARGV[1] = capacity, ARGV[2] = refill_per_sec, ARGV[3] = now_sec local data = redis.call("HMGET", KEYS[1], "tokens", "ts") local tokens = tonumber(data[1]) or tonumber(ARGV[1]) local last_ts = tonumber(data[2]) or tonumber(ARGV[3]) local elapsed = math.max(0, tonumber(ARGV[3]) - last_ts) tokens = math.min(tonumber(ARGV[1]), tokens + elapsed * tonumber(ARGV[2])) if tokens < 1 then redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", ARGV[3]) redis.call("EXPIRE", KEYS[1], 120) return 0 end redis.call("HMSET", KEYS[1], "tokens", tokens - 1, "ts", ARGV[3]) redis.call("EXPIRE", KEYS[1], 120) return 1
Zero race conditions, smooth refill, and no more boundary double-dipping. Sometimes 20 lines of Lua in Redis is all you need.