Token Bucket

KnobControls
capacityHow many coins the cup holds = your maximum burst size
refill rateHow fast new coins drip in = your sustained long-run rate

How it works

Bucket state is stored as (tokens, last_refill_time) in a Redis hash. You never run a background goroutine — you compute how many tokens accumulated since last_refill_time when a request arrives (lazy evaluation).

-- Runs atomically on the Redis server, so read -> compute -> write
-- below cannot interleave with another request (no race on the token count).
local key      = KEYS[1]              -- bucket key, e.g. "rl:tb:user123"
local capacity = tonumber(ARGV[1])    -- max tokens / burst size
local rate     = tonumber(ARGV[2])    -- tokens per second (float)
local now      = tonumber(ARGV[3])    -- unix nanoseconds; supplied by the caller
                                      -- to keep the script deterministic

-- Load current bucket state: token count and when it was last refilled.
local data = redis.call("HMGET", key, "tokens", "last")
local tokens = tonumber(data[1])
local last   = tonumber(data[2])

-- First request for this key: HMGET returned nils. Start the bucket FULL so a
-- user's first burst is allowed up to capacity.
if tokens == nil then
    tokens = capacity
    last   = now
end

-- Lazy refill: compute how many tokens dripped in since "last", cap at capacity.
local elapsed = (now - last) / 1e9  -- ns to seconds
local refill  = elapsed * rate
tokens = math.min(capacity, tokens + refill)
last   = now

-- Try to spend one token. tokens stays fractional internally for sub-1/sec
-- precision; remaining is floored to report a clean integer.
local allowed = 0
local remaining = math.floor(tokens)
if tokens >= 1 then
    tokens  = tokens - 1
    allowed = 1
    remaining = math.floor(tokens)
end

-- Persist. TTL = time for an empty bucket to fully refill (capacity/rate) + 1s.
-- Once idle that long the bucket would be full anyway, so expiring loses nothing.
redis.call("HSET", key, "tokens", tokens, "last", last)
redis.call("PEXPIRE", key, math.ceil(capacity / rate * 1000) + 1000)

return {allowed, remaining}
func (tb *TokenBucket) Allow(ctx context.Context, userID string) (bool, int64, error) {
    key := fmt.Sprintf("rl:tb:%s", userID)
    now := time.Now().UnixNano()

    result, err := tb.script.Run(ctx, tb.rdb, []string{key},
        tb.capacity, tb.rate, now,
    ).Int64Slice()
    if err != nil {
        return false, 0, err
    }
    return result[0] == 1, result[1], nil
}

Why Lua instead of a pipeline here

The refill computation depends on last_refill_time, which you just read from Redis. You cannot pipeline this — you need the read result before you can write the new value. Lua runs atomically on the server, so HMGET → compute → HSET is a single atomic operation with no round trip in between.

Burst vs sustained rate

capacity = 100, rate = 10/sec

Idle for 10s → bucket full (100 tokens)
Burst: 100 requests arrive → all allowed (drains bucket)
Next 100 requests → rejected until tokens refill (10/sec)

The bucket allows bursts up to capacity — that's the design. For strict 10 req/sec with no burst, set capacity = 1.

Once empty: retries succeed purely as a function of elapsed time

tokens_now = min(capacity, tokens_last + elapsed_seconds × rate) you need 1/rate seconds to earn one token

rate = 10/sec:
empty, wait 0.05s → 0.5 tokens → still < 1 → REJECTED
empty, wait 0.10s → 1.0 tokens → spend 1  → ALLOWED, 0 remaining

rate = 1/sec, capacity = 1  (slow rate — "succeed then immediately fail"):
call             → ALLOWED (spends the 1 token → 0 left)
call immediately → ~0.001 tokens → REJECTED
wait 1 full second → 1 token → ALLOWED

So a successful call does not mean you have credit for a while — it means enough time had passed to have ≥1 token. A slow rate gates you to roughly one call per 1/rate seconds.

Rate limiting vs. back pressure

This is a rejecting rate limiter, not back pressure in the classic sense. It does not hold, queue, or slow the caller — it returns "0 remaining" and drops the request. The caller decides whether to retry.

Token bucket (this code)True back pressure
On overloadRejects immediately (drop)Slows / blocks the producer
Who waitsClient decides whether to retrySystem enforces the wait
BufferingNone — stateless rejectOften a bounded queue

It enables back pressure only if the client cooperates — return remaining or a Retry-After derived from 1/rate and a well-behaved client backs off. Leaky bucket is closer to true back pressure: it models a queue draining at a fixed rate.

Memory / userO(1) — one hash, two fields
Burst handlingExplicit capacity parameter
Latency~1 RTT (Lua script)
Best forAPIs that allow short bursts but enforce a sustained rate