Sliding Window Log
How it works
A Redis sorted set (ZSET) is that shoebox. Every item has a number attached called a score, and Redis keeps items sorted by score at all times. The one idea that makes everything work: use the request's timestamp as the score. The box is then always sorted oldest-to-newest for free.
Limit = 3 requests per 60 s. It's now t=100s and the box holds requests from t=10, t=50, t=95:
ZSET "rl:swl:alice" → [ 10 ] [ 50 ] [ 95 ] (sorted by score = timestamp)
Step 1 — throw away expired slips (window starts at 100 − 60 = 40)
ZREMRANGEBYSCORE key 0 40 → [ 50 ] [ 95 ]
Step 2 — count what's left
ZCARD key → 2 2 < limit 3 → ALLOWED, add it
→ [ 50 ] [ 95 ] [ 100 ]A fourth request a second later would see count 3, which is not under the limit of 3 → rejected.
Why a ZSET and not a list? Because items stay sorted by score, Redis jumps straight to the expired range and deletes it in O(log N) instead of scanning every slip — and ZCARD is instant.
func (sl *SlidingWindowLog) Allow(ctx context.Context, userID string) (bool, int64, error) {
key := fmt.Sprintf("rl:swl:%s", userID)
now := time.Now()
windowStart := now.Add(-sl.window)
// All operations in one pipeline — but NOT atomic. See #6 for why that matters.
pipe := sl.rdb.Pipeline()
// Remove timestamps older than the window
pipe.ZRemRangeByScore(ctx, key, "0", fmt.Sprintf("%d", windowStart.UnixNano()))
// Count remaining entries
zcard := pipe.ZCard(ctx, key)
// Record this request (score = timestamp, member = unique nano)
pipe.ZAdd(ctx, key, redis.Z{Score: float64(now.UnixNano()), Member: now.UnixNano()})
pipe.Expire(ctx, key, sl.window+time.Second)
if _, err := pipe.Exec(ctx); err != nil {
return false, 0, err
}
count := zcard.Val() // count BEFORE adding this request
remaining := sl.limit - count - 1
if remaining < 0 {
remaining = 0
}
return count < sl.limit, remaining, nil
}Careful: the ZADD is unconditional
Look at the order. The pipeline always adds the current request — before we've checked whether it's under the limit. The allow/deny decision happens afterward, in Go, using the count that came back. There is no "if allowed, then add."
window holds: [50] [95] [100] count = 3, limit = 3
new request at t=101 arrives
→ ZREMRANGEBYSCORE: nothing expired
→ ZCARD returns 3
→ ZADD adds 101 anyway → [50] [95] [100] [101]
→ in Go: count(3) < limit(3) is false → return REJECTEDWhy it's usually acceptable: the stray entry ages out on its own, so a rejected request just slightly delays recovery, and keeping everything in one pipeline stays simple and fast.
Why it can bite you: a client already over the limit that keeps retrying 100×/sec has every rejected retry ZADD-ed back into the set. The window never drains below the limit, so the client locks itself out far longer than the nominal 60 seconds — its own rejected traffic keeps refilling the box. Depending on your goals that's either a nice "punish abusers" property or a surprising footgun.
How to make it conditional: you can't decide-then-add inside a plain pipeline, because zcard.Val() isn't readable until after Exec(). Two options:
- Two round-trips — read the count, decide, then
ZADDonly if allowed. Loses the single-round-trip benefit and reopens the race between read and add. - A Lua script (recommended) — trim, count, and then
ZADDonly when under the limit, all server-side in one atomic step. Solves both problems at once.
| Memory / user | O(limit) — one entry per request |
|---|---|
| Accuracy | Exact — no boundary artifacts |
| Latency | ~1 RTT (pipeline) |
| Best for | Low-volume, high-accuracy needs (payment APIs) |