Redis fixed-window limiter that fails open

Share a fixed window across API instances with Redis INCR and EXPIRE NX in a transaction pipeline, with a short timeout and an in-memory fallback that logs once.

Objective

Build a Redis-backed fixed-window rate limiter that shares counters across API instances while keeping requests available when Redis is unreachable. The limiter implements the existing Limiter interface and falls back to the in-memory FixedWindow from exercise 1.14 when Redis operations fail.

By the end:

  • Multiple limiter instances sharing Redis enforce the same per-key limit.
  • Each time window has its own Redis counter and expiry.
  • Redis operations have a strict 50 ms timeout.
  • Redis failures fall back to in-memory rate limiting instead of rejecting requests.
  • The first Redis failure is logged once, without flooding the logs during an outage.

Deliverables

  • backend/internal/ratelimit/redis_window.go: Implement RedisFixedWindow, its constructor, its Allow method, and the compile-time interface assertion.

    The type must contain:

    • rdb *redis.Client
    • limit int
    • size time.Duration
    • A 50 ms timeout
    • fallback *FixedWindow
    • sync.Once for logging the first Redis failure

    Required constructor and interface method:

    go
    func NewRedisFixedWindow(
        rdb *redis.Client,
        limit int,
        size time.Duration,
    ) *RedisFixedWindow
    
    func (rw *RedisFixedWindow) Allow(key string) bool

    The implementation uses github.com/redis/go-redis/v9. Add the dependency with go get if it is not already present.

Requirements

Constraints

  • Implement a fixed-window counter using Redis. The window start must be part of the Redis key, not stored only as an expiry.

  • Implement the existing Go interfaces contract: Allow(key string) bool. Do not change the Limiter interface to accept a context.

  • Create a request-scoped Go context using context.WithTimeout(context.Background(), 50*time.Millisecond) for each Redis operation. Defer the cancellation function.

  • The timeout must be enforced through Context timeout and deadline so an unavailable or slow Redis server cannot stall requests indefinitely.

  • Construct the Redis key using the key and the current window start:

    go
    fmt.Sprintf("rl:%s:%d", key, time.Now().Truncate(size).Unix())
  • Use a single Redis connection from Go owned by the caller. The limiter must not close the client. The caller remains responsible for Close.

  • For every call to Allow, create one Redis pipelines using rdb.TxPipeline(). Queue the following operations in this order:

    1. INCR the counter.
    2. Set the expiry with ExpireNX using the window size.
    3. Execute the transaction pipeline with Exec(ctx).
  • Use a Redis transactions rather than a plain pipeline. Do not issue INCR and EXPIRE as separate round trips.

  • Redis 7 is required for EXPIRE NX. The Docker Compose setup from exercise 1.3 provides Redis 7.

  • If Exec returns an error, use Redis fail-open behavior behavior:

    • Log the first Redis failure through sync.Once.
    • Include the error in a slog.Warn message.
    • Return the result of fallback.Allow(key).
  • Do not panic when Redis is unavailable.

  • If Redis succeeds, allow the request only when the returned counter value is less than or equal to the configured limit.

  • Add the compile-time assertion:

    go
    var _ Limiter = (*RedisFixedWindow)(nil)

Acceptance criteria

  • Shared Redis counter: TestW1B7_RedisWindowCountsAcrossInstances passes. Two RedisFixedWindow instances using the same Redis client and the same unique key, with a limit of 3 and a one-minute window, return true, true, true, then false when called alternately.

  • Redis outage: TestW1B7_FailsOpenWhenRedisIsDown passes. With Redis pointed at 127.0.0.1:1, three calls all return true through the in-memory fallback, and the calls together finish in under two seconds.

  • Tests remain unchanged: Both provided tests carry the redis build tag and read TEST_REDIS_ADDR. They skip when that variable is absent. Do not rewrite or weaken them.

  • Redis integration test: From backend/, run:

    bash
    make up
    TEST_REDIS_ADDR=127.0.0.1:6379 go test -tags redis -race -count=1 ./internal/ratelimit/

    Alternatively, run the course test target:

    bash
    TEST_REDIS_ADDR=127.0.0.1:6379 make test W=1B7
  • Outage verification: With the API running, stop Redis using docker compose stop redis. Requests must continue to succeed through the in-memory fallback, subject to its per-process limit. Only one Redis failure warning should be logged, even when multiple requests encounter the outage.

  • Bounded latency: Each Redis attempt uses a 50 ms context timeout. The fallback must be used when Redis operations fail or time out.

  • Correct window expiry: A new window uses a new key. The expiry is set only once for that key and is not extended by later requests.

Finished Exercise 1.22?

Distributed rate limiting with Redis

3 items

  • 1.20Redis fundamentals and the Go clientnot completed
  • 1.21Redis atomicity, transactions, Lua and failure handlingnot completed
  • 1.22Redis fixed-window limiter that fails opennot completed

Continuous integration

Up next · Module 7 · 2 items · about 1 h 15 min

Start module 7

Implementation

Run locally

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

  1. NewRedisFixedWindow(rdb *redis.Client, limit int, size time.Duration) satisfies Limiter.
  2. The key is rl:{key}:{windowStart} and one transaction pipeline does INCR then EXPIRE NX for the window size.
  3. Redis calls use a 50 ms timeout.
  4. On any Redis error the call falls back to an in-memory FixedWindow, and the first failure is logged once.
  5. Two limiter instances sharing one Redis count together.
  6. Stopping Redis does not make the API fail.

Commands

terminal
cd backend && make up
terminal
cd backend && go get github.com/redis/go-redis/v9
terminal
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 go test -tags redis -count=1 ./internal/ratelimit/...

Tests

  • TestW1B7_RedisWindowCountsAcrossInstances in backend/internal/ratelimit/redis_window_test.go
  • TestW1B7_FailsOpenWhenRedisIsDown in backend/internal/ratelimit/redis_window_test.go