Design a URL shortener
medium 45 minTurn a long URL into a short code and redirect anyone who opens it.
API and data
The contract first, then the data that serves it.
Entities
Name the things first
Four nouns are enough to start: Link (code, long URL, owner, expiry), User, Domain and Click. Add fields when a request needs them, and take the owner from the sign-in token, never from the request body.
API
Endpoints and status codes
POST /api/v1/urls{ "long_url": "https://www.example.com/very/long/path?query=params", "custom_alias": "my-link", (optional) "expires_at": "2027-12-31", (optional) "domain": "go.brand.com" } (optional, enterprise)→ 201 { "short_url": "https://sho.rt/my-link", "short_code": "my-link", "long_url": "...", "created_at": "2026-01-15T10:30:00Z", "expires_at": "2027-12-31T23:59:59Z", "qr_code_url": "https://sho.rt/qr/my-link.png" }GET /{short_code}→ 302 Found Location: https://www.example.com/very/long/path?query=params Cache-Control: public, max-age=0, s-maxage=60GET /api/v1/urls/{short_code}/stats?from=2026-01-01&to=2026-01-31→ 200 { "total_clicks": 15420, "unique_visitors": 8932, "clicks_by_country": { "US": 5200, "UK": 2100, "IN": 1800, "DE": 1500 }, "clicks_by_referrer": { "twitter.com": 4500, "direct": 3200, "google.com": 2100 }, "clicks_by_device": { "mobile": 9200, "desktop": 5800, "tablet": 420 }, "clicks_by_hour": [ { "hour": "2026-01-15T10:00:00Z", "clicks": 523 } ] }DELETE /api/v1/urls/{short_code}→ 204 soft delete: later redirects return 410, the code is never reusedStatus codes
| Code | Meaning here |
|---|---|
| 201 Created | Short URL created |
| 302 Found | Temporary redirect, the default (analytics) |
| 301 Moved Permanently | Permanent redirect (SEO, less load) |
| 400 Bad Request | Invalid URL |
| 404 Not Found | Code does not exist |
| 409 Conflict | Custom alias already taken |
| 410 Gone | Expired or deleted |
| 429 Too Many Requests | Rate limit exceeded, with Retry-After |
API decisions
Interviewer
What are the key design decisions?
You
One per endpoint:
- Create: retries carry an idempotency key. Same owner and same URL may return the same code; different owners get different codes, so their analytics stay apart.
- Create: return the full short URL, not only the code, so clients can use it directly.
- Redirect: the hot path, about 99% of traffic. No body, just
Location. Default 302, with 301 as an option. - Stats: hourly, daily or weekly aggregates, never raw clicks; paginate by date range and cache for 5 minutes.
Interviewer
How do you protect against abuse?
You
Three layers, with
X-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Resetheaders so good clients can behave:- Gateway limits: sliding window counters in Redis with a TTL. Anonymous: 10 creates and 1,000 redirects an hour per IP. Signed in: 100 creates. Enterprise: 10,000 creates.
- Validation: http and https only, blocked domains, Google Safe Browsing, optional reachability check (it adds latency).
- Detection: the same URL from many IPs (bots), bulk links to similar domains (spam), and a model that scores URLs.
Database
Data model
Three stores, three access patterns
Why each database
| Store | Use | Why | Alternatives |
|---|---|---|---|
| DynamoDB | URL mappings | Single-digit ms, scales by key, global tables | Cassandra |
| Redis | Hot link cache | Sub-ms reads, TTL | Memcached |
| PostgreSQL | Users, billing, domains | ACID, complex queries, not on the hot path | MySQL |
| ClickHouse | Analytics (OLAP) | Columnar, fast aggregates, good compression | BigQuery, Druid |
| Kafka | Event stream | Decouples, durable | Kinesis, Pulsar |
Indexes
| Store | Index | Serves |
|---|---|---|
| DynamoDB | partition key short_code | redirect, |
| DynamoDB | GSI user_id | list a user's links |
| DynamoDB | GSI long_url_hash | find this owner's duplicate |
| ClickHouse | order by (short_code, hour) | time series of one link |
| ClickHouse | partition by month | drop old data cheaply |
| ClickHouse | skip index on country | geographic filters |
CREATE TABLE click_stats_hourly ( short_code String, hour DateTime, total_clicks SimpleAggregateFunction(sum, UInt64), visitors AggregateFunction(uniq, UInt64), by_country SimpleAggregateFunction(sumMap, Map(String, UInt64)), by_referrer SimpleAggregateFunction(sumMap, Map(String, UInt64)), by_device SimpleAggregateFunction(sumMap, Map(String, UInt64))) ENGINE = AggregatingMergeTreePARTITION BY toYYYYMM(hour)ORDER BY (short_code, hour);SELECT sum(total_clicks), uniqMerge(visitors)FROM click_stats_hourlyWHERE short_code = 'abc123' AND hour >= '2026-01-01' AND hour < '2026-02-01';Consistency and invalidation
Interviewer
How do you keep the caches correct?
You
The database is the source of truth and every cache has a TTL.
- Create: write the database, then Redis with 24 hours.
- Update or delete: update the database, delete the Redis key, purge the CDN.
- Miss: read the database, fill Redis (cache-aside), let headers fill the CDN.
- Not write-behind: losing Redis before a sync would lose links.
- Popular links can keep 24 hours; unpopular ones 1 hour or nothing. Redis evicts with LRU.
- Include the host in the cache key, so custom domains never share entries.
Interviewer
Where do you need strong consistency?
You
Only for claiming a code: a conditional write decides. Clicks may be minutes late. With multi-region tables that replicate asynchronously, a condition is checked against the local copy only, so I send each alias claim to one home region.