~learn.
0:00 / 1:30
Interview problem · URL shortener

Two servers, the same millisecond: who gets which short code?

transcript

Two servers shorten two links. In the same millisecond. How do you promise they never hand out the same code?

Hash the URL, keep seven characters? Truncation collides. Random codes? Every insert needs a uniqueness check. And two servers can race on it. A counter gives every link its own integer. It never collides, by construction.

But here's the catch. Every server now shares one counter. A network call per link, to one place. That's a bottleneck.

So each server leases a block of 10,000 IDs. One atomic bump of one row. Every new link takes the next ID from local memory. No network call. Consecutive IDs would give consecutive codes. So scramble them. Unique in, unique out. Encode in base 62, seven characters. Write it only if it's absent.

The whole fleet creates about 40 links a second. So the allocator gets touched a few times an hour. Not on every link. A server crashes? It just wastes the rest of its block.

One honest caveat. The scramble hides the order from casual eyes. It isn't encryption. Real enumeration threat? Use random codes, or longer ones.

No collisions. No race. One counter write per 10,000 links. Lease the counter. Don't call it.

Full breakdown in the lecture.