Skip to content
Blog

← All articles

The Myth of the Short UUID: Encoding Math vs. String Length

Why a 22-character Base62 short UUID is exactly as unique as the 36-character original, why cutting characters off is not, and how to store short IDs: a tested BigInt implementation, birthday-paradox numbers at 10 billion IDs, and what PostgreSQL 18 and MySQL 8.4 do with short IDs stored as text.

By 12 min read

Libraries and blog posts offer "short UUIDs": 22 characters like 034u0i5NnXmfJTzCqD24Pv instead of 01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17. Some developers avoid them because shorter sounds less unique; others go further and cut IDs down to 8 characters because shorter looks harmless. Both get the math wrong in opposite directions. A short UUID that re-encodes all 128 bits loses nothing. An ID cut down by dropping characters loses bits, and the birthday paradox makes that much more expensive than it looks.

This article works through the encoding math, gives a BigInt implementation of Base62 that was tested on 100,000 UUIDs, puts numbers on truncation, and checks the usual storage advice against PostgreSQL 18 and MySQL 8.4. You can try the conversion in our Short UUID Converter.

The short answer#

The footprint matrix#

EncodingAlphabetLengthURL-safeSorts like the UUIDBits kept
Hex (standard)0-9 a-f and 4 hyphens36YesYes128
Base620-9 A-Z a-z22Yes, letters and digits onlyYes, padded to 22128
Base58Base62 without 0 O I l22Yes, letters and digits onlyYes, padded to 22128
Base64urlA-Z a-z 0-9 - _22 (without ==)Yes, with - and _No128

"Bits kept" is the point of the whole article: every row holds the same 128 bits. What changes is how many characters it takes to write them, and a few practical properties. Base58 drops characters that look alike, for IDs people read or type. Base64url is the only one with a standard alphabet (RFC 4648), but its - and _ can look odd at the ends of an ID, and it doesn't sort like the UUID. Base62 has no standard alphabet at all: 0-9A-Za-z is the most common order, and it is the one that sorts correctly, but some libraries use 0-9a-zA-Z.

How the encoding works#

Hex has 16 symbols, so each character carries log₂(16) = 4 bits, and 128 bits take 32 hex digits (plus 4 hyphens). A bigger alphabet carries more per character: log₂(62) ≈ 5.95 bits for Base62, 5.86 for Base58, and exactly 6 for Base64url. Dividing 128 by those gives 21.5, 21.9, and 21.3 characters, so all three round up to 22. The fraction left over means the 22nd character is never fully used. In Base62, 22 characters could hold numbers up to 2131, and the first character of a short UUID is always between 0 and 7.

Base62 and Base58 treat the UUID as one big number and write it in base 62 or 58, the same way you'd write a number in decimal: divide by the base, and the remainder is the last digit; repeat. Base64url works differently. It encodes the 16 bytes six bits at a time from the left, and the 22nd character carries the last 2 bits plus 4 unused zero bits. It gives different characters than a base-64 number would, which is also why it doesn't preserve sort order.

Base62 in JavaScript with BigInt#

A 128-bit number doesn't fit in a JavaScript Number, which is exact only up to 2⁵³, so the conversion uses BigInt:

short-uuid.mjs
// short-uuid.mjs: a UUID as 22 Base62 characters, and back. No dependencies.
const B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const UUID = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
const MAX = (1n << 128n) - 1n;

export function encodeToBase62(uuid) {
  if (!UUID.test(uuid)) throw new Error(`not a UUID: ${uuid}`);
  let n = BigInt("0x" + uuid.replace(/-/g, "")); // all 128 bits, exactly
  let s = "";
  while (n > 0n) {
    s = B62[Number(n % 62n)] + s; // the remainder is the last digit
    n /= 62n;
  }
  return s.padStart(22, B62[0]); // fixed length, so short IDs sort like the UUIDs
}

export function decodeFromBase62(short) {
  if (short.length !== 22) throw new Error("a short UUID is 22 characters");
  let n = 0n;
  for (const ch of short) {
    const d = B62.indexOf(ch);
    if (d < 0) throw new Error(`not a Base62 character: ${ch}`);
    n = n * 62n + BigInt(d);
  }
  // 22 Base62 digits can hold up to 2^131, so not every 22-character string is a UUID.
  if (n > MAX) throw new Error("more than 128 bits: not a UUID");
  const h = n.toString(16).padStart(32, "0");
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
}

Three details matter more than they look:

  • Padding to 22 characters with the alphabet's zero digit gives every ID the same length. With fixed length and an alphabet in ASCII order, short IDs sort exactly like their UUIDs. In our test, 10,000 v7 short IDs sorted as plain strings stayed in time order.
  • The 128-bit check on decode. 22 Base62 characters can encode numbers up to about 2131, so 87.4% of all 22-character Base62 strings aren't UUIDs. Without the check, zzzzzzzzzzzzzzzzzzzzzz decodes to 33 hex digits, and the function returns a malformed UUID instead of an error.
  • No shared state. Both functions are pure: they only read their argument and a constant alphabet, so they're safe to call from anywhere, including several workers at once.

We tested it on 100,000 random v4 and v7 UUIDs: every one encoded to 22 characters and decoded to the same UUID. The nil UUID encodes to 22 zeros and the max UUID to 7n42DGM5Tflk9n8mt7Fhc7; max + 1, wrong lengths, and characters outside the alphabet are rejected. Our Short UUID code examples give the same results in Python, Go, and Java.

Same bits, same uniqueness#

Encoding is a one-to-one mapping: every UUID has exactly one 22-character Base62 form, and that form decodes back to exactly that UUID. Two short IDs can only be equal if their UUIDs are equal, so the collision risk of short UUIDs is precisely the collision risk of the UUIDs themselves, no more and no less.

That risk depends on the UUID version, not on the encoding. A v4 UUID has 122 random bits; the other 6 mark the version and variant. A v7 UUID has a 48-bit millisecond timestamp and 74 random bits, so only UUIDs made in the same millisecond can collide. (Our UUID v4 vs. v7 article compares them.) Shortening either keeps exactly that.

Truncation and the birthday paradox#

The trouble starts when an ID is made shorter by dropping characters, or by generating fewer random bits, to fit a short URL or a code people type. With d = 2bits possible values, the chance of at least one duplicate among n random IDs is approximately

P ≈ 1 − e^(−n(n−1) / 2d)

and it reaches 50% at about 1.18 × √d IDs. The square root is the birthday paradox: 23 people are enough for a 50% chance of a shared birthday, not 183. For 10 billion IDs:

Random bitsChance of a duplicate among 10 billionIDs for a 50% chance
128 bits (any full UUID, as a number)1.5 × 10⁻¹⁹2.2 × 10¹⁹
122 bits (a v4 UUID, long or short)9.4 × 10⁻¹⁸2.7 × 10¹⁸
64 bits (a random 64-bit number)93.3%5.06 billion
47.6 bits (8 random Base62 characters)≈ 100%17.4 million
44.6 bits (the first 8 characters of a short UUID)≈ 100%6.1 million
32 bits (8 hex characters)≈ 100%77,200

A full UUID is safe at any scale anyone will reach. Halving the bits to 64 doesn't halve the safety; it takes it from "never" to "more likely than not" at 5 billion IDs. And 8 characters, a common length for short links, reaches a 50% chance of a duplicate somewhere between 6 and 17 million IDs.

A duplicate isn't always a disaster. If the ID is a primary key, the unique index rejects the second insert and the application can retry with a new ID. It's worse where nothing checks: file names in object storage, cache keys, tokens in links. There, a duplicate silently overwrites or exposes something. You can explore any combination in our collision calculator.

Short in the URL, 16 bytes in the database#

Short IDs are for places people see. In the database, keep the UUID in its native 16-byte type, and convert at the edge of the application:

lookup.mjs
// lookup.mjs: short IDs in the URL, 16-byte UUIDs in the database. Decode at the edge, query with the UUID.
import { decodeFromBase62, encodeToBase62 } from "./short-uuid.mjs";

export async function getOrder(db, shortId) {
  let id;
  try {
    id = decodeFromBase62(shortId);
  } catch {
    return { status: 404 }; // a malformed ID is simply not found; no query needed
  }
  const { rows } = await db.query("SELECT id, total FROM orders WHERE id = $1", [id]);
  if (rows.length === 0) return { status: 404 };
  return { status: 200, body: { id: encodeToBase62(rows[0].id), total: rows[0].total } };
}

Our test stored an order under its UUID, then looked it up by short ID: the row was found, and a malformed ID or an unknown one returned 404 without reaching the wrong row. We also measured what storing the short string instead would cost, and found three problems, of which size is the smallest.

Size

We loaded the same 1,000,000 random UUIDs into two PostgreSQL 18 tables, one keyed by uuid and one by their Base62 forms in a varchar(22). The uuid table took 42.2 MB with a 37.4–37.8 MB index; the varchar(22) table took 49.8 MB with a 50.3–51.1 MB index, about a third bigger (two runs). Every foreign key that refers to the ID pays the same again.

Sort order depends on the collation

Fixed-length Base62 sorts like the UUID only when strings are compared byte by byte. PostgreSQL's default collation in the official Docker image is en_US.utf8, which sorts letters case-insensitively first. We stored 2,000 v7 UUIDs and their short forms: ORDER BY short did not return them in time order, while ORDER BY short COLLATE "C" did. A uuid column sorts correctly with no collation to think about.

Case-insensitive comparison

Base62 is case-sensitive: a and A are different digits. MySQL's default collation, utf8mb4_0900_ai_ci, is not:

mysql.sql
-- mysql.sql: MySQL's default collation (utf8mb4_0900_ai_ci) ignores case. Base62 doesn't.
CREATE TABLE links_text (id VARCHAR(22) PRIMARY KEY);
INSERT INTO links_text VALUES ('5yK2bQ9xLm0aZt7RcV3pNd');
INSERT INTO links_text VALUES ('5Yk2BQ9XLM0AzT7rCv3PnD'); -- a different ID: rejected as a duplicate
SELECT id FROM links_text WHERE id = '5YK2BQ9XLM0AZT7RCV3PND'; -- a third ID finds the first one

-- Store the UUID itself: 16 bytes, compared byte for byte.
CREATE TABLE links (id BINARY(16) PRIMARY KEY);
INSERT INTO links VALUES (UUID_TO_BIN('01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17'));
SELECT BIN_TO_UUID(id) AS id FROM links;

On MySQL 8.4, the second INSERT failed with ERROR 1062: Duplicate entry, even though it's a different ID, and the SELECT for a third ID returned the first one. For full 22-character IDs, an accidental clash like this is still extremely unlikely, but a lookup matching an ID that wasn't asked for is a bug waiting for an attacker who tries case variants. For short random codes, the effect is measurable: compared case-insensitively, 8 Base62 characters behave like 8 Base36 ones, 41.4 bits instead of 47.6, and the 50% point drops from 17.4 million codes to about 2 million. The BINARY(16) table at the end of the script stores the UUID itself and compares bytes.

FAQ#

Is there a standard for short UUIDs?

No. RFC 9562 defines UUIDs as 128 bits and their 36-character text form; anything shorter is a convention between your systems. Write down the alphabet, its order, and whether IDs are padded, because Base62 and Base58 libraries disagree on all three.

Why do some libraries give 21 characters?

They don't pad. About 1 UUID in 8 is small enough to fit in 21 Base62 characters, and Bitcoin-style Base58 libraries write leading zero bytes differently. Unpadded IDs decode fine but no longer sort like the UUIDs. Pick one convention and use it on both sides.

Should I use Base64url instead?

It's a good choice when both sides already have a Base64 library and sort order doesn't matter. Strict decoders want the == padding back: in Python, base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)). Base62 and Base58 have no padding, because they're numbers, not byte groups.

Is a short ID a secret?

No more than the UUID. Re-encoding doesn't hide anything: a short v7 UUID still contains its creation time, and anyone can decode it. For tokens that must be unguessable, use a dedicated random token of 128 bits or more.

Try it in your browser

  • Short UUID Converter: convert UUIDs to Base62, Base58 or Base64url and back, and check the collision odds of any ID length.
  • UUID & GUID Generator: generate v4 and v7 UUIDs to shorten, and decode the timestamp inside a v7.