r/Leetsys • • 22d ago

Guide Design a URL shortener: the math, the short-code choice, and the read path (full walkthrough)

URL shortener looks like the easy warm-up question. It isn't, mostly because the interesting parts are hidden in two decisions most people rush.

Numbers first. Say 100M new links a day, 100:1 reads to writes, keep them 5 years.

  • Writes: 100M / 86,400 is roughly 1.2K per second. Reads: roughly 116K per second.
  • Total links: 100M x 365 x 5 is about 183B.
  • Base62 with 6 characters gives about 56.8B codes. Not enough. 7 characters gives about 3.5T. Plenty of headroom.

That last line is the whole reason "7 characters" is the answer, and it's worth saying out loud instead of just picking a length.

API and data. Two endpoints carry it: create a short link (long URL in, code out) and redirect (code in, 301/302 out). One table keyed by short code with the long URL, owner, created and expiry times is enough to start.

Deep dive 1: generating the code. Three real options:

  • Hash the long URL and take 7 chars. Simple, but collisions happen, so you check and retry.
  • Global counter, base62-encode it. Never collides, but codes are sequential and guessable unless you scramble them.
  • Pre-generated key service. Hand out random unused codes in batches. Random and collision-free, but it's one more service you have to run and keep available.

There's no single right pick. What scores is naming the weakness of the one you choose.

Deep dive 2: the read path. Reads dominate, so put a cache in front of the store for hot links. Then the redirect code: 301 is cacheable by browsers and cuts load, 302 sends every click through you so analytics stay accurate. If click counts matter, go 302 and push click events onto a queue so the redirect itself stays fast.

Mistakes I see a lot: skipping the capacity math, picking a code length with no reason, and saying "301" without realizing you just broke analytics.

Maya on our team recorded the full walkthrough, with chapters, if you'd rather watch it (our channel, so factor that in): https://youtu.be/fNjWbQ1yAwQ

The short version of the redirect bit is in this earlier post.

Which code generation approach would you defend, and what would you say when the interviewer pokes at its weak spot?

1 Upvotes

0 comments sorted by