Courses / System Design Interview / Chapter 34
Module 8 · Design Problems III: Links, Crawling and Collaboration · Chapter 34 of 49
Design a URL Shortener like TinyURL
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Back-of-the-Envelope Estimates, DNS: Turning Names into Addresses, Databases: Choosing, Replicating and Partitioning, Content Delivery Networks, Unique IDs: Sequencers, UUIDs and Snowflake IDs, Distributed Caches, Distributed Message Queues and Rate Limiters. Next up: Design a Web Crawler.
Part 1 · Requirements and estimates
What the service must do
A URL shortener turns a long web address into a short one and sends anyone who opens the short link to the long one. The problem is small to state, and it is a good place to study ids, caching and what an HTTP redirect really means.
The functional requirements are: create a short link for a long URL; send a visitor who opens the short link to the long URL; let the creator choose a custom alias if it is free; let a link expire; and count visits. Editing the target of a link, user accounts with teams, and link previews are out of scope.
The non-functional requirements come from who is affected. A short link is pasted into messages, printed on posters and read out on the radio. If the redirect fails, someone else's page is broken, so availability matters more than almost anything else. A redirect must be fast, because it adds a step before the page the visitor wanted; we set a target of about 50 milliseconds on the server side. A code, once issued, must keep pointing to the same URL until it expires. Creating a link may be slower and may fail more often than redirecting.
| Question to ask | Answer we assume |
|---|---|
| How many new links? | 5 crore a month |
| How many redirects? | 100 for each link created |
| How long is a code? | 7 characters of letters and digits |
| How long do links live? | Until they expire or are disabled; plan for five years |
| How big is a record? | About 400 bytes with the long URL and dates |
| Do codes need to be secret? | No. A code is public, and a link is not a password |
Traffic and storage
The estimate follows the pattern of the estimates chapter: requests a second, then storage, then the size of the code space, then how much to keep in memory. The scene walks through traffic and storage.
Plan redirects for: ≈ 5,800 /s (the peak, about 3 times the average)
Read it as steps
A few thousand redirects a second and about a terabyte after five years.
The same arithmetic as code lets you change an assumption and see what moves.
# Assumptions of ours. new_links_per_month = 5_00_00_000 # 5 crore reads_per_link = 100 # redirects per link created record_bytes = 400 # code, long URL, owner, dates years = 5 month = 30 * 86_400 writes_per_s = new_links_per_month / month reads_per_s = writes_per_s * reads_per_link peak = 3 # busiest second vs average print(f"creates/s avg {writes_per_s:>7,.0f} " f"peak {writes_per_s * peak:>7,.0f}") print(f"redirects/s avg {reads_per_s:>7,.0f} " f"peak {reads_per_s * peak:>7,.0f}") links = new_links_per_month * 12 * years print(f"links after {years} years: {links:,}") print(f"storage: {links * record_bytes / 1e12:.2f} TB " f"(x3 replicas: {links * record_bytes * 3 / 1e12:.2f} TB)")
Python 3.12.10. Save this and the next block together as shortener_estimate.py.
# How many codes must we be able to name? 7 characters of [0-9a-zA-Z]. space = 62 ** 7 print(f"62^7 = {space:,} codes; " f"{links / space:.2%} used after {years} years") # Starting guess: a cache for 1% of all links; a later lesson tests it. hot = links * 0.01 print(f"cache sized for 1% of links: {hot:,.0f} links, " f"{hot * record_bytes / 1e9:.0f} GB")
Continue in the same file.
Reading the numbers
Creating 19 links a second is a trivial write load. Redirecting 1,929 times a second on average and 5,787 at the busiest second is more, but still small beside the services in the other case chapters. A single well-provisioned database could hold the whole table, since 300 crore links at 400 bytes is 1.2 TB, or 3.6 TB with three replicas. The reason to design more than one machine is therefore not capacity. It is availability: one machine that fails takes every short link down.
The workload is read-heavy, with 100 redirects for each create. That points to caching. The script's last line sizes a cache for 1 percent of all links as a starting guess: 3 crore links at 400 bytes is 12 GB, which fits in the memory of one cache node. How many redirects that cache would absorb depends on how uneven the traffic is, which we do not know yet. The fifth lesson measures it on a made-up trace and finds the guess too small for that trace.
Code length comes from the code space. Seven characters drawn from 62 symbols, the ten digits and the two cases of the alphabet, give 62^7, or 3,521,614,606,208 codes, about 3.5 lakh crore. Three hundred crore links use 0.09 percent of that. Six characters would give 62^6, which is about 5,680 crore codes, enough for the first five years but with less room for random choice. We pick seven.
Why is the design needed for availability and not for capacity, using the numbers above?
- Five years of links is about 1.2 TB, which fits one database. A single machine would still be a single point of failure for every short link.
What share of the 7-character code space do five years of links use?
- 0.09 percent: 300 crore links out of about 3.5 lakh crore possible codes.
What does the script assume to arrive at a 12 GB cache?
- A cache sized for 1 percent of the links, 3 crore of them, at 400 bytes each. It is a starting guess, not a measured hit ratio, and a later lesson tests it on a made-up trace.
Part 2 · API and data model
The API
Two calls carry almost all the traffic: create a link and follow a link. A few more manage links. The creator's calls need authentication, and the redirect never does, since anyone with the link must be able to follow it.
POST /v1/links HTTP/1.1 Authorization: Bearer <token> Content-Type: application/json {"url": "https://example.com/a/very/long/path?x=1", "alias": "chai-menu", "expires_at": "2027-03-31T18:30:00Z"}
Create a link. The alias and expiry are optional.
{
"code": "chai-menu",
"short_url": "https://sho.example.com/chai-menu",
"expires_at": "2027-03-31T18:30:00Z"
}The reply, with status 201 Created.
GET /chai-menu HTTP/1.1
Host: sho.example.comFollowing a link: no authentication.
| Call | What it does | Notes |
|---|---|---|
POST /v1/links | Create a link | Returns 409 if the alias is taken, 400 for a bad URL |
GET /{code} | Redirect to the long URL | The hot path; 404 unknown, 410 expired or disabled |
DELETE /v1/links/{code} | Disable a link | Only the owner; takes effect everywhere quickly |
GET /v1/links/{code}/stats | Click counts | Eventually consistent |
| Status | When the service returns it |
|---|---|
201 Created | The link exists; the body holds the code and the short URL |
400 Bad Request |
The table
The link table is keyed by code. A redirect is a lookup by that key and nothing else, so the primary key is the only index it needs. A second index on (owner, created_at) supports the creator's list. Clicks go into a separate table, because they are written far more often than links and are only read in aggregate.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE link ( code TEXT PRIMARY KEY, -- the short code long_url TEXT NOT NULL, owner INTEGER, -- NULL for anonymous links created_at INTEGER NOT NULL, expires_at INTEGER, -- NULL means never disabled INTEGER NOT NULL DEFAULT 0 -- 1 after an abuse report ); CREATE INDEX link_by_owner ON link (owner, created_at DESC); CREATE TABLE click ( -- analytics, written later code TEXT NOT NULL, at INTEGER NOT NULL, country TEXT); """)
Python 3.12.10 with sqlite3. Save this and the next block as shortener_schema.py.
db.execute("INSERT INTO link (code, long_url, created_at)" " VALUES ('aB3xY9k', 'https://example.com/long', 1000)") try: db.execute("INSERT INTO link (code, long_url, created_at)" " VALUES ('aB3xY9k', 'https://example.com/other', 1001)") except sqlite3.IntegrityError as e: print("second insert of the same code:", e) print(db.execute("EXPLAIN QUERY PLAN SELECT long_url FROM link" " WHERE code = 'aB3xY9k'").fetchall()[0][3])
Continue in the same file: a duplicate code, then the query plan of a lookup.
second insert of the same code: UNIQUE constraint failed: link.code SEARCH link USING INDEX sqlite_autoindex_link_1 (code=?)
Output of the script.
The primary key makes a duplicate code impossible, and the database says so. This matters for more than aliases. When two requests try to create the same alias at the same moment, the unique constraint decides the winner and the other receives an error, with no locking in our code. The second line of output shows that a lookup by code is a search on the primary key's index, which is the cheapest query a database has.
At the scale of 300 crore rows, the table is split by code, using the partitioning ideas of the databases chapter. A hash of the code picks the partition, so a redirect goes to exactly one. Range partitioning would put codes issued around the same time together, which would make new links hot; hashing spreads them. The disabled column and expires_at let a link be switched off without deleting its row, so a later request can answer 410 Gone and not 404.
Part 3 · High-level design
Two paths
The service has two paths with very different loads. The create path accepts a long URL, gets a code, saves the pair and returns the short URL. It handles about 19 requests a second. The redirect path takes a code, finds the long URL and answers with a redirect. It handles about 1,929 a second on average and is where the design effort goes.
Both paths go through stateless API servers behind a load balancer. Behind them are three things. A code allocator hands out codes, described in the next lesson. A database holds every link, partitioned by code with replicas for availability. A cache holds recently used links in memory, so most redirects never reach the database.
Watch for a create writing once while redirects mostly stop at the cache
Read it as steps
A create writes once; redirects then mostly stop at the cache.
In the scene the create path touches the allocator and the database and never the cache. The redirect path touches the cache first, and only a miss goes on to the database, which then fills the cache. Nothing on the redirect path writes: counting clicks is done off to the side, which the sixth lesson covers.
Why this shape
The allocator is separate because it is the only part that needs coordination. If every API server invented its own code, two could pick the same one. Giving each server its own block of numbers, as the sequencer chapter described for range allocation, means the allocator is called once per block and not once per link. A server that loses contact with the allocator can keep issuing codes until its block runs out.
The cache sits in front of the database, in the cache-aside pattern of the cache chapter: look in the cache, and on a miss read the database and fill the cache. A link almost never changes, so stale data is rarely a problem. The exceptions are a link that is disabled or expires, and the fifth lesson shows how the cache must handle them.
| Part | Scales by | If it fails |
|---|---|---|
| API servers | More stateless copies | The load balancer routes around them |
| Code allocator | Rarely called; a replicated service | Servers use the rest of their current block |
| Cache | Sharding by code | Reads fall through to the database, which sees more load |
| Link database | Partitions and replicas | A replica takes over; the cache serves hot links meanwhile |
Replicas and regions
Reads can also be served by database replicas, since a link rarely changes and a replica a second behind is fine. The one exception is the creator's own first click straight after creating: if it hits a replica that has not yet received the row, it would see a 404. Sending the creation response through the primary, or retrying a miss once against the primary, fixes it, as the databases chapter explained for read-your-writes.
The last decision is where the redirect path runs. Visitors are everywhere, and a round trip across the world adds delay the visitor feels, as the cdn chapter showed. The redirect path can therefore run in several regions, with DNS sending each visitor to a near one, as in the dns chapter. Each region holds a copy of the links and its own cache. Creates go to one primary region and replicate out. A link created a moment ago may not have reached a distant region yet, so a miss there is retried once against the primary before the service answers 404.
Why does the redirect path never write to the database?
- Writing on every click would add load to the busiest path. Clicks are counted off the hot path, in batches.
Why is a code allocator handing out blocks better than one that issues each code?
- It is called once per block, so it is not a bottleneck, and a server can keep working for a while if the allocator is unreachable.
In the scene, what fills the cache?
- The API server, after the database answers a miss. The first click pays for the lookup, and later clicks hit the cache.
Part 4 · Deep dive: short codes
Counter and base 62
A base 62 number uses 62 symbols, here 0-9, A-Z and a-z, as its digits. Turning a counter into a code is a change of base: divide by 62 repeatedly and map each remainder to a symbol. It is the same idea as writing a number in binary or hexadecimal, with a bigger alphabet. Seven digits cover the numbers up to 62^7 - 1.
The first scheme is a counter. Each new link takes the next number and encodes it. There can be no collision, because each number is issued once. The cost is coordination: a single counter is a single point of failure, and the fix is the range allocation of the sequencer chapter, where each API server takes a block of, say, 1,000 numbers and works through it alone.
The drawback is that codes are predictable. The 1000th link has a code next to the 1001st, and anyone can walk through all links by counting. Predictable codes are not a security problem if links are public, but they let a scraper list every link and let a competitor see how many you create. A cheap remedy is a reversible shuffle: multiply the counter by a constant that has no common factor with 62^7, and take the remainder. Different numbers still give different codes, since the multiplication is reversible, but the codes no longer count up by one. The shuffle is weak: for small counters the first character is still 0, and each code differs from the previous one by the same step. It hides the order from a glance, nothing more.
import string ALPHABET = (string.digits + string.ascii_uppercase + string.ascii_lowercase) SPACE = 62 ** 7 def to_base62(n, width=7): out = [] while n: n, r = divmod(n, 62) out.append(ALPHABET[r]) return "".join(reversed(out)).rjust(width, ALPHABET[0]) def from_base62(s): n = 0 for ch in s: n = n * 62 + ALPHABET.index(ch) return n K = 3_141_592_653 # gcd(K, 62^7) is 1, so the shuffle reverses
Python 3.12.10. Save these three blocks together as codes.py.
def scramble(n): """A reversible shuffle of 0..62^7-1. It hides the order of the counter from casual readers; it is not a secret.""" return (n * K) % SPACE for n in (1, 2, 3, 3_000_000_000): print(f"counter {n:>13,} plain {to_base62(n)}" f" scrambled {to_base62(scramble(n))}") print("round trip ok:", from_base62(to_base62(123456789)) == 123456789) print("100,000 scrambled values distinct:", len({scramble(n) for n in range(100_000)}) == 100_000)
Continue in codes.py: the shuffle and a first run.
Random codes and collisions
The scheme above is obfuscation, not secrecy. Anyone who creates two links in a row sees the constant, because the difference between consecutive scrambled values is the multiplier, taken modulo 62^7. The shuffle is just a multiplication. If a link must not be guessable, protect it with authentication, not with an unusual code.
The second scheme needs no coordination at all: pick seven random symbols and try to insert them. If the code already exists, the unique constraint rejects the insert and we pick again. How often does that happen? The birthday bound from the sequencer chapter gives the chance of a repeat among n random picks from N possibilities. The script checks the formula first on a small space, where a simulation is cheap, and then applies it to our numbers.
import math, random def p_any_collision(n, space): """Birthday bound: chance that some two of n random codes match.""" return 1 - math.exp(-n * (n - 1) / (2 * space)) # A small code space, so the formula can be checked by simulation. space, n, trials = 62 ** 3, 500, 2000 rnd = random.Random(1) hits = sum(len({rnd.randrange(space) for _ in range(n)}) < n for _ in range(trials)) print(f"62^3 = {space:,}, {n} random codes:") print(f" formula {p_any_collision(n, space):.3f}," f" simulated {hits / trials:.3f}") print("random 7-char codes pairs that match new code collides") for n in (1_000_000, 100_000_000, 3_000_000_000): print(f"{n:>19,} {n * n / (2 * SPACE):>16,.1f}" f" {n / SPACE:>16.4%}")
Continue in codes.py.
62^3 = 238,328, 500 random codes: formula 0.408, simulated 0.406 random 7-char codes pairs that match new code collides 1,000,000 0.1 0.0000% 100,000,000 1,419.8 0.0028% 3,000,000,000 1,277,823.0 0.0852%
Output of the second block.
For 500 random codes in a space of 62^3, the formula gives 0.408 and 2,000 simulated trials gave 0.406, so we can trust it. Now the real sizes. With 300 crore random 7-character codes and no checking, there would be about 12.8 lakh matching pairs, so collisions are certain over the life of the service. The number that matters is the last column: when 300 crore links exist, a new random code collides with an existing one 0.0852 percent of the time. Each insert is retried on a collision, so on average it takes about 1.001 tries.
The collision rate rises as the table fills. At 10 crore links it is 0.0028 percent. The expected number of tries for one insert is 1 divided by the free fraction, so even at half full it is two. The scheme is safe as long as the table is far from full and the insert is a conditional one that the database can refuse.
Part 5 · Deep dive: redirects and caching
Which redirect
A redirect is an HTTP response with a status code in the 3xx range and a Location header holding the new address. Four codes are in common use, and RFC 9110 defines how they differ. 301 Moved Permanently and 308 Permanent Redirect say the move is permanent, and both are heuristically cacheable, so a browser or a proxy may remember the answer and skip our server next time. 302 Found and 307 Temporary Redirect say the move is temporary, and the RFC does not give them that default.
The other difference is the request method. For 301 and 302 the RFC says a client may change a POST into a GET when it follows the redirect, which is old behaviour kept for compatibility. 307 and 308 are the method-preserving redirects: 307 requires the client to keep the method, and the RFC adds 308 for the same purpose on permanent moves. We built a small server to see this. It answers /301/aB3xY9k, /302/aB3xY9k and so on with the chosen status, and also answers a plain /aB3xY9k with 302. The first two blocks are its storage and cache; the third is the handler.
import sqlite3, sys from collections import OrderedDict from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer db = sqlite3.connect(":memory:", check_same_thread=False) db.execute("CREATE TABLE link (code TEXT PRIMARY KEY, long_url TEXT)") TARGET = "http://127.0.0.1:55523/echo" # where our one link points db.execute("INSERT INTO link VALUES ('aB3xY9k', ?)", (TARGET,)) class LRU: def __init__(self, capacity): self.capacity, self.items = capacity, OrderedDict() def get(self, key): if key in self.items: self.items.move_to_end(key) # most recently used return self.items[key] def put(self, key, value): self.items[key] = value self.items.move_to_end(key) if len(self.items) > self.capacity: self.items.popitem(last=False) # drop the oldest
Python 3.12.10. Save these three blocks together as server.py. Save the first two together as core.py as well.
cache = LRU(1000) counts = {"hit": 0, "miss": 0} def lookup(code): """Return (long_url or None, 'hit' or 'miss').""" url = cache.get(code) if url is not None: counts["hit"] += 1 return url, "hit" counts["miss"] += 1 row = db.execute("SELECT long_url FROM link WHERE code = ?", (code,)).fetchone() if row: cache.put(code, row[0]) return (row[0] if row else None), "miss"
Continue: the cache lookup.
What the server showed
curl -sI http://127.0.0.1:55523/301/aB3xY9k # also 302, 307, 308 curl -sI http://127.0.0.1:55523/nope123 curl -sL -d x=1 http://127.0.0.1:55523/301/aB3xY9k
From another terminal. The last command follows the redirect with a POST.
$ curl -sI http://127.0.0.1:55523/301/aB3xY9k HTTP/1.0 301 Moved Permanently Location: http://127.0.0.1:55523/echo X-Cache: miss $ curl -sI http://127.0.0.1:55523/302/aB3xY9k HTTP/1.0 302 Found Location: http://127.0.0.1:55523/echo X-Cache: hit $ curl -sI http://127.0.0.1:55523/307/aB3xY9k HTTP/1.0 307 Temporary Redirect Location: http://127.0.0.1:55523/echo X-Cache: hit $ curl -sI http://127.0.0.1:55523/308/aB3xY9k HTTP/1.0 308 Permanent Redirect Location: http://127.0.0.1:55523/echo X-Cache: hit $ curl -sI http://127.0.0.1:55523/nope123 HTTP/1.0 404 Not Found POST to /301/aB3xY9k, followed with -L: got GET POST to /302/aB3xY9k, followed with -L: got GET POST to /307/aB3xY9k, followed with -L: got POST POST to /308/aB3xY9k, followed with -L: got POST
Output, trimmed to the status line, Location and X-Cache of each reply.
Each status code came back as asked and carried the same Location. The first request was a cache miss and the rest were hits, since the cache now held aB3xY9k. The unknown code returned 404. In the last four lines curl followed the redirect with -L after a POST: with 301 and 302 the target saw a GET, with 307 and 308 it saw a POST. The RFC only says a client may change the method on 301 and 302, and curl does it unless told otherwise, so the safe way to keep the method is to use 307 or 308.
Which one should a shortener use? For most links, 302. It is not cached by default, so every click reaches us. That is what lets us count clicks, switch a link off, let it expire and change where it points without anyone's browser holding on to an old answer. A permanent redirect saves us traffic, but it hands control to every cache in between: a browser that remembers a 301 will keep going to the old target after we disable the link. Use 301 or 308 only for links that will never be counted or revoked, and consider adding an explicit Cache-Control header whichever you pick. The RFC also notes that 308 is younger than the others (2014) and may not be recognised everywhere.
An LRU cache in front of the database
The redirect lookup uses the cache-aside pattern from the cache chapter. The LRU class in core.py evicts the least recently used link when the cache is full, and lookup returns the long URL and whether the cache had it. How big must the cache be? The script below draws 2 lakh requests over 20,000 links with a skewed popularity, in which link number 1 is twice as popular as link number 2, three times as popular as number 3, and so on, a distribution called Zipf with exponent 1. Then it replays the trace against caches of different sizes and counts the database reads.
import random, time from core import LRU, db N = 20_000 # distinct links rows = [(f"c{i}", f"https://example.com/{i}") for i in range(N)] db.executemany("INSERT INTO link VALUES (?, ?)", rows) rnd = random.Random(3) weights = [1 / (rank + 1) for rank in range(N)] # Zipf with s = 1 trace = [f"c{i}" for i in rnd.choices(range(N), weights, k=200_000)] print("cache size hit ratio sqlite reads time (this machine)") for size in (0, 100, 200, 1000, 5000): cache, reads = LRU(size), 0 t0 = time.perf_counter() for code in trace: if size and cache.get(code) is not None: continue row = db.execute("SELECT long_url FROM link WHERE code = ?", (code,)).fetchone() reads += 1 if size: cache.put(code, row[0]) secs = time.perf_counter() - t0 print(f"{size:>10,} {1 - reads / len(trace):>8.1%}" f" {reads:>12,} {secs:>6.2f} s")
Save as trace.py next to core.py and run: python trace.py
cache size hit ratio sqlite reads time (this machine)
0 0.0% 200,000 0.34 s
100 35.3% 129,323 0.28 s
200 43.0% 113,979 0.25 s
1,000 61.3% 77,389 0.19 s
5,000 80.5% 39,064 0.13 sOutput. The time column is on this machine and varies from run to run.
Reading the trace
With no cache, all 2 lakh requests read the database. A cache holding 100 links, 0.5 percent of them, absorbs 35.3 percent of the requests. The 1 percent size from the first lesson, 200 links, absorbs 43.0 percent. A cache of 1,000 links, 5 percent, absorbs 61.3 percent, and one of 5,000, a quarter of all links, absorbs 80.5 percent. The skew in a real workload decides how much a cache helps, and ours is made up, so treat the shape and not the figures as the lesson: the first few links buy the most, and every further step buys less.
This tests the starting guess from the first lesson. In this trace a cache of 1 percent of the links absorbs 43.0 percent of the requests, which is not most of them. To reach 80 percent the trace needs a quarter of all links. Scaled up to 300 crore links, a quarter would be 75 crore links, or 300 GB at 400 bytes each: several cache nodes, not one. That scaling holds only for this made-up trace. A real service must measure its own hit ratio, for example by logging cache hits for a week, before sizing the cache.
The time column falls from 0.34 to 0.13 seconds, but the database here is SQLite in memory, which is far faster than a database across a network. With a network in between, each avoided read saves much more, as the latency ladder in the estimates chapter showed.
Three details make the cache correct. Each entry should carry the link's expiry, so that the cache never serves a link past its end: set the time-to-live to the smaller of the usual lifetime and the time left. When a link is disabled, delete its cache entry at once; the race described in the cache chapter, where a slow reader refills the cache with an old value after the delete, is closed by also giving every entry a short time-to-live. And remember unknown codes, briefly: a scanner trying random codes would otherwise send every request to the database, so a short-lived entry for a code that was not found protects it.
What does a 302 let the service do that a 301 does not?
- Keep seeing every click. Browsers do not cache a 302 by default, so counting, expiry and disabling keep working.
Using the run, what share of requests did a cache of 1,000 links absorb?
Part 6 · Custom aliases, expiry, abuse and failures
Aliases and targets
A custom alias is a code the creator chooses, so the same unique key that protects random codes must protect it. Beyond that, an alias needs rules. It should use a limited character set and length, so that it is safe in a URL and easy to type. It must not collide with the service's own paths, such as api or login. And it should be compared without regard to case, so that Sale and sale cannot belong to different people and fool visitors.
The target needs checking too. A shortener hides where a link goes, which makes it attractive for phishing and malware. Two cheap checks help: accept only http and https, so that a javascript: or ftp: address is refused, and compare the host to a blocklist that grows from abuse reports. The script runs both checks.
import re from urllib.parse import urlsplit RESERVED = {"api", "admin", "login", "static", "health", "favicon.ico"} ALIAS = re.compile(r"[A-Za-z0-9_-]{3,16}") BLOCKED_HOSTS = {"bad.example.net"} # fed by abuse reports def check_alias(alias, taken): if not ALIAS.fullmatch(alias): return "use 3 to 16 letters, digits, - or _" if alias.lower() in RESERVED: return "reserved" if alias.lower() in {t.lower() for t in taken}: return "taken" # also blocks Sale vs sale look-alikes return "ok" def check_target(url): u = urlsplit(url) if u.scheme not in ("http", "https") or not u.hostname: return "only http and https links" if u.hostname in BLOCKED_HOSTS: return "blocked host" return "ok" taken = {"Sale", "diwali-offer"} for alias in ("Sale", "sale", "api", "a", "my link", "chai-menu"): print(f"alias {alias!r:<12} -> {check_alias(alias, taken)}") for url in ("ftp://example.com/f", "javascript:alert(1)", "https://bad.example.net/x", "https://example.com/ok"): print(f"target {url:<28} -> {check_target(url)}")
Python 3.12.10, standard library. Save this and the next block together as rules.py.
alias 'Sale' -> taken alias 'sale' -> taken alias 'api' -> reserved alias 'a' -> use 3 to 16 letters, digits, - or _ alias 'my link' -> use 3 to 16 letters, digits, - or _ alias 'chai-menu' -> ok target ftp://example.com/f -> only http and https links target javascript:alert(1) -> only http and https links target https://bad.example.net/x -> blocked host target https://example.com/ok -> ok
Output of the first block.
Expiry and click counts
A link past its expires_at must stop redirecting. The check is done when the link is read, not by a background job, because a job runs only now and then and a link must stop at the right moment. The answer is 410 Gone, which says the link existed and is not coming back. A code that was never issued gets 404 Not Found. A background job later deletes expired rows to save space, and removes their cache entries.
Click counts come from events. The redirect handler must not write to the database on each click, or the busiest path becomes a write path. It appends the click to an in-memory buffer or a queue, and a consumer adds the counts in batches. The second block does this with a buffer that flushes at 1,000 clicks.
from collections import Counter links = { # code -> (url, expires_at, disabled) "live": ("https://example.com/a", None, 0), "old": ("https://example.com/b", 1000, 0), "bad": ("https://example.com/c", None, 1), } def resolve(code, now): row = links.get(code) if row is None: return 404 url, expires_at, disabled = row if disabled or (expires_at is not None and now >= expires_at): return 410 # Gone: it existed, now it does not return 302 for code in ("live", "old", "bad", "missing"): print(code, resolve(code, now=2000)) # Click analytics: buffer in memory, flush in batches, off the hot path. buffer, totals = [], Counter() def record(code): buffer.append(code) if len(buffer) >= 1000: totals.update(buffer) buffer.clear() for i in range(2500): record("live" if i % 5 else "old") print("flushed:", dict(totals), "still in memory:", len(buffer))
Continue in rules.py.
live 302 old 410 bad 410 missing 404 flushed: {'old': 400, 'live': 1600} still in memory: 500
Output of the second block.
The first four lines show the answers for four links: a live one redirects with 302, an expired one and a disabled one return 410, and an unknown code returns 404. Then 2,500 clicks were recorded. Two flushes counted 1,600 for live and 400 for old, and 500 were still in the buffer. That is the trade in this design. A buffer is fast and loses its contents in a crash. For counts that matter, the events go to a durable queue, as in the message queue chapter, and the consumer deduplicates, since delivery is at least once. For a rough click count, losing a few seconds of events is acceptable, and the design should say so.
Failures and trade-offs
| Failure | What happens | What we do |
|---|---|---|
| Cache node lost | Its keys miss; the database sees more reads | Spread keys over nodes; keep headroom in the database |
| Database partition down | Codes on it cannot be created or followed from the database | Replica takes over; the cache serves hot links |
| Code allocator down | Servers run out of numbers after their block | Large blocks; random codes as a fallback |
| Clicks queue down | Counts are delayed | Buffer locally and drop the oldest; redirects continue |
| A region is lost | Visitors there cannot follow links | A second region with the same data; DNS or anycast sends traffic there |
The rule behind the table is that the redirect must survive the loss of everything except a way to read a link. Counting, creating, listing and the dashboard may all fail, and following a link still has to work. This is why the redirect path has so few dependencies, and why analytics is kept off it.
Several choices in this chapter could have gone the other way. Counter or random codes: the counter has no collisions and needs an allocator; random codes need nothing and rely on a unique key and a retry. 301 or 302: a permanent redirect is cheaper and loses control. Hash of the URL: the same URL always maps to the same code and can save space, but collisions still occur and two creators cannot have separate statistics. Expiry on read or by job: read-time checking is exact, and the job is only housekeeping.
Extensions reuse the same parts. Link previews fetch the target page and store a title, as a background job. QR codes encode the short URL. Per-user dashboards read the click aggregates. Custom domains map a customer's domain to the same lookup, with the domain added to the key. None of them changes the redirect path.
All chapters · Previous: Design a Photo-Sharing Service like Instagram