The whole course ▾
System Design · Mock interview 1 of 20
Design a URL shortener (Bitly)
Design a URL shortener like Bitly.
Try it first
Before you read the interview, answer the question yourself. Give yourself 10 minutes: say your design out loud, or sketch it on paper. What would you ask? Which numbers matter? Which boxes, and what's the hard part? Then read on, and score yourself with the feedback at the end.
Got a doubt? Ask in the comments under the video.Subscribe
Requirements
Requirements
Clarifying questions
->
Custom short names? -> Yes, optional
->
Do links expire? -> If the user asks
->
How many new links? -> 100M a month
->
Count clicks? -> Yes, per link
Functional requirements
Shorten a long URL
Redirect a short code to it
Optional custom alias
Optional expiry date
Count the clicks on each link
Non-functional requirements
->
100M new links a month
->
100 redirects for every new link
->
Redirects fast: under 100 ms
->
Always up: links live everywhere
->
No two links share a code
Out of scope
Accounts and a dashboard
Editing where a link points
Spam and malware checks
interviewer
Hi, thanks for joining. Let's get straight into it.
candidate
Sounds good. I'll use the whiteboard as I go, if that's okay.
interviewer
So, today I'd like you to design a URL shortener. Something like Bitly.
candidate
Okay. So a user pastes a long link, gets a short one back, and anyone who opens the short one lands on the long one. Before I draw anything, can I ask a few questions?
interviewer
Sure, go ahead.
candidate
Can users pick a custom short name, like slash big-sale?
interviewer
Yes, but it's optional.
candidate
Do links expire?
interviewer
Only if the user sets a date.
candidate
Roughly how many new links should I plan for?
interviewer
About a hundred million a month.
candidate
And do we need to count clicks?
interviewer
Yes. A click count for every link.
candidate
Okay, let me write down what it has to do. Shorten a long URL. Redirect anyone who opens the short code. An optional custom alias. An optional expiry date. And count the clicks on each link.
interviewer
Good.
candidate
Then how well it has to do it. A hundred million new links a month. I'd guess around a hundred redirects for every link created. Is that fair?
interviewer
That's fair.
candidate
So it's mostly reads. Redirects should be fast, under a hundred milliseconds, so nobody notices them. It has to stay up, because short links get printed on posters and sit in old emails. And no two links can ever share a code, or someone lands on the wrong page.
candidate
And I'll leave a few things out, unless you want them: user accounts and a dashboard, editing where a link points, and scanning links for spam and malware. A real product needs that last one, but not today. Does this match what you had in mind?
interviewer
Yes, that's the scope. Go ahead.
Estimation
Estimation
Back of the envelope
100M a month ÷ 30 ~ 3.3M links a day
3.3M ÷ 100,000 s ~ 35 writes/s
× 100 = 3,500 reads/s; peak ~ 10,000/s
5 years: 6B links × 500 B ~ 3 TB
7 base62 characters: 62⁷ ~ 3.5 trillion codes
WHAT THE NUMBERS DECIDE
10,000redirects/satpeak:
designforreads.3.5trillion
codesfor6billionlinks:7
charactersisplenty.
candidate
Let me size it quickly. Only the numbers that change a decision.
interviewer
Sure. How big does this get?
candidate
I'll use two shortcuts: a day is about a hundred thousand seconds, and the peak is about three times the average.
candidate
A hundred million a month is about three point three million a day. Divided by a hundred thousand seconds, that's about thirty-five writes a second. Reads are a hundred times that, three and a half thousand a second, with a peak around ten thousand. Over five years that's six billion links, at about five hundred bytes each: three terabytes. And for the code length, seven characters from sixty-two symbols give about three and a half trillion codes.
candidate
So, what this tells me. Ten thousand redirects a second against thirty-five writes: I'm designing for reads. Seven characters is plenty. And three terabytes fits on one database server, so storage isn't the hard part. Speed is, and never handing out the same code twice.
interviewer
Agreed. Keep going.
API and data
API and data
Links
code (key), long_url,
expires_at
Click counts
code, day, count
1 : many
Endpoints
1
POST /urls -> 201 + the short
URL
2
GET /{code} -> 302 to the long
URL
3
409 alias taken · 404 unknown ·
410 expired
candidate
Next, the API, and what we store.
interviewer
What does the API look like?
candidate
Two endpoints. For each one I'll say the method, the path, what goes in, and what comes back, including the errors.
candidate
POST slash urls takes the long URL, plus an optional alias and expiry date, and returns two hundred and one, created, with the short URL. GET slash the code returns a redirect: a three hundred and two, with the long URL in the Location header, and the browser follows it on its own. And the errors: four hundred and nine if the alias is taken, four hundred and four for a code that never existed, and four hundred and ten, gone, for one that expired.
candidate
For the data, two tables. Links: the code as the primary key, the long URL, when it was made, and when it expires. And click counts: how many clicks each code got on each day. Every redirect is a lookup by one key.
interviewer
Which database would you pick?
candidate
Postgres. Three terabytes is small, and the primary key gives me something for free: the database itself refuses a duplicate code.
High-level design
High-level design
User
API
servers
several
copies
Code
generator
Links DB
Postgres
POST
/urls
1
new code?
2
save the link
3
201 +
short URL
4
Visitor
clicks
the
link
Destination
site
GET /aB3x9Kp
find the code
302 + Location
opens it
On every redirect
1
Find the code: one key lookup
2
Expired? -> 410 Gone
3
Count the click
4
Answer 302 with the long URL
TWO PROMISES
Everyredirectisone
keylookup,andnotwo
linksevergetthesame
code.
candidate
Okay. Let me draw the high-level design.
interviewer
Walk me through it, one request at a time.
candidate
Sure. Two paths: creating a link, and following one. I'll number the steps, starting with creating a link.
candidate
The user sends POST slash urls to the API servers. There are several identical copies, so any of them can answer. The server asks a code generator for a fresh code, saves the code and the long URL in the links DB, and returns the short URL. If the user asked for a custom alias, the server skips the generator and saves the alias instead. And if the database rejects it as a duplicate, the user gets a four hundred and nine.
candidate
Now the path that's used a hundred times more. A visitor clicks the short link, and the browser sends GET slash the code. The API server looks the code up in the links DB by its primary key, in about a millisecond, and answers three hundred and two with the long URL. The browser opens the destination site by itself.
interviewer
How long does our part take?
candidate
A few milliseconds. Almost all of the waiting is the network, and the site itself.
candidate
So on every redirect the server does four things, in this order. Find the code: one key lookup. Check whether it has expired, and if it has, return four hundred and ten. Count the click. And answer with the three hundred and two.
interviewer
That third step is a database write on every single click.
candidate
Right. I'll come back to that.
interviewer
So what does this design promise?
candidate
Two things. Every redirect is a single key lookup, with nothing slow in its way. And no two links ever get the same code. That one depends on the code generator.
interviewer
Then let's go there.
Deep dive: unique codes
Deep dive: unique codes
Hash the long URL
Hash it, keep 7 characters
Same URL, same code
Collisions: look up, then retry
Count, then base62
The next number from a counter
Written in base62
Never collides, never retries
THE CHOICE
Acounter,writtenin
base62:uniqueby
construction,sono
lookupsandnoretries.
Link number 1,000,000,000 -> 15FTGg
High-level design
User
API
servers
several
copies
Code
generator
Links DB
Postgres
POST
/urls
1
new code?
2
save the link
3
201 +
short URL
4
Visitor
clicks
the
link
Destination
site
GET /aB3x9Kp
find the code
302 + Location
opens it
ID
counter
next free
number
1,000 at a time
block of 1,000
On every redirect
1
Find the code: one key lookup
2
Expired? -> 410 Gone
3
Count the click
4
Answer 302 with the long URL
TWO PROMISES
Everyredirectisone
keylookup,andnotwo
linksevergetthesame
code.
interviewer
I want to dig into the box you haven't explained yet.
interviewer
How does the code generator make codes that are short, and never repeat?
candidate
I see two options. Let me compare them, then pick one.
candidate
Option one: hash the long URL, say with MD5, and keep the first seven characters. The same URL always gets the same code, which is nice. But two different URLs can share those seven characters, and with billions of links it will happen. So every new link needs a lookup first, and a retry when the code is taken. Option two: a counter. Each new link takes the next number, one, two, three, and I write that number in base sixty-two. Two links never share a number, so they can never share a code.
candidate
I'd go with the counter. It's unique by construction, so creating a link never needs a lookup or a retry. Base sixty-two is ten digits, twenty-six small letters and twenty-six capitals. Link number one billion is just six characters: one, five, capital F, capital T, capital G, small g. Six billion links still fit in six characters.
interviewer
And where does the counter live?
candidate
In a small database: an ID counter, one row that only ever counts up. But asking it for every new link would make it the bottleneck. So each generator takes numbers in blocks, a thousand at a time, and hands them out from memory. Ten thousand new links are just ten trips to the counter. And if a generator crashes, the rest of its block is never used. Gaps in the numbers cost nothing.
interviewer
Counted codes are guessable, though. If my link ends in a small g, the one made before it ends in an f. Is that a problem?
candidate
For public links, usually not. But if links can be private, I'd scramble the number before encoding it, with a fixed, reversible shuffle of its bits. Neighbours turn into codes that look random. And they're still unique, because the shuffle never maps two numbers to the same result.
interviewer
What if someone's custom alias is a code the counter reaches later?
candidate
The primary key catches it. The insert is refused, and the generator moves on to its next number. That's the one rare retry in the whole design, and it's safe, because the database enforces uniqueness, not my code.
interviewer
Good.
Deep dive: redirects at scale
Deep dive: redirects at scale
301: moved permanently
The browser remembers it
Repeat clicks skip our servers
We never see those clicks
302: found, for now
Every click reaches us
Every click is counted
Expiry works at once
High-level design
User
API
servers
several
copies
Code
generator
Links DB
Postgres
POST
/urls
1
new code?
2
save the link
3
201 +
short URL
4
Visitor
clicks
the
link
Destination
site
GET /aB3x9Kp
find the code
302 + Location
opens it
ID
counter
next free
number
1,000 at a time
block of 1,000
Cache
hot
codes
in
memory
Read
replicas
copies of
Links DB
check first
on a miss
copy
30 GB
one row, 17,000 writes/s
Click
log
one
line per
click
Tally job
adds up
every
minute
a click
in batches
one total
On every redirect
1
Find the code: one key lookup
2
Expired? -> 410 Gone
3
Count the click
4
Answer 302 with the long URL
TWO PROMISES
Everyredirectisone
keylookup,andnotwo
linksevergetthesame
code.
interviewer
Let's switch to the side with all the traffic.
interviewer
Redirects outnumber new links a hundred to one. How do you keep them fast, and the system up?
candidate
First, a choice that matters a lot here: which redirect we send back.
candidate
A three hundred and one says the link moved permanently. The browser remembers it and sends repeat clicks straight to the destination. Less traffic for us, but we never see those clicks, and an expired link can keep working in that browser. A three hundred and two says found, for now, so every click comes back to us. Every click is counted, and expiry works at once. We have to count clicks, so I'd send three hundred and two, and pay for it with more traffic.
candidate
So I make those reads cheap. Clicks are lopsided: a small share of links gets most of them. The top one percent is sixty million links at five hundred bytes each, about thirty gigabytes, which fits in memory. So the API servers check a cache first, and only go to the database on a miss. And those misses go to read replicas, copies of the links DB, so the main one only takes writes.
interviewer
Makes sense.
interviewer
Okay. A link goes viral: a million clicks in one minute. What breaks?
candidate
Let me walk one click through the board, box by box.
candidate
A million a minute is about seventeen thousand redirects a second, all for one code. The lookup is fine: the cache answers every one of them, and the database never sees them. What breaks is the counting. Seventeen thousand updates a second to the same row of click counts, each one waiting for the one before it. That one row becomes the bottleneck of the whole system.
candidate
So I'd stop counting inline. The API server appends one line per click to a click log, which takes microseconds and locks nothing, and answers the visitor straight away. A tally job reads the log, adds up the clicks for each code, and writes one total a minute. A million clicks become one database write.
interviewer
So the counts lag a little?
candidate
About a minute. For a click counter, that's fine.
Wrap-up
Wrap-up
Next steps
1
Load balancers in front
2
One main database: replicas, then sharding
3
A nightly job deletes expired links
4
Watch latency, 404s and cache hits
5
Block spam and malware links
INTERVIEWER'S FEEDBACK
Strong:questionsfirst,numbers
thatdecided,codesuniqueby
design.Nexttime:raisetherisky
boxyourself.Verdict:hire,mid-level.
interviewer
We're almost at time.
interviewer
What would you improve with more time?
candidate
A few things. Let me list them, starting with the biggest risk.
candidate
First, load balancers in front of the API servers. Second, the main database is still one machine: replicas first, and later sharding by code. Third, a nightly job that deletes expired links. Fourth, I'd watch redirect latency, the rate of four hundred and fours, and the cache hit rate. They're the three numbers that warn you first. And fifth, I'd check new links against spam and malware lists, before someone's scam goes out under our name.
interviewer
Okay, let's stop there. A few thoughts. That was solid. You asked before you drew, your numbers actually drove decisions, and your codes are unique by design, not by luck. One thing to work on: you explained the code generator only when I asked. Bring up the risky box yourself next time. I'd say a hire at mid-level, and close to senior.
candidate
Thank you, that's really helpful.
Interviewer's feedback
Strong: questions first, numbers that decided, codes unique by design. Next time: raise the risky box yourself. Verdict: hire, mid-level.
Score yourself
Interviewers score these seven things. Give your own attempt a tick for each one you did.
- Asks before drawing. Agrees what the system does, and how well: scale, speed, consistency.
- Turns users into requests a second and bytes a day, and says what the numbers decide.
- A small, clear contract, and a data model that fits how the data is read.
- A working path end to end before any detail. Every box has a reason.
- Picks the hard parts, compares two options, and chooses one with a trade-off said out loud.
- What breaks, what happens then, and how users notice. Retries, duplicates, limits.
- Thinks out loud, checks in with the interviewer, and takes a hint without losing the thread.
0 of 7
Your progress stays on this device.
New System Design videos at 6 pm
Lessons on weekdays, the week's revision on Saturday, a mock interview on Sunday.