Course contentsShow
← System Design
Lesson 1798 of 1,91943. Real-World System: Rate Limiter ServiceFree lesson

Token Bucket Implementation in Redis

Design token bucket algorithm using Redis with timestamp tracking and token regeneration logic in Lua.

Token Bucket Implementation in Redis

What You'll Learn

You'll learn how to implement a token bucket rate limiter in Redis using Lua scripts to atomically track timestamps, regenerate tokens over time, and enforce request limits.

Core Idea

A token bucket holds a maximum number of tokens (capacity) and refills at a fixed rate. Each request consumes one token. Unlike sliding windows that track individual request timestamps, token bucket calculates how many tokens should have regenerated since the last request based on elapsed time, then checks if enough tokens remain.

The challenge: you must atomically (1) calculate time elapsed, (2) regenerate tokens, (3) check availability, and (4) consume a token—all in one operation. Redis Lua scripts guarantee this atomicity.

Redis Data Model

Store two fields per rate limit key:

  • tokens: Current token count (float)
  • last_refill_time: Unix timestamp of last update (integer)

Lua Script Logic

-- KEYS[1]: rate limit key
-- ARGV[1]: max_tokens (capacity)
-- ARGV[2]: refill_rate (tokens per second)
-- ARGV[3]: current_time (Unix timestamp)

local max_tokens = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])

local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens')) or max_tokens
local last_refill = tonumber(redis.call('HGET', KEYS[1], 'last_refill_time')) or now

-- Calculate tokens to add based on elapsed time
local elapsed = now - last_refill
local tokens_to_add = elapsed * refill_rate
tokens = math.min(max_tokens, tokens + tokens_to_add)

if tokens >= 1 then
    tokens = tokens - 1
    redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_refill_time', now)
    return 1  -- allowed
else
    return 0  -- denied
end

The script regenerates tokens proportionally to time elapsed, caps at max capacity, then consumes one if available.

Key Takeaway:
Token bucket in Redis uses Lua scripts to atomically calculate token regeneration from elapsed time, update state, and decide whether to allow requests—enabling smooth rate limiting with burst tolerance.