Redis Fixed-Window Rate Limiter
Source: Custom
Topics: Redis (INCR/EXPIRE), distributed rate limiting, go-redis
Problem
Implement a distributed rate limiter using Redis as shared state — the pattern used when
multiple gateway instances must agree on one limit per client/key.
Requirements:
New(rdb *redis.Client, limit int64, window time.Duration) *Limiter
Allow(ctx context.Context, key string) (bool, error) — atomically increment a per-key counter; on the first increment in a window, set the key's TTL to window. Return true if the resulting count is <= limit.
- Different keys must not interfere with each other.
- After the window expires (TTL), the counter resets and requests are allowed again.
Type:
type Limiter struct { ... }
func New(rdb *redis.Client, limit int64, window time.Duration) *Limiter
func (l *Limiter) Allow(ctx context.Context, key string) (bool, error)
Key concepts
- Fixed-window counter:
INCR key returns the new count; if it's 1, this goroutine created the key, so set EXPIRE key window. Simple and cheap, at the cost of allowing up to 2x limit at window boundaries (vs. a sliding-window log).
- Atomicity of INCR: Redis executes
INCR atomically — no separate read-modify-write race, even across multiple processes.
- miniredis: an in-memory Redis implementation used in tests (
github.com/alicebob/miniredis/v2) — mr.FastForward(d) simulates time passing for TTL expiry without real sleeps.
Run
go test -v -race ./challenges/networking/redis-rate-limiter/
Sign in to submit your solution.