nulid 0.1.0

Nanosecond-Precision Universally Lexicographically Sortable Identifier
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# NULID

**Nanosecond-Precision Universally Lexicographically Sortable Identifier**

[![Crates.io](https://img.shields.io/crates/v/nulid.svg)](https://crates.io/crates/nulid)
[![Documentation](https://docs.rs/nulid/badge.svg)](https://docs.rs/nulid)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kakilangit/nulid/blob/main/LICENSE)
[![Rust Version](https://img.shields.io/badge/rust-1.91%2B-blue.svg)](https://www.rust-lang.org)

---

## Overview

NULID is an extension of [ULID](https://github.com/ulid/spec) that provides **nanosecond-precision timestamps** for high-throughput, distributed systems. While the original ULID is optimal for many use-cases, some high-concurrency systems require finer granularity for true chronological sorting and enhanced collision resistance.

### Why NULID?

**The Challenge:**

- ULID's 48-bit millisecond timestamp is insufficient for high-throughput, distributed systems that generate thousands of IDs within the same millisecond
- In systems processing millions of operations per second, millisecond precision can lead to sorting ambiguities

**The Solution:**

- NULID uses a **70-bit nanosecond timestamp** for precise chronological ordering
- Preserves ULID's robust **80-bit randomness** for collision resistance
- Maintains all the benefits of ULID while extending precision

### Features

โœจ **150-bit identifier** (18.75 bytes) for maximum feature set\
โšก **1.21e+24 unique NULIDs per nanosecond** (80 bits of randomness)\
๐Ÿ“Š **Lexicographically sortable** with nanosecond precision\
๐Ÿ”ค **30-character canonical encoding** using Crockford's Base32\
๐Ÿ• **Extended lifespan** โ€” valid until **~45,526 AD** (4ร— longer than ULID)\
๐Ÿ”’ **Case insensitive** for flexible string handling\
๐ŸŒ **URL safe** โ€” no special characters\
โš™๏ธ **Monotonic sort order** within the same nanosecond

---

## Installation

### As a Library

Add this to your `Cargo.toml`:

```toml
[dependencies]
nulid = "0.1"
```

### As a CLI Tool

Install the NULID command-line tool:

```bash
cargo install nulid
```

This installs the `nulid` binary for generating and inspecting NULIDs from the command line.

## Performance

Benchmark results measured on modern hardware with `cargo bench`:

| Operation                        | Time    | Throughput          |
| -------------------------------- | ------- | ------------------- |
| **Generation**                   | ~1.1 ยตs | ~900,000 NULIDs/sec |
| **String Encoding**              | ~71 ns  | -                   |
| **String Decoding**              | ~97 ns  | -                   |
| **String Round-trip**            | ~168 ns | -                   |
| **Byte Serialization**           | ~0.9 ns | -                   |
| **Byte Deserialization**         | ~1.5 ns | -                   |
| **Byte Round-trip**              | ~2.1 ns | -                   |
| **Equality Check**               | ~1.3 ns | -                   |
| **Ordering Check**               | ~1.0 ns | -                   |
| **Sort 1,000 NULIDs**            | ~2.3 ยตs | 436 Melem/s         |
| **Batch (1,000)**                | ~1.1 ms | 900K NULIDs/sec     |
| **Concurrent (10 threads, 10K)** | ~3.3 ms | -                   |
| **Serde JSON Serialize**         | ~104 ns | -                   |
| **Serde JSON Deserialize**       | ~132 ns | -                   |
| **Serde JSON Round-trip**        | ~237 ns | -                   |

Key performance characteristics:

- โšก **Sub-microsecond generation** - ~900K IDs per second
- ๐Ÿš€ **Sub-nanosecond byte operations** - extremely fast binary serialization
- ๐Ÿ“ฆ **~71 ns string encoding** - efficient Base32 encoding
- ๐Ÿ”„ **~237 ns JSON round-trip** - fast serde integration
- ๐Ÿ”’ **Thread-safe** - concurrent generation across multiple threads
- ๐Ÿ’พ **Zero-allocation hot paths** - minimal memory overhead

## Quick Start

### Library Usage

```rust
use nulid::Nulid;

// Generate a new NULID
let id = Nulid::new()?;
println!("{}", id); // 01GZTV7EQ056J0E6N276XD6F3DNGMY
# Ok::<(), nulid::Error>(())
```

### CLI Usage

```bash
# Generate a single NULID
$ nulid generate
01GZTYKA3WZKB8VGCA3WHV101KRWB7

# Generate multiple NULIDs
$ nulid gen 5
01GZTYKA3WZKB8VGCA3WHV101KRWB7
01GZTYKA3X04XRYAYMXQKVX9BTHN9W
01GZTYKA3X09T0QVJF6V1G450QYTMR
01GZTYKA3X0BRG16DN1BY7XJEYPGJH
01GZTYKA3X0EP8JVJCDA4KVXRX4YX6

# Inspect NULID details
$ nulid inspect 01GZTYKA3WZKB8VGCA3WHV101KRWB7
NULID:       01GZTYKA3WZKB8VGCA3WHV101KRWB7
Timestamp:   1765233596749041000 (1765233596749041000 ns since epoch)
Randomness:  dc18a1f23b08033c7167
Bytes:       00187f5e9a87cfcd68dc18a1f23b08033c7167
Date/Time:   2025-12-08T22:39:56.749041000 TAI

# Validate NULIDs
$ nulid validate 01GZTYKA3WZKB8VGCA3WHV101KRWB7 INVALID
01GZTYKA3WZKB8VGCA3WHV101KRWB7: valid
INVALID: invalid (Invalid length: expected 30 characters, found 7)

Valid:   1
Invalid: 1
```

## Usage Examples

### Basic Generation

```rust
use nulid::Nulid;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Generate a new NULID
    let id = Nulid::new()?;
    println!("Generated NULID: {}", id);

    // Convert to string (30 characters)
    let id_string = id.to_string();
    println!("String: {}", id_string); // 01GZTV7EQ056J0E6N276XD6F3DNGMY

    // Parse from string (case-insensitive)
    let parsed: Nulid = id_string.parse()?;
    assert_eq!(id, parsed);

    Ok(())
}
```

### Byte Serialization

```rust
use nulid::Nulid;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let id = Nulid::new()?;

    // Convert to bytes (19 bytes)
    let bytes = id.to_bytes();
    println!("Bytes: {:02X?}", bytes);

    // Reconstruct from bytes
    let restored = Nulid::from_bytes(&bytes)?;
    assert_eq!(id, restored);

    Ok(())
}
```

### Lexicographic Sorting

```rust
use nulid::Nulid;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut ids = vec![];
    for _ in 0..5 {
        ids.push(Nulid::new()?);
    }

    // NULIDs are naturally sortable by timestamp
    ids.sort();

    // Verify chronological order
    assert!(ids.windows(2).all(|w| w[0] < w[1]));

    Ok(())
}
```

---

## ๐Ÿ› ๏ธ Specification

The NULID is a **150-bit** (18.75 byte) binary identifier composed of:

```text
70_bit_time_high_precision                    80_bit_randomness
|--------------------------------|            |--------------------------------|
           Timestamp                                    Randomness
            70 bits                                       80 bits
```

### Components

#### **Timestamp** (70 bits)

- **Size:** 70-bit integer
- **Representation:** UNIX time in **nanoseconds** (ns)
- **Rationale:** 70 bits provides 4ร— the lifespan of the original 68-bit design โ€” valid until the year **45,526 AD**
- **Encoding:** Most Significant Bits (MSB) first to ensure lexicographical sortability based on time

#### **Randomness** (80 bits)

- **Size:** 80 bits
- **Source:** Cryptographically secure source of randomness (when possible)
- **Rationale:** Preserves ULID's collision resistance with **1.21e+24** unique values per nanosecond
- **Collision Probability:** Astronomically low, even at extreme throughput

---

## ๐Ÿ“ Canonical String Representation

```text
tttttttttttttt rrrrrrrrrrrrrrrr
```

where:

- **`t`** = Timestamp (14 characters)
- **`r`** = Randomness (16 characters)

**Total Length:** 30 characters

### Encoding

NULID uses **Crockford's Base32** encoding, preserving the original ULID alphabet:

```text
0123456789ABCDEFGHJKMNPQRSTVWXYZ
```

**Character Exclusions:** The letters `I`, `L`, `O`, and `U` are excluded to avoid confusion and abuse.

#### Encoding Breakdown

| Component  | Bits    | Characters | Calculation |
| ---------- | ------- | ---------- | ----------- |
| Timestamp  | 70      | 14         | โŒˆ70 รท 5โŒ‰    |
| Randomness | 80      | 16         | โŒˆ80 รท 5โŒ‰    |
| **Total**  | **150** | **30**     | โŒˆ150 รท 5โŒ‰   |

---

## ๐Ÿ”ข Sorting

NULIDs are **lexicographically sortable**:

- The **left-most character** is sorted first
- The **right-most character** is sorted last
- Nanosecond precision ensures IDs are sorted correctly even when multiple IDs are generated within the same millisecond

### Example Sort Order

```text
7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAV  โ† Earlier
7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAW
7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAX
7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAY  โ† Later
```

---

## โš™๏ธ Monotonicity

When generating multiple NULIDs within the same nanosecond:

1. The **80-bit random component** is treated as a **monotonic counter**
2. It increments by **1 bit** in the least significant bit position (with carrying)
3. This ensures deterministic sort order within the same nanosecond

### Example

```rust
use nulid::Nulid;

// Assume these calls occur within the same nanosecond
Nulid::new(); // 7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAV
Nulid::new(); // 7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAW
Nulid::new(); // 7VVV09D8H01ARZ3NDEKTSV4RRFFQ69G5FAX
```

### Overflow Condition

If more than **2^80** NULIDs are generated within the same nanosecond (an extremely unlikely scenario), the generation will fail with an overflow error.

```rust,no_run
use nulid::Nulid;
// After 2^80 generations in the same nanosecond:
Nulid::new(); // panics with: "NULID overflow!"
```

---

## ๐Ÿ—‚๏ธ Binary Layout and Byte Order

The NULID components are encoded as **19 bytes (150 bits used, with 2 bits reserved)** with the **Most Significant Byte (MSB) first** (network byte order).

### Structure

```text
Byte:     0       1       2       3       4       5       6       7       8       9      ...     18
      +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
Bits: |RR|   Timestamp (70 bits)      |  T|R  |    Randomness (80 bits)               ...
      +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
       ^^
       Reserved (2 bits) - must be 0
```

**Detailed Layout:**

- **Byte 0 (bits 0-1):** 2 reserved bits (must be 0)
- **Bytes 0-8:** 70-bit timestamp (using remaining 70 bits)
- **Bytes 9-18:** 80-bit randomness

**Reserved Bits:**

- The 2 most significant bits in byte 0 are reserved for future use
- Current specification requires these bits to be set to `00`
- Future versions may define meaning for these bits
- Decoders SHOULD accept any value but MUST preserve them

This structure ensures:

- โœ… Maximum chronological sortability (nanosecond precision)
- โœ… Maximum lifespan (valid until 45,526 AD)
- โœ… Maximum collision resistance (80 bits of randomness)
- โœ… Future extensibility (2 reserved bits)

---

## ๐Ÿ“Š Comparison: ULID vs NULID

| Feature               | ULID              | NULID            |
| --------------------- | ----------------- | ---------------- |
| **Total Bits**        | 128               | 150              |
| **String Length**     | 26 chars          | 30 chars         |
| **Timestamp Bits**    | 48 (milliseconds) | 70 (nanoseconds) |
| **Randomness Bits**   | 80                | 80               |
| **Time Precision**    | 1 millisecond     | 1 nanosecond     |
| **Lifespan**          | Until 10889 AD    | Until 45,526 AD  |
| **IDs per Time Unit** | 1.21e+24 / ms     | 1.21e+24 / ns    |
| **Sortable**          | โœ…                | โœ…               |
| **Monotonic**         | โœ…                | โœ…               |
| **URL Safe**          | โœ…                | โœ…               |

---

## ๐Ÿš€ Features

- **Zero dependencies** for core functionality
- **Optional serde support** for serialization
- **Thread-safe** monotonic generation
- **No unsafe code**
- **Comprehensive test coverage**
- **Benchmark suite** included

## ๐ŸŽฏ Use Cases

NULID is ideal for:

- **High-frequency trading systems** requiring nanosecond-level event ordering
- **Distributed databases** with high write throughput
- **Event sourcing systems** where precise ordering is critical
- **Microservices architectures** generating many concurrent IDs
- **`IoT` platforms** processing millions of sensor readings per second
- **Real-time analytics** systems requiring precise event sequencing

---

## CLI Reference

The NULID CLI provides command-line utilities for working with NULIDs:

### Commands

- `generate, gen, g [COUNT]` - Generate NULID(s) (default: 1)
- `parse, p <NULID>` - Parse and validate a NULID string
- `inspect, i <NULID>` - Inspect NULID components in detail
- `decode, d <NULID>` - Decode NULID to hex bytes
- `validate, v [NULID...]` - Validate NULID(s) from args or stdin
- `help, -h, --help` - Print help message
- `version, -v, --version` - Print version information

### Examples

```bash
# Decode to hex
$ nulid decode 01GZTYKA3WZKB8VGCA3WHV101KRWB7
00187f5e9a87cfcd68dc18a1f23b08033c7167

# Parse a NULID
$ nulid parse 01GZTYKA3WZKB8VGCA3WHV101KRWB7
01GZTYKA3WZKB8VGCA3WHV101KRWB7

# Validate from stdin
$ cat nulids.txt | nulid validate
01GZTYKA3WZKB8VGCA3WHV101KRWB7: valid
01GZTYKA3X04XRYAYMXQKVX9BTHN9W: valid

Valid:   2
Invalid: 0

# Use in shell scripts
$ for i in {1..3}; do nulid gen; done
01GZTYKA3WZKB8VGCA3WHV101KRWB7
01GZTYKA3X04XRYAYMXQKVX9BTHN9W
01GZTYKA3X09T0QVJF6V1G450QYTMR
```

---

## ๐Ÿ”’ Security Considerations

1. **Use cryptographically secure random number generators** when possible
2. **Do not rely on NULID for security purposes** โ€” use proper authentication/authorization
3. **Timestamp information is exposed** โ€” NULIDs reveal when they were created
4. **Randomness must be unpredictable** โ€” avoid weak PRNG implementations

---

## ๐Ÿ› ๏ธ Development

### Building

```bash
cargo build --release
```

### Testing

```bash
cargo test
```

### Benchmarks

```bash
cargo bench
```

## ๐Ÿ“š Background

NULID builds upon the excellent work of the [ULID specification](https://github.com/ulid/spec). The original ULID addressed many shortcomings of UUID:

- โŒ UUID v1/v2 requires access to MAC addresses
- โŒ UUID v3/v5 requires unique seeds and produces random distribution
- โŒ UUID v4 provides no temporal information
- โŒ UUID uses inefficient encoding (36 characters for 128 bits)

NULID extends this foundation by addressing the millisecond precision limitation while maintaining ULID's core benefits.

---

## ๐Ÿ“ฆ Cargo Features

- `default` - Core NULID functionality
- `serde` - Enable serialization/deserialization support
- `std` - Standard library support (enabled by default)

To use with serde:

```toml
[dependencies]
nulid = { version = "0.1", features = ["serde"] }
```

---

## ๐Ÿ“œ License

Licensed under the MIT License. See [LICENSE](https://github.com/kakilangit/nulid/blob/main/LICENSE) for details.

---

**Built with โšก by developers who need nanosecond precision**