Try
↑ ↓ move↵ openesc close
In this lesson · topic 4 of 7
  1. 1. A short link is a tiny key-value store
  2. 2. Requirements, numbers, API and data model
  3. 3. Make codes and follow them in the lab
  4. 4. Random codes meet the birthday bound
  5. 5. Counter ranges, random codes or hashes
  6. 6. Hot links, caches and 301 against 302
  7. 7. The URL shortener in review

Topic 4

Random codes meet the birthday bound

4 min read

Collisions come early

A repeat among random codes does not wait for the space to fill. It follows the birthday bound. With a space of N codes, the first repeat is likely after about the square root of N draws. For seven characters that is around two million links, while the space holds 3.5 trillion.

So a service that never checks will serve a wrong page long before it runs out of codes. A service that checks and retries pays a small cost per draw. The cost is what the lab shows.

With 3 characters the lab saw 8.6 percentmeasured collisions, which is 3754measured failed draws out of 43754measured attempts. With 4 characters it fell to 0.11 percentmeasured. With 5 characters it was 0.0 percentmeasured.

Each character multiplies the space by 62, so it cuts the chance of a hit by the same factor. That is why most services pick a length with a wide margin and then add a check.

The check is part of the design

A retry is cheap if the check is cheap. The insert itself can be the check. Make the code the primary key and let the database reject a duplicate. On a rejection, draw again. There is no separate read and no race between two servers that picked the same code at once.

If the table is split by code, the check stays local to one partition. See partitioning.

What the model leaves out

The lab holds every code in one set and checks it for free. A real table is spread over many machines, and a check costs a network call. It also ignores deleted and expired links. A code that expires may be reused or kept out of reuse, and that is a product decision.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms