System Design · Concept Library · Free article
How Do URL Shorteners Generate Unique Short Codes?
Size the code space, enforce collisions at the database, then choose how much coordination and guessability the product can accept.
A short-code system maps each stored object to a compact public identifier. Base62 packs letters and digits into each character, but a large code space does not guarantee collision-free random generation. Small systems can generate a random code, enforce a unique database constraint, and retry conflicts. Counters guarantee uniqueness but expose order unless transformed. At larger scale, range allocation, time-ordered UUIDs, or Snowflake-style IDs trade shorter output for less coordination. The database constraint remains the final correctness boundary whenever collisions are possible.
How do you generate a short unique URL code?
Encode a value in base62 and let a unique constraint in the database settle collisions, retrying on a conflict. The three requirements pull in different directions, so decide them separately. Hatch turns a long destination into hatch.app/x7Gk2. The suffix must be short enough to share, unique enough that one link never resolves to another, and suitable for public exposure. Those goals do not choose an algorithm by themselves.
First estimate the required space. An alphabet with N symbols and a fixed length L has N^L possible strings. Base62 uses 26 lowercase letters, 26 uppercase letters, and 10 digits. Six characters give 62^6 = 56,800,235,584 values; seven give 62^7 = 3,521,614,606,208.
The interactive version of this example is available when JavaScript loads.
Random code, unique constraint, retry
A practical first design is simple: generate a random base62 code, attempt the insert, and retry if the database rejects a duplicate. Do not run a separate “is this free?” query before the insert. Two creators can pass that check at the same time. The unique constraint is the atomic decision point.
Random codes do not reveal creation order, and application servers can generate them without coordinating. Their collision probability rises as the space fills, so choose enough room, cap retries, and observe conflict rates. The insert path must treat a uniqueness violation as an expected retry case, not as permission to overwrite an existing link.
The interactive version of this example is available when JavaScript loads.
Push the code length down and the curve is the argument for sizing the space before shipping. Collisions are not rare-then-sudden: the probability climbs smoothly as the table fills, so a length that looks generous at launch becomes a retry storm at a volume you can predict in advance. The retry loop is what makes the design correct, and the length is what keeps it cheap. Pick the length from the number of links you expect to hold, not from how short the code looks in a message.
Random codes or a counter: which should you use?
A counter when density and length matter most, random codes when the objects should not be enumerable, and a keyed permutation over a counter when you want both. A database sequence hands out a different integer for each link. Encoding that number in base62 produces dense, short strings with no random collision. The trade-off is visibility: nearby codes reveal ordering and let someone enumerate public objects. A reversible, keyed permutation can hide the obvious sequence before encoding, but it must be designed and reviewed as a mapping, not advertised as access control.
A short code is never a password. Private destinations still need authentication and authorization. Codes should also remain retired after deletion; reusing one can redirect old messages and QR codes to a new owner.
The interactive version of this example is available when JavaScript loads.
Encode a few consecutive numbers and the trade-off is visible in the output itself: the codes are dense, every one is unique without a single retry, and consecutive links differ by one character in a way anybody can read. That is the whole exchange this section describes. A counter buys away collisions and pays for it in enumerability, which matters only when the objects behind the codes are worth enumerating.
Reduce coordination when one sequence becomes a bottleneck
A single sequence is often sufficient far longer than a whiteboard answer suggests. If ID issuance becomes a measured bottleneck or must survive independent regions, the system can allocate blocks of numbers to generators, embed a generator identifier, or use a standard distributed format.
Range allocation amortizes coordination: a service leases a block and issues from it locally. Gaps are harmless, but the allocator remains part of the availability story. Snowflake-style IDs combine time, a generator identifier, and a per-time-unit sequence. They are roughly ordered and generated locally, but uniqueness depends on assigning generator identifiers correctly and handling clock regressions.
UUIDv4 and UUIDv7 solve a different length problem
UUIDv4 supplies 122 random bits and needs no central issuer. Its usual text form is too long for a human-friendly short URL, and random values have poor B-tree locality. RFC 9562 defines UUIDv7 with a Unix-millisecond timestamp in the most significant 48 bits and random or monotonic data in the remaining variable fields. That time order improves index locality while retaining decentralized generation.
Use UUIDv7 when a 128-bit identifier and time ordering fit the storage model. Do not truncate a UUID or cryptographic hash to a short string and then claim collisions are impossible. Once truncated, the result has only the entropy of the shortened space and needs an explicit collision policy.
| Strategy | Strength | Cost |
|---|---|---|
| Random base62 + unique insert | Independent generators and non-sequential codes | Possible conflicts; retry policy required |
| Sequence → base62 | Compact and unique by construction | Central issuer and enumerable order |
| Allocated ranges | Many local issues per allocator call | Leases, gaps, and allocator recovery |
| Snowflake-style ID | Local generation and rough time order | Generator assignment and clock handling |
| UUIDv7 | Standard 128-bit, time-ordered format | Longer public representation |
The right first answer for Hatch
At Hatch’s launch scale, a random base62 code with enough length, a UNIQUE constraint, and a bounded retry is easy to explain and operate. The database owns the final uniqueness decision. An index on the same column keeps the redirect fast. If code creation later becomes a real bottleneck, Hatch can change the issuer without changing what the public code means.
That separation matters: Databases owns the durable row and integrity rule; Database indexing owns the lookup; this pattern owns how candidate identifiers are produced.
Primary references
Pick an issuer and keep a correctness boundary
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.