Skip to the page

Redis in depth · mid

Lua scripts and rate limiting in Redis

A Lua script runs as one unit, so a check and an update cannot race. It is the right tool for a sliding-window rate limiter, if you write it carefully.

The notes

What you must know

  • A script runs without other commands in between, so two servers cannot both read 4 and both add. Three separate calls from the app would race.
  • Sliding log in a sorted set per key (for example otp:rl:{phone}), with request times as scores. ZREMRANGEBYSCORE to drop old entries, ZCARD to count, ZADD and PEXPIRE if allowed, otherwise return a retry-after time from the oldest entry. Pass keys in KEYS and other values in ARGV. Never build key names inside the script, so Cluster can route it.
  • The sorted set member must be unique (time plus a request id). With the time alone, same-millisecond requests overwrite each other and are undercounted. Use Redis TIME inside the script for one clock across API servers, or pass a well-synchronised app time.
  • Load once with SCRIPT LOAD and call EVALSHA, falling back to EVAL on NOSCRIPT (most clients do this). Denied requests return HTTP 429 with Retry-After.
  • Alternatives: a fixed window with INCR and EXPIRE (allows a double burst at the window edge), or a token bucket script for smoother limits. Decide what happens when Redis is down: for OTP limits, usually fail closed.
  • A script is not a rollback transaction. If it errors halfway, earlier writes stay. Validate everything first and write last.
  • Never call KEYS inside a script: it walks the whole keyspace on the main thread and blocks everyone. A script that has written cannot be stopped with SCRIPT KILL.

The red pen

Common traps: mistake → fix

  • Mistake: GET then SET from the app is a limiter

    Fix: it races across servers.

  • Mistake: The timestamp alone is a safe member

    Fix: equal times overwrite.

  • Mistake: Scripts roll back on error

    Fix: they do not; atomic only means no interleaving.

  • Mistake: SCAN inside a script replaces KEYS safely

    Fix: a script must stay short; design keys instead.

Easy to hard

Questions interviewers ask, easy to hard

  1. Write a limiter: 5 OTP requests per phone in any 10 minutes.
  2. Why must the script be one unit?
  3. Review this coupon Lua script that freezes Redis.
  4. Fixed window or sliding window?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview