lock

package
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package lock provides distributed mutual exclusion for work that must run on at most one replica at a time — most often a scheduled job (see the cron package and `skit add cron --lock`). A Locker hands out a short-lived, best-effort lock keyed by a name; the holder does the work and releases it.

Backends

  • PG: Postgres advisory locks, pg_try_advisory_lock on a dedicated connection. No infrastructure beyond the database the service already has; the lock goes when the holding connection dies, so PG ignores ttl.
  • Redis: SET NX PX and a release that checks a random token. The ttl bounds how long a crashed holder blocks the others; the token keeps one holder from freeing the lock of another.

Usage

TryLock never blocks: it takes the lock now or reports it is held elsewhere. A caller that misses the lock skips this round rather than waits — the right behavior for periodic jobs:

locker := lock.NewPG(db, log) // or lock.NewRedis(client, log)

release, ok, err := locker.TryLock(ctx, "report", time.Minute)
if err != nil {
    return err // the store is unreachable: the lock may be free or not
}
if !ok {
    return nil // another replica runs the job
}
defer release()
return runReport(ctx)

A periodic job that ends quickly keeps the lock a while longer, until the ticks of the other replicas are past: released at once, it lets a replica whose tick fires a moment later run the job again. The template of `skit add cron --lock` does so.

Example

A cron job fires on every replica; the lock lets one of them run it. A replica that misses the lock skips this round. The example needs Postgres, so go test builds it but does not run it.

package main

import (
	"context"
	"log/slog"
	"time"

	"github.com/assanoff/skit/cron"
	"github.com/assanoff/skit/dbx/pg"
	"github.com/assanoff/skit/lock"
)

func main() {
	ctx := context.Background()
	log := slog.Default()
	db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
	if err != nil {
		log.ErrorContext(ctx, "open", "err", err)
		return
	}
	defer func() { _ = db.Close() }()
	locker := lock.NewPG(db, log)

	sched := cron.New(log, cron.Config{Name: "reports"})
	err = sched.Add("0 3 * * *", "nightly-report", func(ctx context.Context) error {
		release, ok, err := locker.TryLock(ctx, "nightly-report", time.Minute)
		if err != nil {
			return err // the store is unreachable: the lock may be free or not
		}
		if !ok {
			return nil // another replica runs the job
		}
		defer release()
		log.InfoContext(ctx, "building the nightly report")
		return nil
	})
	if err != nil {
		log.ErrorContext(ctx, "cron", "err", err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Locker

type Locker interface {
	// TryLock attempts to acquire the lock named key without blocking. On
	// success it returns ok==true and a Release to free the lock. If another
	// holder has it, ok==false and Release is a no-op. err is non-nil only on an
	// infrastructure failure (the caller cannot tell whether the lock is free).
	//
	// ttl bounds how long the lock survives a crashed holder: the Redis backend
	// expires the key after ttl, while the Postgres backend ignores ttl and
	// relies on connection death (its lock is session-scoped). Hold the lock
	// while the guarded work needs it, then Release; with Redis keep ttl above
	// that time.
	TryLock(ctx context.Context, key string, ttl time.Duration) (Release, bool, error)
}

Locker grants best-effort, single-holder locks.

type PG

type PG struct {
	// contains filtered or unexported fields
}

PG is a Locker backed by Postgres session-scoped advisory locks (pg_try_advisory_lock). Each TryLock checks out a dedicated connection and holds the lock on it; Release unlocks and returns the connection. If the holder crashes, Postgres drops the connection and releases the lock automatically, so a lock can never leak — this is why PG ignores ttl.

func NewPG

func NewPG(db *dbx.DB, log *slog.Logger) *PG

NewPG builds a Postgres advisory-lock Locker over db. log may be nil.

func (*PG) TryLock

func (p *PG) TryLock(ctx context.Context, key string, _ time.Duration) (Release, bool, error)

TryLock acquires pg_try_advisory_lock(key-hash) on a dedicated connection. ttl is ignored (the lock is session-scoped and released on Release or connection death). ok==false means another session holds the lock.

type Redis

type Redis struct {
	// contains filtered or unexported fields
}

Redis is a Locker backed by Redis. It acquires with SET key token NX PX ttl (atomic "set if absent with expiry") and releases with a Lua script that deletes the key only if it still holds this holder's token. The token fence stops one holder from freeing a lock that already expired and was retaken by another — the classic Redlock single-instance release.

func NewRedis

func NewRedis(client redis.Cmdable, log *slog.Logger) *Redis

NewRedis builds a Redis Locker over client (a *redis.Client or *redis.ClusterClient). log may be nil.

Example

Redis takes the lock with SET NX PX: the ttl frees it when the holder crashes, so keep it above the time the work takes.

package main

import (
	"context"
	"log/slog"
	"time"

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

	"github.com/assanoff/skit/lock"
)

func main() {
	ctx := context.Background()
	log := slog.Default()
	client := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
	defer func() { _ = client.Close() }()
	locker := lock.NewRedis(client, log)

	release, ok, err := locker.TryLock(ctx, "reindex", 10*time.Minute)
	if err != nil || !ok {
		return
	}
	defer release()
	log.InfoContext(ctx, "reindexing")
}

func (*Redis) TryLock

func (r *Redis) TryLock(ctx context.Context, key string, ttl time.Duration) (Release, bool, error)

TryLock runs SET key token NX PX ttl. ok==false means the key already exists (another holder). ttl must be > 0; it bounds how long a crashed holder blocks others.

type Release

type Release func()

Release frees a held lock. It is safe to call exactly once; implementations make a best effort and never panic. A Release returned with ok==false from TryLock is a no-op.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL