Optional: Token bucket in Redis with Lua and EVALSHA
Move the token bucket into Redis as one Lua script that refills and takes a token atomically, run through go-redis with EVALSHA, sharing state across instances and failing open.
Objective
Implement a Redis-backed token bucket limiter using a single Redis Lua script executed through Redis EVALSHA. The script must refill the bucket and consume a token atomically, allowing multiple application instances to share the same rate-limit state. You will use a Redis connection from Go, Go contexts and a context timeout to bound Redis operations. When Redis is unavailable, the limiter must follow Redis fail-open behavior and allow the request. The implementation must satisfy the existing Go interface contract.
This exercise is optional extra practice. It is not part of the required Week 1 work and never blocks the week. Complete it if you want additional experience with Redis scripting and distributed rate limiting.
By the end:
- Understand why a token bucket's read-modify-write operation must execute atomically.
- Implement token refill and consumption in Redis using Lua.
- Share bucket state across multiple limiter instances.
- Execute a Redis script using
EVALSHAand handle script cache misses. - Apply a short timeout to Redis operations.
- Handle Redis failures by allowing requests without an in-memory fallback.
Deliverables
-
Create
backend/internal/ratelimit/redis_token_bucket.go.Implement the following constructor:
go func NewRedisTokenBucket(rdb *redis.Client, capacity, refill float64) *RedisTokenBucketImplement the limiter method:
go func (rb *RedisTokenBucket) Allow(key string) boolThe implementation must satisfy the existing
Limiterinterface. -
The tests are already provided in
backend/internal/ratelimit/redis_token_bucket_test.go. Do not create, modify, or edit this test file.
Requirements
Constraints
- Keep the implementation in
backend/internal/ratelimit/redis_token_bucket.go. Do not modify existing limiter implementations or shared interfaces. - Use
redis.NewScript(luaSource)to create the Lua script once in the constructor. Do not recreate the script on every request. - Store bucket state in a Redis hash with the fields
tokensandts, wheretsrepresents the last update time in milliseconds. - Use
redis.call("TIME")inside Lua to obtain the current time. Do not calculate the authoritative refill time using Go's local clock. - Calculate elapsed time, refill tokens up to the configured capacity, and consume one token only when at least one token is available.
- Use the Redis key format
tb:{key}so the supplied bucket key determines the shared bucket state. - Keep the refill and consumption operations inside the same Lua script. Do not split them into separate Redis commands from Go.
- Set a
PEXPIRETTL long enough for an empty bucket to refill to capacity. When the refill rate is zero, use a one-hour TTL. - Execute the script through
redis.Script.Run, passing the Redis key and the bucket configuration as arguments. - Use a 50 ms context timeout for each Redis operation.
- On any Redis or script execution error, log a warning through
slog.Warnonly once usingsync.Once, then returntrue. - Do not implement an in-memory fallback. This exercise deliberately differs from the Redis fixed-window limiter.
- Do not introduce a new dependency or change the existing
Limiterinterface. - Include the compile-time interface assertion for
RedisTokenBucket.
Acceptance criteria
- Run
make upfirst to start the local Redis service. - The provided tests must pass without modification.
TestW1O4_BurstThenRejectverifies that a bucket with capacity three permits three immediate requests and rejects the fourth.TestW1O4_SharedAcrossInstancesverifies that two limiter instances using the same Redis connection and key share one bucket.TestW1O4_RefillsOverTimeverifies that an exhausted bucket refills according to its configured rate.TestW1O4_SurvivesScriptFlushverifies that the limiter reloads its script after Redis executesSCRIPT FLUSH.redis.Script.Runmust handle theNOSCRIPTresponse by loading the script and retrying.TestW1O4_FailsOpenWhenRedisIsDownverifies that requests are allowed when Redis is unavailable and that Redis calls fail within a reasonable time.- The implementation must compile, pass
gofmt, and pass the repository's configured lint checks.
Run the tests with:
cd backend && make up
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1O4The tests use the redis and w1o4 build tags. The make test W=1O4 target enables these automatically.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
NewRedisTokenBucket(rdb *redis.Client, capacity int, refillPerSec float64)returns a*RedisTokenBucketthat satisfiesLimiter.- The bucket state is a Redis hash with tokens and the last refill time, refilled and decremented inside one Lua script.
- The script is created once with
redis.NewScriptand run withRun, which uses EVALSHA and falls back to loading the script. - Each call uses a 50 ms timeout and fails open on any Redis error.
TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1O4passes.
Commands
cd backend && make upcd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1O4Tests
TestW1O4_BurstThenRejectinbackend/internal/ratelimit/redis_token_bucket_test.goTestW1O4_SharedAcrossInstancesinbackend/internal/ratelimit/redis_token_bucket_test.goTestW1O4_RefillsOverTimeinbackend/internal/ratelimit/redis_token_bucket_test.goTestW1O4_SurvivesScriptFlushinbackend/internal/ratelimit/redis_token_bucket_test.goTestW1O4_FailsOpenWhenRedisIsDowninbackend/internal/ratelimit/redis_token_bucket_test.go