Design a URL Shortener, stage 2 of 9: decide
Generate short codes
Every link needs a code like aZ3kQ9x. Codes must be short, two links must never share one, and knowing one code must not let anyone find others.
System so far· 5 parts
Select a component to see what it is responsible for and which state it owns.
- 1Redirect service → Postgres: Look up code
- 2Customer dashboard → Links API: Create, edit, disable
- 3Links API → Postgres: Insert with unique code
What you need to know
Codes use base62: the characters
a–z,A–Zand0–9. Each character has 62 possible values, so a code of n characters has 62ⁿ possible values.Length Possible codes 5 about 916 million 6 about 57 billion 7 about 3.5 trillion Check
You'll create about 1.2 billion links a year, and codes are chosen at random. Which length should you use?There are three common ways to produce a code.
- Counter. Keep an auto-incrementing number and write it in base62. Link 1 gets
1, link 125 gets21, and so on. - Hash. Hash the long URL (with SHA-256, say) and keep the first 7 characters. The same URL always gives the same code.
- Random. Pick 7 random characters from a cryptographically secure generator.
- Counter. Keep an auto-incrementing number and write it in base62. Link 1 gets
Think first
Codes come from a counter, and you know one link:sho.rt/aZ3kQ9x. What could you do with it?Check
With hashing, two different customers shorten the same URL,https://shop.com/sale. What happens?That leaves random codes. They reveal nothing and need no coordination between servers, but two creations can pick the same code.
Don't try to prevent that by checking first. Make the code the table's primary key and just insert. If the code is taken, the database rejects the insert, all in one atomic step, and you try again with a new random code.
Check
Why not runSELECT … WHERE code = $1first, and only insert if the code is free?