Snowflake

1 min read Tweet this post

Snowflake is a distributed ID generation system that generates unique 64-bit IDs using a combination of timestamp, worker ID, and sequence number. Snowflake is designed to be highly scalable and can generate up to 4096 unique IDs per millisecond per worker.

The structure of a Snowflake ID is as follows:

|------41 bits------|------10 bits-------|------12 bits------|
|  timestamp in ms  | worker ID (or node)|  sequence number  |
  • The first 41 bits represent the timestamp in milliseconds since a custom epoch (in Snowflake, this epoch is set to January 1, 2010).
  • The next 10 bits represent the worker ID (or node ID) that is generating the ID. This allows us to generate unique IDs across multiple machines.
  • The final 12 bits represent the sequence number, which is incremented for each ID generated by the same worker in the same millisecond.

By combining these three values, we can generate a unique ID that is both sortable and distributed.

To generate Snowflake IDs in Go, we can use the snowflake package from the third-party github.com/bwmarrin/snowflake library. Here’s an example of how to use the snowflake package to generate Snowflake IDs:

package main

import (
	"fmt"

	"github.com/bwmarrin/snowflake"
)

func main() {
	// Create a new node with a unique worker ID
	node, err := snowflake.NewNode(1)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Generate a new ID and print it
	id := node.Generate()
	fmt.Println(id)
}

In this example, we create a new Snowflake node with a unique worker ID of 1. We then generate a new ID using the Generate method and print it to the console.

When we run this code, we should see a unique Snowflake ID printed to the console, like this:

797535774244278272

Snowflake is a powerful system for generating unique IDs that are both sortable and distributed. By using the snowflake package in Go, we can easily generate Snowflake IDs in our applications.

go hash general