tuid

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: MIT Imports: 6 Imported by: 1 module, 1 package

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

Time-based Unique Identifiers (TUID)

Go Reference Go Report Card

A TUID is an immutable, chronologically sortable, unique identifier with an embedded nanosecond-resolution timestamp. Internally, it is a big integer value, expressed as a case-sensitive base-62 string (digits 0-9, characters A-Z, and characters a-z). The left bits are the embedded nanoseconds since epoch, and the right 32 bits are entropy (a random integer). Valid IDs in the 21st century are 16 characters long, and the bit length ranges from 92-94 bits. Example: 91Mq07yx9IxHCi5Y is a TUID with a UTC timestamp of 2021-03-08T05:54:09.208207Z. Because the left bits are the nanoseconds since epoch, the IDs sort in chronological order.

A TUID compares nicely with a 128-bit UUID (Universally Unique Identifier), but it's not a UUID. While a Version 1 UUID has an embedded timestamp, it's not chronologically sortable. A random Version 4 UUID is more common. Example: 05cd1093-c52c-48e5-a343-9e0017454067. And, while a UUID is readily available in a Go uuid package, a TUID has significant advantages:

  • A TUID is sortable chronologically (alphabetically), making it easy to order a collection of things with IDs.
  • A TUID has an embedded nanosecond resolution timestamp, making it easy to track when things were created.
  • A TUID is shorter than a UUID (16 characters vs. 36 characters), requiring less space in a database or URL.
  • A TUID has no hyphens, making it easy to copy and paste into other systems.

A TUID also compares nicely with a FriendlyID (Friendly Identifier). Example: 5wbwf6yUxVBcr48AMbz9cb. A FriendlyID is a base-62 encoded 128-bit UUID without the hyphens, making it shorter and easier to work with than a UUID. A FriendlyID has the great advantage of being interoperable with any existing UUID, but it's missing the embedded timestamp and is not chronologically sortable. Also, a FriendlyID version of a full 128-bit UUID is 22 characters, whereas a TUID is only 16 characters.

So, why use a TUID? Because you like the embedded timestamp, and you like being able to sort things with IDs chronologically.

Installation

go get github.com/voxtechnica/tuid-go

Usage

Creating a new TUID is simple:

package main

import (
	"fmt"
	"time"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	// Cast a string to a TUID
	id := tuid.TUID("91Mq07yx9IxHCi5Y")

	// Create a new TUID with current time and random entropy
	newID := tuid.NewID()
	fmt.Println("New ID:", newID)

	// Create a TUID with a specific timestamp
	timeID := tuid.NewIDWithTime(time.Now().UTC())

	// Create the first TUID for a specific time (zero entropy, useful for pagination)
	firstID := tuid.FirstIDWithTime(time.Now().UTC())

	// Validate a TUID
	isValid := tuid.IsValid(newID)
	fmt.Println("Is Valid:", isValid)

	// Extract the timestamp
	timestamp, _ := id.Time()
	fmt.Println("Created at:", timestamp)

	// Extract both timestamp and entropy
	info, _ := id.Info()
	fmt.Printf("Info - Time: %v, Entropy: %d\n", info.Timestamp, info.Entropy)

	// Calculate the duration between two IDs
	duration, _ := tuid.Duration(id, newID)
	fmt.Println("Duration between IDs:", duration)
}

Since TUID is an alias for a string, it serializes to and from JSON transparently as a string. The package also provides a TUIDInfo struct with JSON tags for convenience when returning detailed ID information from an API.

If you have an ID string, and you want to check if it's a valid TUID, you can use the function tuid.IsValid(id). Valid means that it has only base-62 characters (digits 0-9, letters A-Z, and letters a-z), and that it has an embedded timestamp in the 21st century.

If you have a pair of IDs (e.g. two events), you can compute the time.Duration between them with tuid.Duration(startID, stopID).

Documentation

Overview

Package tuid provides facilities for generating and working with Time-based Unique Identifiers (TUID).

A TUID is an immutable, chronologically sortable, unique identifier with an embedded nanosecond-resolution timestamp. Internally, it is a big integer value, expressed as a case-sensitive base-62 string (digits 0-9, characters A-Z, and characters a-z). The left bits are the embedded nanoseconds since epoch, and the right 32 bits are entropy (a random integer). Valid IDs in the 21st century are 16 characters long, and the bit length ranges from 92-94 bits.

Example: `91Mq07yx9IxHCi5Y` is a TUID with a UTC timestamp of `2021-03-08T05:54:09.208207Z`. Because the left bits are the nanoseconds since epoch, the IDs sort in chronological order.

Index

Examples

Constants

View Source
const MaxID = "MuklDY5bgW1s9Ev2"

MaxID is the first ID at 2100-01-01T00:00:00Z

View Source
const MinID = "5Hr02eJHAfTt1tTM"

MinID is the first ID at 2000-01-01T00:00:00Z

Variables

This section is empty.

Functions

func Compare

func Compare(t1 TUID, t2 TUID) int

Compare supports sorting TUIDs chronologically

func Duration

func Duration(start TUID, stop TUID) (time.Duration, error)

Duration returns the number of nanoseconds between two TUIDs as a time.Duration

Example
package main

import (
	"fmt"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	startID := tuid.TUID("9AxgffrWr9qCnfIT")
	stopID := tuid.TUID("9AxjEL0lPtoGAbLE")

	// Calculate duration between two TUIDs
	duration, _ := tuid.Duration(startID, stopID)

	fmt.Println(duration)
}
Output:
32m2.322640879s

func IsValid

func IsValid(t TUID) bool

IsValid checks to see if the provided TUID has valid characters and a reasonable embedded timestamp

Example
package main

import (
	"fmt"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	validID := tuid.TUID("91Mq07yx9IxHCi5Y")
	invalidID := tuid.TUID("not-a-valid-tuid")

	fmt.Println(tuid.IsValid(validID))
	fmt.Println(tuid.IsValid(invalidID))
}
Output:
true
false

Types

type TUID

type TUID string

TUID is a Time-based Unique Identifier (e.g. 91Mq07yx9IxHCi5Y) that has an embedded timestamp and sorts chronologically. It's a 16-digit base-62 big integer, where the leftmost bits are a timestamp with nanosecond resolution (e.g. 2021-03-08T05:54:09.208207000Z) and the rightmost 32 bits are "entropy" (a random number), providing some assurance of uniqueness if multiple IDs are created at the same moment. Collisions in a single information system are extremely unlikely. The Zero value of a TUID is an empty string.

func FirstIDWithTime

func FirstIDWithTime(t time.Time) TUID

FirstIDWithTime creates a TUID with the provided timestamp and zero entropy, useful for query offsets

Example
package main

import (
	"fmt"
	"time"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	// Create a specific time for our example
	t := time.Date(2021, 3, 8, 5, 54, 9, 208207000, time.UTC)

	// Create the first TUID for this exact nanosecond (zero entropy)
	id := tuid.FirstIDWithTime(t)
	fmt.Println(id)
}
Output:
91Mq07yx9IvZeYJE

func NewID

func NewID() TUID

NewID creates a new TUID with the current UTC time.

Example
package main

import (
	"fmt"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	id := tuid.NewID()

	// A TUID is always 16 characters long
	fmt.Println(len(id))
}
Output:
16

func NewIDWithTime

func NewIDWithTime(t time.Time) TUID

NewIDWithTime creates a TUID with the provided timestamp

func NewIDWithTimeAndEntropy added in v1.0.2

func NewIDWithTimeAndEntropy(t time.Time, e uint32) TUID

NewIDWithTimeAndEntropy creates a TUID with the provided timestamp and entropy be very careful with this function as you get ID collisions if the caller does not manage entropy values carefully

func (TUID) Entropy

func (t TUID) Entropy() (uint32, error)

Entropy extracts the random 32 bits from the specified TUID

Example
package main

import (
	"fmt"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	id := tuid.TUID("9AxhASm3k3MVH8se")

	// Extract the entropy (random bits)
	entropy, _ := id.Entropy()

	fmt.Println(entropy)
}
Output:
1588339652

func (TUID) Info

func (t TUID) Info() (TUIDInfo, error)

Info extracts the timestamp and entropy from the specified TUID. The returned timestamp is in UTC.

func (TUID) Int

func (t TUID) Int() (*big.Int, error)

Int decodes the specified base-62 encoded TUID into a big integer

func (TUID) String

func (t TUID) String() string

String implements the fmt.Stringer interface

func (TUID) Time

func (t TUID) Time() (time.Time, error)

Time extracts the embedded timestamp from the specified TUID. The returned time is in UTC.

Example
package main

import (
	"fmt"
	"time"

	"github.com/voxtechnica/tuid-go"
)

func main() {
	id := tuid.TUID("91Mq07yx9IxHCi5Y")

	// Extract the embedded timestamp
	ts, _ := id.Time()

	// Format the timestamp
	fmt.Println(ts.Format(time.RFC3339Nano))
}
Output:
2021-03-08T05:54:09.208207Z

type TUIDInfo

type TUIDInfo struct {
	ID        TUID      `json:"id"`
	Timestamp time.Time `json:"timestamp"` // UTC timestamp extracted from the ID.
	Entropy   uint32    `json:"entropy"`
}

TUIDInfo is a convenience type for parsing a TUID's timestamp and entropy.

Jump to

Keyboard shortcuts

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