ratelimit.lua28 lines, 1.1 KB
| 1 | -- A token bucket. KEYS[1] holds up to ARGV[1] tokens, refilled evenly over |
| 2 | -- ARGV[2] milliseconds, and every request takes one. Redis runs a script all |
| 3 | -- at once, so two gateways can never both take the last token. |
| 4 | local limit = tonumber(ARGV[1]) |
| 5 | local period = tonumber(ARGV[2]) |
| 6 | |
| 7 | -- Redis's clock, not ours: every gateway instance agrees on the time. |
| 8 | local t = redis.call('TIME') |
| 9 | local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000) |
| 10 | |
| 11 | -- A new bucket starts full. Then add what trickled in since the last request. |
| 12 | local bucket = redis.call('HMGET', KEYS[1], 'tokens', 'at') |
| 13 | local tokens = tonumber(bucket[1]) or limit |
| 14 | local at = tonumber(bucket[2]) or now |
| 15 | tokens = math.min(limit, tokens + (now - at) * limit / period) |
| 16 | |
| 17 | local allowed = 0 |
| 18 | if tokens >= 1 then |
| 19 | tokens = tokens - 1 |
| 20 | allowed = 1 |
| 21 | end |
| 22 | redis.call('HSET', KEYS[1], 'tokens', tokens, 'at', now) |
| 23 | -- After a whole period without requests the bucket is full: forget it. |
| 24 | redis.call('PEXPIRE', KEYS[1], period) |
| 25 | |
| 26 | -- Milliseconds until the next whole token. |
| 27 | local wait = math.ceil(math.max(0, 1 - tokens) * period / limit) |
| 28 | return {allowed, math.floor(tokens), wait} |