How it works
Base62 uses digits and uppercase and lowercase letters. Six characters provide about 56.8 billion combinations, which the example’s 55 billion mappings would almost fill; seven provide about 3.52 trillion, leaving room for reservations and uneven allocation. At 30 million new links a day, six characters would run out in about 5.2 years.
A unique integer encoded in base62 is compact and free of collisions (two links receiving one key) when the ID allocator is truly unique. It also exposes a guessable sequence unless keys are obfuscated or access policy accepts enumeration: someone holding x7Kp2Qa can simply try x7Kp2Qb. A 64-bit Snowflake ID, the scheme Twitter published, avoids a central counter but takes 11 base62 characters, which gives back much of the shortness.
A random key hides ordering but needs collision detection. Generate a candidate, insert with a unique constraint, and retry on conflict. Postgres exposes this as INSERT ... ON CONFLICT, and DynamoDB as a conditional write. With 55 billion of 3.52 trillion keys taken, about one candidate in 64 collides by year five, so a creation averages about 1.02 inserts. The same 55 billion in a six-character space would fill 96% of it, and a creation would average about 28 inserts.
Truncating a hash of the destination also creates collision risk and couples identity to URL normalization, the rules for deciding whether two spellings are the same URL. Merely checking for an existing key before insertion is not safe under concurrent writers, because two servers can both see “unused” before either writes. Custom aliases need the same atomic uniqueness guarantee.
Two creation servers generate the same random key at once. Both check that it is unused. What prevents duplicate ownership?
A database unique constraint or equivalent atomic reservation allows only one insertion. The losing server generates another candidate and retries. A separate read-before-write check cannot close the race.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Estimate key-space from lifetime creations, not daily traffic alone.
- Let an atomic unique constraint decide collisions under concurrency.