postgres

package
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: 8 Imported by: 0

Documentation

Overview

Package postgres provides a snowflake.NodeRegistry that leases node IDs from a PostgreSQL table.

The registry creates its table on first use and fills it with one row per node ID. Each process leases the lowest free row and renews the lease in the background; a crashed process's node ID becomes free again once its lease expires. All times are taken from the database clock, so clock differences between hosts don't matter.

Requires PostgreSQL 9.5 or later (FOR UPDATE SKIP LOCKED). The caller opens the *sql.DB, for example with github.com/jackc/pgx/v5/stdlib.

Index

Constants

View Source
const DefaultTable = "snowflake_nodes"

DefaultTable is the table name used when no WithTable option is given.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*config)

Option configures a Registry.

func WithOwner

func WithOwner(owner string) Option

WithOwner sets the identifier recorded as the lease holder (at most 255 characters). Defaults to the hostname plus a random suffix.

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL sets how long a lease lasts without renewal. It is renewed every TTL/3. A shorter TTL frees a crashed process's node ID sooner, but tolerates shorter database outages. Defaults to one minute; must be at least 3 seconds.

func WithTable

func WithTable(table string) Option

WithTable sets the table name. It must be a lowercase identifier (letters, digits, underscores) and is created in the connection's default schema.

type Registry

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

Registry leases node IDs from a PostgreSQL table. It is safe for concurrent use.

func New

func New(db *sql.DB, opts ...Option) (*Registry, error)

New creates a Registry backed by db.

func (*Registry) Acquire

func (r *Registry) Acquire(ctx context.Context) (int64, error)

Acquire leases the lowest free node ID and starts renewing it in the background. It returns snowflake.ErrNoNodeIDAvailable if all node IDs are leased.

func (*Registry) Lost

func (r *Registry) Lost() <-chan struct{}

Lost is closed if the lease could not be renewed in time or was taken over.

func (*Registry) Release

func (r *Registry) Release(ctx context.Context) error

Release stops renewing the lease and frees the node ID.

Jump to

Keyboard shortcuts

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