Problem Statement
Sketch a Redis-backed token bucket that works across many API instances without double-spending tokens.
Explanation
Use a single LUA script to compute tokens available since last refill, cap by burst size, and atomically decide allow/deny. Store last_refill_ts and tokens_left per key. The script reads, calculates new tokens using now, clamps, then decrements if request fits, returning remaining and reset.
This read–modify–write in one command prevents races across instances. Add key expiry based on idle time to reclaim memory and return headers based on the script output.
Code Solution
SolutionRead Only
EVALSHA(bucket.lua) -> {allowed, remaining, resetEpoch}