Build a Link-Shortening Service That Scales to Billions
System DesignModel answerLast updated
Design a service that maps long URLs to compact aliases and redirects visitors quickly, covering APIs, storage, code generation, caching, and sharding.
Design a Link-Shortening Service
Your team wants an internal product that works like a public link shortener. A user submits a long web address and gets back a short one. Anyone who opens the short address is sent to the original destination.
What the service must do
Functional
- Create a short link. Take a long URL and return a unique short URL, such as
sho.rt/Ab3dE9z. - Redirect. Opening a short URL sends the visitor to the original URL using an HTTP redirect (permanent or temporary; you decide and justify).
- Custom aliases. The creator may optionally choose the short string themselves.
- Expiry. Links live forever by default, but the creator may set an expiration date.
Non-functional
- Redirects must be low latency and highly available.
- Traffic is read-heavy, around 100 redirects for every link created.
- Data must be durable for the lifetime of the link.
What to cover in your answer
- A high-level architecture (describe or sketch the components and the request flow).
- The API: request and response shapes for creating a link and for following one, including error cases.
- The data model: SQL or NoSQL, with a schema and your reasoning.
- Short-code generation: how you guarantee uniqueness (for example Base62 encoding, hashing, random codes, or a dedicated ID service) and the trade-offs between these.
- Scaling: caching, load balancing, replication, and how the database is partitioned.
- Back-of-the-envelope numbers for traffic, storage, and key-space size.
Hints
Hint 1
Start with estimates: derive writes per second from monthly volume, multiply by 100 for reads, and compute total records over a long horizon. Then check how many Base62 characters you need to cover that many codes with generous headroom.
Hint 2
The access pattern is almost entirely point lookups by short code, with no joins. Let that drive your storage choice, and use a conditional 'insert if absent' to enforce uniqueness for both generated codes and custom aliases.
Hint 3
Compare three generation strategies (hash, random, counter) by collision handling, coordination needs, and guessability. Consider handing each app server a block of IDs so no per-request coordination is needed, then scrambling the ID before encoding.
Hint 4
Think about what 301 versus 302 does to caching, analytics, and the ability to change or expire a link later.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
This is a read-heavy key-value problem. The interesting parts are code generation, a cache-first read path, and partitioning. The guiding principle: the database is the system of record, not the hot path.
1. Requirements and estimates
Assumptions (state them out loud):
- Writes: 100M new links per month is about 40 writes/s on average, roughly 400/s at peak.
- Reads: at 100:1, about 4K redirects/s on average and about 40K/s at peak. Viral links create hot keys.
- Storage: 100M x 12 x 10 years = 12B records. At about 500 bytes each, that is roughly 6 TB. Large but easy to shard.
- Key space: 7 Base62 characters give 62^7, about 3.5 trillion codes, roughly 290x headroom over 12B.
- Targets: redirect p99 under about 50 ms server-side, 99.99% availability on reads. Reads matter more than writes.
2. API
POST /api/v1/urls
{ "long_url": "https://...", "custom_alias": "spring-sale", "expires_at": "2026-01-01T00:00:00Z" }
-> 201 { "short_url": "https://sho.rt/spring-sale", "code": "spring-sale", "expires_at": "..." }
-> 400 invalid URL or alias, 409 alias taken, 429 rate limited
GET /{code}
-> 302 Location: <long_url>
-> 404 unknown code, 410 expired
DELETE /api/v1/urls/{code} (owner only)
301 vs 302. A 301 is cached by browsers, so repeat visits never reach you. That saves load but kills click analytics and means you cannot later change or expire the link. Default to 302 (or 307) when analytics or expiry matter, and say why.
3. Data model
Access is nearly all point lookups by code: no joins, huge volume, trivial partitioning. A key-value or wide-column store (DynamoDB, Cassandra) fits well and gives horizontal scaling and multi-region replication. A sharded SQL database also works at this size; the choice is about operational ease, not feasibility.
urls (partition key: code)
code, long_url, user_id (nullable), created_at,
expires_at (nullable, usable as store-native TTL), is_custom
urls_by_user (partition key: user_id, sort key: created_at) -> code
Enforce uniqueness with a conditional write (insert if not exists) on code. This covers custom aliases and any rare collision without a separate lock.
4. Short-code generation
| Approach | Pros | Cons |
|---|---|---|
| Hash of URL, first 7 Base62 chars | Stateless, can dedupe | Collisions need check and retry; deduping conflicts with per-user expiry and analytics |
| Random 7-char code | Stateless, hard to guess | Collision rate rises as the space fills; needs conditional insert and retry |
| Counter + Base62 | No collisions, compact | A single global counter is a bottleneck and SPOF; sequential codes are enumerable |
Recommended: range-allocated counter. A small coordination service (etcd/ZooKeeper or one DB sequence row) leases each app server a block of, say, 1M IDs. Servers allocate from memory with no per-request coordination. If a server dies, the rest of its block is skipped, which is harmless against 3.5T capacity. The coordinator sees about one call per million writes, so its availability barely matters.
To stop people from enumerating links, pass the ID through a reversible permutation (a Feistel network, or multiplication by a coprime modulo 62^7) before Base62 encoding. It stays collision-free but looks random.
Custom aliases use the same conditional insert. Validate charset and length, block reserved words (api, admin), and return 409 on conflict. If a generated code collides with an existing custom alias, the conditional write fails and the server simply takes the next ID.
5. Architecture
Client -> DNS/GeoLB -> CDN/edge cache (hot codes, short max-age)
| miss
v
L7 load balancer
| |
Redirect service Write service <- ID-range allocator
(stateless) (stateless, rate limiter)
| |
Redis cluster (LRU) |
| miss v
+-------> KV store, sharded by hash(code), RF=3
Redirect service --async--> Kafka (click events) -> stream job -> OLAP store
Read path: edge cache, then Redis, then the database, populating the cache on a miss.
- Traffic is power-law distributed, so caching the hottest ~20% of links (a few hundred GB) absorbs most reads.
- Briefly cache negative results to blunt scanners.
- Cache TTL is the smaller of the default TTL and the link's
expires_at. - Expired links are rejected at read time and purged by store TTL or a background sweeper.
Write path: validate the URL, rate limit, allocate an ID, permute and encode, conditionally insert, return. Writes are rare, so favor durability over latency.
6. Scaling and availability
- Stateless tiers autoscale behind load balancers.
- Sharding: partition by hash(code) using consistent hashing with virtual nodes. Even load, and sequential IDs are fine because the permutation or hash scatters them.
- Replication: RF=3, multi-region async replication, reads served from the local region. A just-created link that has not replicated yet falls back to the home region on a miss.
- Hot keys: CDN plus Redis replicas, or a small in-process LRU in the redirect service.
- Failures: Redis down means falling back to the database (provision headroom for this). Allocator down means servers keep using their leased blocks. Region down means GeoDNS fails over.
7. Follow-ups
Click analytics. Never increment a counter synchronously on the redirect path. Emit an event (code, timestamp, referrer, geo, user agent) through a non-blocking local buffer to Kafka, pre-aggregate per code per minute in a stream processor (which also collapses hot keys), and store aggregates in an OLAP database. Keep raw events in object storage for reprocessing. This relies on using 302, since 301 hides repeat clicks.
Abuse. Rate limit creation per user and IP, check destinations against a malicious-URL list, and allow takedown.
Common mistakes
- Using a single global auto-increment counter with no plan for failure or throughput.
- Choosing 301 without acknowledging the loss of analytics and control.
- Hashing the URL and ignoring collisions.
- Hitting the database on every redirect.
- Incrementing click counters synchronously.
- Skipping the estimate that justifies 7 characters.