Unique ID Generation Cheat Sheet (original) (raw)

Unique identifiers are crucial for ensuring data integrity and uniqueness in applications. They help track, reference, and ensure consistency across various systems and services. This article contains a Cheat Sheet and descriptions of the different types of unique identifier generators, their methods, and tradeoff analysis to help you choose the best option for your application.

Unique ID Generation Cheat Sheet by bool.dev

You can find a high-resolution PDF here.

0. Database Auto-Increment

. Database Auto-Increment

Auto-increment fields in databases automatically generate unique identifiers for new records.

Example ID: 1, 2, 3 (incrementing sequentially)

Pros:

Cons:

Database ID Implementation

CREATE TABLE Users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);

1. Twitter Snowflake

1. Twitter Snowflake

A 64-bit identifier that includes a timestamp, machine ID, and sequence number, ensuring uniqueness across distributed systems.

Example ID: 13572484591234567

Pros:

Cons:

Twitter Snowflake Implementation

2. UUID V4 (Universally Unique Identifier)

UUID (Universally Unique Identifier)

A 128-bit identifier that is globally unique and can be generated independently by different systems without coordination.

Example ID: 550e8400-e29b-41d4-a716-446655440000

Pros:

Cons:

UUID Generation

Mostly supported by default in different programming languages

Python

import uuid

# Generate a UUID
uuid_generated = uuid.uuid4()

print(uuid_generated)

Java

import java.util.UUID;

public class Main {
    public static void main(String[] args) {
        // Generate a UUID
        UUID uuid = UUID.randomUUID();
        
        System.out.println(uuid.toString());
    }
}

Node.js

const { v4: uuidv4 } = require('uuid');

// Generate a UUID
const uuid = uuidv4();

console.log(uuid);

JavaScript

function uuidv4() {
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
    (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
  );
}

console.log(uuidv4());

C#

using System;

class Program
{
    static void Main()
    {
        // Generate a UUID
        Guid uuid = Guid.NewGuid();
        
        Console.WriteLine(uuid.ToString());
    }
}

PHP

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

Ruby

require 'securerandom'

# Generate a UUID
uuid = SecureRandom.uuid

puts uuid

Go

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    // Generate a UUID
    uuid := uuid.New()

    fmt.Println(uuid.String())
}

Bash

#!/bin/bash

# Generate a UUID
uuid=$(uuidgen)

echo $uuid

3. UUID v7

UUIDv7 is a new variant of UUID that incorporates a timestamp for sortable and unique identifiers, combining elements of UUID and ULID.

Example ID: 01890c8e-bc4d-7b3f-915e-0d4d4e310e67

Pros:

Cons:

4. ULID (Universally Unique Lexicographically Sortable Identifier)

ULID (Universally Unique Lexicographically Sortable Identifier)

A 128-bit, lexicographically sortable identifier combines timestamps and randomness to ensure uniqueness and orderability.

Example ID: 01ARZ3NDEKTSV4RRFFQ69G5FAV

Pros:

Cons:

ULID Implementation

5. KSUID (K-Sortable Unique Identifier)

KSUID

A 160-bit identifier that is also sortable by time and includes a timestamp, random payload, and checksum.

Example ID: 0ujsszwN8NRY24YaXiTIEEIo7K0

Pros:

Cons:

KSUID Implementation

6. MongoDB Object ID

MongoDB ObjectID

A 96-bit identifier that includes a timestamp, machine ID, process ID, and a counter, ensuring uniqueness and a rough creation order.

Example ID: 507f1f77bcf86cd799439011

Pros:

Cons:

7. CUID (Collision-resistant Unique Identifier)

CUIDs are designed to be highly unique, focusing on being readable and less prone to collisions even in high-concurrency environments.

A Collision-resistant Unique Identifier (CUID) with 25 characters in base-36 encoding typically has a size of around 129 bits. This provides a substantial level of uniqueness while keeping the identifier relatively compact.

Example ID: cjld2cyuq0006s1rxy8123456

Pros:

Cons:

CUID implementation

8. NanoID

NanoID

NanoID is a tiny, secure, URL-friendly unique string ID generator that is designed to be more flexible and performant than UUID.

Example ID: V1StGXR8_Z5jdHi6B

Pros:

Cons:

NanoID Implementation

9. Sonyflake

Sonyflake

Sonyflake is a distributed unique ID generator inspired by Twitter Snowflake, optimized for 64-bit IDs, and designed to be more efficient for generating unique IDs in a single data center.

Example ID: 1132088477364927953

Pros:

Cons:

Sonyflake Implementation

10. FlakeID

FlakeID

FlakeID is a decentralized unique ID generator that creates 128-bit IDs based on timestamps, machine IDs, and random numbers.

Flake IDs have 128-bit size:

Example ID: 4zqG3B2TnMs57S1PvQ

Pros:

Cons:

FlakeID Implementation

11. Base62

Base62 encoding is a method of encoding IDs that combines uppercase and lowercase letters and digits, making it URL-friendly and compact. The size of Base62 of length 22 characters =22×5.95≈130.9-bit

Example ID: 1B2M2Y8AsgTpgAmY7PhCfg

Pros:

Cons:

Base62 implementation

Summary

When selecting a unique identifier format for your application, consider the specific requirements, including uniqueness, scalability, performance, orderability, and storage efficiency. Each type of identifier has its tradeoffs, and the best choice will depend on your application's context.

By understanding these tradeoffs, you can make an informed decision that aligns with your application's needs for uniqueness, performance, and simplicity.

References and Further Reading

  1. UUID Specification
  2. Twitter Snowflake
  3. MongoDB ObjectID
  4. NanoID Documentation