In this lesson · topic 5 of 7
Topic 5
Counter ranges, random codes or hashes
6 min read
Counter ranges
Keep a counter and write each number in base 62. No two links ever share a number, so there are no collisions. In the lab a counter had 0 collisionsmeasured and needed 3 charactersmeasured for the count it reached. A count of 40,000 needs 3 digitsmeasured in base 62.
One counter on one machine is a bottleneck and a single point of failure. The usual fix is ranges. A small coordination service hands each creation server a block, say a million numbers. The server uses its block with no further coordination and asks for another when it runs low. Coordination happens once per block, not once per link. A lease on the range keeps two servers from holding the same block. See leases and fencing.
The costs are real. Codes are guessable, because the next one is one more than the last, so people can walk through every link. A crashed server wastes the unused part of its block, which is harmless. You can scramble the number with a reversible mix to hide the order, but that hides it and does not secure it.
Random codes
Draw a code at random and check it. No coordination is needed, because each server draws on its own. Codes are hard to guess if the space is large and the table is sparse. The price is the collision check and retries, as the last topic showed.
Use a secure random source if the codes must not be guessable. Do not use one that is seeded from the clock.
Hashes
Hash the long address and keep the first few characters. The same address always gives the same code, so you get de-duplication for free. A user who submits the same link twice gets the same short link.
Two different addresses can share the first few characters, and the birthday bound applies as it does for random codes. The fix is to detect the clash and hash again with a salt. That also means a given address may not always map to the same code. Hashes cannot give each user their own link to the same address, since the code depends only on the address. Add the user or a salt to the input if you need that.
Choosing
- Counter ranges: one call per block, no collisions, guessable, the same address gets two codes.
- Random codes: no coordination, collisions are retried, hard to guess, the same address gets two codes.
- Hashes: no coordination, collisions are re-salted, hard to guess, the same address gets one code.