Lesson 1 · Unit 04
Design a URL shortener
Short codes, a fast redirect, and ids that do not collide
What you practise
- Id generation and base-62, read-heavy caching, the redirect path, storage estimate, custom aliases and expiry
Try a question from this lesson
Pick one
A link shortener creates 100 links per second and serves 10,000 redirects per second. Which path deserves the design effort first?
Correct answer
The redirect: looking up a code
Why
There are 100 redirects for every create, and each one sits between a person and the page they clicked. The system is read-heavy, so the lookup of code to URL is the path to make fast and cheap.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Base 62
Give every link a number, then write that number in base 62. It is the same idea as binary or hex, with 62 digits.
Take the remainder to get the last digit, divide, repeat. Link number 3,844 becomes 100, and seven characters can number 3.5 trillion links.
from string import digits, ascii_letters
CHARS = digits + ascii_letters # 62
def encode(n):
s = ""
while n > 0:
s = CHARS[n % 62] + s
n //= 62
return s
print(encode(125), encode(3844))11 more exercises in the app
- 2× type the answer
- 2× order the lines
- 5× multiple choice
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.