Scrivio Interview library
DebuggingIntermediate6 min read · updated 13 November 2026

An API gateway calls a Redis rate-limit script on every request: a sorted-set sliding log, with limits up to 10,000 requests per minute for large API keys. At 180,000 checks per second the Redis primary reaches 95 percent CPU and adds 8 ms to p99.

Find where the cost comes from and redesign the limiter so it scales.

The cost comes from running a sorted-set sliding log on one Redis thread at 180,000 checks per second, with keys holding up to 10,000 members each: every check trims, counts and inserts into a large skiplist inside a Lua script, and INFO commandstats shows evalsha dominating CPU time. We move high-limit tiers to O(1) algorithms such as GCRA, a token bucket or a sliding-window counter, make sure the gateway calls EVALSHA or a function, cut calls by leasing tokens in small blocks per gateway instance, and shard keys across a Redis Cluster.

Background to this question

A rate limiter is supposed to protect the platform, so it is embarrassing when it becomes the bottleneck. This scenario is common because the sliding-window log is the first algorithm people learn, and it works well until the biggest customers get the biggest limits. In this answer, we will find where the CPU goes, then fix it in four layers: a cheaper algorithm, cheaper script calls, fewer calls, and more Redis primaries.

1Finding Where the Cost Comes From

Redis executes commands on a single main thread, so 95 percent CPU on the primary means that thread is nearly saturated, and every command, including the limiter's own, queues behind the others. That queueing is the 8 ms we see at p99.

INFO commandstats shows, for each command, the number of calls, total microseconds and microseconds per call. Here cmdstat_evalsha dominates usec, and its usec_per_call is far higher than a plain GET's. SLOWLOG and LATENCY DOCTOR confirm that the script is where time goes.

YAML
INFO commandstats
# cmdstat_evalsha:calls=982110345,usec=3210554012,usec_per_call=3.27,...
# cmdstat_get:calls=120044500,usec=96035600,usec_per_call=0.80,...

Now look at what each check does for a large key. The sorted set holds up to 10,000 members, so Redis stores it as a skiplist with a hash table, around a megabyte per busy key. ZREMRANGEBYSCORE costs O(log N + M), where M is the number removed, ZADD costs O(log N), and ZCARD is O(1); on top of that come the Lua call overhead, memory allocation for every new member and cache misses walking a large structure. The per-check work grows only slowly with the limit, but memory grows linearly, and at 180,000 checks per second everything runs on one thread. The design simply does not scale with the biggest tiers.

2Fix 1: O(1) Algorithms for High-Limit Tiers

Keep the sliding log only where limits are small, and move large tiers to algorithms that store one or two numbers per key. GCRA or a token bucket stores one value and does a GET and SET per check. A sliding-window counter stores two integer counters, the current fixed window and the previous one, and estimates the sliding count by weighting the previous window by the share of it still inside the sliding window.

SQL
-- sliding-window counter, window = 60 s, limit = 10000
-- now = 12:01:15, so 15 s into the current minute
local prev = tonumber(redis.call('GET', KEYS[1])) or 0 -- count for 12:00, e.g. 8000
local curr = tonumber(redis.call('GET', KEYS[2])) or 0 -- count for 12:01, e.g. 3500
local elapsed = tonumber(ARGV[1]) -- 15000 ms
local estimate = prev * (60000 - elapsed) / 60000 + curr -- 8000 * 0.75 + 3500 = 9500
if estimate < 10000 then
redis.call('INCR', KEYS[2]) -- 3501
redis.call('PEXPIRE', KEYS[2], 120000)
return 1
end
return 0
Per-check cost for a 10,000 per minute key
AlgorithmMemory per keyWork per check
Sorted-set log~1 MB (10,000 members)O(log N) plus trims and allocation
Sliding-window counterTwo integersTwo GETs and an INCR
GCRA / token bucketOne numberOne GET and one SET

Notice that the counter assumes requests in the previous minute were spread evenly. It is slightly approximate, which is acceptable for a 10,000-per-minute limit, and it costs the same whether the limit is 100 or 100,000. In Redis Cluster both keys need the same hash tag, such as rl:{apiKey}:1200 and rl:{apiKey}:1201, so the script can touch them together.

3Fix 2: Make Sure Scripts Are Not Resent

Check how the gateway calls the script. If it sends EVAL with the full script body on every request, Redis receives and hashes the body each time before finding the cached compiled version. Spring's DefaultRedisScript sends EVALSHA with the SHA1 of the body and falls back to EVAL only when the server answers NOSCRIPT, for example after a restart. Redis 7 functions go further: the library is loaded once and survives restarts, and the gateway calls it by name with FCALL. commandstats showing cmdstat_eval with many calls is a sign this fix is needed.

4Fix 3: Fewer Calls Through Token Leasing

The biggest saving is not making most calls at all. Each gateway instance leases tokens from Redis in small blocks, for example 50 at a time, with one script call that subtracts 50 from the customer's budget. It then spends those tokens locally, in memory, and goes back to Redis only when the block runs out. For a large customer at 10,000 per minute spread over 40 instances, Redis now sees one call per 50 requests instead of one per request.

The price is a bounded overshoot. Tokens leased near the end of a window can be spent after the window has moved on, so in the worst case the customer gets up to one unspent block per instance more than the limit in a window. Leases with a short lifetime, such as one second, and block sizes scaled to the limit keep that small.

Step throughLeasing tokens in blocks
Gateway instanceLocal counterRedis
lease 50 tokens for apiKey A
granted 50
spend 1 token per request
49, 48, ... 0
lease 50 more
granted 50, or fewer if budget is low

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

One Redis call now covers 50 requests.

5Fix 4: Spread the Keys Across Primaries

Rate-limit keys are independent of each other, so they shard perfectly. Moving to Redis Cluster with keys like rl:{apiKey} spreads customers across several primaries, each with its own main thread. With six primaries, each sees about a sixth of the checks. This is the fix that buys headroom for growth, but it works best after the first three, since sharding an expensive algorithm just spreads the expense.

6Follow-up questions

How much overshoot does token leasing allow with 40 gateway instances?

In the worst case each instance holds one partly unspent block when the window moves on, so the overshoot is at most 40 x 50 = 2,000 requests in a window for a single API key, about 20 percent of a 10,000 limit. That is the bound to document. To shrink it, scale the block size with the limit, for example one percent of the limit divided by the number of instances, expire leases after a second, and let instances return unused tokens on shutdown.

Would read replicas help?

No. Every check writes, because it records the request or updates the TAT, and writes must go to the primary. Replicas cannot share this load.

Should small-limit tiers stay on the sliding log?

They can. For limits of a few dozen per minute, the log is cheap, exact and easy to explain, and those keys are not where the CPU goes. Many platforms use the exact algorithm for small tiers and an O(1) one for large tiers.

7Conclusion

In this answer, we saw that the limiter's cost came from running a sorted-set sliding log on one thread for keys with up to 10,000 members at 180,000 checks per second, visible in commandstats as evalsha time. We fixed it by moving high tiers to GCRA, token buckets or a sliding-window counter, calling scripts by EVALSHA or as functions, leasing tokens in blocks per gateway instance with a documented bounded overshoot, and sharding the independent keys across a Redis Cluster.

What to say in the interviewAbout 80 seconds aloud

Open with

Redis runs commands on one main thread, so 95 percent CPU means everything queues, which is our 8 ms. INFO commandstats would show evalsha dominating total CPU time.

Then, if they want more

For the big API keys, each check trims and inserts into a sorted set of up to 10,000 members, a skiplist of about a megabyte per key, inside a Lua script, 180,000 times a second. The per-check work is O(log N) plus trims and allocation, and memory grows with the limit, so it does not scale for the large tiers.

I would fix it in layers. First, move high-limit tiers to an O(1) algorithm: GCRA or a token bucket with one value per key, or a sliding-window counter that weights the previous window's count by the part of it still inside the window.

Second, make sure the gateway uses EVALSHA or Redis functions, not EVAL with the full body; Spring's DefaultRedisScript does EVALSHA with a NOSCRIPT fallback. Third, cut calls by letting each gateway instance lease tokens in blocks of, say, 50 and spend them locally, accepting a bounded overshoot of at most one block per instance. Fourth, since limits are independent, shard keys like rl:{apiKey} across a Redis Cluster.

About this answer

Last updated
13 November 2026
Versions it names
Redis 7
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 "Find where the cost comes from and redesign the limiter so it scales.": https://scrivio-interview-library.netlify.app/databases/redis-patterns/ff82e9949d/