Building a Scalable Short-Link Service from Scratch
System DesignModel answerLast updated
Design a service that maps long web addresses to compact codes and serves redirects at very high read volume, covering API, storage, code generation and caching.
Task
Design a link-shortening platform in the spirit of well-known public services. A user submits a long web address and gets back a compact, unique code. Anyone who opens the compact link is sent to the original address.
Core operations
create(long_url)returns a short link.resolve(code)returns the original address so the client can be redirected.
Quality goals
- Fast, highly available redirects. Resolving a link is the hot path and must feel instant.
- Large scale. Roughly 100 million new links per day, with about 100 reads for every write.
- Durability. Links stay valid indefinitely unless the creator sets an expiry.
Numbers to plan around
- Data is retained for 5 years.
- About 10 billion redirects per day.
- About 100 million creations per day.
What to cover in your answer
- API: request and response shapes, plus status codes for the main outcomes.
- Data model: the schema (and storage technology) for the code-to-address mapping.
- Code generation: how you produce unique codes of about 6 to 8 characters, and how you avoid or resolve collisions.
- Architecture: load balancers, application servers, database, cache and any supporting components, with reasoning for each.
Example
- Submitted address:
https://www.example.com/very/long/path/to/resource - Returned short link:
https://tiny.url/aB3dEf - Visiting
https://tiny.url/aB3dEfproduces a 302 response pointing to the original address.
Hints
Hint 1
Convert the daily volumes into per-second rates (average and peak), then compute the total number of links over 5 years. Use that total to decide how many Base62 characters you need.
Hint 2
Compare three ways of making codes: hash-and-truncate, a unique counter encoded in Base62, and a pre-built pool of random codes. Ask which of them need a collision check on every write, and how counter allocation can avoid a network call per request.
Hint 3
Reads dominate by 100 to 1. Think about cache-aside with a skewed popularity distribution, protection against hot keys and invalid-code scans, and keeping the redirect path independent of the code-allocation component.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
Work from requirements to numbers, then API, storage, code generation and architecture. Spend the most depth on two points: producing unique codes without coordinating on every request, and serving roughly 100k+ redirects per second cheaply.
1. Clarify requirements
- Optional features: custom aliases and expiry dates are supported but not mandatory.
- Duplicate submissions: by default, return the same code for the same long address from the same user. Otherwise issue a new one. State the choice explicitly.
- Redirect status: use 302. Every click reaches the service, so analytics, disabling and editing links all work. A 301 is cached by browsers, which reduces load but hides traffic.
- Consistency: a new link must resolve almost immediately for its creator. A few seconds of cross-region lag for everyone else is fine.
2. Capacity estimates
| Metric | Calculation | Result |
|---|---|---|
| Write rate | 100M / 86,400 s | ~1.2k/s average, ~5k/s peak |
| Read rate | 10B / 86,400 s | ~116k/s average, ~300-500k/s peak |
| Links in 5 years | 100M x 365 x 5 | ~183B |
| Code length | 62^6 ≈ 57B (too few); 62^7 ≈ 3.5T | 7 Base62 characters |
| Storage | 183B x ~500 B | ~90 TB raw, ~270 TB at 3x replication |
| Cache | ~100M hot records x 500 B | ~50 GB, fits a small Redis cluster |
Derive the length from the numbers rather than asserting it. 7 characters leaves about 19x headroom over the 5-year total.
3. API
POST /api/v1/urls
body: { "long_url": "...", "custom_alias": "optional", "expires_at": "optional" }
201 { "short_url": "https://tiny.url/aB3dEf1", "short_code": "aB3dEf1", "expires_at": null }
400 invalid or blocked URL
409 custom alias already taken
GET /{code}
302 with Location header
404 unknown code
410 expired
DELETE /api/v1/urls/{code} (owner only)
Authenticate writes with an API key or token. This enables rate limiting and per-user dedup.
4. Data model
The only read pattern is a point lookup by code. There are no joins and the dataset is huge, so a partitioned key-value or wide-column store (DynamoDB, Cassandra) is the natural fit.
url_mapping (partition key: short_code)
short_code string(7)
long_url text (<= 2 KB)
user_id bigint
created_at timestamp
expires_at timestamp, nullable
url_dedup (optional; key: user_id + sha256(long_url)) -> short_code
Handle expiry with the store's native TTL, or a lazy check on read plus a background sweeper. A sharded SQL database also works, but it buys transactions that this workload does not need.
5. Code generation
Option A: hash and truncate. Hash the address, Base62-encode, keep 7 characters.
- Stateless and simple.
- At ~183B keys, collisions are certain (birthday effect), so each write needs a conditional insert and a retry with a salt. Contention rises as the keyspace fills.
Option B: counter plus Base62 (recommended).
- A unique integer maps to a unique code, so collisions are impossible by construction.
- To avoid a single hot counter, a coordinator (ZooKeeper or a database row incremented by 1,000,000) leases ranges to app servers. Each server then issues IDs from memory with no network hop.
- A crashed server wastes its unused range. With 3.5T codes available, that is negligible.
- Sequential codes are guessable and enumerable. Pass the ID through a bijective permutation (a small Feistel network, or multiplication by a coprime modulo 62^7) before encoding. It stays collision-free but looks random.
Option C: pre-generated key service. Create random codes offline, keep them in an "unused" pool, and let servers fetch batches. Codes look random and never collide at request time, but you now run another highly available component.
Custom aliases skip the generator. Use a conditional insert and return 409 on conflict. Keep aliases in a separate namespace (different length or prefix) so they cannot clash with generated codes.
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62(n: int, length: int = 7) -> str:
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out)).rjust(length, "0")
Encoding is O(log n) per ID, effectively constant for 7 characters.
6. Architecture
Client -> GeoDNS -> (optional CDN/edge) -> Load balancer -> Stateless app servers
Write: validate -> local ID range -> permute -> base62 -> conditional insert -> respond
Read: Redis (cache-aside, LRU) -> on miss -> replicated KV store
-> 302 and async click event to Kafka -> stream processor -> analytics store
ID range coordinator (ZooKeeper) is used only by the write path.
Key points:
- Cache hit rate. Link popularity is heavily skewed, so a cache-aside Redis layer should reach 90%+ hits. That leaves 10-30k QPS for the database, which a sharded cluster handles.
- Hot keys. A viral link can saturate one cache shard. Add a small in-process cache per app server and brief edge caching.
- Negative caching. Cache 404s for a short time so random-code scanning does not reach the database.
- Availability. Run app servers across several availability zones, replicate the database 3x (multi-region if required) and replicate Redis. The redirect path touches only cache and database, never the ID coordinator, so a coordinator outage does not stop redirects.
- Abuse control. Rate-limit per key and screen submitted addresses against malware and phishing lists.
7. Trade-offs to state
- 301 vs 302: lower load versus visibility and control.
- Counter vs hash: no collisions but needs coordination and obfuscation, versus stateless but needs retries.
- NoSQL vs SQL: horizontal scale and fast point reads versus transactions you rarely need.
- Consistency: read-your-writes for the creator, eventual elsewhere.
Common mistakes
- Choosing 6 characters without checking it against 183B links.
- Using one global auto-increment counter on the write path.
- Exposing sequential codes that can be enumerated.
- Forgetting negative caching, expiry handling and abuse protection.
- Letting the redirect path depend on the ID allocator.