coordination

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

distributed-coordination

Backend-neutral distributed-coordination contracts for Go: fenced leases, keepalive, mutexes, leader election, expiring membership and reusable barriers, with a deterministic in-memory reference backend, a cross-process local-filesystem backend, and a conformance suite for backend authors. It is for Go services and tools that run more than one worker and need to agree who owns what, and for library authors who want to write coordination logic once and plug in any backend.

Features

  • Fenced leases. Backend.Acquire grants exclusive, expiring ownership of a key with a FencingToken that strictly increases per key, even after release or expiry.
  • Keepalive. KeepAlive renews a lease immediately and then every ttl/3, and reports cancellation, loss or renewal errors through a concurrency future.
  • Mutex and leader election. Mutex and Campaign work with any Backend and hand out fencing tokens.
  • Membership and barriers. Registry tracks expiring group members with metadata; Barrier is a reusable rendezvous with generations.
  • In-memory backend (memory): synchronized, deterministic, implements every contract; ideal for tests and single-process coordination.
  • File backend (file): separate processes on one host exclude each other through operating-system locks, with crash release and persistent tokens.
  • Conformance suite (conformance): one call verifies that a backend adapter behaves like the reference.

Installation

go get github.com/justusschock/distributed-coordination@latest

Requires Go 1.25 or newer. The only non-standard-library dependencies are github.com/justusschock/concurrency (the future returned by KeepAlive) and golang.org/x/sys (operating-system locks in package file).

Quick start

Acquire a fenced lease and pass its token to the protected resource (from example_test.go):

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	coordination "github.com/justusschock/distributed-coordination"
	"github.com/justusschock/distributed-coordination/memory"
)

func main() {
	ctx := context.Background()
	backend := memory.NewBackend(nil)

	lease, err := backend.Acquire(ctx, coordination.AcquireRequest{
		Key:   "reports/daily",
		Owner: "worker-a",
		TTL:   30 * time.Second,
		Wait:  true,
	})
	if err != nil {
		fmt.Println("acquire:", err)
		return
	}
	defer func() { _ = lease.Release(context.Background()) }()

	// A second owner cannot take the key while the lease is held.
	_, err = backend.Acquire(ctx, coordination.AcquireRequest{
		Key:   "reports/daily",
		Owner: "worker-b",
		TTL:   30 * time.Second,
	})
	fmt.Println("contended:", errors.Is(err, coordination.ErrNotAcquired))

	// The protected store must reject writes carrying an older token.
	fmt.Println("token:", lease.Info().Token)
}

The token must be checked by the protected database, object store or service: a lock alone cannot reject a late write from a paused former owner. Tokens are ordered only within one key.

More examples, all runnable and tested, are on pkg.go.dev: ExampleNewMutex, ExampleCampaign, ExampleKeepAlive, memory.ExampleBackend_Join, memory.ExampleBackend_Wait, file.ExampleNewBackend and conformance.ExampleRun.

Leases
  • Empty keys or owners and non-positive TTLs return ErrInvalidRequest.
  • A contended request with Wait: false returns ErrNotAcquired immediately; with Wait: true it waits for release or expiry and honours context cancellation.
  • Lease.Done closes exactly once on release or loss.
  • Renew extends the deadline from the backend clock's current time.
  • Renew and Release return ErrLeaseLost after release, expiry or replacement.
Mutex
mutex, err := coordination.NewMutex(backend, "billing/close", "worker-a", 30*time.Second)
if err != nil {
	return err
}
token, err := mutex.Lock(ctx)
if err != nil {
	return err
}
defer mutex.Unlock(context.Background())
return store.Write(ctx, token, data)

One Mutex value represents one owner and holds at most one lease. Duplicate Lock calls, including one made while that value is still acquiring, return ErrNotOwner promptly; so does Unlock without a lease. Mutex does not renew its lease: choose a TTL that bounds the critical section, or use a raw lease with KeepAlive.

Leader election
leadership, err := coordination.Campaign(ctx, backend, coordination.ElectionOptions{
	Name:      "scheduler",
	Candidate: "node-a",
	TTL:       15 * time.Second,
})
if err != nil {
	return err
}
defer leadership.Resign(context.Background())

select {
case <-leadership.Lost:
	return coordination.ErrLeaseLost
case <-ctx.Done():
	return context.Cause(ctx)
}

Campaign waits for the lease election/<name> and keeps it alive until Resign, lease loss or cancellation of ctx; Lost closes in each case. Cancellation stops the keepalive without releasing, so the lease lapses after one TTL. Resign releases at most once and every call returns the first result.

Membership and barriers

The memory backend implements Registry and Barrier. Join registers a member with its own TTL and copies metadata; a duplicate active group/ID returns ErrNotAcquired; after leave or expiry the ID may join again. List returns active members sorted by ID. Wait blocks until Parties distinct, unexpired participants arrive and returns the generation number and sorted participants to every active waiter. The first Wait fixes a barrier's party count; a different count returns ErrInvalidRequest. Canceled arrivals are removed; expired ones are removed and return ErrNotAcquired.

File backend
backend, err := file.NewBackend("/var/lib/myapp/locks")

file.NewBackend(dir, opts...) creates dir if needed. Options:

Option Default Effect
WithClock(clock) real clock Clock for lease timestamps and expiry.
WithPollInterval(d) 100ms Maximum delay between attempts of a waiting acquisition. Attempts start at d/16 and back off exponentially with jitter.
WithFileMode(mode) 0644 Permission bits for created lock and state files; must include owner read and write. A created directory receives matching execute bits.

Each key maps to a lock file, locked with flock (Linux, macOS, BSDs) or LockFileEx (Windows), and a JSON state file holding the owner, token and deadline, written atomically under the lock. Guarantees and limits:

  • Mutual exclusion across processes, Backend values and lease handles on one host.
  • Crash release: the operating system drops the lock when the holder exits or is killed.
  • Persistent fencing: tokens increase across processes and restarts; a corrupt or foreign state file fails acquisition instead of resetting.
  • Holder-enforced expiry: a live but suspended holder cannot be pre-empted; rely on fencing tokens at the protected resource.
  • Local filesystems only: lock semantics on NFS or SMB vary.
  • Locks are advisory, and one lock and one state file remain per key ever used. Other platforms get errors.ErrUnsupported from NewBackend.

Packages

Package Description
coordination (root) Contracts (Backend, Lease, Registry, Membership, Barrier, Clock), helpers (KeepAlive, Mutex, Campaign) and errors.
memory In-process reference backend implementing every contract.
file Cross-process backend over lock files in a local directory.
conformance Run, the test suite every Backend implementation must pass.

Packages under internal/, should any be added, are not part of the API.

Writing a backend

Implement coordination.Backend and run the suite from your tests, giving each subtest a fresh backend and a hook that advances its clock:

func TestBackend(t *testing.T) {
	conformance.Run(t, func(t *testing.T) (coordination.Backend, func(time.Duration)) {
		clock := newManualClock()
		return newBackend(clock), clock.Advance
	})
}

Production adapters must provide atomic acquisition, durable per-key monotonically increasing tokens, expiry and record-identity checks.

Design and guarantees

  • Concurrency. Every exported type is safe for concurrent use. Blocking operations take a context.Context and return promptly when it is done.
  • Errors. Sentinels for errors.Is: ErrInvalidRequest (invalid input), ErrNotAcquired (immediate contention, duplicate membership, expired barrier arrival), ErrLeaseLost (expired, released or replaced) and ErrNotOwner (mutex or leadership operation without ownership). Canceled operations return the context error or cancellation cause.
  • Time. Expiry compares stored deadlines with the backend Clock, so a late timer never extends ownership. Inject a Clock or use testing/synctest for deterministic tests.
  • No logging. The library reports only through return values, futures and channels.
  • Scope. The memory backend does not coordinate processes; the file backend coordinates processes on one host. Adapters for etcd, SQL, Redis and similar systems belong in other modules.
  • Stability. The module is v0.x: minor releases may break the API. Every break is listed in CHANGELOG.md.

Documentation

  • docs/: requirements (PRD) and architecture decision records (ADRs).
  • API reference on pkg.go.dev.

Contributing

Contributions go through pull requests; see AGENTS.md for the docs-first workflow, engineering rules and the checks to run before opening one.

License

Apache License 2.0; see LICENSE and NOTICE.

Documentation

Overview

Package coordination defines backend-neutral contracts for distributed coordination: fenced leases, lease keepalive, mutexes, leader election, expiring group membership and reusable barriers.

A Backend grants exclusive, time-bounded [Lease]s on string keys. Every successful acquisition carries a FencingToken that is strictly greater than every token previously granted for the same key, even after release or expiry. Protected resources must check the token: a lease alone cannot stop a paused former owner from writing late.

The helpers in this package (KeepAlive, Mutex, Campaign) work with any Backend. Implementations live in sub-packages:

  • memory: a synchronized in-process reference backend that also implements Registry and Barrier;
  • file: a cross-process backend over lock files in a local directory;
  • conformance: the test suite every Backend implementation must pass.

Errors

Operations report the sentinel errors ErrInvalidRequest, ErrNotAcquired, ErrLeaseLost and ErrNotOwner; test for them with errors.Is. Canceled operations return the context's error or cancellation cause.

Concurrency

All interfaces in this package must be safe for concurrent use by implementations. Mutex is safe for concurrent use; Leadership values may be copied and their Resign method called from any goroutine.

Example

Acquire a fenced lease and pass its token to the protected resource.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	coordination "github.com/justusschock/distributed-coordination"
	"github.com/justusschock/distributed-coordination/memory"
)

func main() {
	ctx := context.Background()
	backend := memory.NewBackend(nil)

	lease, err := backend.Acquire(ctx, coordination.AcquireRequest{
		Key:   "reports/daily",
		Owner: "worker-a",
		TTL:   30 * time.Second,
		Wait:  true,
	})
	if err != nil {
		fmt.Println("acquire:", err)
		return
	}
	defer func() { _ = lease.Release(context.Background()) }()

	// A second owner cannot take the key while the lease is held.
	_, err = backend.Acquire(ctx, coordination.AcquireRequest{
		Key:   "reports/daily",
		Owner: "worker-b",
		TTL:   30 * time.Second,
	})
	fmt.Println("contended:", errors.Is(err, coordination.ErrNotAcquired))

	// The protected store must reject writes carrying an older token.
	fmt.Println("token:", lease.Info().Token)
}
Output:
contended: true
token: 1

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidRequest reports an empty required field, a non-positive
	// count or a non-positive TTL.
	ErrInvalidRequest = errors.New("coordination: invalid request")
	// ErrNotAcquired reports immediate lease contention (Wait: false), a
	// duplicate active membership, or a barrier arrival whose TTL expired.
	ErrNotAcquired = errors.New("coordination: not acquired")
	// ErrLeaseLost reports that a lease or membership expired, was released
	// or was replaced, so it can no longer be renewed or released.
	ErrLeaseLost = errors.New("coordination: lease lost")
	// ErrNotOwner reports a Mutex or Leadership operation without matching
	// active ownership.
	ErrNotOwner = errors.New("coordination: not owner")
)

Sentinel errors returned by the coordination helpers and by conforming backends. Test for them with errors.Is; implementations may wrap them.

Functions

func KeepAlive

func KeepAlive(ctx context.Context, lease Lease, ttl time.Duration) (*concurrency.Future[LeaseInfo], error)

KeepAlive renews lease with ttl immediately and then every ttl/3 (at least every nanosecond) on its own goroutine. The returned future resolves with the latest LeaseInfo and

  • the cancellation cause of ctx when ctx is done,
  • ErrLeaseLost when lease.Done closes, or
  • the first error returned by Renew.

Cancel ctx to stop renewing; the lease itself is not released. KeepAlive returns ErrInvalidRequest for a nil lease or a non-positive ttl.

Example
package main

import (
	"context"
	"fmt"
	"time"

	coordination "github.com/justusschock/distributed-coordination"
	"github.com/justusschock/distributed-coordination/memory"
)

func main() {
	backend := memory.NewBackend(nil)
	lease, err := backend.Acquire(context.Background(), coordination.AcquireRequest{
		Key: "index/rebuild", Owner: "worker-a", TTL: 30 * time.Second,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = lease.Release(context.Background()) }()

	ctx, stop := context.WithCancel(context.Background())
	defer stop()
	future, err := coordination.KeepAlive(ctx, lease, 30*time.Second)
	if err != nil {
		fmt.Println(err)
		return
	}

	// ... long-running work protected by lease.Info().Token ...

	stop()
	_, err = future.Await(context.Background())
	fmt.Println("keepalive stopped:", err)
}
Output:
keepalive stopped: context canceled

Types

type AcquireRequest

type AcquireRequest struct {
	// Key names the coordinated resource. It must not be empty.
	Key string
	// Owner identifies the requester. It must not be empty and is recorded
	// in [LeaseInfo]; backends do not interpret it.
	Owner string
	// TTL bounds the lease lifetime from the moment of acquisition. It must
	// be positive.
	TTL time.Duration
	// Wait selects the behaviour under contention: false returns
	// [ErrNotAcquired] immediately, true waits for release or expiry until
	// the context is done.
	Wait bool
}

AcquireRequest describes a lease acquisition.

type Backend

type Backend interface {
	// Acquire grants a lease on request.Key. It returns [ErrInvalidRequest]
	// for an empty key or owner or a non-positive TTL, [ErrNotAcquired] when
	// the key is held and request.Wait is false, and the context's error
	// when ctx is done while waiting.
	Acquire(ctx context.Context, request AcquireRequest) (Lease, error)
}

Backend grants fenced leases. Implementations must be safe for concurrent use and must pass the conformance suite in package conformance.

type Barrier

type Barrier interface {
	// Wait blocks until Parties distinct, unexpired participants have
	// arrived, then returns the completed generation to every active waiter.
	// It returns [ErrInvalidRequest] for invalid fields or a party count
	// that differs from the barrier's, [ErrNotAcquired] when the arrival's
	// TTL expires first, and the context's cancellation cause when ctx is
	// done first. Expired and canceled arrivals are removed from the
	// generation.
	Wait(ctx context.Context, request BarrierRequest) (BarrierResult, error)
}

Barrier is a reusable rendezvous of a fixed number of participants. Implementations must be safe for concurrent use.

type BarrierRequest

type BarrierRequest struct {
	// Name identifies the barrier. It must not be empty.
	Name string
	// Participant identifies the arriving party. It must not be empty; a
	// participant counts once per generation even with concurrent waiters.
	Participant string
	// Parties is the number of distinct participants that complete a
	// generation. It must be positive, and every waiter of a barrier must
	// use the same value.
	Parties int
	// TTL bounds how long the arrival counts towards the current generation.
	// It must be positive.
	TTL time.Duration
}

BarrierRequest describes one participant's arrival at a named barrier.

type BarrierResult

type BarrierResult struct {
	Name string
	// Generation increases monotonically per barrier name, starting at 1.
	Generation uint64
	// Participants lists the participants of the generation, sorted.
	Participants []string
}

BarrierResult describes a completed barrier generation.

type Clock

type Clock interface {
	// Now returns the current time.
	Now() time.Time
	// After returns a channel that receives the time once d has elapsed.
	After(d time.Duration) <-chan time.Time
}

Clock is the time source a backend uses for lease timestamps and expiry. Backends accept a Clock so adapters and tests can control time; pass nil to the constructors in this module to use the real clock.

type ElectionOptions

type ElectionOptions struct {
	// Name identifies the election; the lease key is "election/" + Name.
	Name string
	// Candidate identifies this participant and becomes the lease owner.
	Candidate string
	// TTL is the leadership lease lifetime, renewed every TTL/3.
	TTL time.Duration
}

ElectionOptions configures Campaign.

type FencingToken

type FencingToken uint64

FencingToken orders the leases granted for one key. Each successful acquisition of a key receives a token strictly greater than every token previously granted for that key. Tokens of different keys are unrelated and must not be compared.

type Leadership

type Leadership struct {
	// Token is the fencing token of the leadership lease.
	Token FencingToken
	// Lost is closed when the lease is lost or its keepalive stops, including
	// after Resign or cancellation of the Campaign context.
	Lost <-chan struct{}
	// contains filtered or unexported fields
}

Leadership is won leadership of an election. It may be copied; all copies share the same lease.

func Campaign

func Campaign(ctx context.Context, backend Backend, options ElectionOptions) (Leadership, error)

Campaign waits until it acquires the election lease for options.Name, then keeps it alive with KeepAlive until ctx is done, the lease is lost or Leadership.Resign is called. It returns ErrInvalidRequest for a nil backend, an empty name or candidate, or a non-positive TTL, and otherwise the backend's acquisition error.

Example
package main

import (
	"context"
	"fmt"
	"time"

	coordination "github.com/justusschock/distributed-coordination"
	"github.com/justusschock/distributed-coordination/memory"
)

func main() {
	ctx := context.Background()
	backend := memory.NewBackend(nil)

	leadership, err := coordination.Campaign(ctx, backend, coordination.ElectionOptions{
		Name:      "scheduler",
		Candidate: "node-a",
		TTL:       15 * time.Second,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("leader with token", leadership.Token)

	if err := leadership.Resign(ctx); err != nil {
		fmt.Println(err)
	}
	<-leadership.Lost
	fmt.Println("resigned")
}
Output:
leader with token 1
resigned

func (Leadership) Resign

func (l Leadership) Resign(ctx context.Context) error

Resign stops the keepalive and releases the leadership lease. The release happens at most once; every call returns the first call's result. The zero Leadership returns ErrNotOwner.

type Lease

type Lease interface {
	// Info returns the latest snapshot of the lease, including renewals.
	Info() LeaseInfo
	// Done is closed exactly once when the lease is released or lost
	// (expiry, replacement or, for some backends, loss of the underlying
	// lock).
	Done() <-chan struct{}
	// Renew extends the deadline to the backend clock's current time plus
	// ttl. It returns [ErrInvalidRequest] for a non-positive ttl and
	// [ErrLeaseLost] after release, expiry or replacement.
	Renew(ctx context.Context, ttl time.Duration) (LeaseInfo, error)
	// Release gives up the lease and closes Done. It returns [ErrLeaseLost]
	// if the lease was already released, expired or replaced.
	Release(ctx context.Context) error
}

Lease is exclusive, time-bounded ownership of one key. Implementations must be safe for concurrent use.

type LeaseInfo

type LeaseInfo struct {
	Key        string
	Owner      string
	Token      FencingToken
	AcquiredAt time.Time
	ExpiresAt  time.Time
}

LeaseInfo is a snapshot of a lease.

type Member

type Member struct {
	// Group names the group. It must not be empty.
	Group string
	// ID identifies the member within the group. It must not be empty.
	ID string
	// Metadata is optional, opaque data published with the member.
	// Registries copy it defensively.
	Metadata map[string]string
}

Member identifies a participant in a group.

type MemberInfo

type MemberInfo struct {
	Member    Member
	JoinedAt  time.Time
	ExpiresAt time.Time
}

MemberInfo is a snapshot of an active membership.

type Membership

type Membership interface {
	// Info returns the latest snapshot of the membership.
	Info() MemberInfo
	// Done is closed exactly once when the membership is left or expires.
	Done() <-chan struct{}
	// Renew extends the deadline to the registry clock's current time plus
	// ttl. It returns [ErrInvalidRequest] for a non-positive ttl and
	// [ErrLeaseLost] after leave, expiry or replacement.
	Renew(ctx context.Context, ttl time.Duration) (MemberInfo, error)
	// Leave ends the membership and closes Done. It returns [ErrLeaseLost]
	// if the membership already ended.
	Leave(ctx context.Context) error
}

Membership is an expiring registration of one member. Implementations must be safe for concurrent use.

type Mutex

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

Mutex is a fenced mutual-exclusion lock over a Backend for one key and one owner. A Mutex value holds at most one lease at a time and does not renew it: choose a TTL that bounds the critical section or use KeepAlive on a raw Lease.

A Mutex is safe for concurrent use, but concurrent Lock calls on the same value do not queue: the second returns ErrNotOwner.

func NewMutex

func NewMutex(backend Backend, key, owner string, ttl time.Duration) (*Mutex, error)

NewMutex returns a Mutex for key and owner whose leases last ttl. It returns ErrInvalidRequest for a nil backend, an empty key or owner, or a non-positive ttl.

Example
package main

import (
	"context"
	"fmt"
	"time"

	coordination "github.com/justusschock/distributed-coordination"
	"github.com/justusschock/distributed-coordination/memory"
)

func main() {
	ctx := context.Background()
	backend := memory.NewBackend(nil)

	mutex, err := coordination.NewMutex(backend, "billing/close", "worker-a", 30*time.Second)
	if err != nil {
		fmt.Println(err)
		return
	}
	token, err := mutex.Lock(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("locked with token", token)
	if err := mutex.Unlock(ctx); err != nil {
		fmt.Println(err)
	}
}
Output:
locked with token 1

func (*Mutex) Lock

func (m *Mutex) Lock(ctx context.Context) (FencingToken, error)

Lock waits until the lease for the mutex key is acquired and returns its fencing token, which callers pass to the protected resource. It returns ErrNotOwner promptly if this Mutex already holds or is acquiring a lease, and the context's error if ctx is done while waiting.

func (*Mutex) Unlock

func (m *Mutex) Unlock(ctx context.Context) error

Unlock releases the held lease. It returns ErrNotOwner when no lease is held. If the lease was already lost it returns ErrLeaseLost and the Mutex may be locked again; other release errors keep the lease so Unlock can be retried.

type Registry

type Registry interface {
	// Join registers member for ttl. It returns [ErrInvalidRequest] for an
	// empty group or ID or a non-positive ttl and [ErrNotAcquired] while the
	// same group and ID are already active. After leave or expiry the same
	// ID may join again as a fresh membership.
	Join(ctx context.Context, member Member, ttl time.Duration) (Membership, error)
	// List returns the active members of group sorted by ID. It returns
	// [ErrInvalidRequest] for an empty group.
	List(ctx context.Context, group string) ([]MemberInfo, error)
}

Registry tracks expiring group membership. Implementations must be safe for concurrent use.

Directories

Path Synopsis
Package conformance provides the test suite every coordination.Backend implementation must pass.
Package conformance provides the test suite every coordination.Backend implementation must pass.
Package file implements coordination.Backend with cross-process leases on a local filesystem directory.
Package file implements coordination.Backend with cross-process leases on a local filesystem directory.
Package memory provides a synchronized, in-process reference implementation of the coordination contracts.
Package memory provides a synchronized, in-process reference implementation of the coordination contracts.

Jump to

Keyboard shortcuts

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