To create unique IDs, you can use various techniques depending on your project’s needs, especially in distributed systems. Here’s a breakdown of some effective approaches:
1. UUIDs (Universally Unique Identifiers)
UUID (v4): Generates a random 128-bit identifier, generally unique with a very low collision probability.
- Python: import uuid; unique_id = uuid.uuid4()
- Java: UUID uniqueID = UUID.randomUUID();
- Node.js: const { v4: uuidv4 } = require('uuid'); const uniqueID = uuidv4();
2. ULIDs (Universally Lexicographically Sortable Identifiers)
Useful for IDs that need to be time-ordered. ULIDs generate a 128-bit identifier based on timestamp and randomness.
- Python: import ulid; unique_id = ulid.new()
- Node.js: const ulid = require('ulid'); const uniqueID = ulid.ulid();
3. ObjectID
ObjectIDs are unique, 12-byte identifiers that combine a timestamp, machine ID, process ID, and a counter.
- Python (bson library): from bson import ObjectId; unique_id = ObjectId()
- Node.js (MongoDB): const { ObjectId } = require('mongodb'); const uniqueID = new ObjectId();
4. Custom ID Generators with Timestamps + Randomness
Concatenate a timestamp and a random number for uniqueness.
For Python
import time, random
unique_id = f"{int(time.time() * 1000)}-{random.randint(1000, 9999)}"
For Node.js
const uniqueID = `${Date.now()}-${Math.floor(Math.random() * 10000)}`;
5. Snowflake IDs
Snowflake IDs are 64-bit unique IDs optimized for distributed systems, popularized by X.
- Python: Libraries like snowflake-id or snowflake-connector-python
- Node.js: const { Snowflake } = require('node-snowflake'); const uniqueID = Snowflake.generate()