Considering rate limiting in Lua
I’m looking into ways to implement rate limiting and throttling patterns, such as token bucket and leaky bucket, using Lua. It’s important to include concurrency management with semaphores. I’ll also consider distributed counters like Redis and mechanisms for handling bursts, idempotency, backoff, and observability. Including example configurations and code snippets will help clarify these concepts. I’m aiming to provide a comprehensive final answer in markdown format. Let's get started!
1) Core decisions (before code)
What to limit
- Dimension(s):
userId, apiKey, ip, tenant, route, method, orgId, region
- Example key:
rl:{route}:{method}:{userId|ip}
What “rate” means
- Requests/sec, requests/min, bytes/sec, concurrent in-flight requests, or “cost” units per request (cheaper reads vs expensive writes).
What to do when over limit
- Reject:
429 Too Many Requests + Retry-After
- Queue/defer (throttle): accept then process later
- Degrade: serve cached/partial results
Headers (recommended)
Use the IETF draft headers (or legacy X-RateLimit-*):
RateLimit-Limit: 60;w=60
RateLimit-Remaining: 12
RateLimit-Reset: 23 (seconds)
Retry-After: 23 (on 429)
2) Token bucket (burst-friendly)
Behavior: tokens accumulate at rate, up to capacity. Each request consumes cost tokens. Allows bursts up to capacity.
In-process pseudocode
refill = (now - last) * rate
tokens = min(capacity, tokens + refill)
if tokens >= cost:
tokens -= cost
allow
else:
reject(429)
last = now
Redis token bucket (atomic Lua)
Store tokens + ts in a Redis hash per key.
Lua script (EVALSHA in production):
-- KEYS[1] = bucket key
-- ARGV[1]=rate_per_ms, ARGV[2]=capacity, ARGV[3]=now_ms, ARGV[4]=cost
local key = KEYS[1]
local rate = tonumber(ARGV[1])
local cap = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local v = redis.call("HMGET", key, "tokens", "ts")
local tokens = tonumber(v[1])
local ts = tonumber(v[2])
if tokens == nil then tokens = cap end
if ts == nil then ts = now end
local delta = math.max(0, now - ts)
tokens = math.min(cap, tokens + delta * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call("HMSET", key, "tokens", tokens, "ts", now)
-- expire after ~2 fill periods to prevent unbounded keys
local ttl_ms = math.ceil((cap / rate) * 2)
redis.call("PEXPIRE", key, ttl_ms)
return { allowed, tokens }
Usage example (Node.js-ish)
const now = Date.now();
const key = `rl:token:${route}:${userOrIp}`;
const [allowed, tokensLeft] = await redis.eval(lua, 1, key,
0.001, // rate_per_ms = 1 token/sec
10, // capacity = burst up to 10
now,
1 // cost
);
if (allowed === 0) throw rateLimited(tokensLeft);
3) Leaky bucket (smooth output / shaping)
Behavior: requests enter a queue; they “leak” at constant rate. If queue full → reject (or drop/overwrite). This is closer to throttling than rate limiting.
Pattern options
- Queue + worker drain: accept until
queue_size, drain at leak_rate
- GCRA (Generic Cell Rate Algorithm): queue-less approximation commonly used in proxies
Simple queue-based leaky bucket sketch
if queue_length >= max_queue: reject(429)
else enqueue(req)
worker every (1/leak_rate):
if queue not empty: dequeue and process
Where it fits
- Protect downstreams (DB, third-party APIs) by smoothing spikes.
- Combine with token bucket at edge: bucket decides “can enqueue?”, leaky bucket controls processing rate.
4) Sliding window (more accurate than fixed windows)
4.1 Fixed window counter (cheap, can spike at boundary)
Redis INCR + EXPIRE
# key = rl:fw:{user}:{route}:{windowStart}
INCR key
EXPIRE key 60 # only set on first increment in practice
Atomic-ish pattern (set TTL only when new):
local n = redis.call("INCR", KEYS[1])
if n == 1 then redis.call("EXPIRE", KEYS[1], ARGV[1]) end
return n
4.2 Sliding window log (accurate, heavier)
Use a ZSET of timestamps.
Redis ZSET approach (needs atomicity via Lua in real use)
ZADD rl:sw:{key} 1734200000123 "reqid-uuid"
ZREMRANGEBYSCORE rl:sw:{key} 0 (now-window_ms)
ZCARD rl:sw:{key} # count in window
PEXPIRE rl:sw:{key} window_ms
4.3 Sliding window counter (approx, good tradeoff)
Keep two adjacent fixed-window counters and weight them by overlap:
count = curr + prev * (1 - elapsed/window)
This avoids ZSET cost while reducing boundary spikes.
5) Distributed counters (Redis) + correctness notes
When you need Redis
- Multiple app instances/pods
- Multiple edge nodes
- Need consistent enforcement per key
Correctness & scaling tips
- Use Lua for atomic multi-step checks (INCR+EXPIRE+compare).
- Prefer hash tags in Redis Cluster to keep a key on one shard:
rl:{user123}:routeA (braces ensure same slot for related keys if needed)
- Use server time (
TIME) if client clocks drift matters.
- Keep TTLs tight to avoid key buildup.
6) Per-user / per-IP keys (and tiers)
Key strategy
- Unauthenticated:
ip (and maybe ip+ua carefully)
- Authenticated:
userId or apiKey (prefer stable identity), optionally also enforce an IP limit.
Example composite:
- Per-user per-route:
rl:tb:user:{userId}:{method}:{route}
- Per-IP global:
rl:tb:ip:{ip}
Multi-limit enforcement (common)
Apply multiple buckets and reject if any fails:
global (protect service)
per-tenant
per-user
per-ip (abuse prevention)
7) Burst handling patterns
A) Token bucket capacity
- Set
capacity > rate*window to allow bursts.
- Example:
rate=5 rps, capacity=20 allows short spikes.
B) Dual limits (short + long)
- Short:
20 req / 1s (burst)
- Long:
300 req / 60s (sustained)
C) Separate read/write budgets
- Reads: higher rate
- Writes: lower rate or higher “cost”
D) Concurrency limit (protect CPU/DB)
Use a semaphore per key:
- Redis
INCR in-flight, DECR on completion, with safety TTL.
- Or at proxy: max connections / pending requests.
8) Idempotency (so retries don’t multiply side effects)
Especially for POST/charge/create operations.
Contract
- Client sends
Idempotency-Key: <uuid>
- Server stores result keyed by
(userId, idempotencyKey) for TTL.
- Repeat request returns the same response (status+body), not re-executed.
Redis example
- Key:
idem:{userId}:{idemKey} → response blob
- Use
SET key value NX EX 86400 to lock execution
- If lock exists, return stored response (or “in progress” if you store a placeholder)
Sketch:
if SET(lockKey, "in-progress", NX, EX=30) succeeds:
result = doWork()
SET(resultKey, serialize(result), EX=86400)
DEL(lockKey)
return result
else:
if resultKey exists: return it
else: return 409/202 ("in progress, retry")
9) Backoff & retry (client-side throttling discipline)
On 429 / 503, clients should back off with jitter.
Server response
429 Too Many Requests
Retry-After: <seconds> (or HTTP date)
- Include rate headers.
Exponential backoff with full jitter (example)
import random, time
base = 0.25
cap = 10.0
for attempt in range(1, 8):
sleep = random.uniform(0, min(cap, base * (2 ** attempt)))
time.sleep(sleep)
# retry request
Also support:
- Respect
Retry-After if present (override backoff).
- Cap total retries; make retries idempotent (or use idempotency keys).
10) Observability (you can’t tune what you can’t see)
Metrics (tag by route, key-type, decision)
rate_limit_allowed_total{route, limit_type}
rate_limit_blocked_total{route, reason=exhausted}
rate_limit_tokens_remaining (gauge/sample)
rate_limit_latency_ms (p50/p95 for Redis/Lua)
redis_errors_total and fallback behavior counters
Logs
- Include:
key, route, identity(user/ip), limit, remaining, reset, decision, retry_after
Tracing
- Annotate spans with
rate_limited=true, limit_key_hash, bucket_remaining
Dashboards
- Block rate over time by route
- Top limited keys (hashed/anonymized)
- Redis p95 latency & error rates
11) Example proxy/gateway configurations
NGINX (fixed-window-ish, leaky bucket with burst queue)
limit_req_zone $binary_remote_addr zone=ip_rl:10m rate=5r/s;
server {
location /api/ {
# "burst" allows short queue, "nodelay" makes it token-bucket-ish behavior
limit_req zone=ip_rl burst=20 nodelay;
limit_req_status 429;
add_header Retry-After 1 always;
}
}
Envoy (local rate limit filter)
http_filters:
- name: envoy.filters.http.local_ratelimit
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
stat_prefix: local_rl
token_bucket:
max_tokens: 20
tokens_per_fill: 5
fill_interval: 1s
filter_enabled:
runtime_key: local_rl_enabled
default_value: { numerator: 100, denominator: HUNDRED }
filter_enforced:
runtime_key: local_rl_enforced
default_value: { numerator: 100, denominator: HUNDRED }
12) Practical “put it together” recipe (common production setup)
- Edge proxy (Envoy/NGINX/API Gateway): coarse per-IP + global burst protection.
- App-level Redis token bucket: per-user/per-tenant/per-route enforcement with tiers.
- Concurrency limiter around expensive dependencies (DB/search/3rd-party).
- Idempotency keys for side-effecting endpoints.
- 429 + Retry-After everywhere; client backoff with jitter.
- Metrics + logs to tune limits and detect abuse.
If you share your stack (language/framework, Redis vs Memcached, gateway/proxy), I can provide a drop-in middleware example and a Redis Lua script wired to your exact request identity + route scheme.