Skip to content

Instantly share code, notes, and snippets.

@sescobb27
Created July 6, 2015 14:26
Show Gist options
  • Save sescobb27/ee08e5d1922125a5a3be to your computer and use it in GitHub Desktop.
Save sescobb27/ee08e5d1922125a5a3be to your computer and use it in GitHub Desktop.
generating "sequential" random IDs
package main
import (
"crypto/rand"
"fmt"
"log"
"math/big"
"time"
)
func main() {
seq, err := GenerateSequence(1001)
if err != nil {
log.Fatal(err)
}
fmt.Println(seq)
}
// GenerateSequence is a take on on http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
// that uses random integers instead of an auto-incrementing sequence.
func GenerateSequence(shardID int64) (int64, error) {
epoch := time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC)
ms := time.Since(epoch).Nanoseconds() / 1000000
// Fill the first 41 bits with our time (in ms)
id := ms << (64 - 41)
// Generate a random int between 1 & 100000
num, err := rand.Int(rand.Reader, big.NewInt(100000))
if err != nil {
return id, err
}
// Fill the next 13 bits
id |= num.Int64() % 2000 << (64 - 41)
// Fill the remaining 10 bits
id |= (shardID % 1024)
return id, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment