Skip to content
Lesson 38

Design a URL shortener

Design StayHub's short links end to end: a tiny write path and a huge, skewed read path, collision-free codes, a cached read-only redirect, the CDN for viral links, and counting after the answer.

The lesson in text

Click a paragraph to hear it.

01One long link

Monday morning. Maya is about to send the summer-sale text to 400,000 guests. One problem: the hotel link in it is so long that the message has 214 characters. A single SMS holds 160. So every guest gets two messages, and StayHub pays for two.

At about four cents for each extra message, that one long link costs €16,000. Maya wants short links instead, like stay.hb/x7Kp2. The sale is in three weeks.

This time Lina hands it over: you lead the design, and she checks your answers. So you run the system design method: ask, estimate, define, draw, dig, decide.

02A cloakroom

Picture a theatre cloakroom. During the evening, people hand in their coats one at a time and get a numbered ticket. It's slow and steady. Nobody is in a hurry.

Then the show ends, and everyone wants their coat back at the same moment. That's the hard part. A smart attendant keeps the coats people ask for most right by the counter.

A link shortener is the same. Creating a short link is handing in a coat: rare and calm. Clicking it is fetching the coat: frequent, all at once, and it must feel instant. Two paths, designed separately.

And the tickets come off a numbered roll, so two people never get the same number. Keep that in mind: it's how we'll make the codes.

03Size both paths

First, the numbers. At the 10× plan, StayHub creates about 100,000 links a day: booking texts, guest shares, partner newsletters. Divided by 100,000 seconds, that's about one a second. Tiny.

Clicks: about a million a day, so ten a second on average. But here the average lies. When the sale text reaches 400,000 phones, about 20% of guests tap within ten minutes: 80,000 clicks, most of them in the first minute. About 1,000 clicks a second, all on one code.

And if a travel influencer posts a link, it can reach 5,000 clicks a second, again on a single code. One key that gets most of the traffic is called a hot key.

Storage is small. 100,000 links a day for five years is about 180 million links. At 500 bytes each, about 90 gigabytes. One PostgreSQL table holds that easily.

Two paths, very different sizes (10× plan)
Create: 100,000 links a day ÷ 100,000 s ≈ 1 a secondcalm
Click: 1,000,000 a day ÷ 100,000 s ≈ 10 a secondaverage
Sale text: 400,000 × 20% = 80,000 clicks in 10 minutesmost in the first minute
→ about 1,000 clicks a second, on one codehot key
Viral post: up to 5,000 clicks a second, on one codehot key
Storage: 100,000 × 365 × 5 ≈ 180M links × 500 B ≈ 90 GBone PostgreSQL table
A day is rounded to 100,000 seconds. The write path is tiny; the read path is big, and worse, it's skewed: most clicks land on one code at a time.

04Making the codes

Now the codes. The five characters after the slash use base 62: ten digits, 26 lowercase and 26 uppercase letters. Five characters give 62 to the power of 5: about 916 million codes.

In five years we'll use about 180 million of them: a fifth of the space. That fraction decides how the codes are made.

Random codes look tempting. But once a fifth of all codes are taken, every random pick has a one-in-five chance of hitting a used one, and must try again. And it gets worse every year.

So, like the cloakroom's roll, we use a counter: link number one, two, three, each written in base 62. A counter never collides. And so the database isn't asked for every number, each server reserves a block of 10,000 at a time.

The cost: counter codes are guessable. Someone can try the next one. For links to public hotel pages that's harmless, and you write that trade-off down.

How codes are made
OptionGoodCostFor StayHub
Counter in base 62 (blocks of 10,000 per server)Never collides; shortest codes; one database call per 10,000 linksCodes are guessableChosen: links go to public hotel pages
Random 5 charactersUnguessable1 in 5 picks collide by year five; needs a uniqueness check and retriesNot chosen
62⁵ = 916,132,832 ≈ 916 million codes5 characters
180 million used in 5 years ≈ 20%a fifth of the space
62 = 10 digits + 26 lowercase + 26 uppercase letters. With a fifth of the space used, random codes collide one pick in five; a counter never does.

05The click

Next, the path that matters: the click. The phone asks for stay.hb/x7Kp2, and StayHub answers with a redirect: a short reply that says, go to this hotel page instead.

To find the address fast, the app looks in the cache first: Redis answers in about half a millisecond. Only on a miss does it ask PostgreSQL, one or two milliseconds, and then it keeps the answer in the cache for next time.

Codes that don't exist are cached too, for a minute. So a script that guesses random codes can't hammer the database.

Which redirect? A 301 means moved permanently: the browser remembers it and never asks again. A 302 means found, for now: every click comes back to us. Maya needs click counts per campaign, and a wrong link must stay fixable. So: 302.

One click, end to end
Guest's phone
StayHub app
Redis cache
PostgreSQL
GET stay.hb/x7Kp2
link:x7Kp2 ? (~0.5 ms)
miss
SELECT url … (~1–2 ms)
the hotel page URL
keep it for 1 hour
302 → stayhub.com/hotels/42
The redirect only reads. Unknown codes are cached for a minute too, so scripts guessing codes never reach PostgreSQL. A 302 keeps every click visible and every link fixable; a 301 would be remembered by browsers forever.

06The viral link

Now the viral link: 5,000 clicks a second on one code. Our 4 app servers handle about 400 a second each: 1,600 together. Even with a perfect cache, there are too few servers.

So the answer must happen before our servers. The CDN, the network of copies close to the guests, may keep the redirect for ten seconds. Each CDN location asks us once every ten seconds, and answers everyone else itself.

Even with dozens of locations, that's a few requests a second for us instead of 5,000. The price: when we fix a link, it takes up to ten seconds to change everywhere. Fine for hotel links.

A viral link, absorbed before our servers
Where the click is answeredRequests a second reaching StayHub
Every click at StayHub's servers5,000: too many for 1,600 of capacity
CDN keeps the redirect 10 s, each location asks once per 10 sa few (e.g. 30 locations ÷ 10 s ≈ 3)
5,000 clicks a second is more than StayHub's 4 servers × 400 = 1,600. The CDN keeps the 302 for 10 seconds; the price is that a fixed link takes up to 10 seconds to change everywhere.

07One row, three thousand clicks

Omar has seen this go wrong. Last October, StayHub ran a quick beta of short links. At eight in the evening, an influencer posted one: about 3,000 clicks a second.

Every click ran one database command: add one to this link's click count. All 3,000 a second hit the same row, in the same main database that checkout uses.

Two changes to one row can't happen at the same time: each one waits for the previous one to finish. That row managed a few hundred a second. The rest waited in line, and each waiting click held a database connection.

Redirects went from 2 milliseconds to 2 seconds. The pool of database connections ran empty. Then checkout couldn't get a connection either. A click counter took bookings down.

The beta bug, and the fix
Before: one write per click, on one row
Phone
StayHub app
PostgreSQL (shared with checkout)
click (× 3,000 a second)
UPDATE links SET clicks = clicks + 1
wait for the row lock… (2 ms → 2 s)
After: read, answer, count later
Phone
StayHub app
Queue + worker
PostgreSQL
click
302 at once
note: clicked (no waiting)
every 10 s: one total
Changes to one row take turns. In the beta, 3,000 a second waited in line, each holding a database connection, until checkout couldn't get one. The fix moves counting after the answer.

08Count after the answer

The fix: the redirect never writes. It drops a small note, "this code was clicked", onto a queue, and answers straight away, without waiting.

A worker adds up the notes every ten seconds and writes one total per link. For a viral link, that's one write every ten seconds, instead of 30,000.

Counts arrive a few seconds late, and nobody notices. The rule to keep: on a path that must be fast, only read. Anything that counts, logs or learns happens after the answer.

09Who may make links

One last decision, and it isn't technical: who may create links? If anyone can shorten any address, spammers will use stay.hb for scam pages, and email providers will start blocking the whole domain.

So links may point only to StayHub pages, created by our own systems and verified partners. One rule, and most of the abuse problem is gone.

The decisions to hand to Claude Code
DecisionBecause
Counter codes in base 62, blocks of 10,000 per serverA fifth of the code space used in 5 years; no collisions
Redirect answers 302, the CDN may keep it 10 sClick counts per campaign; links stay fixable; viral peaks of 5,000 a second
Redis in front of PostgreSQL; unknown codes cached 60 sSale peaks of 1,000 clicks a second on one code; scanners
No write in the redirect: queue + worker every 10 sThe beta: 3,000 updates a second on one row took checkout down
Links only to StayHub pages, by our systems and verified partnersNo scam links on our domain, no email blocking
Each one comes from a number or a requirement in the lesson. Give them to the agent as decisions, not as open questions.

10Your job as lead

When you hand this to Claude Code, give it the decisions, not just the feature: counter codes in base 62, a 302 with a short cache time, Redis in front of the database, and no write in the redirect.

Then read the redirect code yourself. An update to the links table in it is the beta bug. A 301 needs a reason. And before the sale, ask for a load test of one code at 1,000 clicks a second.

Let's recap. A tiny write path, and a huge, skewed read path. Counter codes, a cache for clicks, the CDN for viral links, and counting after the answer. Below the video you'll find the text, the diagrams and ten questions.

Check yourself

0/10 answered
  1. 1In StayHub's short links, which path needs most of the design effort?

  2. 2Codes are 5 characters in base 62. Roughly how many codes is that?

  3. 3After five years, a fifth of all codes are used. With random codes, what happens when a new link is created?

  4. 4Claude Code's redirect handler runs "UPDATE links SET clicks = clicks + 1" on every click. What do you ask for?

  5. 5Why does StayHub answer with a 302 instead of a 301?

  6. 6A viral link brings 5,000 clicks a second. StayHub's 4 app servers handle about 400 a second each. What absorbs the spike?

  7. 7In the beta, why did checkout fail when one short link went viral?

  8. 8Claude Code proposes Kafka and a NoSQL cluster to store new short links. What do you answer?

  9. 9Why are codes that don't exist also kept in the cache for a minute?

  10. 10A partner asks to use stay.hb to shorten links to their own website. What's the best answer for now?

Free account

Save your progress — create a free account

Free. No card. Your finished lessons follow you to any device, and you can ask questions in the community.

Create my free account
Founding members

Every lesson is free while we build. Lock in €9/month for later.

The first 100 members keep the founding price for as long as they stay. Reserving is free: no card, nothing is charged.

See the founding offer

Questions from the community

All questions →