snowflake

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2026 License: BSD-3-Clause Imports: 8 Imported by: 0

README

Untitled design

idflake: Fast Distributed ID Generator for Go

idflake is a Go library for generating unique, time ordered int64 IDs. You use it in backend services where ordering, speed, and safety matter.

Each ID encodes time, node, and sequence data. Each call runs without locks. Each ID works across JSON, databases, and text formats.

Table of Contents

Main Features

  • Time ordered int64 IDs
  • Lock free generation using atomics
  • Monotonic clock support
  • Configurable epoch and bit layout
  • Batch ID generation
  • Built in encoding helpers
  • JSON safe representation
  • SQL database integration

Design

Each ID packs three fields into one int64 value.

  • Timestamp in milliseconds since a custom epoch
  • Node identifier for distributed systems
  • Sequence number for collisions within the same millisecond

The generator relies on a monotonic time source. Clock changes do not break ordering.

Default layout:

  • Node bits: 10
  • Sequence bits: 12
  • Max nodes: 1024
  • Max IDs per millisecond per node: 4096

Getting Started

Create a generator with a node ID. Call Generate to get an ID.

sf := NewSnowFlake(1)
id := sf.Generate()

IDs increase over time on a single node.

Configuration

You adjust layout using options.

Available options:

  • WithEpoch
  • WithNodeBits
  • WithSequenceBits

Example:

sf := NewSnowFlake(
    3,
    WithNodeBits(8),
    WithSequenceBits(14),
)

Batch Generation

You generate many IDs in one call. Returned IDs stay consecutive.

ids, err := sf.GenerateN(100)

Batch size caps at the sequence capacity per millisecond.

Concurrency Model

  • Atomic state only
  • No mutexes
  • Safe across goroutines
  • Strict ordering per node

A single generator instance is safe to share across all goroutines on a node.

Encoding and Conversion

ID supports multiple formats. Each format round trips without loss.

Supported formats:

  • Decimal string
  • Binary string
  • Base32
  • Base36
  • Base64 from decimal bytes
  • Hex
  • Big endian 8 byte array

Examples:

s := id.String()
id2, _ := ParseString(s)

b := id.IntBytes()
id3, _ := ParseIntBytes(b)

JSON Support

IDs marshal as JSON strings. This preserves full int64 precision.

data, _ := json.Marshal(id)
json.Unmarshal(data, &id2)

Database Support

ID implements sql.Valuer and sql.Scanner. You store IDs as int64 columns.

db.Exec("insert into table (id) values (?)", id)

Extracting Components

You read fields back from an ID.

Available helpers:

  • Timestamp
  • Node
  • Sequence
ts := sf.Timestamp(id)
node := sf.Node(id)
seq := sf.Sequence(id)

Limits

  • IDs fit in signed int64
  • IDs turn negative far in the future
  • One generator maps to one node ID
  • GenerateN caps at sequence capacity

Testing

The test suite covers:

  • Ordering
  • Concurrency
  • Batch generation
  • All encodings
  • JSON round trips
  • Database integration
  • Bit field reconstruction

Benchmarks show constant time generation under load.

License

See LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithEpoch

func WithEpoch(epoch int64) func(*SnowFlake)

func WithNodeBits

func WithNodeBits(nodeBits uint8) func(*SnowFlake)

func WithSequenceBits

func WithSequenceBits(sequenceBits uint8) func(*SnowFlake)

Types

type ID

type ID int64

func ParseBase2

func ParseBase2(id string) (ID, error)

func ParseBase32

func ParseBase32(id string) (ID, error)

func ParseBase36

func ParseBase36(id string) (ID, error)

func ParseBase64

func ParseBase64(id string) (ID, error)

func ParseBytes

func ParseBytes(id []byte) (ID, error)

func ParseHex

func ParseHex(id string) (ID, error)

func ParseInt64

func ParseInt64(id int64) ID

func ParseIntBytes

func ParseIntBytes(id [8]byte) (ID, error)

func ParseString

func ParseString(id string) (ID, error)

func (ID) Base2

func (id ID) Base2() string

func (ID) Base32

func (id ID) Base32() string

func (ID) Base36

func (id ID) Base36() string

func (ID) Base64

func (id ID) Base64() string

func (ID) Bytes

func (id ID) Bytes() []byte

func (ID) Hex

func (id ID) Hex() string

func (ID) Int64

func (id ID) Int64() int64

func (ID) IntBytes

func (f ID) IntBytes() [8]byte

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON encodes the ID as a JSON string to preserve full int64 precision

func (*ID) Scan

func (id *ID) Scan(src any) error

func (ID) String

func (id ID) String() string

String returns the decimal string representation of the ID

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(data []byte) error

func (ID) Value

func (id ID) Value() (driver.Value, error)

for DBs

type Option

type Option func(*SnowFlake)

type SnowFlake

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

func NewSnowFlake

func NewSnowFlake(node int64, opt ...Option) *SnowFlake

func (*SnowFlake) Generate

func (s *SnowFlake) Generate() ID

func (*SnowFlake) GenerateN

func (s *SnowFlake) GenerateN(n int) ([]ID, error)

func (*SnowFlake) Node

func (s *SnowFlake) Node(id ID) int64

Node extracts the node ID from the Snowflake ID.

func (*SnowFlake) Sequence

func (s *SnowFlake) Sequence(id ID) int64

Sequence extracts the sequence number from the Snowflake ID.

func (*SnowFlake) Timestamp

func (s *SnowFlake) Timestamp(id ID) int64

Timestamp extracts the relative timestamp (ms since epoch) from the Snowflake ID.

Jump to

Keyboard shortcuts

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