How a Redis lock works with SET NX PX, why release needs a token check, what Redlock does and does not fix, and how fencing tokens in Postgres keep a lost lock from corrupting data.

A distributed lock lets one worker out of many do something at a time: sync an account from a CRM, refresh a shared OAuth token, or run a report that would be expensive to run twice. Redis makes the basic version a single command, SET lock:acct-42 <token> NX PX 30000, which only one caller wins until the key is deleted or expires.
After you acquire the lock, deleting the key without checking the token can release someone else's lock, and an expiry that is too short lets a slow worker overlap with the next one. A garbage collection pause or a stalled network call can leave two processes sure they hold the same lock. Whether that matters depends on whether the lock protects effort or data.
This guide builds the lock from the Redis primitives, explains Redlock and fencing tokens, and starts with Encore, where the Redis cluster and the Postgres database that checks fencing tokens are both declared in Go.
Encore brings infrastructure from code: a cache cluster declared in Go runs in memory under encore run and is provisioned as Redis on ElastiCache or Memorystore when you deploy, and a database declared next to it becomes RDS or Cloud SQL in your own AWS or GCP account. The example below syncs contacts from a CRM per account, with a Redis lease to keep two workers from doing the same sync and a fencing token in Postgres so a worker that lost its lease cannot write.

Run in your terminal to get started locally.
A string keyspace with a 30 second default expiry holds the lease, and SetIfNotExists is Redis SET NX: one caller gets the key, everyone else gets cache.KeyExists. The cluster uses NoEviction, so Redis returns an error under memory pressure instead of silently dropping a lease. The keyspace API has no compare-and-delete, so release is a check followed by a delete, and the comment says exactly what that costs:
// crmsync/lease.go
package crmsync
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"time"
"encore.dev/storage/cache"
)
// A separate cluster with NoEviction, so Redis never drops a lease to make room.
var locks = cache.NewCluster("locks", cache.ClusterConfig{
EvictionPolicy: cache.NoEviction,
})
const leaseTTL = 30 * time.Second
// leases maps an account ID to the random token of the worker that holds its lease.
var leases = cache.NewStringKeyspace[string](locks, cache.KeyspaceConfig{
KeyPattern: "sync-lease/:key",
DefaultExpiry: cache.ExpireIn(leaseTTL),
})
var errLeaseHeld = errors.New("lease held by another worker")
// tryLease is SET key token NX PX 30000: it succeeds for exactly one caller
// until the key is deleted or expires.
func tryLease(ctx context.Context, account string) (token string, err error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
token = hex.EncodeToString(b)
err = leases.SetIfNotExists(ctx, account, token)
if errors.Is(err, cache.KeyExists) {
return "", errLeaseHeld
}
return token, err
}
// Do not Get then Delete the lease. That can remove a newer worker's key if this
// lease expired in between. Encore's cache has no compare-and-delete, so leave
// the key in place and let the TTL expire.
Every time a worker takes the lease it also increments a per-account number in Postgres, and every write it makes carries that number. The write only lands if the number is still the latest, and FOR SHARE on the fence row makes a new holder's increment wait for a write that is already in flight:
-- crmsync/migrations/1_sync.up.sql
-- One row per account; fence goes up by one every time a worker takes the lease.
CREATE TABLE sync_fences (
account_id TEXT PRIMARY KEY,
fence BIGINT NOT NULL,
lease_until TIMESTAMPTZ
);
CREATE TABLE crm_contacts (
account_id TEXT NOT NULL,
email TEXT NOT NULL,
name TEXT NOT NULL,
synced_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, email)
);
// crmsync/sync.go
package crmsync
import (
"context"
"errors"
"time"
"encore.dev/beta/errs"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("crmsync", sqldb.DatabaseConfig{Migrations: "./migrations"})
type Contact struct {
Email string
Name string
}
// fetchContacts calls your CRM's API for one account.
var fetchContacts = func(ctx context.Context, account string) ([]Contact, error) {
return nil, nil
}
type SyncResult struct {
Written int `json:"written"`
}
// SyncAccount copies one account's contacts from the CRM. Only one worker per
// account runs at a time; a second call while a sync is running gets Aborted.
//
//encore:api private method=POST path=/crm/sync/:account
func SyncAccount(ctx context.Context, account string) (*SyncResult, error) {
ctx, cancel := context.WithTimeout(ctx, leaseTTL-5*time.Second)
defer cancel()
// Take the authoritative Postgres lease first, then the Redis key. Acquiring
// Redis first can leave a key held after the database gate rejects the worker.
var fence int64
err := db.QueryRow(ctx, `
INSERT INTO sync_fences (account_id, fence, lease_until) VALUES ($1, 1, now() + interval '30 seconds')
ON CONFLICT (account_id) DO UPDATE
SET fence = sync_fences.fence + 1, lease_until = now() + interval '30 seconds'
WHERE sync_fences.lease_until IS NULL OR sync_fences.lease_until < now()
RETURNING fence`, account).Scan(&fence)
if errors.Is(err, sqldb.ErrNoRows) {
return nil, &errs.Error{Code: errs.Aborted, Message: "sync already running"}
} else if err != nil {
return nil, err
}
_, err = tryLease(ctx, account)
if errors.Is(err, errLeaseHeld) {
// We hold the authoritative Postgres lease, so a leftover Redis key from a
// previous worker is stale and can be removed, then the lease retried once.
_ = leases.Delete(ctx, account)
_, err = tryLease(ctx, account)
}
if err != nil {
_, _ = db.Exec(ctx, `
UPDATE sync_fences SET lease_until = NULL
WHERE account_id = $1 AND fence = $2`, account, fence)
if errors.Is(err, errLeaseHeld) {
return nil, &errs.Error{Code: errs.Aborted, Message: "sync already running"}
}
return nil, err
}
contacts, err := fetchContacts(ctx, account)
if err != nil {
return nil, err
}
written := 0
for _, c := range contacts {
// The write only lands if no newer worker has taken the lease since.
res, err := db.Exec(ctx, `
INSERT INTO crm_contacts (account_id, email, name)
SELECT $1, $2, $3
WHERE (SELECT fence FROM sync_fences WHERE account_id = $1 FOR SHARE) = $4
ON CONFLICT (account_id, email) DO UPDATE
SET name = EXCLUDED.name, synced_at = now()`,
account, c.Email, c.Name, fence)
if err != nil {
return nil, err
}
if res.RowsAffected() == 0 {
return nil, &errs.Error{Code: errs.Aborted, Message: "lease lost to a newer sync"}
}
written++
}
return &SyncResult{Written: written}, nil
}
We ran the lease logic with encore test against Encore's in-memory Redis: a second tryLease for the same account returned errLeaseHeld. We ran the fencing SQL against Postgres 17: after a second worker took fence 2, a write carrying fence 1 affected zero rows and the newer write landed. Locally the in-memory cache keeps a small number of keys and may purge them, so treat local runs as a check of the logic, not of lease timing.
A scheduled job or a Pub/Sub subscriber can call SyncAccount for each account, and a second call for an account that is already syncing gets Aborted instead of a duplicate run. The Redis cluster and the fence table are declared in the same package as the code that uses them, so a coding agent asked to "stop two syncs from overlapping" adds both in one change and exercises them with encore test.
Best fit: Go backends that need per-entity mutual exclusion across instances, with Redis and Postgres provisioned in their own AWS or GCP account and a fencing check where data is at stake.
The Redis distributed locks pattern for a single instance is SET with NX and PX and a random value, plus a release that deletes the key only if the value still matches. A Lua script makes that check and delete one atomic step, and the same trick extends a lock that is still yours. With go-redis v9:
// lock.go
package lock
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"time"
"github.com/redis/go-redis/v9"
)
var ErrHeld = errors.New("lock held")
// unlock deletes the key only if it still holds our token, in one atomic step.
var unlock = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0`)
// extend pushes the expiry out only if we still hold the lock.
var extend = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
end
return 0`)
type Lock struct {
rdb *redis.Client
key string
token string
}
func Acquire(ctx context.Context, rdb *redis.Client, key string, ttl time.Duration) (*Lock, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return nil, err
}
token := hex.EncodeToString(b)
// SET key token NX PX ttl
err := rdb.SetArgs(ctx, key, token, redis.SetArgs{Mode: "NX", TTL: ttl}).Err()
if errors.Is(err, redis.Nil) {
return nil, ErrHeld
}
if err != nil {
return nil, err
}
return &Lock{rdb: rdb, key: key, token: token}, nil
}
func (l *Lock) Extend(ctx context.Context, ttl time.Duration) (bool, error) {
n, err := extend.Run(ctx, l.rdb, []string{l.key}, l.token, ttl.Milliseconds()).Int()
return n == 1, err
}
func (l *Lock) Release(ctx context.Context) error {
return unlock.Run(ctx, l.rdb, []string{l.key}, l.token).Err()
}
The SET command returns nil when NX fails, which go-redis surfaces as redis.Nil. A worker holding the lock for longer than the TTL should call Extend from a ticker and stop working if it returns false.
That lock lives on one Redis, so a failover to a replica that had not yet received the key can grant it twice. Redlock acquires the key on a majority of independent primaries to survive that, and redsync implements it in Go. Martin Kleppmann's analysis of Redlock points out that process pauses and clock jumps can still produce two holders, and that a lock used for correctness needs a fencing token checked by the storage it protects, which is what the Postgres fence above does. You also provision and secure the Redis yourself, keep a local Redis for each developer, and set maxmemory-policy so the lock keys are not evicted.
Best fit: services that already run Redis and need efficient mutual exclusion, with a Lua release and, for anything that writes data, a fencing token.
If the protected work reads and writes one Postgres database, the database can be the lock. pg_try_advisory_xact_lock(hashtext('sync:' || account_id)) inside the transaction that does the work gives mutual exclusion that is released on commit or rollback and cannot outlive the session that holds it. It does not cover work that spans long external calls outside a transaction, and transaction-mode PgBouncer only supports the transaction-level variant, which is where a Redis lease plus a fence fits better.
Use a single-Redis SET NX lock with a Lua release when duplicate work is wasteful but harmless. Add a fencing token, checked by the database on every write, as soon as a stale holder could corrupt data, and consider Redlock only if you need the lock itself to survive the loss of a Redis primary. Use a Postgres advisory lock when the work lives inside one database transaction. Pick Encore when you want the Redis lease, the Postgres fence and the code that uses them declared together in Go, tested with encore test, and deployed to your own AWS or GCP account.
Set a key with a random token only if it does not exist and with an expiry, using SET lock:key <token> NX PX 30000. The caller that gets OK holds the lock. Release it with a Lua script that deletes the key only if it still holds your token, so you never delete a lock that expired and was taken by someone else.
No. Not on its own if the data must stay correct. It can avoid duplicate work, but a process can pause or a network can stall past the expiry, and two holders then believe they own the lock. When a stale holder must never write, give each holder a fencing token that only increases, and have the database reject writes that carry an older token.
Redlock is the Redis documentation's algorithm for acquiring the same lock on a majority of independent Redis primaries, so the lock survives the loss of one of them. It still relies on timing assumptions about clocks and pauses, which is why Martin Kleppmann's critique recommends fencing tokens for correctness.
If the work you protect writes to Postgres anyway, a Postgres advisory lock or a row lock gives you mutual exclusion inside the same database without a second system. Redis fits when the work is not in one database, when you need many short-lived locks with a timeout, or when you already run Redis for caching.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.