Full answer
Requirements
Functional:
- Given a long URL, return a short URL such as
https://sho.rt/aZ3kP9q. - Visiting the short URL redirects to the long URL.
- Optional custom alias and expiry date; basic click counts.
Non-functional:
- Redirects are fast (low tens of milliseconds at p99 inside a region) and highly available; a broken link is very visible.
- Codes must never collide and should not be easy to enumerate.
- Links last at least 5 years.
Capacity estimates
Assumptions: 100M new links per day, read to write ratio 100:1, 500 bytes per record (long URL, code, owner, timestamps), peak factor 2.
- Writes: 100M / 86,400 = about 1,160 per second; about 2,300 per second at peak.
- Reads: 100 x 1,160 = about 116,000 per second; about 230,000 per second at peak.
- Storage: 100M x 500 B = 50 GB per day, 18.25 TB per year, about 91 TB for 5 years before replication (about 274 TB with 3 replicas).
- Code space: 100M x 365 x 5 = 182.5 billion links. Base62 (a-z, A-Z, 0-9): 62^6 = 56.8 billion is too small; 62^7 = 3.52 trillion leaves plenty of room.
- Cache: keeping the 20% of each day's new links that get most clicks: 20M x 500 B = 10 GB, which fits in memory on a small cache cluster.
API
POST /api/v1/links
body: {"long_url": "https://...", "custom_alias": "optional", "expires_at": "optional ISO 8601"}
201 {"code": "aZ3kP9q", "short_url": "https://sho.rt/aZ3kP9q"}
GET /{code}
302 Location: https://original.example.com/page (or 404 / 410 if expired)
GET /api/v1/links/{code}/stats -> {"clicks": 1234, ...}
Data model
links: code (primary key, string), long_url, owner_id, created_at, expires_at.
Access is almost always "look up by code", so a key-value or wide-column store (DynamoDB, Cassandra) partitioned by code fits well; sharded MySQL or PostgreSQL also works. Click events go to a separate analytics pipeline, not the links table.
High-level design
flowchart LR
C[Client] --> LB[Load balancer]
LB --> W[Write service]
LB --> R[Redirect service]
W --> IDS[ID range allocator]
W --> DB[(Links store)]
R --> CACHE[(Redis cache)]
CACHE -. miss .-> DB
R --> Q[Click events queue] --> AN[Analytics]Generating codes
- Counter plus base62 (chosen). Each write server leases a block of IDs (for example 1 million at a time) from a small coordination service, then converts each ID to base62. No collisions, no database check. To avoid sequential, guessable codes, pass the ID through a reversible scramble (a keyed permutation) before encoding.
- Hash the URL (MD5 or SHA-256, take 7 base62 characters). The same URL gets the same code, but collisions must be checked and retried, which adds a read per write.
- Pre-generated random codes stored in a pool table; workers take unused codes. Works, but the pool needs management.
Custom aliases are inserted with a conditional write ("only if code does not exist").
Redirect path and scaling
The redirect service checks Redis first; on a miss it reads the store and fills the cache with a TTL. At a 90% hit ratio, the store sees about 23,000 reads per second at peak, spread over its partitions. Popular links can also be cached at a CDN edge.
301 or 302? A 301 (permanent) is cached by browsers, so repeat visits never reach you: less load, but no click counts and no way to change the target. A 302 keeps every visit visible for analytics. Most shorteners use 302.
Bottlenecks and trade-offs
- The ID allocator is tiny but critical: run it replicated, and since servers hold blocks, a short outage does not stop writes.
- Hot links (a viral link) are absorbed by the cache and CDN.
- Expired links are removed by a background job or the store's TTL feature; codes are not reused to avoid sending old links to new places.
- Abuse: scan long URLs against malware lists and rate limit creation per user or IP.
- Choosing counters over hashing trades "same URL gets same code" for collision-free writes; most products accept duplicate codes for the same URL.
By level
Fresher: List the requirements, sketch the two endpoints and a table with code and long URL, and explain base62 encoding and caching of redirects. Basic arithmetic for requests per second is a bonus at this level.
Mid: Do the throughput, storage and code-space math, compare key generation methods, choose a datastore and cache, and explain 301 versus 302. The 6 versus 7 character decision should come from the math.
Senior: Cover allocator availability, hot links, multi-region reads and replication, abuse prevention, non-guessable codes, analytics pipelines and storage cost over five years. Expect a clear plan for one region failing.
Key points
- Reads dominate about 100 to 1, so cache the redirect path
- 182.5 billion codes over 5 years need 7 base62 characters
- Counter ranges plus base62 avoid collisions; scramble to avoid guessable codes
- 302 keeps analytics; 301 reduces load but hides clicks
- Key-value store partitioned by code fits the access pattern
Common mistakes
- Using 6 characters without checking the code space against 5-year volume
- Hashing URLs without handling collisions
- Using 301 and then promising click analytics
- Writing click counts synchronously into the links table on every redirect
Follow-ups
- How would you support custom aliases without races?
- How would you prevent people from enumerating all short links?
- How would you serve redirects if one region goes down?
Tips
- Do the code-space arithmetic early; it decides the code length
- Explain the 301 versus 302 choice
- Keep analytics off the hot redirect path
Evaluation rubric
- Clear functional and non-functional requirements
- Correct capacity math including code length
- Sound key generation with collision handling
- Caching, redirect semantics and trade-offs discussed