• Stars
    star
    3,874
  • Rank 11,314 (Top 0.3 %)
  • Language
    Go
  • License
    MIT License
  • Created about 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

xid is a globally unique id generator thought for the web

Globally Unique ID Generator

godoc license Build Status Coverage

Package xid is a globally unique id generator library, ready to safely be used directly in your server code.

Xid uses the Mongo Object ID algorithm to generate globally unique ids with a different serialization (base32hex) to make it shorter when transported as a string: https://docs.mongodb.org/manual/reference/object-id/

  • 4-byte value representing the seconds since the Unix epoch,
  • 3-byte machine identifier,
  • 2-byte process id, and
  • 3-byte counter, starting with a random value.

The binary representation of the id is compatible with Mongo 12 bytes Object IDs. The string representation is using base32hex (w/o padding) for better space efficiency when stored in that form (20 bytes). The hex variant of base32 is used to retain the sortable property of the id.

Xid doesn't use base64 because case sensitivity and the 2 non alphanum chars may be an issue when transported as a string between various systems. Base36 wasn't retained either because 1/ it's not standard 2/ the resulting size is not predictable (not bit aligned) and 3/ it would not remain sortable. To validate a base32 xid, expect a 20 chars long, all lowercase sequence of a to v letters and 0 to 9 numbers ([0-9a-v]{20}).

UUIDs are 16 bytes (128 bits) and 36 chars as string representation. Twitter Snowflake ids are 8 bytes (64 bits) but require machine/data-center configuration and/or central generator servers. xid stands in between with 12 bytes (96 bits) and a more compact URL-safe string representation (20 chars). No configuration or central generator server is required so it can be used directly in server's code.

Name Binary Size String Size Features
UUID 16 bytes 36 chars configuration free, not sortable
shortuuid 16 bytes 22 chars configuration free, not sortable
Snowflake 8 bytes up to 20 chars needs machine/DC configuration, needs central server, sortable
MongoID 12 bytes 24 chars configuration free, sortable
xid 12 bytes 20 chars configuration free, sortable

Features:

  • Size: 12 bytes (96 bits), smaller than UUID, larger than snowflake
  • Base32 hex encoded by default (20 chars when transported as printable string, still sortable)
  • Non configured, you don't need set a unique machine and/or data center id
  • K-ordered
  • Embedded time with 1 second precision
  • Unicity guaranteed for 16,777,216 (24 bits) unique ids per second and per host/process
  • Lock-free (i.e.: unlike UUIDv1 and v2)

Best used with zerolog's RequestIDHandler.

Notes:

  • Xid is dependent on the system time, a monotonic counter and so is not cryptographically secure. If unpredictability of IDs is important, you should not use Xids. It is worth noting that most other UUID-like implementations are also not cryptographically secure. You should use libraries that rely on cryptographically secure sources (like /dev/urandom on unix, crypto/rand in golang), if you want a truly random ID generator.

References:

Install

go get github.com/rs/xid

Usage

guid := xid.New()

println(guid.String())
// Output: 9m4e2mr0ui3e8a215n4g

Get xid embedded info:

guid.Machine()
guid.Pid()
guid.Time()
guid.Counter()

Benchmark

Benchmark against Go Maxim Bublis's UUID.

BenchmarkXID        	20000000	        91.1 ns/op	      32 B/op	       1 allocs/op
BenchmarkXID-2      	20000000	        55.9 ns/op	      32 B/op	       1 allocs/op
BenchmarkXID-4      	50000000	        32.3 ns/op	      32 B/op	       1 allocs/op
BenchmarkUUIDv1     	10000000	       204 ns/op	      48 B/op	       1 allocs/op
BenchmarkUUIDv1-2   	10000000	       160 ns/op	      48 B/op	       1 allocs/op
BenchmarkUUIDv1-4   	10000000	       195 ns/op	      48 B/op	       1 allocs/op
BenchmarkUUIDv4     	 1000000	      1503 ns/op	      64 B/op	       2 allocs/op
BenchmarkUUIDv4-2   	 1000000	      1427 ns/op	      64 B/op	       2 allocs/op
BenchmarkUUIDv4-4   	 1000000	      1452 ns/op	      64 B/op	       2 allocs/op

Note: UUIDv1 requires a global lock, hence the performance degradation as we add more CPUs.

Licenses

All source code is licensed under the MIT License.

More Repositories

1

zerolog

Zero Allocation JSON Logger
Go
10,343
star
2

curlie

The power of curl, the ease of use of httpie.
Go
2,808
star
3

cors

Go net/http configurable handler to handle CORS requests
Go
2,625
star
4

rest-layer

REST Layer, Go (golang) REST API framework
Go
1,257
star
5

SDSegmentedControl

A drop-in remplacement for UISegmentedControl that mimic iOS 6 AppStore tab controls
Objective-C
1,200
star
6

pushd

Blazing fast multi-protocol mobile and web push notification service
CoffeeScript
1,162
star
7

jplot

iTerm2 expvar/JSON monitoring tool
Go
1,140
star
8

SDAVAssetExportSession

AVAssetExportSession drop-in replacement with customizable audio&video settings
Objective-C
800
star
9

SDURLCache

URLCache subclass with on-disk cache support on iPhone/iPad
Objective-C
798
star
10

SafariTabSwitching

A SIMBL plugin for Safari 5.1 allowing tab switching by index (using Cmd-1, Cmd-2…)
Objective-C
472
star
11

jaggr

JSON Aggregation CLI
Go
460
star
12

SafariOmnibar

Safari plugin to add Chrome like omnibar in Safari
Objective-C
416
star
13

dnstrace

DNS resolution tracing tool
Go
270
star
14

dnscache

DNS lookup cache for Go
Go
267
star
15

node-netmask

Parse and lookup IP network blocks
CoffeeScript
253
star
16

xhandler

XHandler is a bridge between net/context and http.Handler
Go
233
star
17

xlog

xlog is a logger for net/context aware HTTP applications
Go
138
star
18

seamless

Seamless restart / zero-downtime deploy for Go servers
Go
107
star
19

xmux

xmux is a httprouter fork on top of xhandler (net/context aware)
Go
98
star
20

vast

Golang VAST 3.0 library
Go
83
star
21

xstats

xstats is a generic client for service instrumentation
Go
82
star
22

gls

A graphical ls command for iTerm2 with icons
Swift
78
star
23

SDNetworkActivityIndicator

Handle show/hiding of the iOS network activity indicator
Objective-C
75
star
24

zkfarmer

ZkFarmer is a set of tools to easily manage distributed server farms using Apache ZooKeeper
Python
74
star
25

logbench

Golang logging library benchmarks
Go
69
star
26

dashplay

Easy dashboard screen management
HTML
67
star
27

SDAdvancedWebView

Add some handy features to you UIWebViews
Objective-C
49
star
28

eve-auth-jwt

Eve OAuth 2.0 JWT token validation authentication module
Python
46
star
29

domcheck

A Python library to validate the ownership of a domain using different strategies
Python
45
star
30

iris-ice

Iris keyboard build with custom case
43
star
31

scanman

ScanSnap manager for Raspberry Pi
Python
40
star
32

formjson

Go net/http handler to transparently manage posted JSON
Go
39
star
33

moquette

MQTT service dispatcher
Go
38
star
34

SDReachability

Easy to use and to embed Reachability library
Objective-C
36
star
35

golp

Go panic logger
Go
27
star
36

xaccess

Go http handler access logger
Go
20
star
37

tzsp

TaZmen Sniffer Protocol (TZSP) parser in Go
Go
20
star
38

rest-layer-mongo

REST Layer MongoDB resource storage handler
Go
18
star
39

audience-meter

Lightweight server to mesure audience of a live event
JavaScript
17
star
40

node-dnsstamp

DNS Stamp encoding/decoding library for node
TypeScript
15
star
41

net-server-mail

Extensible Perl implementation of the STMP protocol and its different evolutions (ie: ESMTP, LMTP)
Perl
15
star
42

vmap

Golang VMAP 1.0 library
Go
14
star
43

SDSRTParser

Objective-C SRT subtitle parser
Objective-C
13
star
44

mysql-genocide

Parallel operations on MySQL processlist
Perl
11
star
45

dnsdump

DNS Packet Dump
Go
10
star
46

pinba_http

Pinba HTTP Gateway
Python
8
star
47

gh-readme

Githup pages template for projects README
CSS
7
star
48

rest-layer-es

REST Layer ElasticSearch resource storage handler
Go
6
star
49

mydbd

A mysqli OO interface with PEAR::DB API compatibility
PHP
5
star
50

local-ip

Go
4
star
51

rest-layer-mem

REST Layer memory storage handler
Go
4
star
52

homebrew-tap

rs homebrew packages
Ruby
3
star
53

xlog-nsq

XLog to NSQ Output
Go
3
star
54

rest-layer-hystrix

REST Layer Hystrix storage handler wrapper
Go
3
star
55

rrdpoller

Easily query and perform threshold tests on RRD files data
Perl
3
star
56

rrdcollect-remote

Collect rrdcollect output from several hosts to update local RRD files
Perl
2
star
57

SiriDailymotion

AssistantExtensions plugin to integrate Dailymotion to Siri on Jailbroken iPhone 4s
Objective-C
2
star
58

proxy

A simple HTTP explicit forward proxy http.Handler
Go
2
star
59

gcs-oauth2-boto-env-plugin

Google Storage auth2 plugin with support for passing service key via environment
Python
2
star
60

rs.github.com

1
star
61

obfu

Go
1
star