Scoping and estimating a link shortener
Turn a one-line shortener prompt into requirements and a three-scenario estimate: why the read:write ratio is an assumption that means clicks per link, average and peak rates, five-year storage, cache memory from distinct hot links, and the click data that outgrows everything else.
Contentsand lesson path
On this page
- The problem
- Step 1: Requirements before numbers
- Step 2: The read:write ratio is an assumption
- Step 3: Run the estimate
- Step 4: What the numbers tell you
- Step 5: What changes when an input changes
- Check your understanding
- Apply it
- Review prompt
Lessons of URL Shortener Design
- Scoping and estimating a link shortener Worked example · 20 min
- Code generation and the data model Worked example · 25 min
- A redirect path that serves 100k reads per second Worked example · 25 min
- Abuse, expiry and analytics without slowing redirects Concept · 15 min
- Shortener design check Knowledge check · 6 questions
What you will learn
- Estimate read/write ratio, storage and cache size for a shortener with stated traffic.
Prerequisites: Requirements & Estimation, Caching Strategies, Unique ID Generation
01. The problem
Suppose you are asked to design lnk.example, a public link shortener. Anyone can paste a long URL and get back a short one such as https://lnk.example/aZ3kP9q; opening the short link sends the browser on to the long URL. Business accounts pay for custom names such as https://lnk.example/spring-sale, expiry dates and click statistics, and they send one short link to hundreds of thousands of people at once in email and text-message campaigns.
A shortener looks like one table and one lookup, so it is tempting to start drawing. The hard parts only show up as numbers: links created and opened per second, average and peak; storage after five years; cache memory; click data. This lesson writes the requirements, then estimates those numbers.
It applies the method of estimating a photo-sharing service (written assumptions, units, three scenarios) without teaching it again. Every number comes from estimate.py, which needs only Python 3.10 or newer. Storage and traffic use decimal units (1 GB = 10^9 bytes); memory uses GiB (2^30 bytes).
02. Step 1: Requirements before numbers
Start with what the system must do. After a talk with the product owner, the core use cases are:
- Anyone can shorten a URL and receive a short link with a random code.
- Opening a short link redirects the browser to its long URL.
- Business accounts can choose a custom alias, set an expiry date, change a link's target and see clicks and unique visitors per day.
- The trust-and-safety team can disable any link.
The non-goals are link previews, QR codes, customers' own domains, live click dashboards and changing a code after it is issued.
Then the non-functional targets, each written so that it can be tested (see targets you can test):
- Latency: 99% of redirects take at most 25 ms inside our servers, measured at the load balancer at peak load in each 5-minute window.
- Availability: 99.95% of valid redirect requests succeed in each 30-day window.
- Durability: a new link is stored on at least two machines before its creator sees it.
- Freshness: a new link works at once for its creator; a disabled or edited link changes for everyone within 5 minutes.
- Statistics: visible within 10 minutes; unique-visitor counts may be off by about 2%.
The last two look like small print, but the freshness target decides how long any cache may keep a redirect (lesson 3), and the tolerance on unique visitors allows an approximate counter (lesson 4).
03. Step 2: The read:write ratio is an assumption
Every shortener estimate needs a read:write ratio, redirects per link created. Before launch nobody can measure it, so treat it as an assumption with a meaning you can check later: in a steady state, the ratio is the average number of clicks a link receives over its whole life.
Here is the reasoning. Suppose 3 million links are created every day and each collects 70 clicks on average over its life, most of them in its first days. Once the service has run for longer than a typical link stays in use, today's clicks come from links of every age, and they add up to about one day's links times 70: 210 million a day. So redirects per second = new links per second × clicks per link, and the ratio is 70:1.
This model leaves things out. Just after launch there are no old links yet, so clicks lag behind creations, and a fast-growing service stays below the steady state for a while. The average is also pulled up by a few viral links, while the median link may be opened only a handful of times. Averages suit rates and totals, which are sums, but they say nothing about which links deserve cache memory (Step 4).
lnk.example has no data of its own, so the estimate uses 40, 70 and 120 clicks per link for the best, expected and worst cases (best means the lightest load we consider plausible). The peak factor, the busiest minute divided by the daily average, is the other key guess: imagine a retailer sending one link to 2 million subscribers at 09:00. The table allows 8, 12 and 18. Writes get a smaller peak, from businesses that create links in bulk before a campaign.
04. Step 3: Run the estimate
Each row of ASSUME is one input with a value per scenario. Byte sizes include the store's or the cache's own overhead per item. hot_days says how recent a link must be to count as worth caching; it gives an upper bound, because many recent links are hardly opened. Save the script as estimate.py.
"""Back-of-the-envelope estimate for the lnk.example shortener (standard library)."""
DAY = 86_400 # seconds
YEARS, REPLICAS = 5, 3
# One column per scenario. Every value is an assumption to check later.
ASSUME = { # best expected worst
"links_per_day": (2e6, 3e6, 4e6),
"clicks_per_link": (40, 70, 120), # over a link's whole life
"read_peak_factor": (8, 12, 18), # busiest minute / daily average
"write_peak_factor": (3, 5, 10),
"record_bytes": (300, 450, 700), # one link in the store
"response_bytes": (500, 700, 1000), # one redirect response
"hot_days": (3, 7, 14), # links young enough to cache
"cache_entry_bytes": (200, 300, 500), # one link in the cache
"event_bytes": (150, 250, 400), # one click event
}
def estimate(a: dict) -> dict:
writes = a["links_per_day"] / DAY
reads = writes * a["clicks_per_link"] # steady state: reads = writes x clicks
links = a["links_per_day"] * 365 * YEARS
raw_tb = links * a["record_bytes"] / 1e12
hot = a["links_per_day"] * a["hot_days"] # upper bound on cached links
clicks = a["links_per_day"] * a["clicks_per_link"] # per day
peak = reads * a["read_peak_factor"]
gbit = peak * a["response_bytes"] * 8 / 1e9
cache_gib = hot * a["cache_entry_bytes"] / 2**30
store_gb = a["links_per_day"] * a["record_bytes"] / 1e9 # growth per day
event_gb = clicks * a["event_bytes"] / 1e9
return {
"read:write": f'{a["clicks_per_link"]}:1',
"writes/s avg|peak": f'{writes:.0f} | {writes * a["write_peak_factor"]:.0f}',
"reads/s avg|peak": f"{reads:,.0f} | {peak:,.0f}",
f"links in {YEARS} years": f"{links / 1e9:.1f} billion",
"store TB raw|x3": f"{raw_tb:.1f} | {raw_tb * REPLICAS:.1f}",
"egress Gbit/s peak": f"{gbit:.2f}",
"cache links|GiB": f"{hot / 1e6:.0f}M | {cache_gib:.1f}",
"clicks per day": f"{clicks / 1e6:.0f}M",
"GB/day links|clicks": f"{store_gb:.1f} | {event_gb:.0f}",
}
names = ("best", "expected", "worst")
cols = [estimate({k: v[i] for k, v in ASSUME.items()}) for i in range(3)]
print(f'{"":20}' + "".join(f"{n:>17}" for n in names))
for row in cols[0]:
print(f"{row:20}" + "".join(f"{c[row]:>17}" for c in cols))python3 estimate.py best expected worst
read:write 40:1 70:1 120:1
writes/s avg|peak 23 | 69 35 | 174 46 | 463
reads/s avg|peak 926 | 7,407 2,431 | 29,167 5,556 | 100,000
links in 5 years 3.6 billion 5.5 billion 7.3 billion
store TB raw|x3 1.1 | 3.3 2.5 | 7.4 5.1 | 15.3
egress Gbit/s peak 0.03 0.16 0.80
cache links|GiB 6M | 1.1 21M | 5.9 56M | 26.1
clicks per day 80M 210M 480M
GB/day links|clicks 0.6 | 12 1.4 | 52 2.8 | 192Check one column by hand before trusting a script:
writes 3,000,000 links a day / 86,400 s about 35 per second
reads 35 x 70 clicks per link about 2,430 per second
peak 2,430 x 12 about 29,000 per second
links 3,000,000 x 365 x 5 about 5.5 billion
store 5.5 billion x 450 bytes about 2.5 TB, 7.4 TB with 3 copies
cache 3,000,000 x 7 days x 300 bytes about 6.3 GB, which is 5.9 GiB
clicks 210 million a day x 250 bytes about 52 GB a day05. Step 4: What the numbers tell you
Reads dominate. Peak redirects run from about 7,400 to 100,000 a second, while writes peak at 463 a second at most, a rate almost any store absorbs. So the design effort goes into the read path, sized for the worst case, 100,000 reads per second: a campaign that cannot be redirected fails in front of the customer's audience. Lesson 3 builds it.
Link storage is modest. After five years the store holds 3.6 to 7.3 billion links: 1.1 to 5.1 TB raw, or 3.3 to 15.3 TB with three copies. Indexes, backups and the free space a store needs to reorganise its files come on top, but it still fits on a handful of machines, so reads and availability, not disk, decide how the data is spread. The link count also sets the code length (lesson 2).
The cache is sized from distinct links. A cache holds each link once, however often it is clicked, so its size is the number of distinct links worth keeping times the bytes per entry, overhead included: here 6 to 56 million recent links, 1.1 to 26.1 GiB, a few cache servers at most. A formula such as requests per day × 20% × bytes counts repeated clicks on one link as separate entries and can overstate memory many times over; treat it as an upper bound at most.
Click data is the big storage line. In the expected case the link store grows by about 1.4 GB a day, but raw click events add about 52 GB a day, some 37 times as much, so lesson 4 counts clicks in a separate pipeline and rolls them up. Egress, the data sent to visitors, stays under 1 Gbit/s even at the worst peak.
06. Step 5: What changes when an input changes
An estimate is most useful when you know which input drives which number. From estimate():
- average reads = links per day × clicks per link; peak reads multiply that by the read peak factor, and egress follows peak reads;
- storage = links per day × days kept × bytes per record;
- cache = links per day × hot days × bytes per cached entry;
- click data = links per day × clicks per link × bytes per event.
So if a large customer doubled the peak factor by mailing twice as many people at once, only peak reads and egress would double: servers and cache need more room, but storage does not move, as no extra links are created. Twice-as-long URLs would grow storage and cache memory while every rate stayed put.
Links per day appears in every row, so it is the first forecast to confirm. The byte sizes are the cheapest to measure: write 10,000 real URLs into a test store and read its size.
07. Check your understanding
08. Apply it
Start the design doc that this skill asks for: a shortener with 100 million new links a month and a 100:1 read ratio.
- Write the requirements: four to six use cases, the non-goals, and latency, availability, durability and freshness targets in the testable form of Step 1.
- Convert 100 million a month into links per day, set it as the expected value in
ASSUME, and choose your own best and worst values for every other row. Give each a one-line reason. - Run
estimate.pyand write what your numbers say, as in Step 4. - Name the two assumptions you would measure first, and how.
09. Review prompt
Without looking back: what does a shortener's read:write ratio mean in a steady state, and why does it not hold just after launch? Which inputs drive peak reads, storage, cache memory and click data? Why is a cache sized from distinct links? Which figures size servers and which size disks? Which line grows fastest for lnk.example?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.