opyebULIDLab

NanoID: designing entropy with alphabet and length

NanoID · entropy · 6 min Read time

In one line: How the default 64-character alphabet and 21 characters produce 126 bits, where short IDs become risky, and the traps in custom alphabets.

NanoID is a library for small, URL-safe, unpredictable string IDs. It has no fixed bit layout like a UUID: you choose the alphabet and the length, which means you also own the entropy budget.

Calculating entropy

With alphabet size A and length L, the number of possible strings is A^L and the entropy is L × log2(A) bits. The default is a 64-character alphabet and 21 characters: 21 × 6 = 126 bits, a little more than the 122 bits of UUIDv4.

AlphabetLengthEntropyTypical use
64848 bitsShort links, internal tags (risky at millions)
641272 bitsShort public IDs, thousands per second
641696 bitsGeneral database keys
6421126 bitsDefault; enough for most services
3621109 bitsLowercase letters and digits only

The risk in short IDs

Eight characters is 48 bits. A 50% collision needs about 20 million IDs and a 1% collision about 2.4 million, which is well within reach of a growing service. If short IDs appear in public URLs with a retry on collision, you need collision detection and a UNIQUE constraint, not just hope.

Traps in custom alphabets

  • Duplicate characters: the same character twice skews the distribution. This tool removes duplicates.
  • Modulo bias: taking byte % alphabetSize makes earlier characters more frequent. NanoID avoids it with rejection sampling, and so does this tool.
  • Confusable characters: removing 0/O or 1/l/I shrinks the alphabet and therefore the entropy. Add length to compensate.
  • URL safety: the default alphabet includes - and _ and is safe in URLs and file names. Avoid spaces, / and +.

NanoID has no time

A NanoID cannot be sorted by creation time: string order is unrelated to when it was made. If you need time ordering, use UUIDv7, ULID or KSUID. NanoID fits session tokens, invitation codes and short public identifiers where the only requirement is uniqueness.

Decode an ID you just made and inspect its bit structure.

Open ULIDLab

Frequently asked questions

Does 21 characters really give 126 bits?

64^21 ≈ 2^126. The implementation must sample uniformly; using a remainder operation without rejection sampling lowers the real entropy slightly. This tool uses rejection sampling.

Can NanoID be a database primary key?

It can, but it is random, so index locality is poor and heavy inserts cause more page splits. Use it for secondary or public keys and prefer a time-ordered ID such as UUIDv7 or ULID for the primary key.

Can the alphabet be non-ASCII?

Technically yes, but URLs, file names and logs can hit encoding problems, and multi-byte characters complicate the entropy calculation. A URL-safe ASCII alphabet is the safer choice.

Sources

Read next