Design a URL shortener
medium 45 minTurn a long URL into a short code and redirect anyone who opens it.
Deep dives
Compare the options before you open them, then say which you would pick.
Deep dive 1
Generating unique IDs
How do many servers make codes that never clash?
BreaksFirst characters of a hash, stored without a check
- How
- Hash the long URL and keep seven characters.
- Limit
- With 3.5 trillion possible codes, the first clash is expected after roughly 2 million links. One user's link would then open another user's page.
- Choose when
- Never without a uniqueness check.
WorksRandom code, inserted only if absent
- How
- Draw seven random characters, write with a condition, retry on a clash.
- Limit
- Each create needs a conditional write, which we do anyway. After five years about 5% of draws clash (182.5B of 3.5T), so retries stay cheap.
- Choose when
- Codes must be hard to guess, or you want no coordinator.
WorksOne shared counter
- How
- Every create increments a counter in Redis or a database, then encodes it.
- Limit
- A network call per link, and creates stop when it does. If failover loses recent increments, numbers repeat, so the conditional write must stay.
- Choose when
- Modest volume and an existing highly available store.
StrongLeased ranges, scrambled
- How
- Lease a million numbers, count in memory, scramble, encode.
- Limit
- Some numbers are wasted on a crash. Scrambling hides order; it does not make codes secret.
- Choose when
- High create rates and short codes: our choice.
| Approach | Good | Bad |
|---|---|---|
| Range allocation (our choice) | No collisions, no network per ID, survives outages | Needs a coordinator; order leaks unless scrambled |
| Hash of the URL, cut to 7 | No coordinator, natural dedup | Collisions: check and retry; same URL for two users |
| Random 7 characters | Unguessable | Check on insert |
| Snowflake ID | No range leases; time-ordered | 64 bits is 11 characters; needs machine IDs and clocks |
| UUID | No coordination | 36 characters, far too long |
| Database auto-increment | Trivial | A call per link, single point of failure, guessable |
Leasing a range
Deep dive 2
Base62 and unguessable codes
Someone is walking through codes to find links. What do you do?
BreaksPlain sequential codes
- How
- Encode 1, 2, 3 as they come.
- Limit
- Anyone can add one and read the next link, or count how many you issue.
- Choose when
- Only for links that are all public and whose volume is not sensitive.
WorksScramble with a secret mix
- How
- A reversible multiply before encoding, plus rate limits on misses.
- Limit
- Enough known pairs reveal a simple multiplier. A keyed cipher over the number (format-preserving encryption) resists that.
- Choose when
- Public links where you only want to deter browsing.
StrongRandom codes and real access control
- How
- Cryptographically random codes, longer for private links, and a sign-in or password before the redirect.
- Limit
- More friction, and private links cannot be cached at a shared edge.
- Choose when
- Anything behind the link is private.
Base62 uses 0-9a-zA-Z. Divide by 62 repeatedly and read the remainders backwards: 1234567 gives 23, 10, 11, 5, so 5ban. Seven digits became four characters.
| Encoding | 1234567 | Verdict |
|---|---|---|
| Decimal | 1234567 (7) | Longer, and easy to enumerate |
| Hex | 12d687 (6) | Longer for the same ID |
| Base58 | 4 characters | Drops 0, O, I, l: good when people type codes |
| Base62 | 5ban (4) | Short and URL-safe |
| Base64 | 4 characters | +, / and = are not URL-safe (the URL variant uses - and _) |
Scramble before encoding
Deep dive 3
Multi-tier caching
One link gets 50,000 clicks a second. How is it served?
BreaksRead the database each time
- How
- Every click is a key lookup.
- Limit
- One key lives in one partition. In DynamoDB that is about 3,000 strongly consistent or 6,000 eventually consistent small reads a second.
- Choose when
- Cold links only.
WorksRedis in front
- How
- Cache-aside with a TTL.
- Limit
- One hot key sits on one node, and when it expires every server asks the database at once.
- Choose when
- Normal popularity; add request coalescing.
StrongEdge, then a small in-process cache, then Redis
- How
- The CDN answers most clicks; each server keeps the hottest links for a second or two; misses are coalesced into one read.
- Limit
- Seconds of staleness in several places; takedowns must purge all of them.
- Choose when
- Viral links are expected, as here.
Each tier filters the next
Average latency
def handle_redirect(code): url = cache.get(code) # 1. try the cache if url is None: url = db.find_long_url(code) # 2. miss: read the database cache.set(code, url or MISSING, ttl=DAY if url else MINUTE) if url is None or url is MISSING: return 404 return 302, {"Location": url}301 or 302? RFC 9110 lets clients cache a 301, so browsers may skip you on later clicks. A 302 keeps them coming back. Choose 301 to cut load when you need neither per-click data nor edits; otherwise 302.
Deep dive 4
The analytics pipeline
How do you count clicks?
BreaksAdd one to the link's row
- How
UPDATE links SET clicks = clicks + 1on each redirect.- Limit
- Writes pile up on one hot row and the redirect waits for them.
- Choose when
- A hobby project.
WorksCount in memory, flush each second
- How
- Every server keeps totals and adds them to Redis or the database in batches.
- Limit
- A crash loses up to a second of counts, and you cannot break them down later.
- Choose when
- Only a total is needed and small loss is fine.
StrongEvents, a queue and rollups
- How
- Send an event without waiting; a stream job deduplicates and aggregates.
- Limit
- More to operate, results minutes late. If the local buffer is lost before Kafka accepts it, those clicks are gone.
- Choose when
- Breakdown by country, device and time is a requirement.
Ten billion clicks a day
- 1
Fire and forget
Look up, return 302, send the event. If Kafka is slow, the redirect is not. Event: id, code, time, hashed IP, country, city, referrer, device, browser.
- 2
One-minute tumbling windows
Drop repeated event IDs, group by code, country, referrer and device. 1,500 events become one row.
- 3
Hourly rollups
AggregatingMergeTree merges parts in the background. Re-inserting a batch would count twice, so deduplicate before this step.
- 4
Retention
Raw events 7 days, rollups by month. 1 TB a day raw becomes about 100 GB, and about 10 GB after columnar compression.
Edge cases
What can go wrong
| Case | Severity | Problem | Answer |
|---|---|---|---|
| Alias collision | medium | "my-brand" is taken | Conditional write, 409 with suggestions; the UI's availability check is only a hint |
| Hash collision | low | Two inputs, one code | Impossible with counted IDs; with hashing, check and retry |
| Expiry race | low | Expires during a redirect | Check expires_at at read time, 410; optional 5-minute grace. TTL deletion is lazy, so never rely on it |
| Malicious URL | high | Phishing link | Check on create, re-scan later, disable, notify and report |
| Thundering herd | high | Hot link's edge copy expires | Stale-while-revalidate and request coalescing |
| Redis down | medium | Latency rises | Circuit breaker after 3 failures, read the database, warm from logs |
| DynamoDB down | critical | Cold links fail | Multi-region replicas, health-check failover, serve what Redis has |
| ZooKeeper down | medium | No new ranges | Ranges in memory last for hours |
| Kafka down | low | Clicks delayed | Buffer, retry with backoff, spill to disk and replay |
| CDN down | high | All traffic hits origin | A second CDN with DNS failover, autoscaling |
Failure priorities
Reads (99%): availability
A slightly stale redirect beats a 503.
Writes (1%): correctness
Reject a request rather than issue a duplicate code.
Analytics: eventually
Buffer and retry; late is fine.
Failure drill: say it before you read it
- 1
Redis is gone
The store sees 35% of traffic instead of 5%: 40,250 reads a second instead of 5,750. Trip the breaker, lengthen edge TTLs, shed the coldest requests, then warm slowly.
- 2
A range lease is given twice
The conditional write refuses the second owner. The server drops that range and leases another. No link is overwritten.
- 3
A takedown must work now
Mark it inactive, delete the Redis key, purge the edge. In-process copies expire in a second or two. Browsers that stored a 301 cannot be reached: one more reason for 302.
- 4
The home region is down
Redirects continue from replicas. Generated codes continue elsewhere because ranges are separate. Custom aliases wait.