In a short-link service using hash-and-truncate seven-character codes, how do you handle collisions, and how does the retry rate change as the keyspace fills?
answer
- truncation discards collision resistance
- same input, same taken code
- same link or a different link
- fill fraction per attempt
- cap attempts, alarm, lengthen
basics
~20 sWrite each code with a conditional insert; if a different link owns it, salt the input and rehash. Each attempt fails with probability equal to the keyspace fill: about 0.34% after ten years at seven characters, so retries stay rare.
solid answer
~40 sTruncated to seven base62 characters, a hash keeps only about 41.7 bits, so it collides like a random value. I write the link with an `insert-if-absent` keyed on the code. If it loses, I read the stored row: the same long URL from the same creator means the link already exists and I return it; a different link means a true collision, and because hashing is deterministic I change the input with a salt, rehash and try again, never overwriting. Each attempt fails with probability equal to the fill fraction: at 100 million links a month a seven-character keyspace is about 0.34% full after ten years, so about one create in 290 retries. I cap attempts, alarm at the cap, and use the retry metric to decide when to lengthen codes.
code
pseudocode · 17 lines// Illustrative: hash-and-truncate with salt-and-retry and a conditional insert.
// Field names are invented. Per-creator reuse is assumed (same URL + same creator -> same code).
MAX_ATTEMPTS = 5
function createLink(longUrl, creatorId):
for attempt in 0 .. MAX_ATTEMPTS - 1:
input = creatorId + "|" + longUrl + "|" + attempt // the salt changes the input
code = toBase62(hash(input)) take first 7 characters
result = insertIfAbsent(links, key = code,
value = { longUrl, creatorId, createdAt: now() })
if result == INSERTED:
return code
existing = get(links, key = code)
if existing.longUrl == longUrl and existing.creatorId == creatorId:
return code // same link made earlier: reuse it
metric.increment("shortlink.create.retry") // a different link owns this code
raise Alarm("no free code after " + MAX_ATTEMPTS + " attempts")go deeper
Recall that a hash cut down to seven characters can map two different URLs to the same short code, so the service must detect it rather than overwrite.
Explain the conditional insert keyed on the code, the same-link versus different-link check after it loses, and why the retry must salt the input.
Derive the per-attempt failure rate from the fill fraction, cap attempts with an alarm, and use the retry metric to schedule lengthening codes.
Weigh the retry loop against a counter's enumerable codes and a key pool's extra service, and decide which failure the product can live with.
## Why hash-and-truncate collides at all **Hash-and-truncate** turns a long URL into a short code by hashing it and keeping only as much of the digest as seven base62 characters can hold, about **41.7 bits**. The full digest of a cryptographic hash is collision resistant; a 41.7-bit slice of it is not. Once truncated, the code behaves like a random value drawn from a keyspace of 62^7, about **3.52 trillion** codes, and two different URLs can land on the same code. The design question is how the create path notices, what it does next, and how often that happens as the keyspace fills. ## Detecting the collision: the write decides The create path writes the new link with a **conditional insert keyed on the code**: insert only if no row with this code exists, as one atomic operation. A read-then-write check is not enough with many servers, because two of them can both see the code free; that general point needs only a clause here. What the shortener adds is what happens when the conditional insert loses: - **The stored row is the same link.** If the existing row has the same long URL and, under a per-creator reuse policy, the same creator, the earlier create already made this link; return its code. - **The stored row is a different link.** This is a real collision. Rehashing the same input would return the same taken code, because hashing is deterministic, so the retry must **change the input**: append a salt such as the attempt number, rehash, and try the next candidate. - **Never overwrite, never reuse.** A taken code belongs to its link forever, even after the link expires, because the old short URL may still be printed, cached or bookmarked. A variant takes a different seven-character window of the same digest on each retry instead of rehashing; it works the same way until the windows run out. ## How the retry rate rises as the keyspace fills Call **f** the fill fraction: codes issued divided by 62^7. If candidates are spread uniformly, one attempt hits a taken code with probability **f**, the chance that k attempts in a row all fail is **f^k**, and the expected number of attempts is **1 / (1 - f)**. With the scenario's 100 million links a month: | time | links issued | fill f | creates needing a retry | all of 5 attempts failing | |---|---|---|---|---| | 1 year | 1.2 billion | about 0.034% | about 1 in 2,900 | negligible | | 10 years | 12 billion | about 0.34% | about 1 in 290 | negligible | | 10 years, if six characters had been chosen | 12 billion of 56.8 billion | about 21% | about 1 in 5 | about 1 in 2,400 | At seven characters the retry is a rounding error for decades: at about 40 creates a second on average (derived from the scenario), roughly one retry every seven or eight seconds at the ten-year mark. The table also shows why the code length matters more than the retry logic: the same loop that is invisible at seven characters becomes a visible cost at six. ## What to operate 1. **Cap the attempts** (five is a generous choice) and raise an alarm when the cap is hit. At a 0.34% fill, two failures in a row happen about once in 86,000 creates and five essentially never; hitting the cap means the hash, the salt or the keyspace is wrong, not bad luck. 2. **Emit a retry metric per create.** The retry rate is a direct, live reading of the fill fraction; when it crosses an agreed threshold, start issuing eight-character codes. Existing codes keep resolving, because lookups key on the whole string. 3. **Put the creator, or a nonce, in the hash input** if the product does not want two creators who shorten the same URL to share a code. With the URL alone as input, anyone who knows the scheme can compute a URL's first candidate and find its short link. ## The alternatives the collision loop is weighed against - **A base62 counter** removes collisions completely, but its codes are sequential and enumerable, which a public link service usually cannot accept. - **A pre-generated pool of unused codes** moves the uniqueness work to generation time, so the request path does no retry loop at all; it costs a small key service and its failure modes. - **Plain random codes** collide at essentially the same rate as hash-and-truncate at the same length, assuming the hash spreads codes evenly; the hash buys determinism, not fewer collisions.
- Why not take the next seven characters of the same digest instead of rehashing with a salt?That works: each window of the digest is another candidate, and it saves a hash call. It runs out after a handful of windows, and the windows of one digest are only as independent as the hash makes them, so most designs fall back to a salt. Either way the input or window must change, because the first candidate is fixed by the URL.
- Does hash-and-truncate collide less often than random codes of the same length?No. Once truncated, a good hash spreads codes like random draws, so both fail with probability equal to the fill fraction. What the hash buys is determinism: the same input gives the same first candidate, which can make reuse of an existing link cheap. What it costs is that anyone can compute a URL's candidate unless the input includes a creator or a nonce.
- A cryptographic hash makes truncated codes unique, so no conditional insert is needed.
- On a collision, simply retry the same input until a free code comes back.
- An expired link's code can be overwritten when a new URL hashes onto it.
- Collisions only start once the keyspace is about half full.
- Hash-and-truncate collides less often than random codes of the same length.