Short links with click analytics
A small team's link shortener must support custom aliases, click analytics and 100 times the traffic.
To design a URL shortener, separate redirects, which are read-heavy, from link creation. Generate unique short codes with a counter or random codes plus a uniqueness check, cache hot links in front of the database, and record clicks asynchronously so analytics never slow a redirect.
The system today: A marketing tool shortens links. One web server takes requests to create a link and to follow one. It writes to a single SQL database table (short code, long URL, created time). It handles a few hundred redirects a day, and the server and the database run on one machine.
What has to change: A customer launches a campaign: expect about 100 million redirects a day, links that people can name themselves (custom aliases), and a dashboard showing clicks per link per day. Redirects must stay fast, and a link must never point to the wrong place.
Questions to ask first
- How long should links live, and can an owner edit or delete one?
- What read-to-write ratio should I assume, and how fast must a redirect be?
- Must click counts be exact and real time, or can they be a few minutes behind?
- Can two people ask for the same custom alias at once, and what happens then?
Where the interviewer digs in
- Generating unique short codes without collisions across many servers
- A cache in front of the database for hot links, and what invalidates it
- Counting clicks without slowing redirects down
What a strong answer covers
- Separates the read path (redirects, very hot) from the write path (creating links) and sizes them: about 1,200 redirects a second on average, several times that at peak.
- Chooses a code scheme and justifies it: a counter or a distributed ID turned into base62, or random codes with a uniqueness check, and says what happens on a collision.
- Puts a cache in front of reads, and handles the alias race with a unique constraint rather than a read-then-write.
- Records clicks asynchronously (a queue or a log), aggregates them in batches, and explains why the dashboard can lag slightly.
Common mistakes
- Hashing the long URL and truncating it without handling collisions.
- Counting clicks with a database update on every redirect, which turns the hot read path into a write path.
- Using a temporary redirect when the requirement was permanent, or the reverse, without discussing caching of redirects.