How go-redis/redis_rate works
Project Type and Purpose
• Type: Go library (SDK) for rate limiting
• Purpose: Provide a GCRA/leaky-bucket algorithm implementation using Redis (requires Redis ≥ 3.2)
File Structure
• Top-level files
– lua.go: embeds the GCRA Lua script
– rate.go: Go wrapper implementing Limiter, Allow, Reserve, etc.
– example_test.go & rate_test.go: usage and unit tests
– go.mod/go.sum: module and dependency definitions
– CI/config files: .travis.yml, renovate.json, .prettierrc, Makefile
• No separate “frontend” or “backend”—it’s a single package that interacts with Redis over the network.
README for Additional Insights
• Describes the GCRA algorithm and Redis EVAL usage
• Shows example user code: application creates a redis.Client, wraps it in redis_rate.NewLimiter, and calls Allow
Main Components and Their Relationships
a. Application Code (User)
– Imports redis_rate/v10
– Constructs a go-redis Client → passes it to redis_rate.NewLimiter
– Calls limiter.Allow or limiter.Reserve
b. Limiter Package (Go)
– rate.go: implements Allow, Reserve, etc.
– lua.go: contains embedded Lua script (the GCRA logic)
– Converts Go parameters into Redis EVAL arguments
c. Redis Server
– Receives EVAL commands
– Executes the embedded Lua script atomically
– Maintains token-bucket state in Redis keys
– Returns result (allowed, remaining, retry_after, etc.)
d. (Optional) External Tools/CI
– Travis CI / GitHub Actions for build/test
– Renovate for dependency updates
– Prettier for code formatting
Architectural Patterns & Design Principles
• Single-entry point for all rate-limiting calls (Limiter struct)
• Embedding Lua script to ensure atomicity in Redis (avoids multi-command races)
• Thin wrapper over go-redis Client—separation of concerns:
– Networking & serialization handled by go-redis
– Algorithm and script management handled by redis_rate
• Go Modules for versioning (v10 import path)
Putting It All Together
• Top-level: Application (Go)
– calls → Limiter Package
• Limiter Package
– loads/embeds → Lua Script
– issues → EVAL command → Redis Server
• Redis Server
– executes GCRA logic
– returns → result to Limiter → forwarded → Application