Scrivio Interview library
CodingFoundations6 min read · updated 13 November 2026

A sliding-window log rate limiter keeps a timestamp for every accepted request and counts how many fall within the last window, which avoids the bursts at window edges that a fixed window allows.

Write a Redis Lua script that allows at most 20 requests per 60 seconds per user using a sorted set, and explain its memory cost and why it has to be a script.

Keep one sorted set per user, rl:{user}, where each accepted request is a member scored by its timestamp. The Lua script removes members older than 60 seconds with ZREMRANGEBYSCORE, counts the rest with ZCARD, and if fewer than 20 remain adds the new request with a unique member and sets PEXPIRE, returning 1, otherwise 0. It must be one script because remove, count and add have to be atomic, and memory grows with the limit since each key holds up to 20 members, which is fine here but costly for limits like 10,000 per minute.

Why this question is asked

Rate limiting is one of the most common uses of Redis, and the sliding-window log is the most precise of the classic algorithms, which makes it a favourite coding question. It also hides three subtle bugs, a race between instances, members that overwrite each other, and clocks that disagree, which is what the interviewer is really testing. In this answer, we will recap the algorithm, write the script line by line, show the race that makes it a script, and then look at memory cost and the clock question.

1A Quick Recap of the Sliding-Window Log

A fixed-window limiter counts requests per calendar minute, so a user can send 20 requests at 12:00:59 and 20 more at 12:01:00, 40 in two seconds. The sliding-window log avoids that by remembering the time of every accepted request and, on each new request, counting how many fall within the last 60 seconds from now.

A Redis sorted set fits this perfectly. It stores unique members, each with a numeric score, kept in score order. We use the request time in milliseconds as the score, so ZREMRANGEBYSCORE can drop everything older than the window in one command, and ZCARD, which is O(1), tells us how many remain.

2The Script, Line by Line

We pass the key in KEYS so Redis Cluster can route it, and the time, window, limit and a unique id in ARGV.

SQL
-- KEYS[1] = rl:{user42}
-- ARGV[1] = now (ms), ARGV[2] = window (60000), ARGV[3] = limit (20), ARGV[4] = unique id
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window) -- drop requests older than 60 s
if redis.call('ZCARD', key) < limit then -- e.g. 19 < 20
redis.call('ZADD', key, now, ARGV[4]) -- record this request
redis.call('PEXPIRE', key, window) -- idle users' keys disappear
return 1 -- allowed
end
return 0 -- rejected: 20 in the last 60 s
Step throughOne rate-limit check
  1. Remove members older than now - 60 sZREMRANGEBYSCORE
  2. Fewer than 20 left?ZCARD
    YesZADD now id, PEXPIRE, return 1NoReturn 0, record nothing

2 steps in order. Play them, or step through them one at a time.

All of this runs as one atomic script.

Notice that we only add the request when it is accepted. Rejected requests are not recorded, so a user hammering the endpoint cannot push their own window forward forever. PEXPIRE refreshes the key's lifetime to one window on every accepted request, so a user who stops calling leaves no key behind after 60 seconds.

From Java, Spring's DefaultRedisScript loads the script and RedisTemplate.execute runs it, sending EVALSHA with the script's hash and falling back to EVAL if the server has not seen it yet.

3Why the Member Must Be Unique

A sorted set stores each member once. If we used the timestamp itself as the member, two requests arriving in the same millisecond would write the same member: the second ZADD would just update the first, and the set would count one request instead of two. Under load, that undercounting is common.

So the member is the timestamp plus something unique, such as the request id or a random suffix: '1731400000123-7f3a'. The score stays the timestamp, so the window logic is unchanged.

4Why It Has to Be a Script

Suppose we did the same steps as separate calls from Java. Two gateway instances handle requests for the same user at the same moment, and the user has 19 requests in the window.

Step throughThe race without a script
Instance ARedisInstance B
ZCARD rl:{user42}
19
ZCARD rl:{user42}
19
ZADD (19 < 20, allow)
ZADD (19 < 20, allow)
set now holds 21 members

7 messages in order. Play them, or step through them one at a time.

Both read 19 before either wrote, so the limit is exceeded.

Both saw 19, both decided to allow, and the user got 21 requests. Redis runs a Lua script as one unit: no other command runs between its steps, so the second check always sees the first request's ZADD. MULTI and EXEC cannot fix this on their own, because inside a transaction we cannot read ZCARD's result and decide whether to ZADD; a script can.

5Memory Cost and Choosing a Clock

Each key holds up to limit members. For 20 per minute that is at most 20 small entries per active user; with sets that small Redis uses the compact listpack encoding, roughly tens of bytes per entry, so a million active users cost on the order of a gigabyte or less. For a limit of 10,000 per minute, each busy key holds up to 10,000 members in the skiplist encoding, around a megabyte per key, and each check does more work. At that scale a sliding-window counter or a token bucket, which store one or two numbers per key, fit better.

The window is only correct if all timestamps come from one clock. If two gateway instances disagree by 300 ms, their requests are placed in the wrong order and the window shifts. There are two clean choices: call redis.call('TIME') inside the script, so the Redis server's clock is the only clock (scripts may do this since Redis 5 replicates their effects rather than the script itself), or pass timestamps from clients whose clocks are synchronised with NTP.

6Follow-up questions

How would you also return how long the client should wait?

When the request is rejected, the oldest member in the window decides when a slot frees up. Inside the script, ZRANGE key 0 0 WITHSCORES returns the oldest timestamp, and the wait is oldest + window - now milliseconds. The script returns {0, wait} instead of 0, and the API turns it into a Retry-After header in seconds, rounded up.

Why not use INCR with a one-minute expiry?

That is a fixed-window counter: cheap and simple, but it allows up to twice the limit across a window boundary. If that burst is acceptable, it is a fine choice; the sliding log exists to remove it.

What happens in Redis Cluster?

Each user's limiter is one key, and the script touches only that key, so it runs on whichever node owns its slot. The braces in rl:{user42} make the user id the hash tag, which keeps any related keys for that user on the same node if the script later needs more than one.

7Conclusion

In this answer, we wrote a sliding-window log limiter as a Lua script over a sorted set: remove members older than the window, count what remains, and add a uniquely named member with a PEXPIRE when under the limit. The member must be unique or same-millisecond requests undercount, the steps must be one script or two instances can both see 19 and both allow, memory grows with the limit so high limits suit other algorithms, and all timestamps should come from one clock.

What to say in the interviewAbout 80 seconds aloud

Open with

I would keep a sorted set per user, say rl:{user42}, with one member per accepted request, scored by its timestamp in milliseconds. The script takes the key in KEYS and now, the 60,000 ms window, the limit of 20 and a unique id in ARGV.

Then, if they want more

It runs ZREMRANGEBYSCORE from 0 to now minus the window to drop old requests, then ZCARD. If the count is under 20, it does ZADD with now as the score and the unique id as the member, sets PEXPIRE to the window so idle keys disappear, and returns 1; otherwise it returns 0 without recording anything.

The member has to be unique, like the timestamp plus the request id, because two requests in the same millisecond would otherwise overwrite each other and be undercounted. It has to be a script because remove, count and add must be atomic; as separate calls, two instances could both read 19 and both add, giving 21.

Memory grows with the limit: 20 members per user is cheap, but 10,000 per minute per key gets expensive, and there I would use a sliding-window counter or a token bucket. And I would use one clock, either Redis TIME inside the script or synchronised client clocks.

About this answer

Last updated
13 November 2026
Versions it names
Redis 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a Redis Lua script that allows at most 20 requests per 60 seconds per user using a...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/dedc285d05/