The problem, stated properly
Take a long URL, give back a short code (bit.ly/a9x2Kq), and redirect anyone who hits that code to the original URL. Tiny product, big lessons: it is the most read-heavy system you will ever design, the key-generation question has at least four legitimate answers, and one HTTP status code decision (301 vs 302) quietly determines whether your analytics business exists at all.
Scale first: read-heavy by two orders of magnitude
Assume 100 million new short URLs per month and a 100:1 read-to-write ratio (typical; links are shared and clicked far more than created).
- Writes: 100M / (30 x 86,400 s) is roughly 40 new URLs/sec. Trivial for any database.
- Reads: 100 x 40 = 4,000 redirects/sec average, 5-10x that at peak, so plan for ~40K QPS.
- Storage: a row is roughly 500 bytes (short code, long URL, owner, timestamps, expiry). 100M/month x 500 B x 5 years is about 30 TB. Fits comfortably in a sharded SQL or any NoSQL store.
- Cache: following the 80/20 rule, 20% of links serve 80% of traffic. Caching the hot 20% of daily writes (100M x 20% x 500 B is about 10 GB/day) in Redis kills most database reads.
The core design decision: where does the short code come from?
Four real strategies, and interviewers expect you to compare at least two:
- Hash + truncate: MD5 or SHA-256 of the long URL, take the first 7 chars. Collision risk is real: with 62^7 (about 3.5 trillion) possible codes, the birthday paradox gives you a 50% collision chance near sqrt(3.5T) which is roughly 1.9 million codes. You must check for collisions on every write and re-hash with a salt or appended counter. Deterministic (same URL gives same code) which some products want and some forbid.
- Counter + Base62: a single auto-increment ID, encoded to Base62 (a-z, A-Z, 0-9). Zero collisions, shortest possible codes, but the counter is a single point of contention and codes are sequential, so competitors can enumerate your links and infer your growth rate.
- Distributed ID generator (the production answer): a ZooKeeper/Redis-based range allocator gives each app server a block of IDs (server A gets 1M-2M, server B gets 2M-3M). No coordination per request, no collisions, scales horizontally. This is what most real systems do.
- Pre-generated Key Generation Service (KGS): an offline worker pre-fills a table of random 7-char codes; servers pull batches of unused keys and mark them used. Zero collision checking on the write path, no sequential leakage, at the cost of one extra moving part that itself needs replication.
301 vs 302: the status code that is actually a business decision
- 301 (permanent): browsers cache the redirect forever. Repeat clicks never touch your servers, which slashes load, but you lose all click analytics after the first visit and can never edit the destination. TinyURL-style.
- 302 (temporary): every click hits your server first. Full analytics (count, referrer, geography, device) and editable destinations, at the cost of owning 100% of redirect traffic forever. Bitly-style. If analytics is the business model, it is 302, and the extra load is the price of the data.
API and data model
POST /api/shortenbody: long_url, optional custom_alias, optional expiry. Returns the short URL. Rate-limit hard: link shorteners are spammer magnets.GET /{code}returns 301/302 with Location header. This endpoint must be pure read: no writes, no joins, cache first.- Schema: url_mapping(code PK, long_url, user_id, created_at, expires_at) plus a separate clicks table for analytics, written asynchronously through a queue so analytics writes never sit in the redirect path.
Production failure modes
- Custom-alias squatting and abuse: without a reservation system and content scanning, short links become phishing infrastructure. Real services run every long URL through a blocklist (Google Safe Browsing API) before accepting it.
- Cache stampede on a viral link: a link in a viral tweet expires from cache and 50K requests hit the DB simultaneously. Defense: request coalescing (single-flight) or a mutex on cache miss.
- KGS key exhaustion: if the pre-generation worker silently stalls, writes fail at 3 AM. Monitor the unused-key pool like you monitor disk space.
- Expired-link ambiguity: returning 404 vs a friendly page vs redirecting to a "this link expired" page is a product decision, not an afterthought.
Common interview traps
- Jumping to "hash the URL" without discussing collisions or the read/write ratio.
- Designing for writes. This system is 99% reads; the redirect path is where all the engineering rigor goes.
- Forgetting rate limiting on creation. Without it, one script fills your keyspace with garbage.
- Never mentioning expiry. Links live forever in toy designs and cost real money in real ones.
Interview Q&A
Q: Base62 or Base64 for codes?
A: Base62. Base64 includes '+' and '/' which are reserved characters in URLs and force ugly percent-encoding. Base62 (10 digits + 26 lowercase + 26 uppercase) is URL-safe with no escaping. Seven Base62 chars give about 3.5 trillion codes, enough for 100M/month for almost 3,000 years.
Q: How do you handle a hot link doing 10K redirects/sec on its own?
A: It is one key, so it lives in one Redis slot. Redis handles ~100K ops/sec per shard, so a single hot key is fine on cache. The failure to plan for is the cache miss: use single-flight so one request repopulates the cache while the rest wait, and consider replicating the hot key across cache nodes so no single Redis box eats all 10K QPS.
Problem ko sahi se samjho
Lambi URL lo, chhota code do (bit.ly/a9x2Kq), aur jo bhi us code pe aaye use original URL pe redirect karo. Product chhota hai, lessons bade hain: ye sabse zyada read-heavy system hai jo tum design karoge, key generation ke 4 valid answers hain, aur ek HTTP status code (301 vs 302) chupke se decide karta hai ki tumhara analytics business exist karega bhi ya nahi.
Pehle scale: reads writes se 100 guna zyada
Maan lo mahine mein 100 million naye short URLs bante hain aur read:write ratio 100:1 hai (links banne se zyada share aur click hote hain).
- Writes: 100M / (30 x 86,400 s) matlab roughly 40 naye URLs/sec. Kisi bhi database ke liye chhota load.
- Reads: 100 x 40 = average 4,000 redirects/sec, peak pe 5-10x, matlab ~40K QPS ke liye plan karo.
- Storage: ek row roughly 500 bytes (code, long URL, owner, timestamps, expiry). 100M/month x 500 B x 5 saal = about 30 TB. Sharded SQL ya koi bhi NoSQL aaram se handle karega.
- Cache: 80/20 rule ke hisaab se 20% links 80% traffic dete hain. Roz ke hot 20% links (about 10 GB/day) Redis mein rakh do to zyadatar DB reads hi khatam.
Core design decision: short code aayega kahan se?
4 real strategies hain, aur interviewer expect karta hai ki tum kam se kam 2 compare karo:
- Hash + truncate: long URL ka MD5/SHA-256, pehle 7 characters lo. Collision risk real hai: 62^7 (about 3.5 trillion) codes mein birthday paradox ke hisaab se ~1.9 million codes ke aas-paas 50% collision chance. Har write pe collision check karna padega aur salt laga ke re-hash. Deterministic hai: same URL hamesha same code degi, kuch products ko ye chahiye, kuch ko bilkul nahi.
- Counter + Base62: ek auto-increment ID ko Base62 (a-z, A-Z, 0-9) mein encode karo. Zero collision, sabse chhote codes, par counter single point of contention hai aur codes sequential hain, matlab competitor tumhare links enumerate karke growth rate nikal sakta hai.
- Distributed ID generator (production answer): ZooKeeper/Redis-based range allocator har app server ko ID ka block deta hai (server A: 1M-2M, server B: 2M-3M). Per request coordination nahi, collisions nahi, horizontally scale hota hai. Real systems mein mostly yahi hota hai.
- Pre-generated Key Generation Service (KGS): ek offline worker random 7-char codes ki table pehle se bharta rahe; servers unused keys ke batch uthate hain aur used mark karte hain. Write path pe collision check zero, sequential leakage nahi, bas ek extra moving part jiska khud replication chahiye.
301 vs 302: status code jo asal mein business decision hai
- 301 (permanent): browser redirect ko hamesha ke liye cache kar leta hai. Repeat clicks tumhare server tak aate hi nahi: load kam, par pehli visit ke baad saara click analytics khatam aur destination kabhi edit nahi kar sakte. TinyURL style.
- 302 (temporary): har click pehle tumhare server pe aata hai. Full analytics (count, referrer, geography, device) aur editable destination, par iska matlab redirect traffic ka 100% hamesha tumhare paas aayega. Bitly style. Agar analytics hi business model hai, to 302 hai, aur extra load us data ka daam hai.
API aur data model
POST /api/shortenbody: long_url, optional custom_alias, optional expiry. Rate limit tight rakho: link shorteners spammers ke favorite hote hain.GET /{code}301/302 with Location header. Ye endpoint pure read hona chahiye: no writes, no joins, cache pehle.- Schema: url_mapping(code PK, long_url, user_id, created_at, expires_at) plus alag clicks table analytics ke liye, jo queue ke through asynchronously likhi jaaye, taaki analytics writes kabhi redirect path mein na aayein.
Production mein kya tootta hai
- Custom-alias squatting aur abuse: reservation system aur content scanning ke bina short links phishing ka tool ban jaate hain. Real services har long URL ko accept karne se pehle blocklist (Google Safe Browsing API) se check karti hain.
- Viral link pe cache stampede: viral tweet ka link cache se expire hua aur 50K requests ek saath DB pe. Defense: request coalescing (single-flight) ya cache miss pe mutex.
- KGS key exhaustion: pre-generation worker chupke se ruk gaya, to raat 3 baje writes fail. Unused-key pool ko disk space ki tarah monitor karo.
- Expired-link ambiguity: 404 dena hai, friendly page, ya "link expired" page? Ye product decision hai, afterthought nahi.
Common interview traps
- Bina collision aur read/write ratio discuss kiye seedha "hash kar do" bolna.
- Writes ke liye design karna. Ye system 99% reads hai; saari engineering redirect path mein hai.
- Creation pe rate limiting bhoolna. Bina iske ek script tumhara keyspace kachre se bhar degi.
- Expiry ka mention hi na karna. Toy designs mein links hamesha jeete hain, asal mein paise lagate hain.
Interview Q&A
Q: Codes ke liye Base62 ya Base64?
A: Base62. Base64 mein '+' aur '/' aate hain jo URLs mein reserved hain aur percent-encoding maangte hain. Base62 (10 digits + 26 lowercase + 26 uppercase) URL-safe hai bina escaping ke. 7 Base62 characters se ~3.5 trillion codes bante hain, 100M/month pe ~3,000 saal ka stock.
Q: Ek hot link khud 10K redirects/sec kar raha ho to?
A: Ek key hai, matlab ek Redis slot mein rahegi. Redis ~100K ops/sec per shard karta hai, to cache pe single hot key theek hai. Jo failure plan maangta hai wo cache miss hai: single-flight lagao taaki ek request cache repopulate kare aur baaki wait karein, aur hot key ko cache nodes pe replicate karo taaki ek hi Redis box pe 10K QPS na pade.