Simplified distributed locking implementation using Redis
Simplified distributed locking implementation using Redis
Simplified distributed locking implementation using Redis. For more information, please see examples.
Full documentation is available on GoDoc
…Set Options.FenceKey to mint a fencing token with the lock: a strictly
increasing value, incremented atomically on each new acquisition and returned by
Lock.FenceToken. Stamp every write to the protected resource with the token and
have the resource reject any write carrying an older token. A lock holder that
pauses (GC, scheduling) long enough to lose the lock without noticing is then
fenced out — its writes carry a stale token and are refused. This is the
mitigation described in Martin Kleppmann's
How to do distributed locking.
func fence() {
client := redis.NewClient(&redis.Options{Network: "tcp", Addr: "127.0.0.1:6379"})
defer client.Close()
locker := redislock.New(client)
ctx := context.Background()
// Obtain a lock with a fencing token.
lock, err := locker.Obtain(ctx, "my-key", time.Second, &redislock.Options{FenceKey: "my-key:fence"})
if err != nil {
log.Fatalln(err)
}
defer lock.Release(ctx)
// FenceToken is 0 without a FenceKey. Stamp writes with the token; reject older ones.
if token := lock.FenceToken(); token != 0 {
fmt.Printf("fenced write with token %d\n", token)
}
}A few notes:
redislock mints and returns the token, but
the check (reject if incoming < highest applied) must happen atomically at the
resource, which is the only place the comparison and the write can be made one
operation.FenceKey, so you control its placement. On Redis Cluster it must
hash to the same slot as the lock key(s) — share a {hashtag}, e.g. lock
{job}:lock with fence {job}:fence — or the script fails with CROSSSLOT.Release.INCR, it can regress.
For strict cross-failover monotonicity, source the token from a linearizable
store instead.redislock deliberately does not bundle a built-in watchdog goroutine: refresh
cadence and error handling are application concerns (log and continue, retry,
cancel the protected work, page someone, etc.). If you need a long-running lock
that outlives its initial TTL, drop a small ticker next to your work and let it
call Refresh for you:
…A few notes:
interval ≈ ttl/3 so a single transient redis blip still leaves room to
retry before the lock expires.Refresh error of redislock.ErrNotObtained means the lock was lost
(expired or stolen) and is usually fatal for the protected work; cancel the
work context so the caller stops.Release stays with the caller, so ownership is explicit.No open issues yet, or sync has not completed.