Super short, fully unique, non-sequential and URL friendly Ids

Overview

Build status Coverage GoReportCard API documentation

Generator of unique non-sequential short Ids

The package shortidenables the generation of short, fully unique, non-sequential and by default URL friendly Ids at a rate of hundreds of thousand per second. It guarantees uniqueness during the time period until 2050!

The package is heavily inspired by the node.js shortid library (see more detail below).

The easiest way to start generating Ids is:

fmt.Printf(shortid.Generate())
fmt.Printf(shortid.Generate())

The recommended one is to initialise and reuse a generator specific to a given worker:

sid, err := shortid.New(1, shortid.DefaultABC, 2342)

// then either:
fmt.Printf(sid.Generate())
fmt.Printf(sid.Generate())

// or:
shortid.SetDefault(sid)
// followed by:
fmt.Printf(shortid.Generate())
fmt.Printf(shortid.Generate())

Id Length

The standard Id length is 9 symbols when generated at a rate of 1 Id per millisecond, occasionally it reaches 11 (at the rate of a few thousand Ids per millisecond) and very-very rarely it can go beyond that during continuous generation at full throttle on high-performant hardware. A test generating 500k Ids at full throttle on conventional hardware generated the following Ids at the head and the tail (length > 9 is expected for this test):

-NDveu-9Q
iNove6iQ9J
NVDve6-9Q
VVDvc6i99J
NVovc6-QQy
VVoveui9QC
...
tFmGc6iQQs
KpTvcui99k
KFTGcuiQ9p
KFmGeu-Q9O
tFTvcu-QQt
tpTveu-99u

Life span

The package guarantees the generation of unique Ids with no collisions for 34 years (1/1/2016-1/1/2050) using the same worker Id within a single (although can be concurrent) application provided application restarts take longer than 1 millisecond. The package supports up to 32 workers all providing unique sequences from each other.

Implementation details

Although heavily inspired by the node.js shortid library this is not just a Go port. This implementation

  • is safe to concurrency (test included);
  • does not require any yearly version/epoch resets (test included);
  • provides stable Id size over a the whole range of operation at the rate of 1ms (test included);
  • guarantees no collisions: due to guaranteed fixed size of Ids between milliseconds and because multiple requests within the same ms lead to longer Ids with the prefix unique to the ms (tests included);
  • supports 32 instead of 16 workers (test included)

The algorithm uses less randomness than the original node.js implementation, which permits to extend the life span as well as reduce and guarantee the length. In general terms, each Id has the following 3 pieces of information encoded: the millisecond since epoch (first 8 symbols, epoch: 1/1/2016), the worker Id (9th symbol), the running concurrent counter within the millisecond (only if required, spanning over all remaining symbols).

The element of randomness per symbol is 1/2 for the worker and the millisecond data and 0 for the counter. The original algorithm of the node.js library uses 1/4 throughout. Here 0 means no randomness, i.e. every value is encoded using a 64-base alphabet directly; 1/2 means one of two matching symbols of the supplied alphabet is used randomly, 1/4 one of four matching symbols. All methods accepting the parameters that govern the randomness are exported and can be used to directly implement an algorithm with e.g. more randomness, but with longer Ids and shorter life spans.

License and copyright

Copyright (c) 2016. Oleg Sklyar and teris.io. MIT license applies. All rights reserved.

Original algorithm: Copyright (c) 2015 Dylan Greene, contributors. The same MIT license applies. Many thanks to Dylan for putting together the original node.js library, which inspired this "port":

Seed computation: based on The Central Randomizer 1.3. Copyright (c) 1997 Paul Houle ([email protected])

Comments
  • index out of range

    index out of range

    Hey Guys, I have a gin project actualy using this library, but sometimes send a panic error when generate a new SortID.

    This is the error: captura de pantalla de 2017-03-25 21-19-53

    An this is my generation code:

    sid, _ := shortid.New(1, shortid.DefaultABC, 2342)
    ssid,e1 := sid.Generate()
    

    What is the reason of this error?

    bug 
    opened by danteay 8
  • Question: Is that safe to remove symbols from DefaultABC?

    Question: Is that safe to remove symbols from DefaultABC?

    Is that safe to remove symbols from DefaultABC? Basically, use the string "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" instead. I am using it to generate shorten URL and do not wish to see symbols from the URL. Thanks a lot for your project.

    Edited:

    Sorry that I didn't try it before asking this question. I tried to remove those two symbols and return error message panic: alphabet must contain 64 unique characters. I think that means I can NOT remove symbols. It will be nice I can remove symbols from URL. The id does not have to be 100% unique. I will check the id existence before insert and re-generate if it exists.

    opened by sgon00 1
  •  Add poweron architecture ppc64le to travis build

    Add poweron architecture ppc64le to travis build

    This is part of the Ubuntu distribution for ppc64le. This helps us simplify testing later when distributions are re-building and re-releasing,We typically build applications for customers and ISVs, and while we don't use this package directly, we do count on all of the packages in debian/ubuntu to build other packages. So we more likely have this as a second or third level dependency and couldn't tell you explicitly which features we use or our usage model,For more info tag @gerrith3.

    opened by asellappen 1
  • use base58 alphabet

    use base58 alphabet

    Does it possible to use only base58 default chars? I wan to avoid symbols that looks identically and also have double click - copy/paste friendly string

    opened by vtolstov 1
  • Returning an error

    Returning an error

    First of all really good job creating this library! Coming from Node.js I was searching for a shortid alternative a year ago, you finally created it!

    When can I expect this library to return an error? Could this happen randomly, should I panic at this point? Or will this only happen during the first Generate() call?

    I'm asking because my current ID generation module does not return an error and I'd prefer to keep my code this way.

    opened by herkyl 1
  • worker id problem

    worker id problem

    when I deploy my application in a docker cluster (k8s or docker-compose), I have no method to assign a worker id for different container, I can only get an docker container ID in my app by $HOSTNAME.I want to know what is the best practice to use the lib or generate an shortid by myself?

    opened by jinze 1
Releases(v1.0)
  • v1.0(Jan 4, 2016)

    The first release of the go-shortid library brings short (normally 9 symbols), unique, non sequential and URL friendly Ids that can be generated without any collisions until 2050.

    Source code(tar.gz)
    Source code(zip)
Owner
teris.io
teris.io
A go module for "friendly" IDs

go-eyed A go module for "friendly" IDs. THIS MODULE IS INCOMPLETE AND NOT CURRENTLY BEING MAINTAINED. THEREFORE, IT SHOULD NOT BE USED Contribution If

Kirk Morales 0 Dec 17, 2021
A distributed unique ID generator of using Sonyflake and encoded by Base58

Indigo About A distributed unique ID generator of using Sonyflake and encoded by Base58. ID max length is 11 characters by unsigned int64 max value. A

Osamu TONOMORI 98 Nov 24, 2022
Quick search and short links for NYC Council Legislation

Quick Search and Short Links for NYC Council Legislation Quick Search Link to searches with /?q=${query}. In-browser searching is implemented with fle

Jehiah Czebotar 7 Oct 12, 2022
Short link 短链接服务器

Go 短链接生成器 Short link 短链接服务器 什么是短链接 就是把普通网址,转换成比较短的网址。

Qian~ 3 May 8, 2021
A super-simple analytics system

A super-simple analytics system

Ash 0 Jan 30, 2022
A non-go engineer tries to write Go to solve Advent of Code

Wherein an engineer (who primarily uses Kotlin, Java, Scala and C#) tries to teach themselves Go by solving Advent of Code challenges. It's... not pre

Evan Nelson 0 Dec 9, 2021
Ecsgo - Cache friendly, Multi threading Entity Component System in Go (with Generic)

ECSGo ECSGo is an Entity Component System(ECS) in Go. This is made with Generic

Vong Kong 17 Oct 19, 2022
Autoname - Friendly names generator with golang

autoname Friendly names generator inspired by moby's work. import "github.com/ci

Ciprian 4 Oct 16, 2022
Go clean architecture fully working example

Burp - clean architecture app Burp is a CRUD app managing beers. Front-end is written in Angular 12. Database in this example is mongodb. Root project

Audren Bouëssel du Bourg 29 Nov 27, 2022
Simple Golang API to demonstrate file upload to fireabase storage and retrieving url of uploaded file.

go-firebase-storage -Work in progress ??️ Simple Golang API that uses Firebase as its backend to demonstrate various firebase services using Go such a

Victor Kabata 4 Oct 4, 2021
A golang URL Shortener

url-shortener A golang URL Shortener with mysql support. Using Bijective conversion between natural numbers (IDs) and short strings Installation Using

Leonidas Maroulis 40 Dec 10, 2022
Simple URL Shortener API

url-shortener POST a URL to /v1/shorturl endpoint and get a JSON response with short_url properties. Example JSON Reponse: {short_url : 'a'} If you pa

Emmanuel Idika 0 Mar 1, 2022
[TOOL, CLI] - Filter and examine Go type structures, interfaces and their transitive dependencies and relationships. Export structural types as TypeScript value object or bare type representations.

typex Examine Go types and their transitive dependencies. Export results as TypeScript value objects (or types) declaration. Installation go get -u gi

Daniel T. Gorski 172 Dec 6, 2022
:chart_with_upwards_trend: Monitors Go MemStats + System stats such as Memory, Swap and CPU and sends via UDP anywhere you want for logging etc...

Package stats Package stats allows for gathering of statistics regarding your Go application and system it is running on and sent them via UDP to a se

Go Playgound 163 Nov 10, 2022
James is your butler and helps you to create, build, debug, test and run your Go projects

go-james James is your butler and helps you to create, build, debug, test and run your Go projects. When you often create new apps using Go, it quickl

Pieter Claerhout 56 Oct 8, 2022
GoThanks automatically stars Go's official repository and your go.mod github dependencies, providing a simple way to say thanks to the maintainers of the modules you use and the contributors of Go itself.

Give thanks (in the form of a GitHub ★) to your fellow Go modules maintainers. About GoThanks performs the following operations Sends a star to Go's r

psampaz 117 Dec 24, 2022
A simple Cron library for go that can execute closures or functions at varying intervals, from once a second to once a year on a specific date and time. Primarily for web applications and long running daemons.

Cron.go This is a simple library to handle scheduled tasks. Tasks can be run in a minimum delay of once a second--for which Cron isn't actually design

Robert K 215 Dec 17, 2022
Library to work with MimeHeaders and another mime types. Library support wildcards and parameters.

Mime header Motivation This library created to help people to parse media type data, like headers, and store and match it. The main features of the li

Anton Ohorodnyk 25 Nov 9, 2022
The new home of the CUE language! Validate and define text-based and dynamic configuration

The CUE Data Constraint Language Configure, Unify, Execute CUE is an open source data constraint language which aims to simplify tasks involving defin

null 3.4k Dec 31, 2022