Redis Distibuted Lock

The core of a Redis distributed lock is the SET key value EX seconds NX command combined with a Lua script. When acquiring the lock, NX guarantees mutual exclusion and EX sets an expiration to prevent deadlocks. When releasing the lock, a Lua script must be used to verify ownership before deleting, which keeps the operation atomic.

Lock acquisition flow:

  1. The client executes SET lock_key uuid EX 30 NX
  2. Redis checks whether lock_key exists
  3. If it doesn’t exist, the key is set and OK is returned, so the lock is acquired
  4. If it already exists, nil is returned, so the lock acquisition fails

Lock release flow:

  1. The client executes a Lua script
  2. GET lock_key retrieves the current value
  3. The script checks whether the value equals the client’s own uuid
  4. If it matches, DEL lock_key runs and the lock is released
  5. If it doesn’t match, 0 is returned, meaning the lock belongs to someone else

Distributed lock problem

The lock expires before the business logic finishes: you set the lock to 30 seconds, but the business logic runs for 35 seconds. The lock is released automatically, another thread slips in and takes it, and the data gets corrupted.

Solution: Start a scheduled background task that keeps “extending the life” of the lock. For example, if the lock expires after 30 seconds, the task resets the expiration to 30 seconds every 10 seconds. As long as the business logic is still running, the lock never expires. When the logic finishes and releases the lock, the scheduled task is stopped too.

Golang Implementation

package redis

import (
	"context"
	"time"

	"github.com/redis/go-redis/v9"
)

// TryLock tries to acquire the distributed lock. It returns true on success and false on failure.
func TryLock(ctx context.Context, rc *redis.Client, key string, expire time.Duration) bool {
	cmd := rc.SetNX(ctx, key, "any value", expire) // SetNX returns true if the key does not exist, writes the key and sets its TTL, if you don't set TTL, later if server died, this key never release because the logic of release lock never run
	if cmd.Err() != nil {
		return false
	} else {
		return cmd.Val()
	}
}

// ReleaseLock releases the distributed lock
func ReleaseLock(ctx context.Context, rc *redis.Client, key string) {
	rc.Del(ctx, key)
}

Test with Try Lock with schedule task

package redis

import (
	"context"
	"fmt"
	"sync"
	"testing"
	"time"
)

func TestLock(t *testing.T) {
	ctx := context.Background()
	LockName := "schedule"
	const C = 5
	wg := sync.WaitGroup{}
	wg.Add(C)
	for i := 0; i < C; i++ {
		go func(i int) { // Use multiple goroutines on a single machine to simulate multiple processes in a distributed environment
			defer wg.Done()
			if TryLock(ctx, client, LockName, 10*time.Minute) {
				fmt.Printf("goroutine %d acquired the lock\n", i)
			}
		}(i)
	}
	wg.Wait()
	ReleaseLock(ctx, client, LockName)
}

// go test -v . -run='^TestLock$' -count=1

Output:

goroutine 4 acquired the lock