Redis in depth · Build it
Build a sliding-window rate limiter in Lua
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Write a Redis-based rate limiter for our OTP API: at most 5 OTP requests per phone number in any 10-minute window, across all API servers. Write the Lua script and the code that calls it, in any language.
Then
Follow-ups the interviewer asks next
- Why one script and not three commands from the app?
- Whose clock do you use, and why?
- Two requests arrive in the same millisecond. What goes wrong with your member value?
- How does this run in Redis Cluster?
- Redis 8.8 added
INCREX. When would that be enough? - Redis is down. Do you allow OTPs or block them?
- How do you test the limiter?
The answer
What a strong answer covers
- A sliding log in a sorted set per phone (
otp:rl:{<phone>}), scores = request times in milliseconds. The script:ZREMRANGEBYSCORE key 0 now-windowto drop old entries;ZCARD key; if under 5,ZADD key now <unique member>,PEXPIRE key window, and return allowed with the remaining count; otherwise read the oldest entry (ZRANGE key 0 0 WITHSCORES) and return denied with retry-after = oldest + window − now. - The script runs as one unit, so two servers can't both read 4 and both add; three separate calls from the app would race.
- The key goes in
KEYS[1], never built inside the script, so Cluster can route it; window, limit and request id go inARGV. - The member must be unique (time plus a request id): same-millisecond requests with the time alone overwrite each other and undercount.
- Clock: Redis's own
TIMEinside the script keeps all API servers on one clock (scripts are replicated as their effects since Redis 7, so that's safe), or pass the app's time if servers are well synchronised. - Calling code: load once (
SCRIPT LOAD, thenEVALSHA, falling back toEVALonNOSCRIPT; most clients do this), or use Redis Functions. Denied → HTTP 429 withRetry-After. - Alternatives: fixed window with
INCRandEXPIRE(allows a double burst at window edges); on Redis 8.8+,INCREX otp:rl:{phone} BYINT 1 UBOUND 5 EX 600 ENXdoes an atomic fixed window in one command; a token bucket script for smoother limits. - Redis down: fail closed for OTPs (each SMS costs money and attackers abuse OTP endpoints), with a small local limit per server as a fallback. Also limit per IP and per device.
- Tests: concurrency tests firing parallel requests at the limit, window edges with a controllable clock, and key expiry.
The red pen
Common traps
Avoid:GET then SET from the app; the timestamp alone as the member; no TTL on the key; building key names inside the script.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.