LLD Guide · Module 2: Problem prep · Lesson 02.11

Prep: URL Shortener

Short codes that can never collide, clicks that are never lost, and long or Unicode URLs that come back byte for byte.

By Cruscible Engineering · Published

Two questions decide this problem: how you know a code has never been used, and how a click is counted when a thousand happen at once.

This lesson prepares you for Build a URL Shortener. It doesn't solve it.

1. What the URL shortener contract asks for

shorten stores a URL and returns a new short code. resolve returns the URL and counts a click. Every call to shorten creates a new mapping, even for a URL you've seen before. All data is persisted (Postgres is recommended).

MethodReturns / does
shorten(longUrl)a new code of 6 to 8 characters from a–z, A–Z, 0–9; throws IllegalArgumentException for null
resolve(code)the original URL, and the click count goes up by one; null if unknown
delete(code)true if the mapping existed, false otherwise
getClickCount(code)resolves so far; 0 for an unknown or deleted code
getStats(code)shortCode, longUrl, clickCount, createdAt (epoch ms); an empty map if unknown

2. Lessons to read before the URL shortener

3. URL shortener design decisions to make first

  1. How are codes generated? The brief names three ways: a counter in Base62, random codes retried on a collision, or a truncated hash. For yours, is a duplicate impossible, or only detected? And who detects it?
  2. How does every code end up 6 to 8 characters? A counter's first values encode to one or two characters. A random code needs a fixed length.
  3. How is a click counted? Reading the count and writing it back in a second step loses clicks under load. Can resolve find the URL and count the click in one statement?
  4. Which column types hold the URL exactly? URLs of 2,048 characters, Unicode and special characters must come back unchanged.
  5. What does delete leave behind? After a delete, resolve gives null, the count is 0 and the stats are empty. Is the row gone, or flagged?
  6. What does an empty URL do? The brief leaves it to you: reject it with IllegalArgumentException, or store it and give "" back.

4. URL shortener pitfalls

⚠️ Trap: don't look up an existing code for a URL you've already shortened. The same URL shortened twice gets two codes and two separate counters.

⚠️ Trap: a VARCHAR(255) column fails or truncates a 2,048-character URL.

⚠️ Trap: checking that a random code is free, then inserting it, is a race. Two threads can pick the same free code in between.

⚠️ Trap: the performance target is 5,000 shorten calls a second at a p99 of 10 ms. Every extra round trip per call counts.

💡 Tip: createdAt is epoch milliseconds as a number, not a timestamp object.

Before you submit

Further reading

After you've tried it

Submit first. The full walkthrough of one solution: Building a URL Shortener.

Open the problem