simpleflakes

Fast, lightweight, and reliable distributed 64-bit ID generation for Node.js and the web
Zero dependencies • TypeScript-ready • 10M+ ops/sec performance
Features
- ⚡ 10M+ ops/sec - Ultra-fast performance
- 🔢 Time-oriented 64-bit IDs - Globally unique, sortable by timestamp at millisecond granularity
- 0️⃣ Zero dependencies - Pure JavaScript, lightweight bundle
- 🏷️ TypeScript-ready - Full type safety and universal module support
- 🚀 Production-ready - 100% test coverage, Snowflake compatible
Table of Contents
What is Simpleflake?
Simpleflake generates unique 64-bit integers that are:
- Time-sortable - IDs from later milliseconds are numerically larger
- Distributed-safe - No coordination needed between multiple generators
- Compact - Fits in a 64-bit integer (vs UUID’s 128 bits)
- URL-friendly - Can be represented as short strings
Perfect for database primary keys, distributed system IDs, and anywhere you need fast, unique identifiers.
Works in Node.js and modern browsers with BigInt and Web Crypto support.
References
Installation
npm install simpleflakes
Supports both CommonJS and native ESM.
Quick Start
JavaScript (CommonJS)
const { simpleflake } = require('simpleflakes');
const id = simpleflake();
console.log(id);
console.log(id.toString());
console.log(id.toString(16));
console.log(id.toString(36));
TypeScript / ES Modules
import { simpleflake, parseSimpleflake, type SimpleflakeStruct } from 'simpleflakes';
// Generate with full type safety
const id: bigint = simpleflake();
// Parse the ID to extract timestamp and random bits
const parsed: SimpleflakeStruct = parseSimpleflake(id);
console.log(parsed.timestamp); // "1693244847123" (Unix timestamp as string)
console.log(parsed.randomBits); // "4567234" (Random component as string)
Advanced Usage
Custom Parameters
const customId = simpleflake(
Date.now(),
12345,
Date.UTC(2000, 0, 1)
);
Working with Binary Data
import { binary, extractBits } from 'simpleflakes';
const id = simpleflake();
console.log(binary(id));
const timestampBits = extractBits(id, 23n, 41n);
const randomBits = extractBits(id, 0n, 23n);
Debugging Existing IDs
If you want an external CLI to inspect a Simpleflake, uuinfo supports it.
uuinfo -f sf-simpleflake 4234673179811182512
uuinfo --compare <id> can also help when you want to compare a numeric ID against other Snowflake-style and UUID formats.
Batch Generation
function generateBatch(count) {
const ids = [];
for (let i = 0; i < count; i++) {
ids.push(simpleflake());
}
return ids;
}
const batch = generateBatch(1000);
console.log(`Generated ${batch.length} unique IDs`);
ID Structure
Each 64-bit simpleflake ID contains:
| <------- 41 bits -------> |
<- 23 bits -> |
| Timestamp |
Random |
| (milliseconds from epoch) |
(0-8388607) |
- 41 bits timestamp: Milliseconds since
2000-01-01T00:00:00.000Z (Date.UTC(2000, 0, 1) / 946684800000)
- 23 bits random: Random number for uniqueness within the same millisecond
- Total: 64 bits = fits in a signed 64-bit integer
This gives you:
- 69+ years of timestamp range, but the 41-bit timestamp exhausts around September 2069 (measured from the 2000-01-01 epoch) — pass a later custom epoch if you need range beyond that
- 8.3 million possible random values per millisecond
- Sortable by timestamp when converted to integers at millisecond granularity; within one millisecond, IDs are not ordered — the 23 random bits carry no sequence counter, so generation order and numeric order can diverge for IDs sharing a millisecond
Collision Envelope
The 23-bit random field is a birthday-bound space, not a per-millisecond counter, so collision probability climbs faster than the 8.3M combinations might suggest:
| IDs generated in the same millisecond (single generator, no coordination) |
Collision probability |
| ~410 |
~1% |
| ~3,400 |
~50% |
This is inherent to simpleflake’s design (23 random bits, no machine/sequence bits) and isn’t a parameter you can tune away. It’s fine for workloads producing up to roughly a few hundred IDs/ms per generator with no cross-generator coordination. If you need higher per-millisecond throughput or coordination guarantees, that calls for a different algorithm — e.g. Twitter Snowflake (machine + sequence bits) or ULID (80 random bits) — rather than adjusting simpleflake’s parameters.
This library is optimized for speed:
| Operation |
Ops/sec |
Time/op |
simpleflake() |
11,468,350 |
87.20 ns |
simpleflake(timestamp, randomBits, epoch) |
14,557,764 |
68.69 ns |
binary() |
22,794,523 |
43.87 ns |
BigInt() |
15,933,159 |
62.76 ns |
parseSimpleflake() |
6,722,882 |
148.75 ns |
Benchmark command:
npm run benchmark
Benchmark environment:
- Node.js v24.14.1
- Linux 6.6.87.2-microsoft-standard-WSL2 (WSL2)
- AMD Ryzen 7 5800X3D 8-Core Processor
- 8 cores / 16 threads
Results will vary across CPUs, Node.js versions, power profiles, and native Linux vs. WSL2 environments.
Perfect for high-throughput applications requiring millions of IDs per second.
Architecture
Why 64-bit IDs?
- Database-friendly: Most databases optimize for 64-bit integers
- Memory efficient: Half the size of UUIDs (128-bit)
- Performance: Integer operations are faster than string operations
- Sortable: Natural ordering across milliseconds; within one millisecond, random bits determine relative order
- Compact URLs: Shorter than UUIDs when base36-encoded
Distributed Generation
No coordination required between multiple ID generators:
- Clock skew tolerant: Small time differences between servers are fine
- Random collision protection: 23 random bits provide 8.3M combinations per millisecond
- High availability: Each service can generate IDs independently
Randomness Considerations
- Cryptographic randomness by default: simpleflake() uses Web Crypto in browsers and Node’s built-in crypto implementation in Node.js.
- No Math.random() fallback: this keeps the default entropy source strong and avoids silently weakening collision resistance.
- Runtime requirements: modern browsers need
crypto.getRandomValues() and Node.js needs version 16 or newer.
- Deterministic or legacy environments: pass
randomBits explicitly if you need repeatable output or if you are targeting a runtime without crypto support.
Use Cases
Database Primary Keys
const userId = simpleflake();
await db.users.create({ id: userId.toString(), name: "John" });
Distributed System IDs
const serviceAId = simpleflake();
const serviceBId = simpleflake();
Short URLs
const shortId = simpleflake().toString(36);
const url = `https://short.ly/${shortId}`;
Event Tracking
const eventId = simpleflake();
await analytics.track({ eventId, userId, action: "click" });
API Reference
Core Functions
simpleflake(timestamp?, randomBits?, epoch?): bigint
Generates a unique 64-bit ID.
Parameters:
timestamp (number, optional): Unix timestamp in milliseconds. Default: Date.now()
randomBits (number, optional): Random bits (0-8388607). Default: random 23-bit number
epoch (number, optional): Epoch start time. Default: Date.UTC(2000, 0, 1) (2000-01-01T00:00:00.000Z, 946684800000)
Returns: BigInt - The generated ID
Throws:
TypeError when timestamp, randomBits, or epoch cannot be converted to an integer BigInt value
RangeError when timestamp - epoch falls outside the supported 41-bit range or when randomBits falls outside the 23-bit range
const id = simpleflake();
const customId = simpleflake(Date.now(), 12345, Date.UTC(2000, 0, 1));
parseSimpleflake(flake, epoch?): SimpleflakeStruct
Parses a simpleflake ID into its components.
Parameters:
flake (bigint | string | number): The ID to parse
epoch (bigint | string | number, optional): Epoch to use when reconstructing the timestamp. Default: SIMPLEFLAKE_EPOCH
Returns: Object with timestamp and randomBits properties (both bigint)
Throws:
TypeError when flake or epoch cannot be converted to an integer BigInt value
RangeError when flake falls outside the unsigned 64-bit range
const parsed = parseSimpleflake(4234673179811182512n);
console.log(parsed.timestamp);
console.log(parsed.randomBits);
const customEpoch = Date.UTC(2020, 0, 1);
const customId = simpleflake(customEpoch + 12345, 99, customEpoch);
const parsedCustom = parseSimpleflake(customId, customEpoch);
binary(value, padding?): string
Converts a number to binary string representation.
Parameters:
value (bigint | string | number): Value to convert
padding (boolean, optional): Whether to pad to 64 bits. Default: true
Returns: String - Binary representation
console.log(binary(42n));
console.log(binary(42n, false));
Extracts a portion of bits from a number.
Parameters:
data (bigint | string | number): Source data
shift (bigint): Starting bit position (0-based from right)
length (bigint): Number of bits to extract
Returns: BigInt - Extracted bits as number
const bits = extractBits(0b11110000n, 4n, 4n);
console.log(bits);
Constants
SIMPLEFLAKE_EPOCH: bigint
The epoch start time (January 1, 2000 UTC) as a Unix timestamp bigint.
import { SIMPLEFLAKE_EPOCH } from 'simpleflakes';
console.log(SIMPLEFLAKE_EPOCH);
TypeScript Types
interface SimpleflakeStruct {
timestamp: bigint; // Absolute Unix timestamp as bigint
randomBits: bigint; // Random component as bigint
}
Migration Guide
From UUID
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4();
import { simpleflake } from 'simpleflakes';
const id = simpleflake().toString(36);
Comparison
For a broader discussion of identifier tradeoffs beyond this library-level summary, see Choose your database identifiers wisely.
Core Characteristics
| Library |
Size |
Time-ordered |
Performance |
| Simpleflake |
64-bit |
✅ Yes |
⚡ 11M/sec |
| UUID v4 |
128-bit |
❌ No |
🔸 ~2M/sec |
| UUID v7 |
128-bit |
✅ Yes |
🔸 ~2M/sec |
| Nanoid |
Variable |
❌ No |
⚡ ~5M/sec |
| KSUID |
160-bit |
✅ Yes |
🔸 ~1M/sec |
| Twitter Snowflake |
64-bit |
✅ Yes |
⚡ ~10M/sec |
Technical Features
| Library |
Dependencies |
Database-friendly |
URL-friendly |
Distributed |
| Simpleflake |
✅ Zero |
✅ Integer |
✅ Base36 |
✅ Yes |
| UUID v4 |
❌ crypto |
❌ String |
❌ Long hex |
✅ Yes |
| UUID v7 |
❌ crypto |
❌ String |
❌ Long hex |
✅ Yes |
| Nanoid |
✅ Zero |
❌ String |
✅ Custom |
✅ Yes |
| KSUID |
❌ crypto |
❌ String |
✅ Base62 |
✅ Yes |
| Twitter Snowflake |
❌ System clock |
✅ Integer |
✅ Base36 |
⚠️ Needs config |
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
License
MIT
Credits
评论