sfid

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 5 Imported by: 0 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

sfid-go

Fast, allocation-free, Twitter-compatible 63-bit Snowflake IDs for Go.

Go Reference Go version GitHub License

Features

  • Lock-free: one clock read and one atomic fetch-and-add per ID
  • Zero allocations: no garbage, no background goroutines
  • Batch generation: Fill fills a whole slice for under 0.4 ns per ID
  • Monotonic time: wall-clock steps never move IDs backwards
  • Two generators: a strictly ordered Generator and a per-CPU Pool
  • Decoding: read the timestamp, node, and sequence back from any ID

Install

go get github.com/colduction/sfid-go@latest

Quick start

generator, err := sfid.New(42) // node ID 0–1023, unique per process
if err != nil {
	log.Fatal(err)
}

id := generator.Generate()
fmt.Println(id, id.Time(), id.Node(), id.Sequence())

Generate a batch into a slice you own:

ids := make([]sfid.ID, len(messages))
generator.Fill(ids)

Spread contention across cores with a Pool of power-of-two buckets:

pool, err := sfid.NewPool(42, 64)

Choosing an API

API Order Best for
Generator.Generate Strictly increasing Most programs; time-ordered keys
Generator.Fill Strictly increasing Batches such as message ingestion
Pool.Generate Unique, unordered Many goroutines on many cores

[!TIP] Store *sfid.Generator or *sfid.Pool directly in your structs. Calls on a concrete type skip interface dispatch.

ID layout

Sign Timestamp Node Sequence
1 bit 41 bits 10 bits 12 bits
0 ms since 1288834974657 [^1] 0–1023 0–4095 per ms

[!IMPORTANT] Each node ID issues at most 4096 IDs per millisecond, or 4.096 million per second. When a millisecond is used up, generation waits for the next one. If you need more, run several generators with different node IDs.

[!WARNING] IDs are unique while a process runs. If the system clock steps backwards across a restart, the restarted process can repeat IDs it issued earlier under the same node ID. Keep clocks synchronized without backward steps, or assign a fresh node ID on each start.

Performance

Cost per ID below the per-node limit, measured on an AMD Ryzen 9 7950X with Go 1.27.1 on Windows 11:

Benchmark 1 goroutine 32 goroutines
Generator.Generate 2.25 ns 1.13 ns
Generator.Fill 0.37 ns —
Pool.Generate 6.68 ns 0.57 ns

[!NOTE] Benchmarks that loop on a single generator report about 244 ns/op. That figure is the 4096-per-millisecond limit (1 ms ÷ 4096), not the cost of a call. On Linux, reading the clock through the vDSO dominates a single Generate call, so Fill gives the largest gain there.

go test -run '^$' -bench . -benchmem
How it works
  • Generator keeps the last timestamp and sequence in one 64-bit word. Generate reserves a sequence with one fetch-and-add and has no retry loop. Compare-and-swap runs only on the first call of each millisecond and after the sequence runs out.
  • Pool gives each processor its own cache-line-padded bucket. When a bucket runs out for the current millisecond, callers move to other buckets. They wait only when every bucket is used up.
  • Fill reserves up to 4096 IDs with one clock read and one atomic operation, then writes them in unrolled blocks.
  • Clock: timestamps come from the runtime's monotonic clock, anchored to the wall clock once at construction. On Windows amd64 and arm64 the clock is a single inlined memory load. Other platforms use runtime.nanotime.

License

MIT

[^1]: The original Twitter Snowflake epoch, 2010-11-04 01:42:54.657 UTC.

Documentation

Overview

Package sfid generates Twitter-compatible 63-bit Snowflake IDs.

A Generator issues strictly increasing IDs and suits most programs. Generator.Fill issues a whole batch at a fraction of the per-ID cost. A Pool trades ordering for less cache-line contention when many goroutines generate IDs on many cores. Each node ID admits at most 4096 IDs per millisecond; generation waits for the next millisecond once the current one is consumed.

Index

Constants

View Source
const (
	// EpochMilliseconds is the original Twitter Snowflake epoch in Unix milliseconds.
	EpochMilliseconds int64 = 1288834974657

	// MaxNodeID is the largest node identifier supported by the 10-bit node field.
	MaxNodeID uint16 = (1 << nodeBits) - 1

	// MaxSequence is the largest sequence value supported within one millisecond.
	MaxSequence uint16 = (1 << seqBits) - 1

	// MaxBucketCount is the largest pool bucket count supported by the sequence field.
	MaxBucketCount uint = 1 << seqBits
)

Variables

View Source
var (
	// ErrInvalidNodeID reports a node identifier outside the 10-bit node field.
	ErrInvalidNodeID = errors.New("sfid: node ID exceeds 10 bits")

	// ErrInvalidBucketCount reports a zero, oversized, or non-power-of-two bucket count.
	ErrInvalidBucketCount = errors.New("sfid: bucket count must be a power of two from 1 through 4096")

	// ErrEpochNotReached reports that the system time is earlier than the Snowflake epoch.
	ErrEpochNotReached = errors.New("sfid: system time is earlier than the epoch")

	// ErrTimestampOverflow reports that the 41-bit timestamp field is exhausted.
	ErrTimestampOverflow = errors.New("sfid: timestamp exceeds 41 bits")
)

Functions

This section is empty.

Types

type Generator

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

A Generator generates strictly increasing Snowflake IDs for one node and is safe for concurrent use.

A Generator issues at most 4096 IDs per millisecond.

func New

func New(nodeID uint16) (*Generator, error)

New constructs a concurrent Snowflake Generator for nodeID.

The caller must assign a unique nodeID to each Generator process that can produce IDs for the same system.

func (*Generator) Fill

func (g *Generator) Fill(ids []ID)

Fill stores strictly increasing Snowflake IDs in every element of ids.

Fill does not allocate, retain ids, or read its previous contents. It reserves each run of IDs within one millisecond with a single clock read and atomic operation, so it costs far less per ID than repeated Generator.Generate calls. Fill waits for the next millisecond whenever the current one is consumed, so filling n IDs spans at least (n-1)/4096 milliseconds, rounded down.

func (*Generator) Generate

func (g *Generator) Generate() ID

Generate reserves and reports the next ID.

Generate does not allocate. It waits for the next millisecond when all sequence values for the current millisecond are consumed.

type ID

type ID int64

An ID is a Twitter-compatible Snowflake identifier.

func (ID) Int64

func (id ID) Int64() int64

Int64 reports id as an int64.

func (ID) Node

func (id ID) Node() uint16

Node reports the node identifier encoded in id.

func (ID) Sequence

func (id ID) Sequence() uint16

Sequence reports the per-millisecond sequence encoded in id.

func (ID) String

func (id ID) String() string

String reports the base-10 representation of id.

func (ID) Time

func (id ID) Time() time.Time

Time reports the creation time encoded in id.

type Pool

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

A Pool generates Snowflake IDs through cache-separated sequence buckets and is safe for concurrent use.

Each goroutine prefers the bucket of the processor it runs on, so concurrent callers rarely share a cache line. A bucket that exhausts its share of a millisecond spills callers to the other buckets. A Pool issues at most 4096 IDs per millisecond, and its IDs are unique but not ordered.

func NewPool

func NewPool(nodeID uint16, bucketCount uint) (*Pool, error)

NewPool constructs a concurrent Snowflake Pool with bucketCount cache-separated sequence buckets for nodeID.

bucketCount must be a power of two from 1 through MaxBucketCount. The caller must assign a unique nodeID to each generator process that can produce IDs for the same system.

func (*Pool) Fill

func (p *Pool) Fill(ids []ID)

Fill stores unique Snowflake IDs in every element of ids.

Fill does not allocate, retain ids, or read its previous contents. It reserves each run of IDs from one bucket and millisecond with a single clock read and atomic operation. A run holds at most 4096/bucketCount IDs, so Generator.Fill suits large batches better. Fill waits for the next millisecond whenever the current one is consumed.

func (*Pool) Generate

func (p *Pool) Generate() ID

Generate reserves and reports the next ID from the Pool.

Generate does not allocate. It waits for the next millisecond when all sequence values for the current millisecond are consumed.

Jump to

Keyboard shortcuts

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