Quick revision
The short answer
The script increments a counter key for the current minute and, only when the count is 1, sets the key's expiry; it returns the count, and Java allows the request if the count is at most 100. We call it from Spring with a DefaultRedisScript<Long> and redisTemplate.execute, passing the key in KEYS so Redis Cluster routes it correctly. A script is better than INCR then EXPIRE from Java because it runs atomically on the server, so a client crash between the two calls cannot leave a counter without a TTL that blocks the key forever.
What to remember
In this answer, we built a fixed-window limiter as a three-line Lua script that increments a per-minute key and sets its expiry only on the first request, called it from Spring with DefaultRedisScript and StringRedisTemplate, and passed the key through KEYS for Cluster routing. We saw that separate INCR and EXPIRE calls can leave a counter without a TTL, which the atomic script prevents, and that fixed windows allow double bursts at edges, which sliding windows and token buckets smooth out.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The script increments a counter key for the current minute and, only when the count is 1, sets the key's expiry; it returns the count, and Java allows the request if the count is at most 100. We call it from Spring with a DefaultRedisScript<Long> and redisTemplate.execute, passing the key in KEYS so Redis Cluster routes it correctly. A script is better than INCR then EXPIRE from Java because it runs atomically on the server, so a client crash between the two calls cannot leave a counter without a TTL that blocks the key forever.
Why this question is asked
Rate limiting is one of the first things a public API needs and one of the most common Redis uses in Spring services. The fixed-window version is short enough to write in an interview, yet it hides a real concurrency trap that separates people who have run it in production from those who have only read about it. In this answer, we will recap how a fixed window works, write the Lua script, call it from Spring Data Redis, see exactly what goes wrong with two separate commands, and then look at the burst problem at window edges and the smoother alternatives.
1A Quick Recap of the Fixed Window
A fixed-window limiter divides time into windows, here one minute each, and keeps one counter per API key per window. Each request increments the counter. If the new value is above 100, the request is rejected, usually with HTTP 429 Too Many Requests. When the minute ends, a new window starts with a new counter, and the old counter expires on its own.
We name the key after the window, for example rate:{key-abc}:202611041015 for the minute 10:15 on 4 November 2026. Including the minute in the name means we never have to reset a counter; a new minute simply uses a new key. The braces form a hash tag, so all of one API key's counters land in the same Redis Cluster slot.
2Writing the Lua Script
Redis runs Lua scripts on the server with EVAL or EVALSHA. Inside, redis.call executes a Redis command. KEYS holds the key names the script touches, and ARGV holds other arguments.
Notice that we set the expiry only when count is 1, that is, on the first request in the window. Setting it on every request would keep pushing the expiry forward. We return the count and compare it in Java, which keeps the limit in application configuration; we could equally pass the limit as ARGV[2] and return 0 or 1 from the script.
We pass the key name in KEYS, never build it inside the script. In Redis Cluster, the client uses KEYS to find the node that owns the slot, and Redis checks that every key the script touches was declared.
3Calling It From Spring Data Redis
Spring Data Redis wraps a script in DefaultRedisScript. It computes the script's SHA1 and uses EVALSHA, falling back to EVAL the first time a node has not seen it, so the script text is not sent on every call.
We use StringRedisTemplate so the key and the "60" argument are sent as plain strings; with a JDK serializer, the arguments would be serialized Java objects and EXPIRE would fail. The result type Long matches Lua's integer reply. A filter or interceptor calls allow(apiKey) and returns 429 with a Retry-After header when it is false.
4Why Not INCR Then EXPIRE From Java?
Here is the version many people write first.
5 messages in order. Play them, or step through them one at a time.
Without a window in the key, this customer stays blocked forever.
If anything stops the client between the two calls, a pod restart, a timeout or an exception, the counter exists with no TTL. Because our key includes the minute, the leftover key only wastes memory forever. But in the common variation where the key is just rate:{apiKey} without a window, the counter never resets, and the customer is blocked permanently once the count passes 100.
The script removes the gap. Redis executes a script atomically: while it runs, no other command from any client runs, and because both commands run inside the server, there is no client in the middle that can disappear between them. The expiry is set in the same step as the first increment. A MULTI/EXEC transaction would also send both together, but it cannot make the EXPIRE conditional on the INCR result without a WATCH and retry loop, which is why the script is the cleaner tool.
5The Burst at Window Edges and Smoother Options
Fixed windows are simple but allow bursts. A client can send 100 requests at 10:15:59 and another 100 at 10:16:00, so 200 requests pass within two seconds, twice the intended rate.
A sliding window log fixes this by storing each request's timestamp in a sorted set and counting entries from the last 60 seconds: ZREMRANGEBYSCORE to drop old ones, ZCARD to count, ZADD to record, all inside one script. It is exact but stores one entry per request. A sliding window counter approximates it by weighting the previous window's count. A token bucket, which the follow-up asks about, allows controlled bursts while enforcing an average rate.
6Follow-up questions
How would you implement a token bucket instead?
Store two fields per API key in a hash: tokens and the last refill time. The script reads both, computes how many tokens have been added since the last refill at the configured rate, for example 100 per 60 seconds, caps the total at the bucket size, and then takes one token if at least one is available, writing back the new count and time and setting an expiry so idle buckets disappear. Passing the current time as an argument or reading it with redis.call('TIME') keeps all clients on one clock. Because all of this happens in one script, two concurrent requests can never both take the last token.
Is the Lua approach safe with Redis Cluster?
Yes, as long as every key the script touches is passed in KEYS and lives in one slot. Our script touches a single key, so it always does. A script that touched counters for two API keys would need them to share a hash tag.
What happens if Redis is down?
The limiter must choose to fail open, letting requests through, or fail closed, rejecting them. For abuse protection most services fail open with a short timeout and an alert, because blocking all traffic is worse than briefly not limiting it.
7Conclusion
In this answer, we built a fixed-window limiter as a three-line Lua script that increments a per-minute key and sets its expiry only on the first request, called it from Spring with DefaultRedisScript and StringRedisTemplate, and passed the key through KEYS for Cluster routing. We saw that separate INCR and EXPIRE calls can leave a counter without a TTL, which the atomic script prevents, and that fixed windows allow double bursts at edges, which sliding windows and token buckets smooth out.
Open with
I would key the counter by API key and minute, for example rate:{apiKey}:202611041015, with the API key in a hash tag so it works in Redis Cluster. The Lua script is: local c = redis.call INCR on KEYS[1]; if c equals 1 then EXPIRE KEYS[1] for ARGV[1] seconds; return c.
Then, if they want more
Setting the expiry only on the first increment keeps it from sliding. In Spring I create a DefaultRedisScript of Long with that text and call stringRedisTemplate.execute with the script, List.of(key) and "60", then allow the request if the count is at most 100 and otherwise return 429. Spring sends it with EVALSHA, so the text is not resent each time.
The script is better than INCR followed by EXPIRE from Java because it runs atomically on the server: no other command interleaves, and there is no gap where the client can crash after INCR but before EXPIRE, leaving a counter with no TTL that never resets.
I would also mention the weakness of fixed windows: a client can send 100 requests at the end of one minute and 100 at the start of the next. If that matters, I would use a sliding window with a sorted set or a token bucket, also implemented as a script.
About this answer
- Last updated
- 12 November 2026
- 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 for a fixed-window rate limiter that allows 100 requests per...": https://scrivio-interview-library.netlify.app/databases/redis/5784be0bdc/