2

I've tried to generate 10k integer from Go's UnixNano, and it doesn't show any collision.

package main

import (
        "fmt"
        "sync"
        "time"
        "strconv"
        "github.com/OneOfOne/cmap"
)

func main() {
        var wg sync.WaitGroup
        k := 1000
        wg.Add(k * 1000)
        coll := cmap.New()
        for z := 0; z < k*1000; z++ {
                go func() {
                        k := strconv.FormatInt(time.Now().UnixNano(),36)
                        if coll.Has(k) {
                                fmt.Println(`collision: `, k)
                        }
                        coll.Set(k,true) 
                        defer wg.Done()
                }()
        }
        wg.Wait()
}

The database only support 64-bit integer at maximum and doesn't support atomic counter/serial.

EDIT 2017-03-06 It has collision

collision:  bb70elvagvqu
collision:  bb70elwbgk98
collision:  bb70elwnxcm7

So if I create a primary key using that number, converted to base-36, appended with 3 digit server key would it be no possible collision right?

Some example:

  0bb4snonc8nfc001 (current time, 1st server)
  1y2p0ij32e8e7zzz (maximum value: 2262-04-11 23:47:16.854775807, 46654th/last server)

Requirement 2017-03-04

  • Lexicographically correct
  • Unique
  • As short as possible
  • Ordered by creation time
3
  • what happens when leap second, or just computer clock was adjusted by ntp? Commented Mar 3, 2017 at 4:35
  • 1
    Can you use a UUID instead of rolling your own? stackoverflow.com/questions/15130321/… Commented Mar 3, 2017 at 4:42
  • 1
    This looks like a half implemented snowflake idea to me. Check out github.com/bwmarrin/snowflake Commented Mar 3, 2017 at 10:44

1 Answer 1

1

You didn't specified which database you want to use, but I suppose to it is MySQL. The best unique ID currently I think is the UUID and the MySQL provide to use it as primary key.

create table users(id varchar(36), name varchar(200));
insert into users values(uuid(), 'Andromeda');

It is provide a unique ID in every cases.

Of course you can use it in every other database, because the Golang and databases supporting it either. You can find many UUID generator on Github for Golang.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.