zid

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 11 Imported by: 3 modules, 4 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

zid

Go Reference Go Version License

Short, ordered, fast — with autonomous worker-ID leases.

zid is a high-performance, concurrency-safe int64 ID generator for Go. It produces compact, millisecond-sortable IDs through a zero-allocation integer hot path, while optional Redis and Kubernetes managers automate worker allocation, lease renewal, fencing, and recovery.

It is designed for databases and distributed services that want the storage and index efficiency of numeric Snowflake IDs together with a complete, tested worker lifecycle.

English · 简体中文

Why zid

  • Short — a positive int64 occupies 8 bytes in a database, at most 19 decimal digits or 11 base-62 characters.
  • Ordered — numeric order follows millisecond time, improving index locality and making creation time directly extractable.
  • Fast — the integer hot path is zero-allocation; local sharding scales concurrent generation to roughly 28–30 million IDs/s in the included benchmark.
  • Autonomous distributed workers — Redis and Kubernetes managers handle worker acquisition, renewal, fencing, and automatic replacement after lease loss.
  • Uniqueness first — when a worker can no longer be proven safe, generation pauses and resumes with a different worker instead of emitting a risky ID.
  • High capacity — the default layout provides 262,144 IDs per millisecond per worker, with configurable worker, shard, and sequence bits.
  • Clock rollback aware — rollback consumes the remaining safe sequence at the last observed millisecond and never manufactures capacity by repeatedly moving logical time forward.
  • Simple application API — configure once, then call zid.NextID() anywhere; use zid.NextIDContext when a request needs cancellation.
  • Focused dependencies — the core module has no third-party runtime dependencies; Redis and Kubernetes integrations are independent Go modules.

Quick start

Install
go get github.com/zohu/zid@latest
Package-level generator

For one process, the package default is the shortest path:

package main

import (
    "fmt"

    "github.com/zohu/zid"
)

func main() {
    id := zid.NextID()

    fmt.Println(id)
    fmt.Println(zid.ExtractTime(id))
    fmt.Println(zid.ExtractWorkerID(id))
}

The initial package default uses worker ID 0 for a single process. For a multi-process deployment, install a managed default before the first package-level generation or extraction call.

Independent generator

Use an explicit generator for dependency injection, a custom layout, or an application-assigned worker ID:

generator, err := zid.New(zid.Options{
    WorkerID:     3,
    WorkerIDBits: 8,
    ShardBits:    4,
    SequenceBits: 10,
})
if err != nil {
    return err
}
defer generator.Close()

id := generator.NextID()
createdAt := generator.ExtractTime(id)
workerID := generator.ExtractWorkerID(id)
shardID := generator.ExtractShardID(id)

This layout supports 256 workers, 16 local shards per worker, and 1,024 IDs per millisecond per shard.

Context, strings, and parsing
id, err := zid.NextIDContext(requestContext)
if err != nil {
    // context cancellation/deadline, or zid.ErrClosed
    return err
}

decimal := zid.NextString()
hex := zid.NextHex()
base36 := zid.NextBase36()
base62 := zid.NextBase62()

parsed, err := zid.ParseBase62(base62)
if err != nil {
    return err
}
generatedAt := zid.ExtractTime(parsed)

ParseHex, ParseBase36, and ParseBase62 reject empty, malformed, negative, or overflowing values. String creation allocates; the integer NextID path does not. Every service that extracts fields from an ID must use the same epoch and bit layout that generated it.

Base62 uses the ASCII-ordered alphabet 0-9A-Za-z. Equal-width encodings retain numeric order under bytewise comparison; because the encoding is variable-width, lexicographic order across different lengths is not numeric order.

How it works

ID layout

zid stores a non-negative ID in a signed int64:

  63 usable bits
┌──────────────────────┬────────────┬───────────┬────────────┐
│ timestamp (>=41 bits)│ worker (w) │ shard (s) │ sequence(q)│
└──────────────────────┴────────────┴───────────┴────────────┘
                         w + s + q <= 22 bits

The timestamp is the number of real milliseconds since the protocol epoch. The default protocol is:

Property Default
Epoch 2026-08-01 00:00:00 UTC
Unix epoch value 1785542400000 ms
Worker bits 4
Local shard bits 0
Sequence bits 18
Workers 16
IDs per millisecond per worker 262,144
Minimum lifetime about 69.7 years

IDs sort numerically by millisecond timestamp. Generation order inside the same millisecond is not a total order when multiple workers or local shards are used.

Generation path
  1. Select a local shard. With one shard this is the only shard; with multiple shards, selection spreads lock contention.
  2. Verify that the generator is open and, in managed mode, that its lease is still inside the local safety window.
  3. Read the wall-clock millisecond. A new millisecond resets the shard sequence.
  4. During clock rollback, hold the last real millisecond already observed and consume its remaining sequence; do not keep incrementing logical time.
  5. If the selected shard is full, try every other shard before waiting.
  6. If all shards are full, one goroutine waits for the real clock to advance; other callers wait on a shared notification instead of creating polling timers of their own.

The result is uniqueness without inventing future timestamps. The tradeoff is intentional backpressure when real-time capacity has actually been exhausted.

Uniqueness scopes
Construction Guarantee scope Caller responsibility
Package default One process lifetime Do not use the initial worker 0 default in multiple processes
zid.New One generator lifetime Assign distinct worker IDs to concurrent generators/processes
zid.NewManaged Distributed, while the coordinator assumptions hold Operate Redis/Kubernetes safely and keep a free worker ID available

Reconstructing a process-local generator with the same worker ID can repeat the last millisecond's sequence. Use managed mode when uniqueness must survive process restarts without application-managed fencing.

Distributed worker IDs

Redis and Kubernetes managers are separate modules, so applications only pull the coordinator they use:

go get github.com/zohu/zid/zidredis@latest
go get github.com/zohu/zid/zidk8s@latest
Redis

The one-step startup API creates the manager and installs it as the package default:

package main

import (
    "context"

    "github.com/redis/go-redis/v9"
    "github.com/zohu/zid"
    "github.com/zohu/zid/zidredis"
)

func configureIDs(ctx context.Context, client redis.UniversalClient) error {
    if err := zidredis.ConfigureDefault(
        ctx,
        client,
        zidredis.Options{},
        zid.Options{WorkerIDBits: 10, SequenceBits: 12},
    ); err != nil {
        return err
    }

    // Call zid.CloseDefault during application shutdown.
    return nil
}

Call ConfigureDefault exactly once during startup, before any package-level generation or extraction helper. A later attempt returns zid.ErrDefaultAlreadyUsed. zidredis.New remains side-effect free when an explicit zid.NewManaged generator is preferable.

manager, err := zidredis.New(client, zidredis.Options{})
if err != nil {
    return err
}
generator, err := zid.NewManaged(ctx, manager, zid.Options{})
if err != nil {
    return err
}
defer generator.Close()

Redis uses SET NX PX with a random owner token. Renewal executes a Lua compare-and-PEXPIRE, so an old owner cannot renew a newer owner's key. Closing a lease does not delete the key immediately; the remaining TTL acts as a worker ID reuse quarantine.

Kubernetes
if err := zidk8s.ConfigureDefault(
    ctx,
    zidk8s.Options{},
    zid.Options{WorkerIDBits: 10, SequenceBits: 12},
); err != nil {
    return err
}
defer zid.CloseDefault()

id := zid.NextID()

Defaults read NAMESPACE and POD_UID from the environment and use in-cluster configuration. Both can be set explicitly in zidk8s.Options.

Minimum namespaced RBAC:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: zid-lease-manager
rules:
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]
    verbs: ["get", "create", "update"]

Each Kubernetes holder identity includes a random instance token. Claims and renewals use resourceVersion compare/update semantics. Non-NotFound API errors are never treated as an absent Lease, and closed Leases remain until expiry as a reuse quarantine.

Lease lifecycle and recovery

Both managers use these defaults:

Setting Default
Lease TTL 30 s
Renewal interval 10 s
Safety margin 10 s
Operation timeout 3 s

The local safety deadline is computed conservatively from the start of the coordinator request. Renewal and recovery behave as follows:

Generator state Can emit IDs? Behavior
GeneratorHealthy Yes Lease is valid and renewals are succeeding
GeneratorDegraded Yes A transient renewal failed, but the local safety deadline has not passed
GeneratorRecovering No The old lease is fenced; a different worker ID is being acquired
GeneratorClosed No The generator was explicitly closed

Use State or package-level DefaultState for readiness and metrics. Healthy means “safe to emit an ID now”, so it remains true while the state is degraded; use the full state when coordinator health must affect readiness.

On permanent loss, the generator:

  1. Stops emitting IDs before the lease can be considered unsafe.
  2. Permanently excludes that worker ID for the generator's remaining lifetime.
  3. Retries acquisition with exponential backoff from 100 ms up to 5 s.
  4. Installs a different worker ID atomically across all local shards.
  5. Wakes blocked callers after the new lease is safe.

Direct NextID, NextString, NextHex, NextBase36, and NextBase62 calls wait during recovery rather than return a possibly duplicated ID. Use NextIDContext where a request must have a deadline.

If the coordinator is temporarily unavailable or no eligible worker ID is free, generation resumes automatically as soon as a safe lease becomes available.

Configuration

Generator options
Field Zero/default behavior Valid range or note
BaseTime 2026-08-01 UTC Must be positive and not in the future
WorkerID 0 Must fit WorkerIDBits; assigned by managed mode
WorkerIDBits 4 0–19 bits
ShardBits 0 0–16 bits
SequenceBits 18 3–22 bits
DisableWorkerID false Cannot be combined with WorkerID or WorkerIDBits

WorkerIDBits + ShardBits + SequenceBits must be at most 22. Reducing the low bit count increases timestamp lifetime; reallocating low bits trades worker count, local parallelism, and per-shard capacity.

For a generator that spends no bits on worker identity:

generator, err := zid.New(zid.Options{
    DisableWorkerID: true,
    ShardBits:       4,
    SequenceBits:    18,
})

Safety and availability behavior

zid preserves uniqueness with explicit backpressure whenever generation cannot continue safely:

Condition Direct Next... methods NextIDContext
Capacity remains Return immediately Return immediately
All shards full in current real millisecond Wait for the real next millisecond Wait or return the context error
Managed lease is recovering Wait for a different safe worker ID Wait or return the context error
Generator is closed Panic with zid.ErrClosed Return zid.ErrClosed

Close is idempotent. A direct call after Close is treated as a lifecycle programming error and panics.

Distributed assumptions

Managed uniqueness requires all of the following:

  • Redis or Kubernetes preserves acknowledged lease writes and provides reliable compare/update semantics. A Redis failover that loses an acknowledged write can break exclusivity.
  • Pairwise node-clock offset and worst-case coordinator latency remain below the configured SafetyMargin.
  • All participants sharing a Redis prefix or Kubernetes Lease prefix use the same TTL and safety settings.
  • The configured worker-ID space has a free eligible lease. A recovering generator never reuses a worker ID it previously lost, so repeated permanent losses can exhaust its candidate set.
  • All consumers agree on the epoch and bit layout.
  • The signed int64 timestamp range has not been exhausted.

During a network partition or coordinator outage, zid prioritizes uniqueness and resumes generation when it can prove that a safe lease is available.

Comparison with other Go ID libraries

These libraries solve different problems. The table compares protocol and operational properties, not benchmark results from different machines.

Library ID shape Time ordering Uniqueness / coordination model Best fit
zid 63-bit positive int64; decimal, hex, base36, base62 Millisecond, numeric Exact sequence within an exclusive worker; built-in optional Redis/Kubernetes leases Compact database keys with explicit distributed fencing
bwmarrin/snowflake 63-bit int64; default 41 time + 10 node + 12 sequence bits Millisecond, numeric Application must keep node numbers unique Simple classic Snowflake with externally managed nodes
Sonyflake 63-bit integer; default 39 time + 8 sequence + 16 machine bits 10 ms by default Machine-ID callback or host-derived default; optional validation Long lifetime or a large machine-ID space
ULID 128 bits; canonical 26-char base32 Millisecond, lexicographic; optional monotonic entropy Random entropy, coordination-free and probabilistic Portable, standard-shaped sortable strings
KSUID 160 bits; canonical 27-char base62 Second, lexicographic 128-bit random payload, coordination-free and probabilistic Portable strings with strong collision resistance

zid is usually a better fit when:

  • the database and APIs benefit from an 8-byte numeric key;
  • worker ownership must be explicit and observable rather than inferred from host metadata;
  • lease renewal, fencing, and automatic worker replacement should have one tested implementation;
  • deterministic per-worker capacity is preferred over probabilistic collision resistance;
  • high local concurrency must not serialize on one generator mutex.

Selection note: use a cryptographically random token when unpredictability is a security requirement. ULID, KSUID, or UUIDv7 are natural choices when canonical cross-language strings or coordination-free generation matter more than compact numeric storage. Strict global total order requires a distributed sequencing service.

Performance

Benchmarks were run on Apple M1 Max with Go 1.26.2. They are measurements, not a cross-library claim:

Benchmark Typical latency Approximate throughput Allocations
BenchmarkGeneratorSingle 55–59 ns/op 17–18 M IDs/s 0 B/op, 0 allocs/op
BenchmarkPackageNextID 55–57 ns/op 17–18 M IDs/s 0 B/op, 0 allocs/op
BenchmarkGeneratorShardedParallel 33–36 ns/op 28–30 M IDs/s 0 B/op, 0 allocs/op

The measured CPU throughput and the protocol capacity are different limits. The default format has space for 262,144 IDs/ms/worker; the benchmark above measures how fast this implementation generated IDs on one machine.

Reproduce locally:

go test -run '^$' \
  -bench 'Benchmark(GeneratorSingle|PackageNextID|GeneratorShardedParallel)$' \
  -benchmem -count=8

Development

Run the full workspace verification:

go test -race ./...
go vet ./...

GOWORK=off go -C zidredis test -race ./...
GOWORK=off go -C zidredis vet ./...

GOWORK=off go -C zidk8s test -race ./...
GOWORK=off go -C zidk8s vet ./...

Current statement coverage is approximately 85.7% for the core, 86.6% for the Redis module, and 81.9% for the Kubernetes module.

Contributing

Contributions should include focused tests for protocol, clock, concurrency, or lease-lifecycle changes. Please open an issue before changing the ID protocol or distributed safety model.

Maintainer release

All three modules are tagged from the same commit. After the two submodules require the target root version and the working tree is committed and clean:

mise release v1.0.1

The task independently runs go mod tidy -diff, go vet, and race-enabled tests for all modules, creates v1.0.1, zidredis/v1.0.1, and zidk8s/v1.0.1, then atomically pushes the branch and tags.

License

MIT

Documentation

Index

Constants

View Source
const (

	// DefaultBaseTime is 2026-08-01 00:00:00 UTC in Unix milliseconds.
	DefaultBaseTime = int64(1785542400000)
)

Variables

View Source
var (
	ErrClosed = errors.New("zid: generator is closed")
)
View Source
var ErrDefaultAlreadyUsed = errors.New("zid: default generator is already configured or has been used")

Functions

func CloseDefault added in v1.0.0

func CloseDefault() error

CloseDefault closes the package-level Generator. Package-level Next methods panic if used after this call.

func ConfigureDefault added in v1.0.0

func ConfigureDefault(ctx context.Context, manager WorkerIDManager, options Options) error

ConfigureDefault installs a distributed default Generator exactly once, before any package-level helper is used. The explicit startup call keeps manager construction free of surprising global side effects.

func ExtractShardID added in v1.0.0

func ExtractShardID(id int64) uint32

func ExtractTime

func ExtractTime(id int64) time.Time

func ExtractTimeBase36

func ExtractTimeBase36(value string) (time.Time, error)

func ExtractTimeBase62

func ExtractTimeBase62(value string) (time.Time, error)

func ExtractTimeHex

func ExtractTimeHex(value string) (time.Time, error)

func ExtractWorkerID added in v1.0.0

func ExtractWorkerID(id int64) uint32

func ExtractWorkerIDBase36 added in v1.0.0

func ExtractWorkerIDBase36(value string) (uint32, error)

func ExtractWorkerIDBase62 added in v1.0.0

func ExtractWorkerIDBase62(value string) (uint32, error)

func ExtractWorkerIDHex added in v1.0.0

func ExtractWorkerIDHex(value string) (uint32, error)

func NextBase36

func NextBase36() string

func NextBase62

func NextBase62() string

func NextHex

func NextHex() string

func NextID added in v1.0.0

func NextID() int64

Package-level helpers use a process-local generator with WorkerID 0. Use New or call ConfigureDefault at startup when multiple processes generate.

func NextIDContext added in v1.0.0

func NextIDContext(ctx context.Context) (int64, error)

NextIDContext is the cancellable counterpart of the package-level NextID.

func NextString

func NextString() string

func ParseBase36 added in v1.0.0

func ParseBase36(value string) (int64, error)

func ParseBase62 added in v1.0.0

func ParseBase62(value string) (int64, error)

func ParseHex added in v1.0.0

func ParseHex(value string) (int64, error)

Types

type Generator added in v1.0.0

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

Generator is an immutable, concurrency-safe ID generator.

func MustNew added in v1.0.0

func MustNew(options Options) *Generator

MustNew is New for applications that treat invalid startup configuration as unrecoverable.

func New added in v1.0.0

func New(options Options) (*Generator, error)

New creates an independent process-local generator.

func NewManaged added in v1.0.0

func NewManaged(ctx context.Context, manager WorkerIDManager, options Options) (*Generator, error)

NewManaged acquires a worker ID before returning a distributed generator. Initialization errors are reported here; NextID remains an error-free hot path. If the lease is later lost, generation is fenced while the Generator automatically acquires a different worker ID.

func (*Generator) Close added in v1.0.0

func (g *Generator) Close() error

Close permanently closes the generator. It is safe to call more than once.

func (*Generator) ExtractShardID added in v1.0.0

func (g *Generator) ExtractShardID(id int64) uint32

func (*Generator) ExtractTime added in v1.0.0

func (g *Generator) ExtractTime(id int64) time.Time

func (*Generator) ExtractWorkerID added in v1.0.0

func (g *Generator) ExtractWorkerID(id int64) uint32

func (*Generator) Healthy added in v1.0.0

func (g *Generator) Healthy() bool

Healthy reports whether the generator can safely produce IDs now. A degraded lease remains safe until its local safety deadline.

func (*Generator) NextBase36 added in v1.0.0

func (g *Generator) NextBase36() string

func (*Generator) NextBase62 added in v1.0.0

func (g *Generator) NextBase62() string

func (*Generator) NextHex added in v1.0.0

func (g *Generator) NextHex() string

func (*Generator) NextID added in v1.0.0

func (g *Generator) NextID() int64

NextID returns a unique ID. It blocks while a managed generator replaces a lost safety lease, because returning a value before recovery would violate the uniqueness contract. Use NextIDContext when the caller needs cancellation.

func (*Generator) NextIDContext added in v1.0.0

func (g *Generator) NextIDContext(ctx context.Context) (int64, error)

NextIDContext is the cancellable counterpart of NextID.

func (*Generator) NextString added in v1.0.0

func (g *Generator) NextString() string

func (*Generator) State added in v1.0.0

func (g *Generator) State() GeneratorState

State reports the current generation and lease lifecycle state.

type GeneratorState added in v1.0.0

type GeneratorState uint8

GeneratorState describes whether a Generator can emit IDs now.

const (
	GeneratorHealthy GeneratorState = iota
	GeneratorDegraded
	GeneratorRecovering
	GeneratorClosed
)

func DefaultState added in v1.0.0

func DefaultState() GeneratorState

DefaultState reports the lifecycle state of the package-level Generator.

func (GeneratorState) String added in v1.0.0

func (state GeneratorState) String() string

type LeaseState added in v1.0.0

type LeaseState uint8

LeaseState describes the coordinator-facing health of a worker-ID lease.

const (
	LeaseHealthy LeaseState = iota
	LeaseDegraded
	LeaseLost
)

func (LeaseState) String added in v1.0.0

func (state LeaseState) String() string

type Options

type Options struct {
	BaseTime        int64
	WorkerID        uint32
	WorkerIDBits    uint8
	ShardBits       uint8
	SequenceBits    uint8
	DisableWorkerID bool
}

Options defines the immutable bit layout of a Generator.

The zero value is valid and uses DefaultOptions. Set DisableWorkerID when a process-local generator should spend no bits on a worker ID. ShardBits adds local shards without consuming the WorkerID namespace.

func DefaultOptions added in v1.0.0

func DefaultOptions() Options

DefaultOptions returns the recommended high-throughput single-generator layout: 16 workers and 262,144 IDs per millisecond per worker.

type WorkerIDLease added in v1.0.0

type WorkerIDLease interface {
	WorkerID() uint32
	Valid() bool
	State() LeaseState
	Lost() <-chan struct{}
	Close() error
}

WorkerIDLease represents an exclusive, self-renewing worker-ID lease. Valid is the authoritative hot-path safety check. Lost is closed when the lease has been permanently fenced.

type WorkerIDManager added in v1.0.0

type WorkerIDManager interface {
	Acquire(ctx context.Context, request WorkerIDRequest) (WorkerIDLease, error)
}

WorkerIDManager acquires a worker ID from a distributed coordinator.

type WorkerIDRequest added in v1.0.0

type WorkerIDRequest struct {
	MaxWorkerID       uint32
	ExcludedWorkerIDs []uint32
}

WorkerIDRequest describes the worker-ID namespace available to a manager. ExcludedWorkerIDs must not be returned, even if their coordinator entries appear free. Generators use this during recovery to avoid uncertain reuse.

func (WorkerIDRequest) Excludes added in v1.0.0

func (r WorkerIDRequest) Excludes(workerID uint32) bool

Excludes reports whether a worker ID is unavailable for this acquisition.

Directories

Path Synopsis
zidredis module

Jump to

Keyboard shortcuts

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