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 EVALSHA and 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) *RedisTokenBucket

    Implement the limiter method:

    go
    func (rb *RedisTokenBucket) Allow(key string) bool

    The implementation must satisfy the existing Limiter interface.

  • 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 tokens and ts, where ts represents 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 PEXPIRE TTL 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.Warn only once using sync.Once, then return true.
  • 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 Limiter interface.
  • Include the compile-time interface assertion for RedisTokenBucket.

Acceptance criteria

  • Run make up first to start the local Redis service.
  • The provided tests must pass without modification.
  • TestW1O4_BurstThenReject verifies that a bucket with capacity three permits three immediate requests and rejects the fourth.
  • TestW1O4_SharedAcrossInstances verifies that two limiter instances using the same Redis connection and key share one bucket.
  • TestW1O4_RefillsOverTime verifies that an exhausted bucket refills according to its configured rate.
  • TestW1O4_SurvivesScriptFlush verifies that the limiter reloads its script after Redis executes SCRIPT FLUSH. redis.Script.Run must handle the NOSCRIPT response by loading the script and retrying.
  • TestW1O4_FailsOpenWhenRedisIsDown verifies 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:

bash
cd backend && make up
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1O4

The tests use the redis and w1o4 build tags. The make test W=1O4 target enables these automatically.

Finished Exercise 1.29?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. NewRedisTokenBucket(rdb *redis.Client, capacity int, refillPerSec float64) returns a *RedisTokenBucket that satisfies Limiter.
  2. The bucket state is a Redis hash with tokens and the last refill time, refilled and decremented inside one Lua script.
  3. The script is created once with redis.NewScript and run with Run, which uses EVALSHA and falls back to loading the script.
  4. Each call uses a 50 ms timeout and fails open on any Redis error.
  5. TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1O4 passes.

Commands

terminal
cd backend && make up
terminal
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1O4

Tests

  • TestW1O4_BurstThenReject in backend/internal/ratelimit/redis_token_bucket_test.go
  • TestW1O4_SharedAcrossInstances in backend/internal/ratelimit/redis_token_bucket_test.go
  • TestW1O4_RefillsOverTime in backend/internal/ratelimit/redis_token_bucket_test.go
  • TestW1O4_SurvivesScriptFlush in backend/internal/ratelimit/redis_token_bucket_test.go
  • TestW1O4_FailsOpenWhenRedisIsDown in backend/internal/ratelimit/redis_token_bucket_test.go