Try
↑ ↓ move↵ openesc close

Interview prep / URL shortener

Mid · URL shortener · System design interview question

Why do random short codes collide, and how do you handle it?

Sketch your own answer first, then compare it with the one below.

A strong answer

Random draws collide by the birthday bound. A repeat becomes likely after about the square root of the code space, long before the space is full.

Handle it with a check on write. Make the code the primary key and let the insert fail on a duplicate, then draw a new code. That removes the race between two servers that drew the same code.

Set a retry limit. If retries keep failing, the code length is too small for the table, and the fix is a longer code.

Sources

Learn it by running it

The design a url shortener lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

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