# simpleflakes

[![CI](https://github.com/leodutra/simpleflakes/actions/workflows/ci.yml/badge.svg)](https://github.com/leodutra/simpleflakes/actions/workflows/ci.yml)
[![npm][npm-badge]][npm-link]
[![coveralls status][coveralls-badge]][coveralls-link]
[![npm downloads](https://img.shields.io/npm/dm/simpleflakes.svg?style=flat)](https://www.npmjs.com/package/simpleflakes)
[![Bundle Size](https://img.shields.io/bundlephobia/minzip/simpleflakes?style=flat)](https://bundlephobia.com/package/simpleflakes)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/node-%3E%3D16.0.0-brightgreen.svg?style=flat)](https://nodejs.org/)
[![Performance](https://img.shields.io/badge/performance-11.5M%20ops%2Fsec-brightgreen?style=flat&logo=javascript)](https://github.com/leodutra/simpleflakes/actions/workflows/ci.yml)
[![Last Commit](https://img.shields.io/github/last-commit/leodutra/simpleflakes.svg?style=flat)](https://github.com/leodutra/simpleflakes)
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fleodutra%2Fsimpleflakes.svg?type=shield&issueType=license)](https://app.fossa.io/projects/git%2Bgithub.com%2Fleodutra%2Fsimpleflakes?ref=badge_shield&issueType=license)

> **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?](#what-is-simpleflake)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Advanced Usage](#advanced-usage)
- [ID Structure](#id-structure)
- [Performance](#performance)
- [Architecture](#architecture)
- [Use Cases](#use-cases)
- [API Reference](#api-reference)
- [Migration Guide](#migration-guide)
- [Comparison](#comparison)
- [Contributing](#contributing)

## What is Simpleflake?

Simpleflake generates **unique 64-bit integers** that are:

1. **Time-sortable** - IDs from later milliseconds are numerically larger
2. **Distributed-safe** - No coordination needed between multiple generators
3. **Compact** - Fits in a 64-bit integer (vs UUID's 128 bits)
4. **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

- **[Original Presentation](http://akmanalp.com/simpleflake_presentation/)** - Introduction to the concept by Mali Akmanalp
- **[Video Discussion](http://www.youtube.com/watch?v=SCQPBGi_QRk)** - Detailed explanation and use cases
- **[Python Implementation](https://simpleflake.readthedocs.org/en/latest/)** - Original reference implementation
- **[Twitter Snowflake](https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html)** - Similar distributed ID system
- **[First Principles](docs/FIRST_PRINCIPLES.md)** - Design rationale for simpleflakes from first principles
- **[Choose your database identifiers wisely](https://racum.blog/articles/identifiers/)** - Broader comparison of serial, UUID, Snowflake-style, and other identifier families

## Installation

```bash
npm install simpleflakes
```

Supports both CommonJS and native ESM.

## Quick Start

### JavaScript (CommonJS)

```javascript
const { simpleflake } = require('simpleflakes');

// Generate a unique ID
const id = simpleflake();
console.log(id); // 4234673179811182512n (BigInt)

// Convert to different formats
console.log(id.toString());    // "4234673179811182512"
console.log(id.toString(16));  // "3ac494d21e84f7b0" (hex)
console.log(id.toString(36));  // "w68acyhy50hc" (base36 - shortest)
```

### TypeScript / ES Modules

```typescript
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

```javascript
// Generate with custom timestamp and random bits
const customId = simpleflake(
  Date.now(),           // timestamp (default: Date.now())
  12345,               // random bits (default: 23-bit random)
  Date.UTC(2000, 0, 1) // epoch (default: 2000-01-01T00:00:00.000Z / 946684800000)
);
```

### Working with Binary Data

```javascript
import { binary, extractBits } from 'simpleflakes';

const id = simpleflake();

// View binary representation
console.log(binary(id));
// Output: "0011101011000100100100110100001000011110100001001111011110110000"

// Extract specific bit ranges
const timestampBits = extractBits(id, 23n, 41n); // Extract 41 bits starting at position 23
const randomBits = extractBits(id, 0n, 23n);     // Extract first 23 bits
```

### Debugging Existing IDs

If you want an external CLI to inspect a Simpleflake, [uuinfo](https://github.com/Racum/uuinfo) supports it.

```bash
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

```javascript
// Generate multiple IDs efficiently
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 (until year 2069)
- **8.3 million** unique IDs per millisecond
- **Extremely low collision chance** - 1 in 8.3 million per millisecond
- **Sortable by timestamp** when converted to integers at millisecond granularity; within one millisecond, random bits determine relative order

## Performance

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:

```bash
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

```javascript
// Perfect for database IDs - time-sortable and unique
const userId = simpleflake();
await db.users.create({ id: userId.toString(), name: "John" });
```

### Distributed System IDs

```javascript
// Each service can generate IDs independently
const serviceAId = simpleflake(); // Service A
const serviceBId = simpleflake(); // Service B
// No coordination needed, guaranteed unique across services
```

### Short URLs

```javascript
// Generate compact URL identifiers
const shortId = simpleflake().toString(36); // "w68acyhy50hc"
const url = `https://short.ly/${shortId}`;
```

### Event Tracking

```javascript
// Time-sortable event IDs for chronological processing at millisecond granularity
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

```javascript
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

```javascript
const parsed = parseSimpleflake(4234673179811182512n);
console.log(parsed.timestamp);  // "1693244847123"
console.log(parsed.randomBits); // "4567234"

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

```javascript
console.log(binary(42n)); // "0000000000000000000000000000000000000000000000000000000000101010"
console.log(binary(42n, false)); // "101010"
```

#### `extractBits(data, shift, length): bigint`

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

```javascript
const bits = extractBits(0b11110000n, 4n, 4n); // Extract 4 bits starting at position 4
console.log(bits); // 15n (0b1111)
```

### Constants

#### `SIMPLEFLAKE_EPOCH: bigint`

The epoch start time (January 1, 2000 UTC) as a Unix timestamp bigint.

```javascript
import { SIMPLEFLAKE_EPOCH } from 'simpleflakes';
console.log(SIMPLEFLAKE_EPOCH); // 946684800000n
```

### TypeScript Types

```typescript
interface SimpleflakeStruct {
  timestamp: bigint;   // Absolute Unix timestamp as bigint
  randomBits: bigint;  // Random component as bigint
}
```

## Migration Guide

### From UUID

```javascript
// Before (UUID v4)
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4(); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// After (Simpleflake)
import { simpleflake } from 'simpleflakes';
const id = simpleflake().toString(36); // "w68acyhy50hc" (shorter!)
```

### From Twitter Snowflake

```javascript
// Simpleflake is backwards compatible with Snowflake structure
// Just different bit allocation:
// - Snowflake: 41 bits timestamp + 10 bits machine + 12 bits sequence
// - Simpleflake: 41 bits timestamp + 23 bits random
//
// *double-check epoch
```

## Comparison

For a broader discussion of identifier tradeoffs beyond this library-level summary, see [Choose your database identifiers wisely](https://racum.blog/articles/identifiers/).

### 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

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

[MIT](https://raw.githubusercontent.com/leodutra/simpleflakes/master/LICENSE)

---

## Credits

- Original concept by [Mali Akmanalp](http://akmanalp.com/)
- TypeScript port and optimizations by [Leo Dutra](https://github.com/leodutra)
- Inspired by [Twitter Snowflake](https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html)

[npm-badge]: https://img.shields.io/npm/v/simpleflakes.svg?style=flat
[coveralls-badge]: https://img.shields.io/coveralls/leodutra/simpleflakes.svg?style=flat

[npm-link]: https://www.npmjs.com/package/simpleflakes
[coveralls-link]: https://coveralls.io/github/leodutra/simpleflakes

[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fleodutra%2Fsimpleflakes.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fleodutra%2Fsimpleflakes?ref=badge_large)
