Sobes.tech
Senior

Has there been any experience with distributed limit or location on Redis before?

sobes.tech AI

Answer from AI

Yes, experience with implementing distributed locks and distributed rate limiting (locks) on Redis is quite common. Redis is often used for such tasks due to its high performance and support for atomic operations.

For distributed locks, the SET command with the NX (set if not exists) and EX (expiration time) parameters is typically used, which guarantees exclusive access to a resource with automatic lock expiration:

// Example of setting a lock in Go using go-redis
ctx := context.Background()
lockKey := "resource_lock"
lockValue := "unique_identifier" // e.g., UUID
expiration := 10 * time.Second

ok, err := redisClient.SetNX(ctx, lockKey, lockValue, expiration).Result()
if err != nil {
    // handle error
}
if !ok {
    // lock is already taken
}

// After work, release the lock by checking that the value matches
// to avoid releasing someone else's lock

For distributed rate limiting, counters with TTL or Lua scripts that atomically increment counters and check limits can be used. For example, implementing a per-minute request limit per user.

Thus, Redis is a convenient tool for implementing distributed locks and rate limits due to its command atomicity and TTL support.