Global Link Shortener: Fast Redirects and Collision-Free Aliases
System DesignModel answerLast updated
Design a worldwide short-link service with fast, always-available redirects, unique compact IDs, custom aliases, expiry, and asynchronous click analytics.
Problem
Design a link-shortening platform that turns long web addresses into compact aliases and serves redirects to users around the world. Redirects must feel instant and must keep working even when parts of the system fail.
Functional requirements
- Create: Given a long URL, return a unique short alias of roughly 7 to 8 characters.
- Custom alias: A user may request a specific alias, which is accepted only if it is free.
- Redirect: Visiting a short link sends the visitor to the original URL with minimal delay.
- Expiry: A link may carry an optional expiration time. After it passes, the service answers with 404 or 410.
- Analytics: Record click count, timestamp, user agent and referrer. Collection must be asynchronous and must not slow the redirect.
Non-functional requirements
- p99 redirect latency under 15 ms for users worldwide.
- 99.999% availability on the redirect path.
- Favor read availability over immediate cross-region write consistency.
- No single point of failure; scale horizontally.
Expected load
- About 500 million new links per month (roughly 200 writes/s on average, 2,000/s at peak).
- A read-to-write ratio of 100:1 (roughly 20,000 reads/s on average, 100,000/s at peak).
- Links are retained for about 5 years. Estimate total storage for links and metadata.
- Aim to hold about 20% of each day's hot links in memory.
What to cover
- API: endpoints, payloads, status codes, and the choice between 301 and 302/307.
- ID generation: compare hashing with collision handling against distributed ID generators or a range-allocation service combined with Base62.
- Storage: database type and partitioning or sharding key.
- Caching and CDN: multiple cache tiers and how stale entries are invalidated.
- Edge routing: how users reach a nearby point of presence to meet the latency goal.
State your assumptions, do the capacity math, and discuss the trade-offs you accept.
Hints
Hint 1
Do the arithmetic first: 500M per month for 60 months, a few hundred bytes per record, and 62^7 versus your total link count. These numbers should justify ID length, storage engine and cache size.
Hint 2
A cross-ocean round trip alone is far larger than 15 ms, so think about where the redirect decision is made rather than only how fast the database is. Also consider what 301 does to analytics and expiry.
Hint 3
For IDs, ask which approach avoids a read-before-write on every create. Consider handing out blocks of counter values to app servers, then scrambling and Base62-encoding them, and keep custom aliases in a separate namespace.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
Confirm scope first: anonymous or authenticated creation, whether destinations can be edited, and how fresh analytics must be. Then size it.
| Quantity | Estimate |
|---|---|
| Total links in 5 years | 500M x 60 = about 30B |
| Record size | about 500 B (ID, long URL averaging ~200 B, owner, timestamps, expiry, status) |
| Raw storage | 30B x 500 B = about 15 TB; about 45 TB with 3x replication |
| ID space | 62^7 is about 3.5 trillion, roughly 100x headroom over 30B, so 7 characters suffice |
| Daily redirects | 20K/s x 86,400 = about 1.7B |
| Cache | 20% x 1.7B x 500 B = about 170 GB as an upper bound; real unique hot keys are far fewer, so a modest Redis cluster is enough |
| Click events | about 1.7B/day x 200 B = about 350 GB/day raw |
The system is read-dominated with tiny writes, so optimize the redirect path and keep creation simple.
2. API
POST /api/v1/urls
{ "long_url": "...", "custom_alias": "promo24"?, "expires_at": "..."? }
201 { "short_url": "https://sho.rt/aZ3kQ9x", "expires_at": ... }
400 invalid URL | 409 alias taken | 429 rate limited
GET /{id} -> 302 (default) | 301 (opt-in) | 404 | 410 expired
DELETE /api/v1/urls/{id} -> 204 (owner only)
GET /api/v1/urls/{id}/stats -> aggregated analytics
301 vs 302/307: browsers cache a 301 indefinitely, so repeat clicks never reach you. You lose analytics, expiry and takedown. Use 302/307 by default, send Cache-Control: private, max-age=0, and do the caching at your own edge, where you control invalidation.
3. ID generation
| Approach | Pros | Cons |
|---|---|---|
| Hash of URL, truncated to 7 chars | Stateless, natural dedup | Birthday collisions at 30B keys, so every write needs a check and retry |
| Snowflake then Base62 | No coordination | About 11 characters; time-ordered, so guessable |
| Range allocation then Base62 | 7 characters, no collisions, no per-write coordination | Needs a small HA allocator; blocks are lost on crash |
Recommendation: a small strongly consistent allocator (etcd, ZooKeeper, or a counter row in a consensus database) gives each app server a block of about 1M integers. The server increments in memory. At 2K writes/s a server returns to the allocator only every several minutes, and it keeps working from its current block if the allocator is briefly down. Wasted ranges after crashes are acceptable given 100x headroom.
To stop people from enumerating links, pass the counter through a bijection (a Feistel network, or multiplication by a coprime modulo 62^7) before encoding. A bijection cannot introduce collisions.
Custom aliases use a conditional insert (put-if-absent) and live in a namespace disjoint from generated IDs, for example a minimum length of 8 or a reserved character class.
4. Storage
Access is a pure key lookup with no joins, and 15 TB must be replicated across regions. Use a distributed key-value or wide-column store (DynamoDB global tables, Cassandra, ScyllaDB).
urls: short_id (PK) | long_url | owner_id | created_at | expires_at | status
user_urls: owner_id (PK), created_at (SK) -> short_id
- Partition by the hash of
short_id; keys are already uniform, so there are no hotspots. - Use native TTL for physical cleanup, but also check
expires_aton every redirect, because TTL deletion is lazy. - Keep analytics out of this table entirely.
5. Architecture
Client -> GeoDNS/Anycast -> CDN edge (cache + edge worker)
-> regional LB -> stateless redirect service (in-process LRU)
-> regional Redis -> multi-region KV store
Redirect service -> Kafka -> stream aggregation -> OLAP store
Create: API -> local ID block -> conditional put -> async replication
Lookup order is edge cache, in-process LRU, Redis, then the database. On a hit, return the 302 and emit the click event fire-and-forget; it must never block the response.
6. Deep dives
Hitting p99 under 15 ms. A cross-ocean round trip is about 100 ms, so the answer must come from a nearby PoP. Route with anycast or GeoDNS and let an edge worker serve from the edge cache or an edge KV replica. A miss goes to regional Redis for roughly 5 to 10 ms more. Cache 404s briefly (about 30 s) to absorb scanners.
Invalidation. Mappings are effectively immutable, which makes caching safe. Only delete, expiry and abuse takedown change state:
- Edge TTL is the smaller of a few minutes and the link's remaining life.
- On delete or block, publish an event that purges the CDN and Redis keys.
- Use cache-aside with single-flight request coalescing to prevent stampedes on a hot miss.
Five nines. The redirect path depends only on caches and read replicas. Every region can serve every link, and an outage of the write path or analytics pipeline does not affect reads. Allow stale-if-error at the edge during origin trouble.
Analytics. Kafka partitioned by short_id feeds stream aggregation into per-minute counters in an OLAP store; raw events go to object storage. Counts are eventually consistent within seconds.
7. Trade-offs
- 302 over 301: more edge traffic in return for analytics, expiry and takedown.
- Async replication: a brand-new link may 404 in a remote region for under a second. Mitigate by falling back to the home region for young links, or by encoding the home region in the ID.
- Range allocation: accepts some wasted IDs to get zero collisions and no write-time coordination.
8. Common mistakes
- Using 301 and then promising analytics or expiry.
- Hashing without a collision strategy, or ignoring the extra read on every write.
- Putting analytics writes on the redirect's critical path.
- Skipping the capacity math, so the choices of 7 characters, a KV store and a small cache are never justified.
- Allowing custom aliases to collide with generated IDs.
- Forgetting that TTL deletion is lazy and the redirect must check expiry itself.