Skip to content

Locks and cache

Two small contracts help an application that runs more than one replica: a lock to serialise work across them, and a cache to share computed values. Each is an interface with several backends. The core packages lock and cache have no database driver dependency; each external backend is its own package, so you import (and compile) only what you use.

Both contracts demand a time-to-live on every call. A lock with no expiry strands the key when its holder crashes; a cache with no expiry grows without bound. Pass a long duration if you really want “rarely expires”.

type Provider interface {
Acquire(ctx context.Context, key string, ttl time.Duration) (Handle, error)
}
type Handle interface {
Release(ctx context.Context) error
}

Acquire is non-blocking. It has three outcomes:

Return Meaning
handle, nil You hold the lock.
nil, nil Someone else holds it. This is not an error: skip, retry or fail as your logic needs.
nil, err A zero or negative TTL (lock.ErrInvalidTTL), or a backend fault (wraps lock.ErrBackend).
h, err := lp.Acquire(ctx, "orders:reconcile", 30*time.Second)
switch {
case err != nil:
return err
case h == nil:
return nil // another replica is running it
}
defer h.Release(ctx)
// critical section

Release is idempotent, and it frees the lock only if you still own it: if your TTL ran out and another holder took the key, your late Release does nothing. Choose a TTL longer than the critical section with some headroom; the lock expires on its own if the process dies.

Backend Package Notes
No-op lock.NewNoOp() Every Acquire succeeds. For when you want the code path without the lock.
Memory lock.NewMemory() A process-local map. Safe for one process only; it does nothing across replicas.
Postgres lock/postgreslock One table, fc_locks by default (WithTable to rename). Acquire is one INSERT ... ON CONFLICT DO UPDATE ... WHERE expires_at <= NOW() RETURNING statement, so it is atomic and reclaims expired rows. Each acquire has a random holder token. ReapExpired(ctx) is optional cleanup.
Redis lock/redislock SET NX PX to acquire and a Lua check-and-delete to release, so a stale releaser cannot delete a reclaimed lock. Keys are prefixed fc:lock: (WithPrefix to change). Accepts any redis.UniversalClient: standalone, sentinel or cluster.

Create the Postgres table once with postgreslock.InitSchema(ctx, pool) (or InitSchemaWithTable), or put this in your migrations:

CREATE TABLE IF NOT EXISTS fc_locks (
key TEXT PRIMARY KEY,
holder TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS fc_locks_expires_at_idx ON fc_locks (expires_at);

The Postgres lock uses a table, not pg_try_advisory_lock, on purpose: an advisory lock has no TTL, so a crashed holder keeps it until its session ends. A row with an expiry cannot get stuck that way.

A lock is a guard against accidental overlap, not a consensus protocol. If your TTL runs out while the work continues, a second holder can enter. Keep critical sections short or make the work idempotent.

scheduledjobs.Runner takes a lock.Provider and acquires scheduled-job:{jobCode} before each handler. See Scheduled jobs.

type Cache interface {
GetBytes(ctx context.Context, key string) ([]byte, bool, error)
SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error
Delete(ctx context.Context, key string) error
}

The interface stores bytes, so it stays driver-agnostic. Three generic helpers give typed access with JSON encoding:

c := cache.NewMemory()
_ = cache.Set(ctx, c, "user:123", &user, 60*time.Second)
u, found, err := cache.Get[User](ctx, c, "user:123") // (zero, false, nil) on a miss or an expired entry
u, err := cache.GetOrSet(ctx, c, "user:123", time.Minute,
func(ctx context.Context) (User, error) { return loadUser(ctx, "123") })
  • A miss and an expired entry look the same: found is false, with no error.
  • SetBytes with a zero or negative TTL returns cache.ErrInvalidTTL.
  • Delete returns nil whether or not the key existed.
  • GetOrSet is not atomic across replicas: two callers racing on a cold key may both call the supplier, and the second write overwrites the first. If the supplier must run once, wrap the call in a lock.
  • Encoding failures are *cache.SerializeError (on write) and *cache.DeserializeError (on read, for example when the stored bytes no longer match T after a schema change). Backend I/O failures wrap cache.ErrBackend.
Backend Package Notes
Memory cache.NewMemory() Process-local, for tests and single-pod use. Expired entries are removed lazily when read; there is no background sweeper, so call ReapExpired(ctx) periodically if you write many distinct keys that are never read again.
Postgres cache/postgrescache Table fc_cache by default (WithTable). Values are BYTEA. Reads filter on expires_at > NOW(), so an expired row is invisible before it is deleted; writes upsert, so writing again refreshes the TTL. ReapExpired(ctx) deletes expired rows.
Redis cache/rediscache New(client) has no key prefix; WithPrefix(client, prefix) prepends prefix: to keep consumers apart on a shared Redis. Accepts any redis.UniversalClient.

Create the Postgres table with postgrescache.InitSchema(ctx, pool) or in your migrations:

CREATE TABLE IF NOT EXISTS fc_cache (
key TEXT PRIMARY KEY,
value BYTEA NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS fc_cache_expires_at_idx ON fc_cache (expires_at);

Backend faults across cache and lock wrap a single sentinel each, so errors.Is(err, lock.ErrBackend) or errors.Is(err, cache.ErrBackend) covers every transient infrastructure failure of that kind. See Errors.