← writing

Building a Distributed Sliding Window Rate Limiter with Redis

Learn how to build a distributed sliding window rate limiter using Redis Sorted Sets, custom TTL management, and atomic Lua scripts. This deep dive covers system architecture, concurrency control, memory management, and practical implementations in Go, C++, and Rust.

·4 min·system-design

Sliding Window Rate Limiting with Redis: Go, C++, and Rust#

Rate limiting controls how frequently a client can access an API within a given period. It protects backend services from excessive traffic, resource exhaustion, and abuse.

One common problem with Fixed Window Rate Limiting is the boundary burst. A client can consume its entire quota just before a window resets and immediately consume another quota afterward.

Sliding Window solves this by evaluating requests relative to the current time rather than using fixed intervals.

In this article, we'll explore how to implement it using Redis Sorted Sets, custom TTL management, and atomic Lua scripting, with practical examples in Go, C++, and Rust.

1. How Sliding Window Works#

Imagine an API that allows 5 requests every 60 seconds.

Instead of resetting a counter every minute, the system tracks individual request timestamps.

Whenever a new request arrives:

  1. Calculate the current timestamp.
  2. Remove requests older than the active window.
  3. Count the remaining requests.
  4. Reject the request if the limit is reached.
  5. Otherwise, record the new request.

The active request window can be represented as:

[W(t)={r_i \mid t-T < r_i \leq t}]

A request is allowed when:

[|W(t)| < L]

Where (T) is the window duration and (L) is the maximum request limit.

2. Redis Sorted Sets and Custom TTL#

Redis Sorted Sets are suitable for this implementation because every member has an associated score.

We use the request timestamp as the score.

Key: rate_limit:user_123

Timestamp

Request

1000

request_1

1010

request_2

1020

request_3

1030

request_4

When a new request arrives, expired records are removed using ZREMRANGEBYSCORE.

We then use ZCARD to count the remaining requests.

Where does custom TTL come in?

There are two separate expiration responsibilities:

  • Request expiration: Remove individual requests outside the sliding window.
  • Key expiration: Use PEXPIRE to delete the entire Redis key after inactivity.

Redis does not support native TTL for individual Sorted Set members. Therefore, expired members must be removed explicitly.

3. System Design#

A distributed rate limiter should maintain shared state across all backend instances.

Client | Load Balancer | +------+------+ | | Go API Go API | | +------+------+ | Rate Limiter | Redis | Sorted Set + LUA Script

Every backend instance uses the same Redis key for a given client.

The critical operation is executed through a Redis Lua script, ensuring that expired records are removed, requests are counted, the limit is checked, and new requests are inserted atomically.

Without atomic execution, two simultaneous requests could both observe an available slot and exceed the configured limit.

4. Core Implementation#

The following Lua script contains the shared rate-limiting logic.

lua
1local key = KEYS[1]
2local limit = tonumber(ARGV[1])
3local window = tonumber(ARGV[2])
4local request_id = ARGV[3]
5
6local time = redis.call("TIME")
7local now = tonumber(time[1]) * 1000
8 + math.floor(tonumber(time[2]) / 1000)
9
10local cutoff = now - window
11
12-- Remove expired requests
13redis.call("ZREMRANGEBYSCORE", key, "-inf", cutoff)
14
15-- Check active requests
16local count = redis.call("ZCARD", key)
17
18if count >= limit then
19 local oldest = redis.call("ZRANGE", key, 0, 0, "WITHSCORES")
20 local retry = tonumber(oldest[2]) + window - now
21
22 return {0, count, math.max(0, retry)}
23end
24
25-- Record accepted request
26redis.call("ZADD", key, now, request_id)
27
28-- Refresh key TTL
29redis.call("PEXPIRE", key, window)
30return {1, count +1 , 0}

The script returns three values:

LUA Script
1[allowed, request_count, retry_after_ms]

Using Redis server time also prevents differences between application server clocks from affecting request calculations.

5. Implementing in Go, C++, and Rust#

The important design decision is to keep the rate-limit operation inside Redis. Each language generates a unique request ID, passes the configuration to the script, and processes its response.

 

Go — go-redis
1func (s *Limiter) Allow(ctx context.Context, key string) (bool, error) {
2 id := uuid.NewString()
3
4 result, err := s.script.Run(
5 ctx,
6 s.redis,
7 []string{key},
8 s.limit,
9 s.window.Milliseconds(),
10 id,
11 ).Slice()
12
13 if err != nil {
14 return false, err
15 }
16
17 return result[0].(int64) == 1, nil
18}

Go's lightweight goroutines make it convenient to integrate the limiter into concurrent HTTP services.

C++ — redis
1bool allowRequest(
2 redisContext* redis,
3 const std::string& key,
4 int limit,
5 long long windowMs
6) {
7 auto id = generateRequestId();
8
9 redisReply* reply = executeLuaScript(
10 redis, key, limit, windowMs, id
11 );
12
13 bool allowed = reply->element[0]->integer == 1;
14
15 freeReplyObject(reply);
16 return allowed;
17}

 

6. Production Considerations#

A Sorted Set sliding window provides accurate request tracking, but it also stores individual request records.

For high-traffic systems, this can increase Redis memory consumption.

Consider these factors:

  • Use unique request IDs to avoid overwriting requests with identical timestamps.
  • Use connection pooling for Redis.
  • Monitor Redis latency and memory usage.
  • Decide whether to fail open or fail closed when Redis becomes unavailable.
  • Use Redis Cluster hash-slot-compatible keys.
  • Consider Token Bucket or Sliding Window Counter when approximate enforcement is acceptable.

The Sorted Set approach is most useful when accurate request accounting is more important than minimizing per-request storage.

Conclusion#

Sliding Window Rate Limiting provides a more accurate alternative to fixed-window counters.

By combining Redis Sorted Sets, custom expiration management, and atomic Lua execution, we can build a distributed rate limiter that works across multiple backend instances.

The key engineering principle is that request expiration, Redis key expiration, and atomic state management are three distinct responsibilities.

Understanding these concepts is more important than the programming language used to implement them.

Technologies: Go · C++ · Rust · Redis · Lua · Distributed Systems · Backend Engineering