Scrivio Interview library
InternalsIntermediate6 min read · updated 13 November 2026

Token bucket and the closely related generic cell rate algorithm (GCRA) enforce a rate with an allowed burst while storing a single number per key.

Explain how GCRA works, give the core of a Redis Lua implementation, and compare it with the sliding-window log in memory, precision and cost.

GCRA stores one number per key, the theoretical arrival time (TAT), the moment when the bucket would be empty again. With an emission interval T = period / limit and a burst tolerance tau = T x (burst - 1), a request at time now is allowed if now >= TAT - tau, and the TAT then becomes max(TAT, now) + T. In Redis that is a five-line Lua script doing one GET and one SET with an expiry, so it costs O(1) time and one value per key, against up to limit members and O(log N) work for a sorted-set log, and it returns an exact retry-after; its weakness is that it is harder to explain than 'N per minute'.

Why this question is asked

Token bucket and GCRA are what most serious rate limiters use once limits grow beyond a few dozen per minute, because they enforce a smooth rate with a controlled burst while storing almost nothing. GCRA in particular looks strange at first, since it stores a time rather than a count, which is exactly why interviewers ask about it. In this answer, we will recap token buckets, build up GCRA from them, trace a few requests by hand, write the Redis script, and then compare it with the sliding-window log.

1A Quick Recap of the Token Bucket

A token bucket holds up to burst tokens and refills at a steady rate, for example 10 tokens per second. Each request takes one token; if the bucket is empty, the request is rejected. The bucket lets a client send a short burst after being quiet, but never more than the long-run rate on average.

A naive implementation stores two numbers, the token count and the last refill time, and recomputes the count on each request. GCRA, the generic cell rate algorithm from telecom networks, is the same behaviour expressed with one number.

2How GCRA Works

GCRA defines the emission interval T as the time one request 'costs': period divided by limit. For 10 requests per second, T is 100 ms. It defines the burst tolerance tau as T x (burst - 1), how far ahead of schedule a client may run. For a burst of 3, tau is 200 ms.

The stored value is the theoretical arrival time, TAT: when this client's next request would be due if it had sent requests exactly on schedule. A request at time now is allowed if now >= TAT - tau, meaning the client is not more than tau ahead of schedule. If allowed, the new TAT is max(TAT, now) + T. The max handles a client that has been quiet: its TAT is in the past, so we restart the schedule from now rather than letting idle time pile up into an unlimited burst.

Tracing 10 per second with burst 3 (T = 100 ms, tau = 200 ms)
Request atTAT beforenow >= TAT - tau?TAT after
1000 msnone, use 10001000 >= 800: allow1100
1000 ms11001000 >= 900: allow1200
1000 ms12001000 >= 1000: allow1300
1000 ms13001000 >= 1100: no, retry in 100 ms1300 (unchanged)
1100 ms13001100 >= 1100: allow1400
Three requests pass at once (the burst), then one every 100 ms.

3The Redis Script

The script reads the TAT, decides, and writes the new TAT with an expiry set to when it would no longer matter. It returns two numbers: allowed or not, and how long to wait.

SQL
-- KEYS[1] = rl:gcra:{apiKey}
-- ARGV[1] = now (ms), ARGV[2] = T (ms), ARGV[3] = tau (ms)
local now = tonumber(ARGV[1])
local T = tonumber(ARGV[2]) -- 100 for 10 per second
local tau = tonumber(ARGV[3]) -- 200 for a burst of 3
local tat = tonumber(redis.call('GET', KEYS[1])) or now -- missing key: start at now
if now < tat - tau then
return {0, tat - tau - now} -- {0, 100}: wait 100 ms
end
local new = math.max(tat, now) + T
redis.call('SET', KEYS[1], new, 'PX', math.ceil(new - now)) -- key vanishes once idle
return {1, 0} -- allowed

Notice the expiry: once real time passes the TAT, the stored value no longer affects any decision, because max(TAT, now) would pick now. So the key can expire at that moment, and idle clients leave nothing behind. GET on a missing key returns false in Lua, tonumber(false) gives nil, and the 'or now' turns that into a fresh schedule.

Two practical points. Use one time source, either redis.call('TIME') inside the script or clients with synchronised clocks, because the whole algorithm is arithmetic on timestamps. And call the script with EVALSHA, or register it as a Redis function and call it with FCALL, so the body is not sent on every request; Spring's DefaultRedisScript does the EVALSHA part automatically.

4Comparing GCRA With the Sliding-Window Log

The sliding-window log keeps a sorted set with one member per accepted request in the window, trims old members and counts the rest on every check. Its memory grows with the limit, and each check does O(log N) work in the sorted set plus the removals. GCRA keeps one value and does O(1) work regardless of the limit, so a limit of 10,000 per minute costs the same as 10 per minute.

On precision, both avoid the window-edge burst of fixed windows. GCRA enforces a smooth rate with a defined burst and gives an exact retry-after for free. The log enforces exactly 'at most N in any 60 seconds', which is easier to explain to customers and matches how plans are usually written. GCRA's 'smooth rate with a burst of B' is harder to put in a pricing page.

Sliding-window log versus GCRA
AspectSliding-window logGCRA
Stored per keyUp to limit membersOne number
Work per checkO(log N) plus removalsO(1)
Window-edge burstsNoneNone, burst set by tau
Retry-afterNeeds extra ZRANGEExact, from the same arithmetic
Easy to explainYes: N per windowLess: rate plus burst
FitsLow limits, exact wordingHigh limits, high traffic

5Follow-up questions

How would you charge 5 tokens for an expensive export request?

Generalise the increment: a request of cost n moves the TAT by n x T instead of T. The new TAT would be max(TAT, now) + n x T, and the request is allowed only if that new TAT minus now is at most tau + T, the full burst capacity in time. For n = 1 this reduces to the normal rule. Pass n as another argument to the script, and reject requests whose cost exceeds the burst, since they could never fit.

Is GCRA the same as a token bucket?

It produces the same allow and reject decisions as a token bucket with the same rate and capacity, just stored differently: the bucket stores how many tokens are left, GCRA stores when the bucket will be full again. Storing a time avoids a separate refill timestamp.

What happens if the clocks of two gateways differ by 50 ms?

Each gateway's requests are judged against a slightly different 'now', so a client can gain or lose up to that skew in tolerance, roughly half a request at 10 per second. Using Redis TIME inside the script removes the problem.

6Conclusion

In this answer, we saw that GCRA stores one theoretical arrival time per key, allows a request when now >= TAT - tau, and moves the TAT to max(TAT, now) + T, which gives a token bucket's smooth rate and burst in one value. The Redis script is a GET, a comparison and a SET with an expiry, called with EVALSHA or as a function and using one clock. Compared with the sliding-window log it costs O(1) time and memory regardless of the limit and gives an exact retry-after, at the cost of being harder to explain than 'N per minute'.

What to say in the interviewAbout 90 seconds aloud

Open with

GCRA is a token bucket expressed as a single timestamp. I compute the emission interval T as the period divided by the limit, so 10 per second gives 100 ms, and the burst tolerance tau as T times burst minus one.

Then, if they want more

Per key I store the theoretical arrival time, when the next request is due if the client stayed exactly on schedule. A request at time now is allowed if now is at least TAT minus tau, and then the TAT becomes max of TAT and now, plus T. The max stops idle time from accumulating.

In Lua: get the TAT, defaulting to now; if now is less than TAT minus tau, return 0 and the wait, which is TAT minus tau minus now; otherwise compute the new TAT, SET it with PX equal to new minus now so the key expires once it no longer matters, and return 1.

Compared with a sorted-set sliding log, it stores one value instead of up to limit members and is O(1) instead of O(log N) with removals, so it suits high limits, and it gives an exact retry-after. The downside is that rate plus burst is harder to explain than N per minute.

I would use one time source, like Redis TIME, and call it with EVALSHA or as a function.

About this answer

Last updated
13 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 "Explain how GCRA works, give the core of a Redis Lua implementation, and compare it with...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/779bc9f873/