Skip to the page

Redis in depth · Build it

Build a sliding-window rate limiter in Lua

The 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

  1. Why one script and not three commands from the app?
  2. Whose clock do you use, and why?
  3. Two requests arrive in the same millisecond. What goes wrong with your member value?
  4. How does this run in Redis Cluster?
  5. Redis 8.8 added INCREX. When would that be enough?
  6. Redis is down. Do you allow OTPs or block them?
  7. 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-window to 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 in ARGV.
  • 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 TIME inside 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, then EVALSHA, falling back to EVAL on NOSCRIPT; most clients do this), or use Redis Functions. Denied → HTTP 429 with Retry-After.
  • Alternatives: fixed window with INCR and EXPIRE (allows a double burst at window edges); on Redis 8.8+, INCREX otp:rl:{phone} BYINT 1 UBOUND 5 EX 600 ENX does 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 voice

Practise 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.

Start your free interview